Skip to content

Commit 95161c2

Browse files
authored
fix(workers): protect in-flight workspace manifests from concurrent retention (#130449)
At high completion concurrency, 12/50 turns failed with 'Cloud worker finished, but its workspace result could not be reconciled' (#129979): between a worker's manifest upload and its verification, a sibling completion could trigger retention with a snapshot holding only the old base manifest — the terminal worker no longer protected the workspace, so cleanup deleted the just-uploaded manifest and verification died on ENOENT. The node workspace runtime now pins the latest transferred manifest per generation and includes it in every cleanup's reachable set (cleared with its generation), and gateway retention snapshots treat unsettled results — an active claim or a pending-result fence — as protection, which also preserves it across restarts when node-local pins are gone. Capture errors retain bounded redacted stderr so this failure class can never be faceless again. No deadlines, protocol, or completion-semantics changes; deterministic 1-turn and 50-turn reproductions fail pre-fix.
1 parent 25a16dd commit 95161c2

11 files changed

Lines changed: 487 additions & 87 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3429,7 +3429,7 @@ src/node-host/node-worker-supervisor.ts 1
34293429
src/node-host/node-worker-transfer-client.ts 3
34303430
src/node-host/node-worker-transfer-http.ts 2
34313431
src/node-host/node-worker-tree-control.ts 2
3432-
src/node-host/node-worker-workspace.ts 7
3432+
src/node-host/node-worker-workspace.ts 6
34333433
src/node-host/plugin-node-host.ts 1
34343434
src/node-host/pty-command.ts 11
34353435
src/node-host/runtime.ts 2

‎docs/gateway/cloud-workers.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,8 @@ unsynced-file and in-flight-work loss boundary as the Control UI confirmation.
368368

369369
Placement moves through a durable state machine (`local → requested → provisioning → syncing → starting → active`), so a Gateway restart mid-dispatch reconciles instead of leaking machines. A failed model turn keeps the active placement available for a retry. Workspace path conflicts keep the local version, apply the rest of the cloud result, and preserve the staged cloud ref for inspection; other reconciliation or lifecycle failures retain their durable recovery fence and diagnostic tail until recovery can safely retry or reclaim the environment.
370370

371+
If a turn reports `Cloud worker finished, but its workspace result could not be reconciled`, inspect the cause after the colon. A failed node manifest capture includes its bounded, redacted stderr, or its termination status when stderr is empty. Node cleanup preserves manifests needed between upload and verification, including when other workers finish simultaneously; increasing transfer timeouts does not repair a missing manifest.
372+
371373
## What survives a dead machine
372374

373375
The Gateway owns the canonical session transcript in both modes. Worker-turn commits each complete user, assistant, and tool-result message before the worker's session write settles; remote-exec uses the normal local harness transcript path because the Codex app-server stays on the Gateway. If the machine disappears mid-message, durable history ends at the last committed message. Partial text or tool progress already shown by the live stream may disappear; the failed turn remains visible, and the failed placement records a bounded terminal reason above the composer.

‎src/gateway/worker-environments/node-worker-tunnel.test-support.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
} from "../../../packages/gateway-protocol/src/client-info.js";
66
import { WORKER_PROTOCOL_FEATURES } from "../../../packages/gateway-protocol/src/schema/worker-admission.js";
77
import { NODE_WORKER_SUPERVISOR_PROTOCOL_FEATURE } from "../../infra/node-runner-inventory.js";
8+
import type { SpawnResult } from "../../process/exec.js";
89
import type { NodeWorkerSupervisorTransport } from "../node-registry-private.js";
910
import type { NodeWorkspaceTransferService } from "./node-workspace-transfer-service.js";
1011
import type { WorkerEnvironmentRecord } from "./store.js";
@@ -79,3 +80,16 @@ export function workspaceTransfer(): NodeWorkspaceTransferService {
7980
revoke: vi.fn(),
8081
} as unknown as NodeWorkspaceTransferService;
8182
}
83+
84+
export function workspaceCommandPayload(workspaceDir: string, result: Partial<SpawnResult>) {
85+
return JSON.stringify({
86+
workspaceDir,
87+
stdout: "",
88+
stderr: "",
89+
code: 0,
90+
signal: null,
91+
killed: false,
92+
termination: "exit",
93+
...result,
94+
});
95+
}

