Skip to content

Commit 459c70e

Browse files
authored
fix(worker): stop Gateway RTT from pacing live previews (#122258)
* fix(worker): decouple live previews from gateway acknowledgements * test(worker): track fault harness temp directories * fix(worker): preserve finishing after preview rejection * fix(worker): recover finishing after early preview failure * test(worker): model terminal resync decisions
1 parent 642fe77 commit 459c70e

14 files changed

Lines changed: 1177 additions & 872 deletions

‎src/gateway/worker-environments/placement-store.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,9 @@ describe("worker session placement store", () => {
695695
liveEvent: 8,
696696
}),
697697
).toMatchObject({ lastTranscriptAckCursor: 4, lastLiveEventAckCursor: 9 });
698+
expect(store.listPendingWorkspaceResults()).toMatchObject([
699+
{ sessionId: SESSION.sessionId, claimId: currentClaim.claimId },
700+
]);
698701
});
699702

700703
it("advances the workspace manifest only under the exact worker turn claim", () => {

‎src/gateway/worker-environments/placement-turn-claims.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,7 @@ export function createPlacementTurnClaimOps(runtime: PlacementStoreRuntime) {
431431
claim: WorkerSessionTurnClaim;
432432
transcript?: number;
433433
liveEvent?: number;
434+
/** @deprecated Workspace result fencing is implied by a live event cursor. */
434435
workspaceResultPending?: boolean;
435436
}): WorkerSessionPlacementRecord {
436437
const sessionId = required(input.claim.sessionId, "session id");
@@ -499,7 +500,7 @@ export function createPlacementTurnClaimOps(runtime: PlacementStoreRuntime) {
499500
if (result.numAffectedRows !== 1n) {
500501
throw new Error(`Worker session placement ${sessionId} changed during ACK`);
501502
}
502-
if (input.workspaceResultPending) {
503+
if (input.liveEvent !== undefined) {
503504
// The terminal event is not ACKed until crash recovery has a durable
504505
// fence protecting remote workspace results from stale-claim teardown.
505506
insertWorkerWorkspacePendingResult(db, input.claim, now(), instanceId);

‎src/gateway/worker-environments/placement-worker-gate.test.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ describe("worker session placement gate", () => {
103103
expect(gate.validateWorkerTurn({ ...binding, ownerEpoch: OWNER_EPOCH + 1 })).toBe(false);
104104
});
105105

106-
it("updates exact-owner cursors and rejects stale descriptor replay", () => {
106+
it("atomically retains the finishing cursor and workspace-result fence", () => {
107107
const runId = "run-worker-ack";
108108
const claim = preclaim(runId);
109109
const gate = createWorkerSessionPlacementGate(store);
@@ -114,13 +114,19 @@ describe("worker session placement gate", () => {
114114
runId,
115115
};
116116

117-
gate.updateAckCursors({ ...binding, transcriptSeq: 4, liveSeq: 9 });
117+
gate.updateAckCursors({ ...binding, transcriptSeq: 4 });
118+
expect(store.listPendingWorkspaceResults()).toEqual([]);
119+
gate.updateAckCursors({ ...binding, liveSeq: 9 });
118120
expect(store.get(SESSION.sessionId)).toMatchObject({
119121
generation: claim.placementGeneration,
120122
lastTranscriptAckCursor: 4,
121123
lastLiveEventAckCursor: 9,
122124
});
123-
store.releaseTurn(claim);
125+
expect(store.listPendingWorkspaceResults()).toMatchObject([
126+
{ sessionId: SESSION.sessionId, runId },
127+
]);
128+
store.acceptWorkspaceResult(claim);
129+
store.completeWorkspaceResultAndReleaseTurn(claim);
124130
expect(store.get(SESSION.sessionId)?.turnClaim).toBeNull();
125131
expect(gate.validateWorkerTurn(binding)).toBe(false);
126132
});

‎src/gateway/worker-environments/placement-worker-gate.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ export type WorkerSessionPlacementGate = {
2323
binding: WorkerPlacementTurnBinding & {
2424
transcriptSeq?: number;
2525
liveSeq?: number;
26-
workspaceResultPending?: boolean;
2726
},
2827
): void;
2928
};
@@ -86,9 +85,6 @@ export function createWorkerSessionPlacementGate(
8685
claim,
8786
...(binding.transcriptSeq === undefined ? {} : { transcript: binding.transcriptSeq }),
8887
...(binding.liveSeq === undefined ? {} : { liveEvent: binding.liveSeq }),
89-
...(binding.workspaceResultPending === undefined
90-
? {}
91-
: { workspaceResultPending: binding.workspaceResultPending }),
9288
});
9389
},
9490
};

‎src/gateway/worker-environments/worker-turn-launcher.test.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -793,7 +793,7 @@ describe("worker turn launcher", () => {
793793
ownerEpoch: OWNER_EPOCH,
794794
runId: "run-worker-turn",
795795
transcriptSeq: 2,
796-
workspaceResultPending: true,
796+
liveSeq: 1,
797797
});
798798
return {
799799
stdout: JSON.stringify({
@@ -1027,7 +1027,7 @@ describe("worker turn launcher", () => {
10271027
ownerEpoch: OWNER_EPOCH,
10281028
runId: "run-persisted-user",
10291029
transcriptSeq: 2,
1030-
workspaceResultPending: true,
1030+
liveSeq: 1,
10311031
});
10321032
return {
10331033
stdout: JSON.stringify({
@@ -1161,7 +1161,7 @@ describe("worker turn launcher", () => {
11611161
ownerEpoch: OWNER_EPOCH,
11621162
runId: "run-reconcile-tunnel-loss",
11631163
transcriptSeq: 2,
1164-
workspaceResultPending: true,
1164+
liveSeq: 1,
11651165
});
11661166
return {
11671167
stdout: JSON.stringify({
@@ -1286,7 +1286,7 @@ describe("worker turn launcher", () => {
12861286
ownerEpoch: OWNER_EPOCH,
12871287
runId: "run-worker-usage",
12881288
transcriptSeq: 2,
1289-
workspaceResultPending: true,
1289+
liveSeq: 1,
12901290
});
12911291
return {
12921292
stdout: JSON.stringify({
@@ -1487,7 +1487,6 @@ describe("worker turn launcher", () => {
14871487
ownerEpoch: OWNER_EPOCH,
14881488
runId: "run-terminal-child-failure",
14891489
liveSeq: 1,
1490-
workspaceResultPending: true,
14911490
});
14921491
return {
14931492
stdout: "",
@@ -2011,7 +2010,7 @@ describe("worker turn launcher", () => {
20112010
ownerEpoch: OWNER_EPOCH,
20122011
runId: "run-overlap",
20132012
transcriptSeq: 2,
2014-
workspaceResultPending: true,
2013+
liveSeq: 1,
20152014
});
20162015
const active = placements.get(SESSION_ID);
20172016
if (active?.state !== "active") {
@@ -2089,7 +2088,7 @@ describe("worker turn launcher", () => {
20892088
ownerEpoch: OWNER_EPOCH,
20902089
runId: "run-model-failed",
20912090
transcriptSeq: 2,
2092-
workspaceResultPending: true,
2091+
liveSeq: 1,
20932092
});
20942093
return {
20952094
stdout: JSON.stringify({
@@ -2118,7 +2117,7 @@ describe("worker turn launcher", () => {
21182117
ownerEpoch: OWNER_EPOCH,
21192118
runId: "run-model-recovered",
21202119
transcriptSeq: 2,
2121-
workspaceResultPending: true,
2120+
liveSeq: 1,
21222121
});
21232122
return {
21242123
stdout: JSON.stringify({
@@ -2240,7 +2239,7 @@ describe("worker turn launcher", () => {
22402239
ownerEpoch: OWNER_EPOCH,
22412240
runId,
22422241
transcriptSeq: 2,
2243-
workspaceResultPending: true,
2242+
liveSeq: 1,
22442243
});
22452244
return {
22462245
stdout: JSON.stringify({

‎src/gateway/worker-environments/worker-turn-rpc.test.ts‎

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ describe("worker environment service", () => {
149149
expect(liveEvents.rotateCredential).not.toHaveBeenCalled();
150150
});
151151

152-
it("persists worker transcript and terminal live ACK cursors", async () => {
152+
it("keeps preview ACKs in memory and persists only transcript and terminal cursors", async () => {
153153
const applyTranscriptCommit = support.successfulTranscriptCommit("entry-placement");
154154
const { liveEvents } = support.sequencedLiveEvents();
155155
const { identity, placementStore, workerService } = support.placementHarness(
@@ -174,15 +174,19 @@ describe("worker environment service", () => {
174174
});
175175

176176
await expect(
177-
workerService.pushLiveEvent(identity, support.terminalEvent(identity)),
178-
).resolves.toEqual({
179-
ok: true,
180-
result: { ackedSeq: 1 },
181-
});
177+
workerService.pushLiveEvent(identity, support.assistantEvent(identity, "preview")),
178+
).resolves.toEqual({ ok: true, result: { ackedSeq: 1 } });
179+
expect(placementStore.updateAckCursors).toHaveBeenCalledOnce();
180+
181+
await expect(
182+
workerService.pushLiveEvent(
183+
identity,
184+
support.terminalEvent(identity, { lastAckedSeq: 1, seq: 2 }),
185+
),
186+
).resolves.toEqual({ ok: true, result: { ackedSeq: 2 } });
182187
expect(placementStore.updateAckCursors).toHaveBeenLastCalledWith({
183188
...binding,
184-
liveSeq: 1,
185-
workspaceResultPending: true,
189+
liveSeq: 2,
186190
});
187191
});
188192

@@ -209,7 +213,6 @@ describe("worker environment service", () => {
209213
expect(placementStore.updateAckCursors).toHaveBeenLastCalledWith({
210214
...support.placementBinding(identity),
211215
liveSeq: 1,
212-
workspaceResultPending: true,
213216
});
214217
});
215218

@@ -288,15 +291,16 @@ describe("worker environment service", () => {
288291
await expect(
289292
workerService.pushLiveEvent(identity, support.terminalEvent(identity, { seq: 2 })),
290293
).resolves.toEqual({ ok: true, result: { ackedSeq: 0 } });
291-
expect(placementStore.updateAckCursors).toHaveBeenCalledWith({
292-
...support.placementBinding(identity),
293-
liveSeq: 0,
294-
workspaceResultPending: true,
295-
});
294+
expect(placementStore.updateAckCursors).not.toHaveBeenCalled();
296295

297296
await expect(
298297
workerService.pushLiveEvent(identity, support.assistantEvent(identity, "fills gap")),
299298
).resolves.toEqual({ ok: true, result: { ackedSeq: 2 } });
299+
expect(placementStore.updateAckCursors).toHaveBeenCalledOnce();
300+
expect(placementStore.updateAckCursors).toHaveBeenCalledWith({
301+
...support.placementBinding(identity),
302+
liveSeq: 2,
303+
});
300304
await expect(
301305
workerService.commitTranscript(
302306
identity,
@@ -352,7 +356,6 @@ describe("worker environment service", () => {
352356
{
353357
...support.placementBinding(identity),
354358
liveSeq: 1,
355-
workspaceResultPending: true,
356359
},
357360
],
358361
]);

‎src/gateway/worker-environments/worker-turn-rpc.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -386,16 +386,10 @@ export function createWorkerTurnRpc(options: WorkerTurnRpcOptions) {
386386
// commits and the terminal mutation fence while this synchronous receiver runs.
387387
const result = options.liveEvents.apply({ identity, request });
388388
if (result.ok) {
389-
const placement = placementBinding(identity);
390389
const processTurn = processTurnBinding(identity);
391-
if (!placement || !processTurn) {
390+
if (!processTurn) {
392391
return { ok: false, closeReason: "placement-mismatch" };
393392
}
394-
options.placementStore?.updateAckCursors({
395-
...placement,
396-
liveSeq: result.result.ackedSeq,
397-
...(isTerminalLiveEvent(request) ? { workspaceResultPending: true } : {}),
398-
});
399393
recordAckCursor(processTurn, { liveSeq: result.result.ackedSeq });
400394
}
401395
return result;
@@ -430,6 +424,12 @@ export function createWorkerTurnRpc(options: WorkerTurnRpcOptions) {
430424
matchesTurnBinding(terminal, processTurn) &&
431425
result.result.ackedSeq >= terminal.terminalLiveSeq
432426
) {
427+
// Only finishing authority crosses the durable boundary. Its live cursor
428+
// and workspace-result recovery fence commit in one placement transaction.
429+
options.placementStore?.updateAckCursors({
430+
...placement,
431+
liveSeq: result.result.ackedSeq,
432+
});
433433
// A gap fill can ACK a previously buffered terminal event. Fence from
434434
// the observed high-water marks, not only from the request carrying it.
435435
terminalTurnFences.set(

‎src/worker/embedded-agent-live.runtime.test.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,6 @@ describe("createWorkerLiveRuntime", () => {
3737
for (const event of events) {
3838
runtime.handleSessionEvent(event);
3939
}
40-
await runtime.flush();
41-
4240
expect(JSON.stringify(emitted)).not.toContain("QUJDRA==");
4341
expect(JSON.stringify(emitted)).not.toMatch(/"[0-9]+":(?:[0-9]+|\{)/u);
4442
expect(emitted).toHaveLength(3);

‎src/worker/embedded-agent-live.runtime.ts‎

Lines changed: 5 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -104,45 +104,6 @@ function boundLiveEvent(event: WorkerLiveEvent): WorkerLiveEvent {
104104
return bounded;
105105
}
106106

107-
function coalescePendingLiveEvent(pending: WorkerLiveEvent[], event: WorkerLiveEvent): boolean {
108-
const index = pending.length - 1;
109-
const previous = pending[index];
110-
if (!previous) {
111-
return false;
112-
}
113-
if (previous.kind === "assistant" && event.kind === "assistant") {
114-
pending[index] = boundLiveEvent({
115-
kind: "assistant",
116-
payload: { ...event.payload, delta: event.payload.text, replace: true },
117-
});
118-
return true;
119-
}
120-
if (previous.kind === "thinking" && event.kind === "thinking") {
121-
if (event.payload.text === "" && event.payload.delta === "") {
122-
return false;
123-
}
124-
pending[index] = boundLiveEvent({
125-
kind: "thinking",
126-
payload: {
127-
text: event.payload.text,
128-
delta: `${previous.payload.delta}${event.payload.delta}`,
129-
},
130-
});
131-
return true;
132-
}
133-
if (
134-
previous.kind === "tool" &&
135-
previous.payload.phase === "update" &&
136-
event.kind === "tool" &&
137-
event.payload.phase === "update" &&
138-
previous.payload.toolCallId === event.payload.toolCallId
139-
) {
140-
pending[index] = boundLiveEvent(event);
141-
return true;
142-
}
143-
return false;
144-
}
145-
146107
function readAssistantText(message: AgentMessage): string {
147108
if (message.role !== "assistant") {
148109
return "";
@@ -170,57 +131,22 @@ type WorkerLiveClient = {
170131
type WorkerLiveRuntime = {
171132
handleSessionEvent: (event: AgentSessionEvent) => void;
172133
enqueueRunFailure: (failure: { aborted: boolean; error: Error }) => void;
173-
flush: () => Promise<void>;
174134
emitTerminal: () => Promise<void>;
175135
};
176136

177137
export function createWorkerLiveRuntime(client: WorkerLiveClient): WorkerLiveRuntime {
178-
const pendingLiveEvents: WorkerLiveEvent[] = [];
179-
let liveDrain: Promise<void> | undefined;
180138
let liveDegraded = false;
181-
const startLiveDrain = () => {
182-
if (liveDrain || liveDegraded || pendingLiveEvents.length === 0) {
183-
return;
184-
}
185-
liveDrain = (async () => {
186-
while (true) {
187-
const event = pendingLiveEvents.shift();
188-
if (!event) {
189-
return;
190-
}
191-
await client.emit(event);
192-
}
193-
})()
194-
.catch(() => {
195-
// Live events are preview-only; transcript commits and inference stay authoritative.
196-
liveDegraded = true;
197-
pendingLiveEvents.length = 0;
198-
})
199-
.finally(() => {
200-
liveDrain = undefined;
201-
startLiveDrain();
202-
});
203-
};
204139
const enqueueLive = (event: WorkerLiveEvent) => {
205140
if (liveDegraded) {
206141
return;
207142
}
208143
try {
209-
const bounded = boundLiveEvent(event);
210-
if (!coalescePendingLiveEvent(pendingLiveEvents, bounded)) {
211-
pendingLiveEvents.push(bounded);
212-
}
213-
startLiveDrain();
144+
void client.emit(boundLiveEvent(event)).catch(() => {
145+
// Preview loss must not block inference, transcript durability, or finishing.
146+
liveDegraded = true;
147+
});
214148
} catch {
215149
liveDegraded = true;
216-
pendingLiveEvents.length = 0;
217-
}
218-
};
219-
const flush = async () => {
220-
let drain = liveDrain;
221-
while (drain) {
222-
await drain;
223-
drain = liveDrain;
224150
}
225151
};
226152
const startedAt = Date.now();
@@ -358,5 +284,5 @@ export function createWorkerLiveRuntime(client: WorkerLiveClient): WorkerLiveRun
358284
}
359285
await client.emit(boundLiveEvent(terminalLiveEvent));
360286
};
361-
return { handleSessionEvent, enqueueRunFailure, flush, emitTerminal };
287+
return { handleSessionEvent, enqueueRunFailure, emitTerminal };
362288
}

‎src/worker/embedded-agent.runtime.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,6 @@ export async function runWorkerEmbeddedTurn(params: RunWorkerEmbeddedTurnParams)
317317
} catch (error) {
318318
finalTranscriptFailure = toWorkerAgentError(error, "Worker transcript flush failed.");
319319
}
320-
await liveRuntime.flush();
321320
if (finalTranscriptFailure === undefined) {
322321
await liveRuntime.emitTerminal();
323322
}

0 commit comments

Comments
 (0)