Skip to content

Commit c28cf4f

Browse files
authored
fix(codex): force bounded settlement when a terminal turn notification stalls (#132413)
* fix(codex): force bounded settlement when a terminal turn notification stalls After a gateway hard-kill mid Codex-harness run and restart, the resumed turn could stay active forever: receiving a terminal turn notification permanently disarmed the completion and terminal idle watches and disabled route-close aborts, while completeTurn() only runs when the serialized notification tail reaches the terminal handler. Any earlier never-settling handler left the run active with every watchdog off - the session kept reporting the dead run active and new chat sends queued behind the phantom indefinitely ("codex app-server notification ignored for inactive turn"). The terminal idle watch now stays armed after terminal receipt and forces settlement through the existing abort path within a 2-minute window (deferring to pending server requests and finalization hooks, bounded by the 30-minute absolute silence budget). Route drains resolve on route release, and finalization's drain join also settles on run abort so Stop cannot hang behind a blocked handler either. Adds failing-first regression coverage for the watch controller, router drain, and run-attempt finalization, plus a real-gateway boundary e2e: SIGKILL mid-run, restart, startup orphan recovery, then a new inbound send must produce a reply. * fix(codex): join queued projection work within a bounded abort grace Racing the finalize drain against the run abort signal skipped projection work already queued on the notification tail whenever a timeout or Stop completed the run, losing e.g. generated image media that the timeout outcome is supposed to preserve. Give the drain a bounded grace after abort instead: queued projections still join, while a blocked handler tail can no longer hold finalization forever. Also scope the pinned old-contract turn-watch test to the new settlement window and add a deterministic queued-projection timeout regression. * test(codex): pin short-window settlement after a queued finalization hook completes Review flagged that hook settlement might leave the terminal watch on the 30-minute budget. Production already re-arms via the next turn-scoped handler's entry touchActivity (attempt-notification-state.ts), so the ordered case settles within the settlement window; this regression pins that contract with the exact ordering: terminal received during a pending hook, hook completes through the production decrement, and the following blocked handler still settles on the short window.
1 parent 2b1eee0 commit c28cf4f

9 files changed

Lines changed: 556 additions & 53 deletions

‎extensions/codex/src/app-server/attempt-timeouts.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ const CODEX_POST_TOOL_RAW_ASSISTANT_COMPLETION_IDLE_TIMEOUT_MS = 5 * 60_000;
1919
export const CODEX_POST_REASONING_REPLY_IDLE_TIMEOUT_MS = 5 * 60_000;
2020
/** Long terminal idle watch for app-server turns that never send completion. */
2121
const CODEX_TURN_TERMINAL_IDLE_TIMEOUT_MS = 30 * 60_000;
22+
// Terminal receipt must still reach settlement; force a bounded abort if the
23+
// handler tail stalls, or the session can remain active forever.
24+
export const TURN_TERMINAL_SETTLEMENT_IDLE_TIMEOUT_MS = 2 * 60_000;
25+
// Aborted/timed-out completions still join queued projection work; this grace
26+
// bounds a blocked handler tail so finalization cannot hang forever.
27+
export const TURN_FINALIZE_DRAIN_ABORT_GRACE_MS = 5_000;
2228

2329
type CodexAppServerStartupErrorReason = "aborted" | "timed_out";
2430

‎extensions/codex/src/app-server/attempt-turn-watches.test.ts‎

Lines changed: 119 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -177,42 +177,147 @@ describe("Codex app-server attempt turn watches", () => {
177177
expect(harness.abortController.signal.aborted).toBe(false);
178178
});
179179

180-
it("keeps terminal idle gated while an app-server request is in flight", () => {
181-
const harness = createController();
182-
harness.activeRequests = 1;
180+
it.each([
181+
{ terminalTimeoutMs: 30 * 60_000, settlementTimeoutMs: 2 * 60_000 },
182+
{ terminalTimeoutMs: 10, settlementTimeoutMs: 10 },
183+
])(
184+
"aborts unsettled terminal delivery within $settlementTimeoutMs ms (terminal budget $terminalTimeoutMs)",
185+
({ terminalTimeoutMs, settlementTimeoutMs }) => {
186+
const harness = createController({ turnTerminalIdleTimeoutMs: terminalTimeoutMs });
187+
harness.controller.armTerminalIdleWatch();
188+
harness.controller.touchActivity("turn:start", { arm: true });
189+
vi.advanceTimersByTime(5);
190+
191+
harness.terminalQueued = true;
192+
harness.controller.noteNotificationReceived("turn/completed");
193+
vi.advanceTimersByTime(settlementTimeoutMs - 1);
194+
expect(harness.timeouts).toEqual([]);
195+
196+
vi.advanceTimersByTime(1);
197+
expect(harness.timeouts).toMatchObject([
198+
{
199+
kind: "terminal",
200+
idleMs: settlementTimeoutMs,
201+
timeoutMs: settlementTimeoutMs,
202+
details: { terminalTurnNotificationQueued: true },
203+
},
204+
]);
205+
expect(harness.abortController.signal.reason).toBe("turn_terminal_idle_timeout");
206+
},
207+
);
208+
209+
it.each(["activeRequests", "activeFinalizationHooks"] as const)(
210+
"defers queued terminal settlement while %s owns the quiet window",
211+
(counter) => {
212+
const harness = createController({ turnTerminalIdleTimeoutMs: 3 * 60_000 });
213+
harness.controller.armTerminalIdleWatch();
214+
harness[counter] = 1;
215+
harness.terminalQueued = true;
216+
harness.controller.noteNotificationReceived("turn/completed");
217+
vi.advanceTimersByTime(2 * 60_000 + 1);
218+
219+
expect(harness.timeouts).toEqual([]);
220+
expect(harness.abortController.signal.aborted).toBe(false);
221+
222+
harness[counter] = 0;
223+
harness.controller.touchActivity(`${counter}:settled`);
224+
vi.advanceTimersByTime(2 * 60_000 - 1);
225+
expect(harness.timeouts).toEqual([]);
226+
227+
vi.advanceTimersByTime(1);
228+
expect(harness.timeouts).toMatchObject([
229+
{
230+
kind: "terminal",
231+
idleMs: 2 * 60_000,
232+
timeoutMs: 2 * 60_000,
233+
details: { terminalTurnNotificationQueued: true },
234+
},
235+
]);
236+
expect(harness.abortController.signal.reason).toBe("turn_terminal_idle_timeout");
237+
},
238+
);
183239

240+
it("does not abort terminal delivery that completes within the settlement window", () => {
241+
const isCompleted = vi.fn(() => false);
242+
const harness = createController({ isCompleted });
184243
harness.controller.armTerminalIdleWatch();
185-
vi.advanceTimersByTime(10);
244+
harness.terminalQueued = true;
245+
harness.controller.noteNotificationReceived("turn/completed");
246+
vi.advanceTimersByTime(9);
247+
248+
isCompleted.mockReturnValue(true);
249+
vi.advanceTimersByTime(20);
186250

187251
expect(harness.timeouts).toEqual([]);
188252
expect(harness.abortController.signal.aborted).toBe(false);
189253
});
190254

191-
it("fires terminal idle after the in-flight request settles and silence resumes", () => {
192-
const harness = createController();
193-
harness.activeRequests = 1;
194-
255+
it("aborts at the absolute idle budget when a queued terminal hook never settles", () => {
256+
const harness = createController({ turnTerminalIdleTimeoutMs: 10 });
195257
harness.controller.armTerminalIdleWatch();
196-
vi.advanceTimersByTime(10);
197-
expect(harness.timeouts).toEqual([]);
198-
199-
harness.activeRequests = 0;
200-
harness.controller.touchActivity("request:item/tool/call:response");
258+
harness.activeFinalizationHooks = 1;
259+
harness.terminalQueued = true;
260+
harness.controller.noteNotificationReceived("turn/completed");
201261
vi.advanceTimersByTime(9);
202262
expect(harness.timeouts).toEqual([]);
203263

204264
vi.advanceTimersByTime(1);
265+
205266
expect(harness.timeouts).toMatchObject([
206267
{
207268
kind: "terminal",
208269
idleMs: 10,
209270
timeoutMs: 10,
210-
lastActivityReason: "request:item/tool/call:response",
271+
details: { terminalTurnNotificationQueued: true },
211272
},
212273
]);
213274
expect(harness.abortController.signal.reason).toBe("turn_terminal_idle_timeout");
214275
});
215276

277+
it("keeps terminal idle gated while an app-server request is in flight", () => {
278+
const harness = createController();
279+
harness.activeRequests = 1;
280+
281+
harness.controller.armTerminalIdleWatch();
282+
vi.advanceTimersByTime(10);
283+
284+
expect(harness.timeouts).toEqual([]);
285+
expect(harness.abortController.signal.aborted).toBe(false);
286+
});
287+
288+
it.each(["before", "after"])(
289+
"defers pre-terminal silence when a request starts %s watch arming until its response",
290+
(requestStarts) => {
291+
const timeoutMs = 30 * 60_000;
292+
const harness = createController({ turnTerminalIdleTimeoutMs: timeoutMs });
293+
harness.activeRequests = requestStarts === "before" ? 1 : 0;
294+
harness.controller.armTerminalIdleWatch();
295+
harness.activeRequests = 1;
296+
297+
vi.advanceTimersByTime(3 * timeoutMs);
298+
expect(harness.timeouts).toEqual([]);
299+
expect(harness.abortController.signal.aborted).toBe(false);
300+
301+
harness.activeRequests = 0;
302+
harness.controller.touchActivity("request:item/tool/call:response");
303+
vi.advanceTimersByTime(timeoutMs - 1);
304+
expect(harness.timeouts).toEqual([]);
305+
expect(harness.abortController.signal.aborted).toBe(false);
306+
307+
vi.advanceTimersByTime(1);
308+
expect(harness.timeouts).toMatchObject([
309+
{
310+
kind: "terminal",
311+
idleMs: timeoutMs,
312+
timeoutMs,
313+
lastActivityReason: "request:item/tool/call:response",
314+
details: { terminalTurnNotificationQueued: false },
315+
},
316+
]);
317+
expect(harness.abortController.signal.reason).toBe("turn_terminal_idle_timeout");
318+
},
319+
);
320+
216321
it("keeps completion idle gated while a request is in flight", () => {
217322
const harness = createController();
218323
harness.activeRequests = 1;

‎extensions/codex/src/app-server/attempt-turn-watches.ts‎

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*/
55
import { embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
66
import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
7+
import { TURN_TERMINAL_SETTLEMENT_IDLE_TIMEOUT_MS } from "./attempt-timeouts.js";
78

89
type Timer = ReturnType<typeof setTimeout>;
910
type WatchTimerKind = "completion" | "assistant" | "attempt" | "terminal";
@@ -159,13 +160,26 @@ export function createCodexAttemptTurnWatchController(params: {
159160
);
160161
}
161162

163+
const terminalWorkIsActive = () =>
164+
params.getActiveAppServerTurnRequests() > 0 ||
165+
(params.isTerminalTurnNotificationQueued() && params.getActiveFinalizationHookCount() > 0);
166+
// Physical-client backstop: requests own quiet windows via their own timeouts;
167+
// responses touch activity and rearm. After terminal receipt, even stuck counters
168+
// must respect the absolute silence budget, or a blocked tail leaves the session active.
169+
const terminalIdleTimeoutMs = () =>
170+
params.isTerminalTurnNotificationQueued() && !terminalWorkIsActive()
171+
? Math.min(TURN_TERMINAL_SETTLEMENT_IDLE_TIMEOUT_MS, turnTerminalIdleTimeoutMs)
172+
: turnTerminalIdleTimeoutMs;
173+
162174
function scheduleTerminalIdleWatch() {
163175
scheduleWatch(
164176
"terminal",
165177
fireTerminalIdleTimeout,
166178
completionLastActivityAt,
167-
turnTerminalIdleTimeoutMs,
168-
terminalIdleWatchArmed && params.getActiveAppServerTurnRequests() === 0,
179+
terminalIdleTimeoutMs(),
180+
terminalIdleWatchArmed &&
181+
(params.isTerminalTurnNotificationQueued() ||
182+
params.getActiveAppServerTurnRequests() === 0),
169183
);
170184
}
171185

@@ -342,32 +356,28 @@ export function createCodexAttemptTurnWatchController(params: {
342356
}
343357

344358
function fireTerminalIdleTimeout() {
345-
// Physical-client liveness backstop. A terminal timeout retires the shared
346-
// client, so it must only measure silence the client owns: while a
347-
// server->client request is pending (approval/elicitation/tool call) the
348-
// app-server legitimately says nothing until we respond. The response path
349-
// touches activity when the request settles, so a wedged client is still
350-
// caught within one terminal window after our response.
351-
if (
352-
params.isCompleted() ||
353-
params.isTerminalTurnNotificationQueued() ||
354-
params.signal.aborted ||
355-
!terminalIdleWatchArmed ||
356-
params.getActiveAppServerTurnRequests() > 0
357-
) {
359+
if (params.isCompleted() || params.signal.aborted || !terminalIdleWatchArmed) {
358360
return;
359361
}
362+
if (!params.isTerminalTurnNotificationQueued() && params.getActiveAppServerTurnRequests() > 0) {
363+
scheduleTerminalIdleWatch();
364+
return;
365+
}
366+
const timeoutMs = terminalIdleTimeoutMs();
360367
const idleMs = Math.max(0, Date.now() - completionLastActivityAt);
361-
if (idleMs < turnTerminalIdleTimeoutMs) {
368+
if (idleMs < timeoutMs) {
362369
scheduleTerminalIdleWatch();
363370
return;
364371
}
365372
reportTimeout({
366373
kind: "terminal" as const,
367374
idleMs,
368-
timeoutMs: turnTerminalIdleTimeoutMs,
375+
timeoutMs,
369376
lastActivityReason: completionLastActivityReason,
370-
details: completionLastActivityDetails,
377+
details: {
378+
...completionLastActivityDetails,
379+
terminalTurnNotificationQueued: params.isTerminalTurnNotificationQueued(),
380+
},
371381
});
372382
}
373383

@@ -454,6 +464,10 @@ export function createCodexAttemptTurnWatchController(params: {
454464
if (options?.attemptProgress) {
455465
recordAttemptProgress(completionLastActivityReason, options);
456466
}
467+
// Receipt precedes the handler tail; arm the shorter settlement watch now.
468+
if (params.isTerminalTurnNotificationQueued()) {
469+
scheduleTerminalIdleWatch();
470+
}
457471
},
458472
extendAttemptIdleWatch: (timeoutMs: number) => {
459473
attemptIdleTimeoutOverrideMs = resolveWatchTimeoutMs(timeoutMs);

‎extensions/codex/src/app-server/run-attempt-finalize.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
import { addAbortListener } from "node:events";
12
import {
23
buildEmbeddedForegroundPromptContext,
34
embeddedAgentLog,
45
formatErrorMessage,
56
runAgentHarnessLlmOutputHook,
67
} from "openclaw/plugin-sdk/agent-harness-runtime";
8+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
79
import { classifyCodexModelCallFailureKind } from "./attempt-diagnostics.js";
810
import {
911
buildCodexAppServerPromptTimeoutOutcome,
@@ -12,6 +14,7 @@ import {
1214
resolveCodexAppServerReplayBlockedReason,
1315
} from "./attempt-results.js";
1416
import { attemptTerminal, type EmbeddedRunAttemptResult } from "./attempt-terminal.js";
17+
import { TURN_FINALIZE_DRAIN_ABORT_GRACE_MS } from "./attempt-timeouts.js";
1518
import { buildCodexContinuityCalibration } from "./context-engine-projection.js";
1619
import { flattenCodexDynamicToolFunctions } from "./protocol.js";
1720
import { readCodexRateLimitsRevision, readRecentCodexRateLimits } from "./rate-limit-cache.js";
@@ -94,8 +97,24 @@ export async function finalizeCodexAttempt(
9497
} = activeTurn;
9598
await completion;
9699
await state.abortCleanup;
97-
// Include projection work already queued when timeout completion wins.
98-
await drainNotificationQueue();
100+
// Timeout and Stop still join queued projections within the abort grace;
101+
// normal completion awaits the full drain.
102+
const drain = drainNotificationQueue();
103+
const abortGraceElapsed = createDeferred<void>();
104+
let abortGraceTimer: ReturnType<typeof setTimeout> | undefined;
105+
const abortListener = addAbortListener(runAbortController.signal, () => {
106+
abortGraceTimer = setTimeout(
107+
() => abortGraceElapsed.resolve(),
108+
TURN_FINALIZE_DRAIN_ABORT_GRACE_MS,
109+
);
110+
abortGraceTimer.unref?.();
111+
});
112+
try {
113+
await Promise.race([drain, abortGraceElapsed.promise]);
114+
} finally {
115+
abortListener[Symbol.dispose]();
116+
clearTimeout(abortGraceTimer);
117+
}
99118
const hasQuiescentCompletedAssistant =
100119
activeProjector.hasCompletedTerminalAssistantText() &&
101120
state.activeAppServerTurnRequests === 0 &&

0 commit comments

Comments
 (0)