Skip to content

Commit 3f4cefc

Browse files
authored
fix(code-mode): release canceled timers and parked execution slots (#131186)
1 parent 0e071ab commit 3f4cefc

13 files changed

Lines changed: 463 additions & 125 deletions

‎docs/tools/code-mode.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,10 @@ QuickJS-WASI snapshot/restore is the resume mechanism:
562562
Snapshots are runtime state, not user artifacts: they live only in an
563563
in-process map (no database or disk write), are size-limited, expire, and are
564564
scoped to the run and session that created them.
565+
Canceling the owning run or tool call, or closing its tool catalog at attempt
566+
teardown, immediately releases parked snapshots and cancels their pending host
567+
work, even if no `wait` call follows. Catalog description refreshes and client
568+
tool additions do not close the owner.
565569

566570
`wait` fails (as a `failed` result) when:
567571

@@ -590,6 +594,8 @@ declare function yield_control(reason?: string): Promise<void>;
590594
```
591595

592596
Guest timers are bridged through the host, so they survive QuickJS snapshot/resume and remain bounded by the Code Mode execution and snapshot limits.
597+
`clearTimeout` also cancels a timer created before an earlier suspension; this
598+
applies to interactive Code Mode and headless automation scripts.
593599

594600
Every effective non-MCP tool is also installed as an async global function.
595601
The model-visible `exec` description includes a bounded, deterministic subset

‎src/agents/code-mode-execution.ts‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
activeRuns,
3636
cancelPendingBridgeStates,
3737
cancelPendingBridgeStatesById,
38+
codeModeAbortedResult,
3839
codeModeWaitingReason,
3940
createCodeModeBridgeDispatchState,
4041
createPendingBridgeStates,
@@ -295,16 +296,7 @@ async function settleCodeModeResult(params: {
295296
// rounds; maxPendingToolCalls stays a per-batch concurrency cap enforced in
296297
// the worker.
297298
const settleDeadline = () => params.deadlineMs + params.approvalWait.pausedMs;
298-
const abortedResult = () => ({
299-
status: "failed" as const,
300-
error: "code mode execution aborted",
301-
code: "aborted" as const,
302-
failurePhase: params.bridgeDispatch.started ? ("bridge" as const) : ("host" as const),
303-
bridgeDispatchStarted: params.bridgeDispatch.started,
304-
output: output.slice(deliveredOutputCount),
305-
replaySafe: params.replaySafe,
306-
telemetry: telemetry(params.runtime),
307-
});
299+
const abortedResult = () => codeModeAbortedResult({ ...params, output, deliveredOutputCount });
308300
// Bridge tool calls (search/describe/call/namespace) run through the same
309301
// policy-checked executor whether the model awaits them one at a time or in a
310302
// batch, so resolve them inline within the exec deadline and resume the VM
@@ -408,6 +400,7 @@ async function settleCodeModeResult(params: {
408400
output,
409401
deliveredOutputCount,
410402
bridgeDispatch: params.bridgeDispatch,
403+
signal: params.signal,
411404
});
412405
}
413406
// Deliver the settled frontier only. Unresolved sibling promises remain
@@ -524,6 +517,7 @@ async function settleCodeModeResult(params: {
524517
output,
525518
deliveredOutputCount,
526519
bridgeDispatch: params.bridgeDispatch,
520+
signal: params.signal,
527521
});
528522
} catch (error) {
529523
cancelPendingBridgeStates(pending);
@@ -612,22 +606,27 @@ export async function runWait(params: {
612606
// pending calls, the resume worker, and the inline settle phase.
613607
const deadlineMs = Date.now() + state.config.timeoutMs;
614608
const approvalWait = observeAgentRunApprovalWait(state.ctx);
609+
// Snapshot closure wakes an observing wait even if its guest budget just expired.
610+
// Transfer releases this signal; worker execution keeps its normal per-call signal.
611+
const parkedSignal = params.signal
612+
? AbortSignal.any([params.signal, state.ownerSignal])
613+
: state.ownerSignal;
615614
let releaseActiveRunSlot: (() => void) | undefined;
616615
try {
617616
const ready = await waitForPending(
618617
state.pending,
619618
state.settlementMode,
620619
Math.max(1, deadlineMs - Date.now()),
621620
approvalWait,
622-
params.signal,
621+
parkedSignal,
623622
);
624623
const resumeBudgetMs = ready
625624
? usableResumeBudgetMs(deadlineMs + approvalWait.pausedMs, state.config)
626625
: undefined;
627626
if (!ready || resumeBudgetMs === undefined) {
628627
// An aborted wait drops the suspended run: nothing will resume it, and
629628
// parking it would pin a process-global active-run slot until TTL expiry.
630-
if (params.signal?.aborted) {
629+
if (parkedSignal.aborted) {
631630
disposeCodeModeRun(state.runId);
632631
return {
633632
status: "failed" as const,
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import { afterEach, describe, expect, it } from "vitest";
2+
import { runCodeModeScriptHeadless } from "./code-mode.js";
3+
import {
4+
createHeadlessCodeModeHarness,
5+
resetCodeModeTestState,
6+
testing,
7+
} from "./code-mode.test-support.js";
8+
9+
describe("headless Code Mode cancellation", () => {
10+
afterEach(() => {
11+
try {
12+
expect(testing.activeRuns.size).toBe(0);
13+
} finally {
14+
resetCodeModeTestState();
15+
}
16+
});
17+
18+
it("completes after canceling a guest timer across two resumes", async () => {
19+
const result = await runCodeModeScriptHeadless({
20+
ctx: createHeadlessCodeModeHarness(),
21+
code: `
22+
const timer = setTimeout(() => {}, 60_000);
23+
await new Promise((resolve) => setTimeout(resolve, 1));
24+
clearTimeout(timer);
25+
await new Promise((resolve) => setTimeout(resolve, 1));
26+
return "done";
27+
`,
28+
wallClockMs: 5_000,
29+
});
30+
31+
expect(result).toEqual({
32+
status: "completed",
33+
value: "done",
34+
output: [],
35+
toolCallCount: 0,
36+
});
37+
});
38+
39+
it("terminates an in-flight worker leg when aborted", async () => {
40+
const ctx = createHeadlessCodeModeHarness();
41+
const config = testing.resolveCodeModeHeadlessConfig(ctx);
42+
const controller = new AbortController();
43+
const resultPromise = testing.runCodeModeWorker(
44+
{
45+
kind: "exec",
46+
source: "while (true) {}",
47+
config,
48+
catalog: [],
49+
apiFiles: [],
50+
namespaces: [],
51+
},
52+
5000,
53+
undefined,
54+
controller.signal,
55+
);
56+
setTimeout(() => controller.abort(), 100);
57+
58+
await expect(resultPromise).resolves.toMatchObject({
59+
status: "failed",
60+
code: "aborted",
61+
error: "code mode execution aborted",
62+
});
63+
});
64+
65+
it("classifies caller aborts before the worker leg as aborted", async () => {
66+
const controller = new AbortController();
67+
controller.abort();
68+
69+
const result = await runCodeModeScriptHeadless({
70+
ctx: createHeadlessCodeModeHarness(),
71+
code: "return true;",
72+
signal: controller.signal,
73+
});
74+
75+
expect(result).toMatchObject({
76+
status: "failed",
77+
code: "aborted",
78+
error: "code mode execution aborted",
79+
});
80+
});
81+
});

0 commit comments

Comments
 (0)