Skip to content

Commit c49e5c4

Browse files
authored
fix(agents): keep exec finalization suspension-safe (#104419)
1 parent cce2d39 commit c49e5c4

5 files changed

Lines changed: 254 additions & 28 deletions

‎src/agents/bash-process-registry.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ export interface ProcessSession {
8282
exitReason?: TerminationReason;
8383
noOutputTimedOut?: boolean;
8484
exited: boolean;
85+
/** Process exit observed; backend cleanup still owns the terminal transition. */
86+
finalizing?: boolean;
8587
truncated: boolean;
8688
backgrounded: boolean;
8789
/** PTY cursor key mode: unknown until a PTY reports smkx/rmkx. */

‎src/agents/bash-tools.exec-runtime.test.ts‎

Lines changed: 161 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
* Covers target resolution, cursor mode tracking, exit outcome classification,
44
* system events, and process lifecycle behavior.
55
*/
6-
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
6+
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
7+
import type { RunExit } from "../process/supervisor/types.js";
78
import { MAX_SAFE_TIMEOUT_DELAY_MS } from "../utils/timer-delay.js";
9+
import type { BashSandboxConfig } from "./bash-tools.shared.js";
810

911
const requestHeartbeatMock = vi.hoisted(() => vi.fn());
1012
const enqueueSystemEventMock = vi.hoisted(() => vi.fn());
@@ -27,15 +29,21 @@ vi.mock("../process/supervisor/index.js", () => ({
2729
}));
2830

2931
let markBackgrounded: typeof import("./bash-process-registry.js").markBackgrounded;
32+
let getActiveBackgroundExecSessionCount: typeof import("./bash-process-registry.js").getActiveBackgroundExecSessionCount;
33+
let resetProcessRegistryForTests: typeof import("./bash-process-registry.js").resetProcessRegistryForTests;
3034
let buildExecExitOutcome: typeof import("./bash-tools.exec-runtime.js").buildExecExitOutcome;
3135
let detectCursorKeyMode: typeof import("./bash-tools.exec-runtime.js").detectCursorKeyMode;
3236
let formatExecFailureReason: typeof import("./bash-tools.exec-runtime.js").formatExecFailureReason;
3337
let renderExecUpdateText: typeof import("./bash-tools.exec-runtime.js").renderExecUpdateText;
3438
let resolveExecTarget: typeof import("./bash-tools.exec-runtime.js").resolveExecTarget;
3539
let runExecProcess: typeof import("./bash-tools.exec-runtime.js").runExecProcess;
40+
let prepareGatewaySuspend: typeof import("../infra/gateway-suspend-coordinator.js").prepareGatewaySuspend;
41+
let resetGatewaySuspendCoordinatorForTest: typeof import("../infra/gateway-suspend-coordinator.js").resetGatewaySuspendCoordinatorForTest;
42+
let resumeGatewaySuspend: typeof import("../infra/gateway-suspend-coordinator.js").resumeGatewaySuspend;
3643

3744
beforeAll(async () => {
38-
({ markBackgrounded } = await import("./bash-process-registry.js"));
45+
({ getActiveBackgroundExecSessionCount, markBackgrounded, resetProcessRegistryForTests } =
46+
await import("./bash-process-registry.js"));
3947
({
4048
buildExecExitOutcome,
4149
detectCursorKeyMode,
@@ -44,14 +52,41 @@ beforeAll(async () => {
4452
resolveExecTarget,
4553
runExecProcess,
4654
} = await import("./bash-tools.exec-runtime.js"));
55+
({ prepareGatewaySuspend, resetGatewaySuspendCoordinatorForTest, resumeGatewaySuspend } =
56+
await import("../infra/gateway-suspend-coordinator.js"));
4757
});
4858

4959
beforeEach(() => {
60+
resetGatewaySuspendCoordinatorForTest();
61+
resetProcessRegistryForTests();
5062
requestHeartbeatMock.mockClear();
5163
enqueueSystemEventMock.mockClear();
5264
supervisorMock.spawn.mockReset();
5365
});
5466

67+
afterEach(() => {
68+
resetGatewaySuspendCoordinatorForTest();
69+
resetProcessRegistryForTests();
70+
});
71+
72+
function createDeferred<T>() {
73+
let resolve!: (value: T | PromiseLike<T>) => void;
74+
let reject!: (reason?: unknown) => void;
75+
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
76+
resolve = resolvePromise;
77+
reject = rejectPromise;
78+
});
79+
return { promise, reject, resolve };
80+
}
81+
82+
function prepareSuspension(requestId: string) {
83+
return prepareGatewaySuspend({
84+
requestId,
85+
pauseScheduling: vi.fn(),
86+
resumeScheduling: vi.fn(),
87+
});
88+
}
89+
5590
function expectExecTarget(
5691
actual: ReturnType<typeof resolveExecTarget>,
5792
expected: {
@@ -503,6 +538,130 @@ describe("exec notifyOnExit suppression", () => {
503538
});
504539
});
505540

541+
describe("sandbox exec finalization suspension", () => {
542+
it.each([
543+
{
544+
scenario: "successful cleanup",
545+
finalizeRejects: false,
546+
processTimesOut: false,
547+
expectedStatus: "completed" as const,
548+
expectedFailureKind: undefined,
549+
},
550+
{
551+
scenario: "failed cleanup",
552+
finalizeRejects: true,
553+
processTimesOut: false,
554+
expectedStatus: "failed" as const,
555+
expectedFailureKind: "runtime-error" as const,
556+
},
557+
{
558+
scenario: "failed cleanup after a process timeout",
559+
finalizeRejects: true,
560+
processTimesOut: true,
561+
expectedStatus: "failed" as const,
562+
expectedFailureKind: "overall-timeout" as const,
563+
},
564+
])(
565+
"keeps suspension busy until asynchronous finalization settles after $scenario",
566+
async ({ finalizeRejects, processTimesOut, expectedFailureKind, expectedStatus }) => {
567+
const exit = createDeferred<RunExit>();
568+
const finalization = createDeferred<void>();
569+
const finalizeExec = vi.fn<NonNullable<BashSandboxConfig["finalizeExec"]>>(
570+
async () => await finalization.promise,
571+
);
572+
supervisorMock.spawn.mockImplementationOnce(
573+
async (input: { onStdout?: (chunk: string) => void }) => {
574+
input.onStdout?.("sandbox output\n");
575+
return {
576+
runId: "sandbox-run",
577+
startedAtMs: Date.now(),
578+
pid: 123,
579+
wait: async () => await exit.promise,
580+
cancel: vi.fn(),
581+
};
582+
},
583+
);
584+
585+
const run = await runExecProcess({
586+
command: "sandbox-command",
587+
workdir: "/tmp",
588+
env: {},
589+
sandbox: {
590+
containerName: "sandbox",
591+
workspaceDir: "/workspace",
592+
containerWorkdir: "/workspace",
593+
buildExecSpec: async () => ({
594+
argv: ["sandbox-command"],
595+
env: {},
596+
stdinMode: "pipe-closed",
597+
finalizeToken: "sandbox-token",
598+
}),
599+
finalizeExec,
600+
},
601+
usePty: false,
602+
warnings: [],
603+
maxOutput: 1000,
604+
pendingMaxOutput: 1000,
605+
notifyOnExit: true,
606+
sessionKey: "agent:main:main",
607+
timeoutSec: null,
608+
});
609+
markBackgrounded(run.session);
610+
expect(getActiveBackgroundExecSessionCount()).toBe(1);
611+
612+
exit.resolve({
613+
reason: processTimesOut ? "overall-timeout" : "exit",
614+
exitCode: processTimesOut ? null : 0,
615+
exitSignal: processTimesOut ? "SIGKILL" : null,
616+
durationMs: 1,
617+
stdout: "",
618+
stderr: "",
619+
timedOut: processTimesOut,
620+
noOutputTimedOut: false,
621+
});
622+
await vi.waitFor(() => expect(finalizeExec).toHaveBeenCalledOnce());
623+
expect(run.session.finalizing).toBe(true);
624+
625+
const busy = prepareSuspension(`before-finalize-${expectedFailureKind ?? "success"}`);
626+
expect(busy.status).toBe("busy");
627+
if (busy.status === "busy") {
628+
expect(busy.blockers).toContainEqual(
629+
expect.objectContaining({ kind: "background-exec", count: 1 }),
630+
);
631+
}
632+
expect(getActiveBackgroundExecSessionCount()).toBe(1);
633+
634+
if (finalizeRejects) {
635+
finalization.reject(new Error("sandbox finalize failed"));
636+
} else {
637+
finalization.resolve();
638+
}
639+
const outcome = await run.promise;
640+
641+
expect(outcome.status).toBe(expectedStatus);
642+
if (outcome.status === "failed") {
643+
expect(outcome.failureKind).toBe(expectedFailureKind);
644+
expect(outcome.reason).toContain(
645+
expectedFailureKind === "runtime-error" ? "sandbox finalize failed" : "timed out",
646+
);
647+
}
648+
expect(finalizeExec).toHaveBeenCalledOnce();
649+
expect(getActiveBackgroundExecSessionCount()).toBe(0);
650+
expect(run.session.finalizing).toBe(false);
651+
expect(enqueueSystemEventMock).toHaveBeenCalledTimes(1);
652+
expect(requireSystemEventCall()[0]).toContain(
653+
expectedStatus === "failed" ? "Exec failed" : "Exec completed",
654+
);
655+
656+
const ready = prepareSuspension(`after-finalize-${expectedFailureKind ?? "success"}`);
657+
expect(ready.status).toBe("ready");
658+
if (ready.status === "ready") {
659+
expect(resumeGatewaySuspend(ready.suspensionId)).toMatchObject({ ok: true });
660+
}
661+
},
662+
);
663+
});
664+
506665
describe("formatExecFailureReason", () => {
507666
it("formats timeout guidance with the configured timeout", () => {
508667
expect(

‎src/agents/bash-tools.exec-runtime.ts‎

Lines changed: 46 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,45 @@ export async function runExecProcess(opts: {
734734
token: sandboxFinalizeToken,
735735
});
736736
};
737+
const finalizeAndSettleSession = async (
738+
outcome: ExecProcessOutcome,
739+
): Promise<ExecProcessOutcome> => {
740+
let finalOutcome = outcome;
741+
session.finalizing = true;
742+
try {
743+
await finalizeSandboxExec({
744+
status: outcome.status,
745+
exitCode: outcome.exitCode,
746+
timedOut: outcome.timedOut,
747+
});
748+
} catch (error) {
749+
if (outcome.status === "completed") {
750+
finalOutcome = buildExecRuntimeErrorOutcome({
751+
error,
752+
aggregated: session.aggregated.trim(),
753+
durationMs: Date.now() - startedAt,
754+
});
755+
} else {
756+
logWarn(`exec: sandbox finalize after process failure failed (${String(error)}).`);
757+
}
758+
} finally {
759+
// Finalization can release remote process/session resources. Keep the
760+
// background-work blocker until that owner transition has settled.
761+
session.finalizing = false;
762+
if (!session.exited) {
763+
markExited(
764+
session,
765+
finalOutcome.exitCode,
766+
finalOutcome.exitSignal,
767+
finalOutcome.status,
768+
finalOutcome.exitReason,
769+
finalOutcome.noOutputTimedOut,
770+
);
771+
maybeNotifyOnExit(session, finalOutcome.status);
772+
}
773+
}
774+
return finalOutcome;
775+
};
737776

738777
const spawnSpec:
739778
| {
@@ -943,49 +982,32 @@ export async function runExecProcess(opts: {
943982
timeoutSec: opts.timeoutSec,
944983
});
945984

946-
markExited(
947-
session,
948-
exit.exitCode,
949-
exit.exitSignal,
950-
outcome.status,
951-
exit.reason,
952-
exit.noOutputTimedOut,
953-
);
954-
maybeNotifyOnExit(session, outcome.status);
955-
if (!session.child && session.stdin) {
956-
session.stdin.destroyed = true;
957-
}
958-
await finalizeSandboxExec({
959-
status: outcome.status,
960-
exitCode: exit.exitCode ?? null,
961-
timedOut: exit.timedOut,
962-
});
985+
const finalOutcome = await finalizeAndSettleSession(outcome);
963986
emitExecProcessCompleted({
964987
command: opts.command,
965988
mode: usingPty ? "pty" : "child",
966-
outcome,
989+
outcome: finalOutcome,
967990
sessionKey: opts.sessionKey,
968991
target: diagnosticTarget,
969992
});
970-
return outcome;
993+
return finalOutcome;
971994
})
972-
.catch((err: unknown): ExecProcessOutcome => {
995+
.catch(async (err: unknown): Promise<ExecProcessOutcome> => {
973996
updatesDisabled = true;
974-
markExited(session, null, null, "failed");
975-
maybeNotifyOnExit(session, "failed");
976997
const outcome = buildExecRuntimeErrorOutcome({
977998
error: err,
978999
aggregated: session.aggregated.trim(),
9791000
durationMs: Date.now() - startedAt,
9801001
});
1002+
const finalOutcome = await finalizeAndSettleSession(outcome);
9811003
emitExecProcessCompleted({
9821004
command: opts.command,
9831005
mode: usingPty ? "pty" : "child",
984-
outcome,
1006+
outcome: finalOutcome,
9851007
sessionKey: opts.sessionKey,
9861008
target: diagnosticTarget,
9871009
});
988-
return outcome;
1010+
return finalOutcome;
9891011
});
9901012

9911013
return {

‎src/agents/bash-tools.process.supervisor.test.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,10 @@ vi.mock("../process/kill-tree.js", () => ({
2626
}));
2727

2828
let addSession: typeof import("./bash-process-registry.js").addSession;
29+
let getActiveBackgroundExecSessionCount: typeof import("./bash-process-registry.js").getActiveBackgroundExecSessionCount;
2930
let getFinishedSession: typeof import("./bash-process-registry.js").getFinishedSession;
3031
let getSession: typeof import("./bash-process-registry.js").getSession;
32+
let markBackgrounded: typeof import("./bash-process-registry.js").markBackgrounded;
3133
let resetProcessRegistryForTests: typeof import("./bash-process-registry.js").resetProcessRegistryForTests;
3234
let createProcessSessionFixture: typeof import("./bash-process-registry.test-helpers.js").createProcessSessionFixture;
3335
let createProcessTool: typeof import("./bash-tools.process.js").createProcessTool;
@@ -76,8 +78,14 @@ function expectTextContent(value: unknown, text: string) {
7678

7779
describe("process tool supervisor cancellation", () => {
7880
beforeAll(async () => {
79-
({ addSession, getFinishedSession, getSession, resetProcessRegistryForTests } =
80-
await import("./bash-process-registry.js"));
81+
({
82+
addSession,
83+
getActiveBackgroundExecSessionCount,
84+
getFinishedSession,
85+
getSession,
86+
markBackgrounded,
87+
resetProcessRegistryForTests,
88+
} = await import("./bash-process-registry.js"));
8189
({ createProcessSessionFixture } = await import("./bash-process-registry.test-helpers.js"));
8290
({ createProcessTool } = await import("./bash-tools.process.js"));
8391
});
@@ -147,6 +155,29 @@ describe("process tool supervisor cancellation", () => {
147155
expectTextContent(result.content[0], "Killed session sess-fallback.");
148156
});
149157

158+
it.each(["kill", "remove"] as const)(
159+
"refuses %s while sandbox finalization owns the terminal transition",
160+
async (action) => {
161+
supervisorMock.getRecord.mockReturnValue({ runId: "sess-finalizing", state: "exited" });
162+
const session = createBackgroundSession("sess-finalizing", 4242);
163+
session.finalizing = true;
164+
addSession(session);
165+
markBackgrounded(session);
166+
const processTool = createProcessTool();
167+
168+
const result = await processTool.execute("toolcall", {
169+
action,
170+
sessionId: "sess-finalizing",
171+
});
172+
173+
expect(supervisorMock.cancel).not.toHaveBeenCalled();
174+
expect(killProcessTreeMock).not.toHaveBeenCalled();
175+
expectSessionState("sess-finalizing", { exited: false });
176+
expect(getActiveBackgroundExecSessionCount()).toBe(1);
177+
expectTextContent(result.content[0], "Session sess-finalizing is finalizing.");
178+
},
179+
);
180+
150181
it("fails remove when no supervisor record and no pid is available", async () => {
151182
supervisorMock.getRecord.mockReturnValue(undefined);
152183
addSession(createBackgroundSession("sess-no-pid"));

0 commit comments

Comments
 (0)