Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions backend/__tests__/unit/routes/agentsRuntime.dm-events.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ jest.mock('../../../services/agentEventService', () => ({
list: jest.fn(),
listInboxPage: jest.fn(),
renewDelivery: jest.fn(),
releaseDelivery: jest.fn(),
holdsEvent: jest.fn(),
}));
jest.mock('../../../services/agentIdentityService', () => ({
Expand Down Expand Up @@ -237,3 +238,47 @@ describe('inbox delivery renewal route', () => {
expect(AgentEventService.renewDelivery).not.toHaveBeenCalled();
});
});

describe('inbox delivery release route (F189)', () => {
const eventId = '0123456789abcdef01234567';
const otherId = '0123456789abcdef01234568';
const response = () => ({ status: jest.fn().mockReturnThis(), json: jest.fn() });
test('releases under the authenticated seat/instance and names only what it released', async () => {
AgentEventService.releaseDelivery.mockReset();
AgentEventService.releaseDelivery.mockImplementation(async (id) => (id === eventId ? 'released' : 'not_held'));
const res = response();
await getRouteHandler('/events/release', 'post')({
agentInstallation: { agentName: 'wren', instanceId: 'writer-instance' },
body: {
agentName: 'victim',
events: [{ eventId, deliveryId: 'nonce' }, { eventId: otherId, deliveryId: 'stale' }],
},
}, res);
expect(AgentEventService.releaseDelivery).toHaveBeenCalledWith(eventId, 'wren', 'writer-instance', 'nonce');
expect(AgentEventService.releaseDelivery).toHaveBeenCalledWith(otherId, 'wren', 'writer-instance', 'stale');
expect(res.json).toHaveBeenCalledWith({ released: [eventId], atCeiling: [] });
});
test('names the events refused at the redelivery ceiling, so the runner can say why', async () => {
AgentEventService.releaseDelivery.mockReset();
AgentEventService.releaseDelivery.mockImplementation(async (id) => (id === eventId ? 'at_ceiling' : 'released'));
const res = response();
await getRouteHandler('/events/release', 'post')({
agentInstallation: { agentName: 'wren', instanceId: 'default' },
body: { events: [{ eventId, deliveryId: 'nonce' }, { eventId: otherId, deliveryId: 'n2' }] },
}, res);
expect(res.json).toHaveBeenCalledWith({ released: [otherId], atCeiling: [eventId] });
});
test.each([
['no events', {}],
['a missing deliveryId', { events: [{ eventId }] }],
['a malformed id', { events: [{ eventId: 'nope', deliveryId: 'n' }] }],
])('refuses %s with 400', async (_label, body) => {
AgentEventService.releaseDelivery.mockReset();
const res = response();
await getRouteHandler('/events/release', 'post')({
agentInstallation: { agentName: 'wren', instanceId: 'default' }, body,
}, res);
expect(res.status).toHaveBeenCalledWith(400);
expect(AgentEventService.releaseDelivery).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// F189/F182: a runner that stops while it holds claimed events hands them
// back, so its replacement gets them on the next poll instead of after the
// 10–20 minute requeue sweep, up to a redelivery ceiling that still retires a
// poison event.
const mongoose = require('mongoose');
const { setupMongoDb, closeMongoDb, clearMongoDb } = require('../../utils/testUtils');
const AgentEvent = require('../../../models/AgentEvent');
const AgentEventService = require('../../../services/agentEventService');

describe('releasing a held delivery back to pending', () => {
beforeAll(setupMongoDb);
afterAll(closeMongoDb);
afterEach(clearMongoDb);

const podId = new mongoose.Types.ObjectId();
const delivery = async (fields = {}) => {
const row = { _id: new mongoose.Types.ObjectId(), agentName: 'wren', instanceId: 'default',
podId, type: 'chat.mention', status: 'delivered', attempts: 1, payload: { content: 'hi @wren' },
deliveryNonce: 'current-nonce', deliveredAt: new Date(), createdAt: new Date(), ...fields };
await AgentEvent.collection.insertOne(row);
return row;
};

test('returns the row to pending with its nonce cleared, keeping the attempt count', async () => {
const row = await delivery();
expect(await AgentEventService.releaseDelivery(String(row._id), 'Wren', 'default', 'current-nonce')).toBe('released');
const after = await AgentEvent.findById(row._id).lean();
expect(after.status).toBe('pending');
expect(after.deliveryNonce).toBeNull();
expect(after.deliveredAt).toBeNull();
// attempts counts deliveries; a hand-back is not a delivery and refunds nothing.
expect(after.attempts).toBe(1);
});

test('the next poll claims a released event at once, under a new nonce', async () => {
const row = await delivery();
await AgentEventService.releaseDelivery(String(row._id), 'wren', 'default', 'current-nonce');
const [claimed] = await AgentEventService.list({ agentName: 'wren', instanceId: 'default', limit: 10 });
expect(String(claimed._id)).toBe(String(row._id));
expect(claimed.payload.deliveryId).toEqual(expect.any(String));
expect(claimed.payload.deliveryId).not.toBe('current-nonce');
// The released runner's nonce can no longer ack it, so it is answered once.
expect(await AgentEventService.acknowledge(String(row._id), 'wren', 'default',
{ outcome: 'posted' }, 'current-nonce', 'cli')).toBeNull();
});

// The ceiling is twice the requeue cap (3 by default): six deliveries.
test('below the redelivery ceiling, a released event is redelivered and not retired', async () => {
// Restarts each claimed and lost this mention: attempts is past the
// requeue cap but under the ceiling. Released, it waits as pending.
const row = await delivery({ attempts: 5, deliveredAt: new Date(Date.now() - 60 * 60 * 1000) });
expect(await AgentEventService.releaseDelivery(String(row._id), 'wren', 'default', 'current-nonce')).toBe('released');
const gc = await AgentEventService.garbageCollect();
expect(gc.expiredDelivered).toBe(0);
expect((await AgentEvent.findById(row._id).lean()).status).toBe('pending');
const page = await AgentEventService.list({ agentName: 'wren', instanceId: 'default', limit: 10 });
expect(page.map((event) => String(event._id))).toEqual([String(row._id)]);
});

test('at the redelivery ceiling a release is refused, and the sweep retires the event', async () => {
// A poison event, or a turn POSTing its own deliveryId, cannot loop
// through release forever: every lap is a claim, and claims raise attempts.
const row = await delivery({ attempts: 6, deliveredAt: new Date(Date.now() - 60 * 60 * 1000) });
expect(await AgentEventService.releaseDelivery(String(row._id), 'wren', 'default', 'current-nonce')).toBe('at_ceiling');
const held = await AgentEvent.findById(row._id).lean();
expect(held.status).toBe('delivered');
expect(held.deliveryNonce).toBe('current-nonce');
await AgentEventService.garbageCollect();
expect((await AgentEvent.findById(row._id).lean()).status).toBe('failed');
});

test('the ceiling follows AGENT_EVENT_REQUEUE_MAX_ATTEMPTS', async () => {
const previous = process.env.AGENT_EVENT_REQUEUE_MAX_ATTEMPTS;
process.env.AGENT_EVENT_REQUEUE_MAX_ATTEMPTS = '2';
try {
const under = await delivery({ attempts: 3 });
const at = await delivery({ attempts: 4 });
expect(await AgentEventService.releaseDelivery(String(under._id), 'wren', 'default', 'current-nonce')).toBe('released');
expect(await AgentEventService.releaseDelivery(String(at._id), 'wren', 'default', 'current-nonce')).toBe('at_ceiling');
} finally {
if (previous === undefined) delete process.env.AGENT_EVENT_REQUEUE_MAX_ATTEMPTS;
else process.env.AGENT_EVENT_REQUEUE_MAX_ATTEMPTS = previous;
}
});

test.each([
['other-seat', 'default', 'current-nonce'], ['wren', 'another-instance', 'current-nonce'],
['wren', 'default', 'old-nonce'], ['wren', 'default', ''],
])('refuses wrong identity or nonce (%s/%s/%s)', async (agent, instance, nonce) => {
const row = await delivery();
expect(await AgentEventService.releaseDelivery(String(row._id), agent, instance, nonce)).toBe('not_held');
const after = await AgentEvent.findById(row._id).lean();
expect(after.status).toBe('delivered');
expect(after.deliveryNonce).toBe('current-nonce');
});

test.each(['pending', 'acked', 'failed'])('does not touch a %s event', async (status) => {
const row = await delivery({ status });
expect(await AgentEventService.releaseDelivery(String(row._id), 'wren', 'default', 'current-nonce')).toBe('not_held');
expect((await AgentEvent.findById(row._id).lean()).status).toBe(status);
});
});
42 changes: 39 additions & 3 deletions backend/routes/agentsRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1443,13 +1443,18 @@ router.post('/bot/events/:id/ack', phase4RateLimit, auth, requireApiTokenScopes(
}
});

// The body of /events/renew and /events/release: 1–50 { eventId, deliveryId }.
const isDeliveryPairList = (events: unknown): events is Array<{ eventId: string; deliveryId: string }> => (
Array.isArray(events) && events.length >= 1 && events.length <= 50
&& events.every((entry: any) => entry && typeof entry.eventId === 'string'
&& /^[a-fA-F0-9]{24}$/.test(entry.eventId) && typeof entry.deliveryId === 'string' && entry.deliveryId)
);

// A live inbox turn may outlast the stale-delivery GC interval. Renew only
// the token owner's current nonce; this never marks work handled.
router.post('/events/renew', phase4RateLimit, agentRuntimeAuth, async (req: any, res: any) => {
const events = req.body?.events;
if (!Array.isArray(events) || events.length < 1 || events.length > 50
|| events.some((entry: any) => !entry || typeof entry.eventId !== 'string' || !/^[a-fA-F0-9]{24}$/.test(entry.eventId)
|| typeof entry.deliveryId !== 'string' || !entry.deliveryId)) {
if (!isDeliveryPairList(events)) {
return res.status(400).json({ message: 'events requires 1–50 eventId/deliveryId pairs' });
}
const agentName = req.agentInstallation?.agentName
Expand Down Expand Up @@ -1479,6 +1484,37 @@ router.post('/events/renew', phase4RateLimit, agentRuntimeAuth, async (req: any,
}
});

// F189/F182: a stopping runner hands back the deliveries it holds but will not
// run, so its replacement gets them on its first poll instead of after the
// requeue sweep. Same shape and nonce binding as /events/renew; never an ack.
// Bounded: past the redelivery ceiling a release is refused (atCeiling).
router.post('/events/release', phase4RateLimit, agentRuntimeAuth, async (req: any, res: any) => {
const events = req.body?.events;
if (!isDeliveryPairList(events)) {
return res.status(400).json({ message: 'events requires 1–50 eventId/deliveryId pairs' });
}
const agentName = req.agentInstallation?.agentName
|| req.agentUser?.botMetadata?.agentName
|| req.agentUser?.botMetadata?.agentType || req.agentUser?.username;
const instanceId = req.agentInstallation?.instanceId || req.agentUser?.botMetadata?.instanceId || 'default';
if (!agentName) return res.status(403).json({ message: 'Agent token not authorized for events' });
try {
const results = await Promise.all(events.map(async (entry: { eventId: string; deliveryId: string }) => ({
eventId: entry.eventId,
outcome: await AgentEventService.releaseDelivery(entry.eventId, agentName, instanceId, entry.deliveryId),
})));
// atCeiling: refused because the event reached the redelivery ceiling; it
// stays delivered and the requeue sweep retires it.
return res.json({
released: results.filter((r) => r.outcome === 'released').map((r) => r.eventId),
atCeiling: results.filter((r) => r.outcome === 'at_ceiling').map((r) => r.eventId),
});
} catch (error: any) {
console.error('Error releasing inbox deliveries:', error.message);
return res.status(500).json({ message: 'Could not release inbox deliveries' });
}
});

router.post('/events/:id/ack', phase4RateLimit, agentRuntimeAuth, async (req: any, res: any) => {
try {
const installation = req.agentInstallation;
Expand Down
37 changes: 37 additions & 0 deletions backend/services/agentEventService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ const ABANDONED_RUN_MINUTES = 30;
// an hour as 'failed' with a reason: a reply that late is no longer an answer,
// and a closed event says so where a pending one says nothing.
const STRANDED_PENDING_MIN_AGE_MS = 60 * 1000;
// F189: the most deliveries a hand-back (POST /events/release) may return to
// pending. Twice the requeue cap, read from the same env var as
// garbageCollect, so the two bounds move together.
const releaseCeiling = (): number => 2 * Math.max(Number(process.env.AGENT_EVENT_REQUEUE_MAX_ATTEMPTS || 3), 1);
const STRANDED_PENDING_MAX_AGE_MS = 30 * 60 * 1000;

// The migration on acknowledge() runs in two phases, and BOTH are in this
Expand Down Expand Up @@ -2567,6 +2571,39 @@ class AgentEventService {
return result.modifiedCount === 1;
}

// F189/F182: a stopping runner hands back the deliveries it holds but will
// never run (a circuit-open carry, a carried greeting, a page it claimed as
// the stop arrived), so its replacement claims them on the next poll rather
// than after the 10–20 minute requeue sweep. Nonce-bound like renew: only
// the runner whose delivery it is can release it, never a replacement's.
// `attempts` is untouched: it counts deliveries, and a hand-back is not one.
// A pending row is outside the requeue cap, so a release must carry its own
// bound or a poison event loops forever across restarts (and a turn could
// loop itself by POSTing its own deliveryId). The ceiling is twice the
// requeue cap, on `attempts`: every lap through a release is a fresh claim,
// and every claim raises attempts, so this bounds restarts and repeated
// releases from one process alike. At the ceiling the row stays `delivered`,
// and the sweep retires it with its visible line.
static async releaseDelivery(
eventId: string, agentName: string, instanceId: string, deliveryId: string,
): Promise<'released' | 'at_ceiling' | 'not_held'> {
if (!eventId || !deliveryId) return 'not_held';
const ceiling = releaseCeiling();
const held = {
_id: eventId,
agentName: String(agentName).toLowerCase(),
instanceId: String(instanceId || 'default'),
status: 'delivered',
deliveryNonce: deliveryId,
};
const result = await AgentEvent.updateOne(
{ ...held, $or: [{ attempts: { $lt: ceiling } }, { attempts: { $exists: false } }] },
{ $set: { status: 'pending', deliveredAt: null, deliveryNonce: null } },
);
if (result.modifiedCount === 1) return 'released';
return await AgentEvent.exists({ ...held, attempts: { $gte: ceiling } }) ? 'at_ceiling' : 'not_held';
}

// True when the event is this agent's own and is mid-flight or already
// checkpointed. A turn that checkpoints (`commonly_checkpoint_event` acks
// mid-turn, which clears the nonce) keeps renewing, and `renewDelivery` then
Expand Down
9 changes: 6 additions & 3 deletions backend/services/runtimeOutsiderGrantRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,12 @@ add(runtime, 'read', [
'GET /memory/shared/:agentName/:instanceId?',
]);
add(runtime, 'own_state', ['POST /events/:id/ack', 'POST /pods/:podId/skill-load']);
// A lease renewal, the seat's own model controls (a page-issued key may change
// only its own BYO installations), and its own read cursor: none reaches anyone else.
add(runtime, 'own_state', ['POST /events/renew', 'PATCH /configuration', 'POST /pods/:podId/catch-up']);
// A lease renewal or hand-back of its own delivery (F189), the seat's own model
// controls (a page-issued key may change only its own BYO installations), and
// its own read cursor: none reaches anyone else.
add(runtime, 'own_state', [
'POST /events/renew', 'POST /events/release', 'PATCH /configuration', 'POST /pods/:podId/catch-up',
]);
add(runtime, 'pod_write', [
'POST /pods/:podId/typing', 'POST /pods/:podId/messages', 'POST /pods/:podId/propose-action',
'POST /pods/:podId/summaries', 'POST /pods/:podId/ask', 'POST /pods/:podId/uploads',
Expand Down
Loading
Loading