Skip to content

Commit e901771

Browse files
authored
fix(hooks): avoid false admission timeouts during runtime reload (#128975)
1 parent ebc70fa commit e901771

6 files changed

Lines changed: 67 additions & 22 deletions

File tree

‎docs/automation/cron-jobs.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -634,12 +634,12 @@ Query-string tokens are rejected.
634634
- Supplying both a concrete `channel` and `to` enables direct announce delivery.
635635
- Set `accountId` with `channel` and `to` to select a configured, enabled account on multi-account channels. Unknown, disabled, or invalid account IDs return `400` and schedule no run.
636636

637-
The HTTP response waits only for runner admission, not for the agent turn to finish. A `200` may take up to 15 seconds and means the run entered its agent runner. Pre-run failures return `{ ok: false, error, runId }` with:
637+
The HTTP response waits only for canonical session/global placement admission, not for the agent turn to finish. A `200` may take up to 15 seconds and means the execution path acquired that admission; the run may still be preparing its model runtime. Pre-admission failures return `{ ok: false, error, runId }` with:
638638

639639
- `400` when delivery coordinates or account selection are invalid; correct the request before retrying.
640640
- `409` when the target session changed or otherwise rejects new work; retry after resolving the session conflict.
641-
- `502` when Gateway or cron preparation fails before runner entry.
642-
- `503` when runner admission does not complete within 15 seconds. Timed-out queued work is canceled and does not start later.
641+
- `502` when Gateway or cron preparation fails before placement admission.
642+
- `503` when placement admission does not occur within 15 seconds. Timed-out queued work is canceled and does not start later.
643643

644644
</Accordion>
645645
<Accordion title="Mapped hooks (POST /hooks/<name>)">

‎docs/gateway/configuration-reference.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1114,8 +1114,8 @@ Validation and safety notes:
11141114
- Direct announce delivery requires both a concrete `channel` and `to`; supplying only one fails before the run is scheduled.
11151115
- `accountId` selects a configured, enabled account for direct announce delivery and requires both `channel` and `to`; invalid selections return `400` before a run starts.
11161116
- Omit both delivery fields for completion-only hooks, or set `deliver: false` to ignore supplied destination data.
1117-
- The request waits up to 15 seconds for runner admission, not run completion. `200` means the agent runner was entered.
1118-
- Pre-run failures return `{ ok: false, error, runId }`: `400` for invalid delivery coordinates or account selection, `409` for session admission conflicts, `502` for other preparation failures, and `503` when the 15-second admission deadline expires. Timed-out queued work is canceled and will not start later.
1117+
- The request waits up to 15 seconds for canonical session/global placement admission, not run completion. `200` means the execution path acquired that admission; the run may still be preparing its model runtime.
1118+
- Pre-admission failures return `{ ok: false, error, runId }`: `400` for invalid delivery coordinates or account selection, `409` for session admission conflicts, `502` for other preparation failures, and `503` when placement admission does not occur within 15 seconds. Timed-out queued work is canceled and will not start later.
11191119
- `POST /hooks/<name>` → resolved via `hooks.mappings`
11201120
- Template-rendered mapping `sessionKey` values are treated as externally supplied and also require `hooks.allowRequestSessionKey=true`.
11211121
- Mapped `agent` actions use the same admission wait and `200`/`400`/`409`/`502`/`503` outcomes.

‎src/agents/embedded-agent-runner/run/lane-controller.queue-liveness.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,8 @@ describe("queued embedded run context liveness", () => {
207207
const registeredAt = 1_000;
208208
const admissionAt = registeredAt + CONTEXT_TTL_MS + 1;
209209
const clock = vi.spyOn(Date, "now").mockReturnValue(registeredAt);
210-
const { controller, params } = createRunController();
210+
const onLaneWait = vi.fn();
211+
const { controller, params } = createRunController({ onLaneWait });
211212
registerAgentRunContext(params.runId, {
212213
lifecycleGeneration: params.lifecycleGeneration,
213214
registeredAt,
@@ -235,13 +236,19 @@ describe("queued embedded run context liveness", () => {
235236

236237
try {
237238
await placementEntered.promise;
239+
expect(onLaneWait).not.toHaveBeenCalledWith(expect.objectContaining({ waiting: false }));
238240
expect(readAgentRunIndexVersion()).toBe(versionBeforeQueue);
239241
clock.mockReturnValue(admissionAt);
240242
expect(sweepStaleRunContexts()).toBe(0);
241243
expect(getAgentRunContext(params.runId)).toBeDefined();
242244

243245
placementAdmitted.resolve();
244246
await remoteStarted.promise;
247+
expect(onLaneWait).toHaveBeenCalledExactlyOnceWith({
248+
waitMs: 0,
249+
queuedAhead: 0,
250+
waiting: false,
251+
});
245252
expect(getAgentRunContext(params.runId)?.lastActiveAt).toBe(admissionAt);
246253
expect(readAgentRunIndexVersion()).toBe(versionBeforeQueue + 1);
247254
expect(localTurn).not.toHaveBeenCalled();

‎src/agents/embedded-agent-runner/run/lane-controller.ts‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,6 @@ export function createEmbeddedRunLaneController<TParams extends LaneParams>(opti
126126
};
127127
const taskWithCurrentLifecycle = async () => {
128128
let params = options.getParams();
129-
params.onLaneWait?.({ waitMs: 0, queuedAhead: 0, waiting: false });
130129
params.replyOperation?.markGlobalLaneWaitEnded();
131130
throwIfAborted();
132131
let lifecycleGeneration = options.getLifecycleGeneration();
@@ -187,6 +186,8 @@ export function createEmbeddedRunLaneController<TParams extends LaneParams>(opti
187186
lifecycleGeneration,
188187
lastActiveAt: Date.now(),
189188
});
189+
// Queue dequeue can still block on writer or placement admission.
190+
params.onLaneWait?.({ waitMs: 0, queuedAhead: 0, waiting: false });
190191
},
191192
),
192193
);
@@ -204,10 +205,6 @@ export function createEmbeddedRunLaneController<TParams extends LaneParams>(opti
204205
};
205206
const enqueueSession = <T>(task: () => Promise<T>, opts?: CommandQueueEnqueueOptions) => {
206207
const sessionOpts: CommandQueueEnqueueOptions = { ...opts, priority: sessionQueuePriority };
207-
const taskWithLaneAdmission = () => {
208-
options.getParams().onLaneWait?.({ waitMs: 0, queuedAhead: 0, waiting: false });
209-
return task();
210-
};
211208
const params = options.getParams();
212209
// Session admission, deferred maintenance, and global admission share one queue owner.
213210
releaseQueuedRunContext = retainQueuedAgentRunContext(
@@ -225,14 +222,10 @@ export function createEmbeddedRunLaneController<TParams extends LaneParams>(opti
225222
let queuedRun: Promise<T>;
226223
try {
227224
if (params.enqueue) {
228-
queuedRun = params.enqueue(taskWithLaneAdmission, withRunLaneWait(sessionOpts));
225+
queuedRun = params.enqueue(task, withRunLaneWait(sessionOpts));
229226
} else {
230227
noteLaneWaitIfBusy(options.sessionLane);
231-
queuedRun = enqueueCommandInLane(
232-
options.sessionLane,
233-
taskWithLaneAdmission,
234-
withRunLaneWait(sessionOpts),
235-
);
228+
queuedRun = enqueueCommandInLane(options.sessionLane, task, withRunLaneWait(sessionOpts));
236229
}
237230
} catch (error) {
238231
releaseQueuedContext("abandoned");

‎src/gateway/server.hooks-admission.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,47 @@ describe("gateway hook admission", () => {
233233
});
234234
});
235235

236+
test("admits an HTTP hook after placement while runtime preparation remains blocked", async () => {
237+
testState.hooksConfig = { enabled: true, token: HOOK_TOKEN };
238+
await withGatewayServer(async ({ port }) => {
239+
const placementAdmissionPublished = createDeferred();
240+
const runtimePreparation = createDeferred();
241+
let runnerEntered = false;
242+
let response: Response | undefined;
243+
cronIsolatedRun.mockClear();
244+
cronIsolatedRun.mockImplementationOnce(async (params: unknown) => {
245+
const callbacks = params as {
246+
onExecutionStarted?: () => void;
247+
onLaneWait?: (info: { waiting: boolean }) => void;
248+
};
249+
callbacks.onLaneWait?.({ waiting: false });
250+
placementAdmissionPublished.resolve();
251+
await runtimePreparation.promise;
252+
runnerEntered = true;
253+
callbacks.onExecutionStarted?.();
254+
return { status: "ok", summary: "done" };
255+
});
256+
const responsePromise = postHook(
257+
port,
258+
"/hooks/agent",
259+
{ message: "Dispatch" },
260+
"placement-admission-before-runtime",
261+
).then((result) => {
262+
response = result;
263+
return result;
264+
});
265+
266+
try {
267+
await placementAdmissionPublished.promise;
268+
await expect.poll(() => response?.status, { timeout: 1_000, interval: 10 }).toBe(200);
269+
expect(runnerEntered).toBe(false);
270+
} finally {
271+
runtimePreparation.resolve();
272+
await responsePromise;
273+
}
274+
});
275+
});
276+
236277
test("shares one pending persistent dispatch without losing its session target", async () => {
237278
testState.hooksConfig = {
238279
enabled: true,

‎src/gateway/server/hooks.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,10 @@ export function createGatewayHooksRequestHandler(params: {
422422
});
423423
const admissionTimeoutError = new Error(HOOK_AGENT_START_ADMISSION_TIMEOUT_ERROR);
424424
const startupAbortController = new AbortController();
425+
const settleSuccessfulAdmission = () => {
426+
startupAbortController.signal.throwIfAborted();
427+
settleAdmission({ ok: true, runId });
428+
};
425429
admissionTimer = setTimeout(() => {
426430
admissionTimedOut = true;
427431
startupAbortController.abort(admissionTimeoutError);
@@ -493,12 +497,12 @@ export function createGatewayHooksRequestHandler(params: {
493497
},
494498
},
495499
abortSignal: startupAbortController.signal,
496-
onExecutionStarted: () => {
497-
// Existing runner-entry callbacks are the final owner-boundary fence:
498-
// a deadline that wins this race prevents the runner call itself.
499-
startupAbortController.signal.throwIfAborted();
500-
settleAdmission({ ok: true, runId });
500+
onLaneWait: (info) => {
501+
if (info?.waiting === false) {
502+
settleSuccessfulAdmission();
503+
}
501504
},
505+
onExecutionStarted: settleSuccessfulAdmission,
502506
});
503507
const result = await runWithScheduledGatewayContext({
504508
...(scheduledGatewayContextResolver

0 commit comments

Comments
 (0)