Skip to content

Commit 38379a9

Browse files
authored
feat(runners): enforce node worker capacity (#123612)
* feat(runners): enforce node worker capacity * test(node-host): mock supervisor initialization * fix(runners): surface capacity exhaustion
1 parent 37a63fb commit 38379a9

18 files changed

Lines changed: 665 additions & 66 deletions

‎docs/nodes/index.md‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -440,11 +440,16 @@ Gateway versions to match exactly. If they differ, update the node before
440440
retrying.
441441

442442
This setting enables supervised session turns on the paired device, including
443-
Gateway-owned workspace transfer and result reconciliation. If the device is
444-
offline before a turn is dispatched, the Gateway waits up to 10 seconds and
445-
then returns a visible retry/reconnect error while keeping the session placement
446-
available for a later attempt. Gateway restart likewise preserves an idle device
447-
placement and reconnects its tunnel lazily on the next turn.
443+
Gateway-owned workspace transfer and result reconciliation. Each node runs at
444+
most two worker processes by default. A third launch waits up to 10 seconds for
445+
a durable slot; while both slots are occupied, the node remains available for
446+
status and cancellation but is not selected for a new session turn.
447+
448+
If the device is offline before a turn is dispatched, the Gateway waits up to
449+
10 seconds and then returns a visible retry/reconnect error while keeping the
450+
session placement available for a later attempt. Gateway restart likewise
451+
preserves an idle device placement and reconnects its tunnel lazily on the next
452+
turn.
448453

449454
See [Anthropic: Claude sessions across computers](/providers/anthropic#claude-sessions-across-computers)
450455
for the Control UI behavior and storage sources.

‎docs/plan/runners.md‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -198,9 +198,13 @@ stated honestly (revision 1 undersold this):
198198
`{ profileId } | { deviceId }`; the device → environment mapping resolves
199199
server-side. Devices are not smuggled through synthesized
200200
`cloudWorkers.profiles` entries.
201-
- **Concurrency slots.** A node declares a session-slot count (default small);
202-
the picker shows busy state; a dispatch that no live runner can satisfy
203-
fails visibly after a bounded wait instead of queuing forever.
201+
- **Concurrency slots.** The node supervisor admits two physical worker
202+
processes by default. Durable `pending` and `running` launches consume those
203+
slots atomically; same-launch replay consumes no additional slot. When full,
204+
the node withdraws `workerRuns` from its live inventory while retaining the
205+
supervisor dialect, restores it after a durable terminal commit, and gives a
206+
third launch up to 10 seconds to acquire capacity before failing visibly.
207+
Public inventory does not expose machine counters.
204208
- **Multi-gateway safety.** The worker install/workspace root on a node is
205209
namespaced by gateway identity so two gateways pairing one machine cannot
206210
corrupt each other's state.
@@ -221,9 +225,11 @@ build. Provider eligibility and new launch selection require the exact handshake
221225
while status and cancellation reacquire only the current supervisor proof and use
222226
the durable launch identity so an upgrade cannot strand an existing worker.
223227
Node-local opt-in advertises the current installation; default nodes remain
224-
non-hosts. Milestone 7 upgrades this to Gateway-pinned, namespaced bundle bytes.
225-
Slots, isolation, checkouts, workspace transfer, and persistent-runner lifecycle
226-
remain milestone 6 work.
228+
non-hosts. The supervisor now owns two atomic durable capacity slots, bounded
229+
10-second admission, restart reconciliation, and full/free inventory edges.
230+
Milestone 7 upgrades this to Gateway-pinned, namespaced bundle bytes. Isolation,
231+
checkout ownership, device dormancy/reaping, and node-host disk GC remain
232+
milestone 6 work.
227233

228234
### Trust model (operator-decided, v1)
229235

‎src/gateway/worker-environments/node-launch-adapter.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
WORKER_PROTOCOL_FEATURES,
88
WORKER_RPC_SET_VERSION,
99
} from "../../../packages/gateway-protocol/src/schema/worker-admission.js";
10+
import { NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE } from "../../infra/node-commands.js";
1011
import { NODE_WORKER_SUPERVISOR_PROTOCOL_FEATURE } from "../../infra/node-runner-inventory.js";
1112
import {
1213
nodeWorkerPlanHash,
@@ -226,6 +227,30 @@ describe("node worker launch adapter", () => {
226227
expect(invoke.mock.calls[1]?.[0].node.connId).toBe("conn-2");
227228
});
228229

230+
it("does not retry or cancel a dispatched launch rejected before capacity admission", async () => {
231+
const invoke = vi.fn<NodeWorkerSupervisorTransport["invoke"]>(async (request) => {
232+
request.onDispatchReady?.("invoke-1");
233+
return {
234+
ok: false,
235+
error: {
236+
code: NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE,
237+
message: "node worker capacity remained full for 10000 ms",
238+
},
239+
};
240+
});
241+
const adapter = createNodeWorkerLaunchAdapter({
242+
getTransport: () => transportWith(invoke),
243+
sleep: async () => {},
244+
});
245+
246+
await expect(adapter.launch(launchRequest())).rejects.toMatchObject({
247+
code: NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE,
248+
message: "device worker capacity remained full",
249+
});
250+
expect(invoke).toHaveBeenCalledOnce();
251+
expect(invoke.mock.calls.map(([request]) => request.command)).toEqual(["worker.launch.v1"]);
252+
});
253+
229254
it("snapshots the launch plan before asynchronous node discovery", async () => {
230255
const input = launchInput();
231256
const expectedInput = structuredClone(input);

‎src/gateway/worker-environments/node-launch-adapter.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { WorkerAdmissionHandshake } from "../../../packages/gateway-protocol/src/schema/worker-admission.js";
22
import { sleepWithAbort } from "../../infra/backoff.js";
33
import {
4+
NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE,
45
NODE_WORKER_SUPERVISOR_CANCEL_COMMAND,
56
NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND,
67
NODE_WORKER_SUPERVISOR_STATUS_COMMAND,
@@ -314,7 +315,9 @@ export function createNodeWorkerLaunchAdapter(options: NodeWorkerLaunchAdapterOp
314315
const code = result.error?.code ?? "UNAVAILABLE";
315316
throw new NodeWorkerLaunchTransportError(
316317
code,
317-
`node worker supervisor invocation failed (${code})`,
318+
code === NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE
319+
? "device worker capacity remained full"
320+
: `node worker supervisor invocation failed (${code})`,
318321
);
319322
}
320323
return parseInvokeReceipt(result.payloadJSON);
@@ -497,6 +500,14 @@ export function createNodeWorkerLaunchAdapter(options: NodeWorkerLaunchAdapterOp
497500
if (!dispatchReady && availabilityDeadline.signal.aborted && !deadline.signal.aborted) {
498501
throw new WorkerRunnerUnavailableError();
499502
}
503+
// The node authors this result only after its durable claim stayed absent.
504+
// Transport dispatch is therefore not launch ambiguity and needs no cancel.
505+
if (
506+
error instanceof NodeWorkerLaunchTransportError &&
507+
error.code === NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE
508+
) {
509+
throw error;
510+
}
500511
if (!mayHaveLaunched) {
501512
throw error;
502513
}

‎src/infra/node-commands.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export const NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND = "worker.launch.v1";
2323
export const NODE_WORKER_SUPERVISOR_STATUS_COMMAND = "worker.status.v1";
2424
export const NODE_WORKER_SUPERVISOR_CANCEL_COMMAND = "worker.cancel.v1";
2525
export const NODE_WORKER_WORKSPACE_EXEC_COMMAND = "worker.workspace.exec.v1";
26+
export const NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE = "WORKER_CAPACITY_EXHAUSTED";
2627
export const NODE_WORKER_PRIVATE_COMMANDS = [
2728
NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND,
2829
NODE_WORKER_SUPERVISOR_STATUS_COMMAND,

‎src/node-host/invoke-worker-supervisor.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
22
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
33
import type { GatewayClient } from "../gateway/client.js";
44
import {
5+
NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE,
56
NODE_WORKER_SUPERVISOR_CANCEL_COMMAND,
67
NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND,
78
NODE_WORKER_SUPERVISOR_STATUS_COMMAND,
@@ -14,6 +15,7 @@ import {
1415
NodeWorkerWorkspaceTransferError,
1516
} from "../worker/node-workspace-transfer-protocol.js";
1617
import { handleInvoke } from "./invoke.js";
18+
import { NodeWorkerCapacityExhaustedError } from "./node-worker-capacity.js";
1719
import type { NodeWorkerLaunchReceipt } from "./node-worker-launch-store.js";
1820
import type { NodeWorkerSupervisorControl } from "./node-worker-supervisor-contract.js";
1921
import {
@@ -433,6 +435,28 @@ describe("node-host worker supervisor commands", () => {
433435
expect(message.length).toBeLessThan(256);
434436
});
435437

438+
it("preserves a terminal capacity result across node invoke", async () => {
439+
const input = launchInput();
440+
const supervisor = supervisorWith(fullReceipt(input));
441+
supervisorMocks(supervisor).launch.mockRejectedValueOnce(
442+
new NodeWorkerCapacityExhaustedError(10_000),
443+
);
444+
445+
const { result } = await invokePrivate({
446+
command: NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND,
447+
paramsJSON: JSON.stringify(input),
448+
supervisor,
449+
});
450+
451+
expect(result).toMatchObject({
452+
ok: false,
453+
error: {
454+
code: NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE,
455+
message: "node worker capacity remained full for 10000 ms",
456+
},
457+
});
458+
});
459+
436460
it("preserves a typed workspace transfer failure across node invoke", async () => {
437461
const workspace = {
438462
exec: vi.fn(async () => {
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
import { NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE } from "../infra/node-commands.js";
2+
import {
3+
NodeWorkerLaunchStore,
4+
type NodeWorkerLaunchClaim,
5+
type NodeWorkerLaunchClaimResult,
6+
type NodeWorkerLaunchReceipt,
7+
} from "./node-worker-launch-store.js";
8+
import {
9+
inspectNodeWorkerProcessIdentity,
10+
type NodeWorkerProcessIdentity,
11+
} from "./node-worker-process-identity.js";
12+
13+
const DEFAULT_WORKER_CAPACITY = 2;
14+
const DEFAULT_CAPACITY_WAIT_MS = 10_000;
15+
const CAPACITY_POLL_MS = 100;
16+
17+
type NodeWorkerCapacityOptions = {
18+
capacity?: number;
19+
capacityWaitMs?: number;
20+
onAvailabilityChanged?: (available: boolean) => void;
21+
};
22+
23+
function capacityAbortReason(signal: AbortSignal): Error {
24+
return signal.reason instanceof Error
25+
? signal.reason
26+
: new Error("node worker admission aborted");
27+
}
28+
29+
export class NodeWorkerCapacityExhaustedError extends Error {
30+
readonly code = NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE;
31+
32+
constructor(waitMs: number) {
33+
super(`node worker capacity remained full for ${waitMs} ms`);
34+
this.name = "NodeWorkerCapacityExhaustedError";
35+
}
36+
}
37+
38+
/** Owns durable worker slot admission and live full/free publication edges. */
39+
export class NodeWorkerCapacity {
40+
private readonly capacity: number;
41+
private readonly waitMs: number;
42+
private readonly onAvailabilityChanged?: (available: boolean) => void;
43+
private readonly waiters = new Set<() => void>();
44+
private readonly closeAbort = new AbortController();
45+
private availability?: boolean;
46+
47+
constructor(
48+
private readonly store: NodeWorkerLaunchStore,
49+
options: NodeWorkerCapacityOptions = {},
50+
) {
51+
this.capacity = options.capacity ?? DEFAULT_WORKER_CAPACITY;
52+
this.waitMs = options.capacityWaitMs ?? DEFAULT_CAPACITY_WAIT_MS;
53+
this.onAvailabilityChanged = options.onAvailabilityChanged;
54+
if (!Number.isSafeInteger(this.capacity) || this.capacity < 1) {
55+
throw new Error("node worker capacity must be a positive safe integer");
56+
}
57+
if (!Number.isSafeInteger(this.waitMs) || this.waitMs < 0) {
58+
throw new Error("node worker capacity wait must be a non-negative safe integer");
59+
}
60+
}
61+
62+
async initialize(
63+
recoverRunning: (receipt: NodeWorkerLaunchReceipt) => Promise<void>,
64+
): Promise<void> {
65+
this.publish(false);
66+
for (const receipt of this.store.listNonterminal()) {
67+
if (receipt.state === "pending") {
68+
const supervisorState = inspectNodeWorkerProcessIdentity(receipt.supervisor);
69+
if (supervisorState === "dead" || supervisorState === "reused") {
70+
this.finish(
71+
{
72+
launchId: receipt.launchId,
73+
planHash: receipt.planHash,
74+
supervisor: receipt.supervisor,
75+
worker: null,
76+
state: "interrupted",
77+
errorText: "node host stopped before the worker launch started",
78+
},
79+
false,
80+
);
81+
}
82+
continue;
83+
}
84+
await recoverRunning(receipt);
85+
}
86+
this.refresh();
87+
}
88+
89+
async claim(
90+
claim: NodeWorkerLaunchClaim,
91+
supervisor: NodeWorkerProcessIdentity,
92+
signal?: AbortSignal,
93+
): Promise<Exclude<NodeWorkerLaunchClaimResult, { action: "at-capacity" }>> {
94+
const deadlineMs = Date.now() + this.waitMs;
95+
while (true) {
96+
if (this.closeAbort.signal.aborted) {
97+
throw new Error("node worker supervisor is closed");
98+
}
99+
signal?.throwIfAborted();
100+
const result = this.store.claim(claim, supervisor, this.capacity);
101+
this.publish(result.nonterminalCount < this.capacity);
102+
if (result.action !== "at-capacity") {
103+
return result;
104+
}
105+
await this.wait(deadlineMs, signal);
106+
}
107+
}
108+
109+
finish(
110+
params: Parameters<NodeWorkerLaunchStore["finish"]>[0],
111+
notify = true,
112+
): NodeWorkerLaunchReceipt {
113+
const receipt = this.store.finish(params);
114+
if (notify && receipt.state !== "pending" && receipt.state !== "running") {
115+
this.changed();
116+
}
117+
return receipt;
118+
}
119+
120+
finishCancelled(
121+
params: Parameters<NodeWorkerLaunchStore["finishCancelled"]>[0],
122+
): NodeWorkerLaunchReceipt | undefined {
123+
const receipt = this.store.finishCancelled(params);
124+
if (receipt && receipt.state !== "pending" && receipt.state !== "running") {
125+
this.changed();
126+
}
127+
return receipt;
128+
}
129+
130+
close(): void {
131+
this.closeAbort.abort();
132+
this.wake();
133+
}
134+
135+
private publish(available: boolean): void {
136+
if (this.availability === available) {
137+
return;
138+
}
139+
this.availability = available;
140+
this.onAvailabilityChanged?.(available);
141+
}
142+
143+
private refresh(): void {
144+
const count = this.store.nonterminalCount();
145+
this.publish(count < this.capacity);
146+
if (count < this.capacity) {
147+
this.wake();
148+
}
149+
}
150+
151+
private changed(): void {
152+
this.wake();
153+
try {
154+
this.refresh();
155+
} catch {
156+
this.publish(false);
157+
}
158+
}
159+
160+
private wake(): void {
161+
for (const wake of this.waiters) {
162+
wake();
163+
}
164+
}
165+
166+
private async wait(deadlineMs: number, signal?: AbortSignal): Promise<void> {
167+
const remainingMs = deadlineMs - Date.now();
168+
if (remainingMs <= 0) {
169+
throw new NodeWorkerCapacityExhaustedError(this.waitMs);
170+
}
171+
if (signal?.aborted) {
172+
throw capacityAbortReason(signal);
173+
}
174+
if (this.closeAbort.signal.aborted) {
175+
throw new Error("node worker supervisor is closed");
176+
}
177+
await new Promise<void>((resolve, reject) => {
178+
const finish = (operation: () => void) => {
179+
clearTimeout(pollTimer);
180+
this.waiters.delete(wake);
181+
signal?.removeEventListener("abort", onAbort);
182+
this.closeAbort.signal.removeEventListener("abort", onClose);
183+
operation();
184+
};
185+
const wake = () => finish(resolve);
186+
const onAbort = () =>
187+
finish(() =>
188+
reject(signal ? capacityAbortReason(signal) : new Error("node worker admission aborted")),
189+
);
190+
const onClose = () => finish(() => reject(new Error("node worker supervisor is closed")));
191+
const pollTimer = setTimeout(wake, Math.min(CAPACITY_POLL_MS, remainingMs));
192+
pollTimer.unref?.();
193+
this.waiters.add(wake);
194+
signal?.addEventListener("abort", onAbort, { once: true });
195+
this.closeAbort.signal.addEventListener("abort", onClose, { once: true });
196+
});
197+
}
198+
}

0 commit comments

Comments
 (0)