‎src/gateway/worker-environments/node-worker-tunnel.test.ts‎

Lines changed: 37 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
environment,
2222
startRequest,
2323
transport,
24+
workspaceCommandPayload,
2425
workspaceTransfer,
2526
} from "./node-worker-tunnel.test-support.js";
2627
import type { NodeWorkspaceTransferService } from "./node-workspace-transfer-service.js";
@@ -875,32 +876,46 @@ describe("node worker tunnel manager", () => {
875876
expect(manager.status("environment-1")).toBe("stopped");
876877
});
877878

878-
it("recaptures the node manifest and rejects divergence before reconciliation", async () => {
879+
it.each([
880+
{
881+
name: "divergence",
882+
result: { stdout: `sha256:${"f".repeat(64)}\n` },
883+
error: "changed during final reconciliation",
884+
},
885+
{
886+
name: "missing manifest",
887+
result: {
888+
code: 1,
889+
stderr: "ENOENT: no such file or directory, open '/worker/manifests/result.json'\n",
890+
},
891+
error: "Node workspace manifest capture failed: ENOENT: no such file or directory",
892+
},
893+
{
894+
name: "timeout without stderr",
895+
result: { code: null, signal: "SIGTERM", killed: true, termination: "timeout" },
896+
error: "Node workspace manifest capture failed: timeout (exit code null, signal SIGTERM)",
897+
},
898+
{
899+
name: "invalid reference",
900+
result: { stdout: "invalid\n" },
901+
error: "Node workspace manifest capture failed: invalid manifest reference",
902+
},
903+
] as const)("reports $name during final manifest verification", async ({ result, error }) => {
879904
const record = environment();
880905
const localPath = tempDirs.make("node-worker-verify-stable-");
881906
const remoteWorkspaceDir = path.join(localPath, "remote");
882907
await fs.mkdir(remoteWorkspaceDir);
883908
const raw = serializeWorkerWorkspaceManifest({ version: 1, baseCommit: null, entries: [] });
884909
const baseManifestRef = `sha256:${createHash("sha256").update(raw).digest("hex")}`;
885-
const divergentManifestRef = `sha256:${"f".repeat(64)}`;
886-
const spawnResult = (stdout: string) =>
887-
JSON.stringify({
888-
workspaceDir: remoteWorkspaceDir,
889-
stdout,
890-
stderr: "",
891-
code: 0,
892-
signal: null,
893-
killed: false,
894-
termination: "exit",
895-
});
896910
const nodeTransport = transport();
897911
nodeTransport.invoke = vi.fn(async ({ params }) => {
898912
const input = params as { transfer?: { direction?: string } };
899913
return {
900914
ok: true,
901-
payloadJSON: spawnResult(
902-
input.transfer ? `${baseManifestRef}\n` : `${divergentManifestRef}\n`,
903-
),
915+
payloadJSON: workspaceCommandPayload(remoteWorkspaceDir, {
916+
stdout: `${baseManifestRef}\n`,
917+
...(!input.transfer ? result : {}),
918+
}),
904919
};
905920
});
906921
const transfer = {
@@ -944,7 +959,7 @@ describe("node worker tunnel manager", () => {
944959
baseManifestRef,
945960
journal: { load: () => undefined, begin: vi.fn(), commit: vi.fn(), abort: vi.fn() },
946961
}),
947-
).rejects.toThrow("changed during final reconciliation");
962+
).rejects.toThrow(error);
948963
});
949964

950965
it("does not republish an accepted manifest already current on the node", async () => {
@@ -954,24 +969,19 @@ describe("node worker tunnel manager", () => {
954969
const manifest = { version: 1 as const, baseCommit: null, entries: [] };
955970
const raw = serializeWorkerWorkspaceManifest(manifest);
956971
const baseManifestRef = `sha256:${createHash("sha256").update(raw).digest("hex")}`;
957-
const spawnResult = (stdout: string) =>
958-
JSON.stringify({
959-
workspaceDir: remoteWorkspaceDir,
960-
stdout,
961-
stderr: "",
962-
code: 0,
963-
signal: null,
964-
killed: false,
965-
termination: "exit",
966-
});
967972
const transferDirections: string[] = [];
968973
const nodeTransport = transport();
969974
const invoke = vi.fn(async ({ params }) => {
970975
const input = params as { transfer?: { direction?: string } };
971976
if (input.transfer?.direction) {
972977
transferDirections.push(input.transfer.direction);
973978
}
974-
return { ok: true, payloadJSON: spawnResult(`${baseManifestRef}\n`) };
979+
return {
980+
ok: true,
981+
payloadJSON: workspaceCommandPayload(remoteWorkspaceDir, {
982+
stdout: `${baseManifestRef}\n`,
983+
}),
984+
};
975985
});
976986
nodeTransport.invoke = invoke;
977987
const publishSnapshot = vi.fn(() => "accepted-download-token");

‎src/gateway/worker-environments/node-worker-tunnel.ts‎

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ import {
4646
type WorkerWorkspaceApplyResult,
4747
} from "./workspace-reconcile.js";
4848
import { workerWorkspaceResultStaging } from "./workspace-result-staging.js";
49-
import { REMOTE_WORKSPACE_MANIFEST_JS } from "./workspace-sync-scripts.js";
5049

5150
const DEFAULT_COMMAND_TIMEOUT_MS = 60_000;
5251
const COMMAND_RESULT_GRACE_MS = 5_000;
@@ -321,25 +320,6 @@ export function createNodeWorkerTunnelManager(options: NodeWorkerTunnelManagerOp
321320
sharedHost: true,
322321
runWorkspaceCommand: async (command) => await exec(command),
323322
});
324-
const captureManifest = async (dir: string, base: string | null, reference: string) => {
325-
const captured = await exec({
326-
argv: [
327-
"node",
328-
"-e",
329-
REMOTE_WORKSPACE_MANIFEST_JS,
330-
dir,
331-
...(base ? [base, "eligible"] : ["", "all"]),
332-
reference.slice("sha256:".length),
333-
],
334-
transportRetry: "idempotent",
335-
});
336-
const manifestRef = captured.stdout.trim();
337-
const validRef = /^sha256:[a-f0-9]{64}$/u.test(manifestRef);
338-
if (captured.termination !== "exit" || captured.code !== 0 || !validRef) {
339-
throw new Error("Node workspace manifest capture failed");
340-
}
341-
return manifestRef;
342-
};
343323
const validateRestoredWorkspace = async (): Promise<void> => {
344324
if (!restoredWorkspace) {
345325
return;
@@ -361,7 +341,7 @@ export function createNodeWorkerTunnelManager(options: NodeWorkerTunnelManagerOp
361341
}
362342
const quiescence = await quiesceWorkspace(restoredWorkspace.remoteWorkspaceDir);
363343
try {
364-
const remoteManifestRef = await captureManifest(
344+
const remoteManifestRef = await workspace.captureManifest(
365345
restoredWorkspace.remoteWorkspaceDir,
366346
prepared.snapshot.manifest.baseCommit,
367347
restoredWorkspace.manifestRef,
@@ -411,7 +391,7 @@ export function createNodeWorkerTunnelManager(options: NodeWorkerTunnelManagerOp
411391
const changed = uploaded.currentManifestRef !== request.baseManifestRef;
412392
let expectedRemoteRef = uploaded.currentManifestRef;
413393
const verifyStable = async () => {
414-
const observed = await captureManifest(
394+
const observed = await workspace.captureManifest(
415395
request.remoteWorkspaceDir,
416396
uploaded.base.baseCommit,
417397
expectedRemoteRef,

‎src/gateway/worker-environments/node-worker-workspace-fallback.ts‎

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import path from "node:path";
44
import { createSubsystemLogger } from "../../logging/subsystem.js";
55
import { runCommandWithTimeout, type SpawnResult } from "../../process/exec.js";
66
import type { WorkerWorkspaceSyncRequest, WorkerWorkspaceSyncResult } from "./tunnel-contract.js";
7+
import { boundedWorkerError } from "./worker-error.js";
78
import {
89
resolveWorkerWorkspaceGitAuthor,
910
validateWorkspaceSyncRequest,
@@ -173,7 +174,34 @@ function succeeded(result: SpawnResult): boolean {
173174

174175
/** Optional published-origin fast path; HTTPS transfer remains the canonical fallback. */
175176
export function createNodeWorkerWorkspaceFallback(exec: WorkspaceExec) {
177+
const capture = async (dir: string, base: string | null, reference?: string) =>
178+
await exec({
179+
argv: [
180+
"node",
181+
"-e",
182+
REMOTE_WORKSPACE_MANIFEST_JS,
183+
dir,
184+
...(base ? [base, "eligible"] : ["", "all"]),
185+
...(reference ? [reference.slice("sha256:".length)] : []),
186+
],
187+
timeoutMs: GIT_TIMEOUT_MS,
188+
transportRetry: "idempotent",
189+
});
176190
return {
191+
async captureManifest(dir: string, base: string | null, reference: string) {
192+
const captured = await capture(dir, base, reference);
193+
const manifestRef = captured.stdout.trim();
194+
if (!succeeded(captured) || !MANIFEST_REF_PATTERN.test(manifestRef)) {
195+
const detail = boundedWorkerError(
196+
captured.stderr.trim() ||
197+
(!succeeded(captured)
198+
? `${captured.termination} (exit code ${captured.code}, signal ${captured.signal})`
199+
: "invalid manifest reference"),
200+
);
201+
throw new Error(`Node workspace manifest capture failed: ${detail}`);
202+
}
203+
return manifestRef;
204+
},
177205
async trySyncWorkspace(
178206
request: WorkerWorkspaceSyncRequest,
179207
expectedManifestRef: string,
@@ -219,18 +247,7 @@ export function createNodeWorkerWorkspaceFallback(exec: WorkspaceExec) {
219247
if (!succeeded(checkedOut) || checkedOut.workspaceDir !== cloned.workspaceDir) {
220248
return { kind: "fallback", reason: "checkout-failed" };
221249
}
222-
const captured = await exec({
223-
argv: [
224-
"node",
225-
"-e",
226-
REMOTE_WORKSPACE_MANIFEST_JS,
227-
checkedOut.workspaceDir,
228-
identity.commit,
229-
"eligible",
230-
],
231-
timeoutMs: GIT_TIMEOUT_MS,
232-
transportRetry: "idempotent",
233-
});
250+
const captured = await capture(checkedOut.workspaceDir, identity.commit);
234251
const manifestRef = captured.stdout.trim();
235252
if (!succeeded(captured) || !MANIFEST_REF_PATTERN.test(manifestRef)) {
236253
return { kind: "fallback", reason: "manifest-capture-failed" };

‎src/gateway/worker-environments/node-workspace-retain-coordinator.test.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ function createHarness(
9494
params: {
9595
environments?: unknown[];
9696
placements?: unknown[];
97+
pendingResults?: ReturnType<WorkerSessionPlacementStore["listPendingWorkspaceResults"]>;
9798
results?: Array<{
9899
applied: boolean;
99100
deleted: number;
@@ -145,7 +146,8 @@ function createHarness(
145146
} as Pick<WorkerEnvironmentService, "list">,
146147
placements: {
147148
list: () => (params.placements ?? [placement()]) as never,
148-
} as Pick<WorkerSessionPlacementStore, "list">,
149+
listPendingWorkspaceResults: () => params.pendingResults ?? [],
150+
} as Pick<WorkerSessionPlacementStore, "list" | "listPendingWorkspaceResults">,
149151
warn,
150152
});
151153
coordinator.bindTransport(transport);
@@ -556,6 +558,54 @@ describe("node workspace retain coordinator", () => {
556558
await coordinator.stop();
557559
});
558560

561+
it.each(["claimed", "pending", "stale-pending"])(
562+
"protects unsettled manifests for %s ownership",
563+
async (state) => {
564+
const { coordinator, invoke } = createHarness({
565+
placements: [
566+
placement({
567+
turnClaim:
568+
state === "claimed"
569+
? {
570+
owner: "worker",
571+
claimId: "claim-1",
572+
runId: "run-1",
573+
generation: 3,
574+
ownerEpoch: 7,
575+
}
576+
: null,
577+
}),
578+
],
579+
pendingResults:
580+
state === "claimed"
581+
? []
582+
: [
583+
{
584+
sessionId: "session-1",
585+
environmentId: "environment-1",
586+
ownerEpoch: state === "pending" ? 7 : 6,
587+
placementGeneration: 3,
588+
claimId: "claim-1",
589+
runId: "run-1",
590+
gatewayInstanceId: "previous-gateway",
591+
recoveryRequestedAtMs: null,
592+
workspaceAcceptedAtMs: null,
593+
stagedResultRef: null,
594+
},
595+
],
596+
});
597+
await coordinator.start();
598+
expect(invoke.mock.calls[0]?.[0].params).toMatchObject({
599+
retain: [
600+
expect.objectContaining({
601+
manifestRefs: state === "stale-pending" ? [`sha256:${"a".repeat(64)}`] : null,
602+
}),
603+
],
604+
});
605+
await coordinator.stop();
606+
},
607+
);
608+
559609
it("acknowledges the node bundle generation on the next same-connection snapshot", async () => {
560610
const { coordinator, invoke } = createHarness({
561611
results: [

‎src/gateway/worker-environments/node-workspace-retain-coordinator.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ const TERMINAL_ENVIRONMENT_STATES = new Set(["destroyed", "failed", "orphaned"])
2424

2525
type NodeWorkspaceRetainCoordinatorOptions = {
2626
gatewayNamespace: string;
27-
placements: Pick<WorkerSessionPlacementStore, "list">;
27+
placements: Pick<WorkerSessionPlacementStore, "list" | "listPendingWorkspaceResults">;
2828
environments: Pick<WorkerEnvironmentService, "list">;
2929
warn: (message: string) => void;
3030
};
@@ -71,6 +71,9 @@ function snapshotEntriesForNode(
7171
const placements = new Map(
7272
options.placements.list().map((placement) => [placement.sessionId, placement] as const),
7373
);
74+
const pendingResults = new Map(
75+
options.placements.listPendingWorkspaceResults().map((result) => [result.sessionId, result]),
76+
);
7477
return nodeEnvironments(options, nodeId)
7578
.flatMap((environment): NodeWorkerWorkspaceRetainEntry[] => {
7679
if (
@@ -82,13 +85,21 @@ function snapshotEntriesForNode(
8285
}
8386
const sessionId = environment.attachedSessionIds[0]!;
8487
const placement = placements.get(sessionId);
88+
const pending = pendingResults.get(sessionId);
89+
// The base is not a complete reachability set until reconciliation settles. Pending
90+
// results preserve this protection across restarts, when node-local transfer pins are lost.
91+
const unsettled =
92+
placement?.turnClaim ||
93+
(pending?.environmentId === environment.environmentId &&
94+
pending.ownerEpoch === environment.ownerEpoch);
8595
const hasExactManifestOwner =
8696
placement?.state === "starting" ||
8797
placement?.state === "active" ||
8898
placement?.state === "draining" ||
8999
placement?.state === "reconciling";
90100
const exactManifest =
91101
hasExactManifestOwner &&
102+
!unsettled &&
92103
placement.environmentId === environment.environmentId &&
93104
placement.workspaceBaseManifestRef &&
94105
(placement.activeOwnerEpoch === environment.ownerEpoch || placement.state === "starting")

0 commit comments

Comments
 (0)