Skip to content

Commit 69d3028

Browse files
fix(embedded-runner): flush partial streaming output before run budget abort (#116253)
Preserve visible streamed assistant text when the hard run budget expires. Drain queued stream events before terminal-owned salvage while keeping cancellations and provider failures non-salvaging. Co-authored-by: SunnyShu0925 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent c1aa335 commit 69d3028

18 files changed

Lines changed: 891 additions & 41 deletions

‎src/agents/embedded-agent-runner/run/abortable.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,19 @@ describe("joinWithRunLivenessDeadline", () => {
8282
});
8383
expect(onTimeout).not.toHaveBeenCalled();
8484
});
85+
86+
it("runs work without an abort signal and remains bounded", async () => {
87+
vi.useFakeTimers();
88+
try {
89+
const joinWork = vi.fn(() => new Promise<never>(() => {}));
90+
const onTimeout = vi.fn();
91+
const join = joinWithRunLivenessDeadline({ joinWork, onTimeout });
92+
await vi.advanceTimersByTimeAsync(RUN_LIVENESS_JOIN_TIMEOUT_MS);
93+
await join;
94+
expect(joinWork).toHaveBeenCalledOnce();
95+
expect(onTimeout).toHaveBeenCalledOnce();
96+
} finally {
97+
vi.useRealTimers();
98+
}
99+
});
85100
});

‎src/agents/embedded-agent-runner/run/abortable.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export const RUN_LIVENESS_JOIN_TIMEOUT_MS = 120_000;
4747
*/
4848
export function joinWithRunLivenessDeadline(input: {
4949
joinWork: () => Promise<void> | void;
50-
runAbortSignal: AbortSignal;
50+
runAbortSignal?: AbortSignal;
5151
timeoutMs?: number;
5252
onTimeout: () => void;
5353
}): Promise<void> {
@@ -59,7 +59,7 @@ export function joinWithRunLivenessDeadline(input: {
5959
}
6060
settled = true;
6161
clearTimeout(timer);
62-
input.runAbortSignal.removeEventListener("abort", onAbort);
62+
input.runAbortSignal?.removeEventListener("abort", onAbort);
6363
if (reason === "timeout") {
6464
input.onTimeout();
6565
}
@@ -71,11 +71,11 @@ export function joinWithRunLivenessDeadline(input: {
7171
input.timeoutMs ?? RUN_LIVENESS_JOIN_TIMEOUT_MS,
7272
);
7373
timer.unref?.();
74-
if (input.runAbortSignal.aborted) {
74+
if (input.runAbortSignal?.aborted) {
7575
finish("abort");
7676
return;
7777
}
78-
input.runAbortSignal.addEventListener("abort", onAbort, { once: true });
78+
input.runAbortSignal?.addEventListener("abort", onAbort, { once: true });
7979
Promise.resolve()
8080
.then(() => input.joinWork())
8181
.then(

‎src/agents/embedded-agent-runner/run/attempt-prompt-phase.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ function createFixture() {
261261
setFinalPromptText,
262262
markBeforeAgentRunBlocked,
263263
markYieldAborted,
264+
isRunBudgetTimeoutAbort: () => false,
264265
readYieldState: () => yieldState,
265266
stopAcceptingSteerMessages,
266267
takePendingMidTurnPrecheckRequest: () => undefined,
@@ -409,6 +410,36 @@ describe("runEmbeddedAttemptPromptPhase", () => {
409410
);
410411
});
411412

413+
it("keeps a run-budget timeout failure-free for partial-output salvage", async () => {
414+
const fixture = createFixture();
415+
const timeoutAbort = new Error("request timed out");
416+
mocks.submitPrompt.mockRejectedValueOnce(timeoutAbort);
417+
mocks.handlePromptError.mockResolvedValueOnce({
418+
promptFailure: { error: timeoutAbort, source: "prompt" },
419+
});
420+
fixture.input.lifecycle.isRunBudgetTimeoutAbort = (error) => error === timeoutAbort;
421+
422+
await runEmbeddedAttemptPromptPhase(fixture.input);
423+
424+
expect(fixture.state.promptError).toBeNull();
425+
expect(fixture.state.promptErrorSource).toBeNull();
426+
});
427+
428+
it("records a provider failure that races a run-budget timeout", async () => {
429+
const fixture = createFixture();
430+
const providerError = new Error("provider failed");
431+
mocks.submitPrompt.mockRejectedValueOnce(providerError);
432+
mocks.handlePromptError.mockResolvedValueOnce({
433+
promptFailure: { error: providerError, source: "prompt" },
434+
});
435+
fixture.input.lifecycle.isRunBudgetTimeoutAbort = () => false;
436+
437+
await runEmbeddedAttemptPromptPhase(fixture.input);
438+
439+
expect(fixture.state.promptError).toBe(providerError);
440+
expect(fixture.state.promptErrorSource).toBe("prompt");
441+
});
442+
412443
it("releases steering when preflight skips provider submission", async () => {
413444
const fixture = createFixture();
414445
const promptError = new Error("preflight rejected");

‎src/agents/embedded-agent-runner/run/attempt-prompt-phase.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ export async function runEmbeddedAttemptPromptPhase(input: {
140140
setFinalPromptText: (prompt: string) => void;
141141
markBeforeAgentRunBlocked: (outcome: BeforeAgentRunOutcome) => void;
142142
markYieldAborted: () => void;
143+
isRunBudgetTimeoutAbort: (error: unknown) => boolean;
143144
readYieldState: () => Pick<
144145
PromptErrorInput,
145146
"yieldAbortSettled" | "yieldDetected" | "yieldMessage"
@@ -398,7 +399,12 @@ export async function runEmbeddedAttemptPromptPhase(input: {
398399
withOwnedTranscriptWrite: input.withOwnedTranscriptWrite,
399400
...input.lifecycle.readYieldState(),
400401
});
401-
if (promptErrorOutcome.promptFailure) {
402+
// The timeout owner records its terminal before aborting the prompt. That
403+
// abort is not a provider failure and must leave timeout salvage eligible.
404+
if (
405+
promptErrorOutcome.promptFailure &&
406+
!input.lifecycle.isRunBudgetTimeoutAbort(promptErrorOutcome.promptFailure.error)
407+
) {
402408
patchState({
403409
promptError: promptErrorOutcome.promptFailure.error,
404410
promptErrorSource: promptErrorOutcome.promptFailure.source,

‎src/agents/embedded-agent-runner/run/attempt-settle.ts‎

Lines changed: 53 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@ import type { NormalizedUsage } from "../../usage.js";
1818
import { log } from "../logger.js";
1919
import type { PromptCacheBreak, PromptCacheChange } from "../prompt-cache-observability.js";
2020
import { clearActiveEmbeddedRun } from "../runs.js";
21-
import { joinWithRunLivenessDeadline, RUN_LIVENESS_JOIN_TIMEOUT_MS } from "./abortable.js";
21+
import {
22+
isOpenClawAbortableWrapper,
23+
joinWithRunLivenessDeadline,
24+
RUN_LIVENESS_JOIN_TIMEOUT_MS,
25+
} from "./abortable.js";
2226
import type {
2327
EmbeddedAttemptExecutionPhaseInput,
2428
EmbeddedAttemptExecutionState,
@@ -335,28 +339,60 @@ export async function runEmbeddedAttemptSettledPhase(
335339
source: "yield_cleanup",
336340
});
337341
},
342+
isRunBudgetTimeoutAbort: (error) =>
343+
readTerminal().timedOutByRunBudget &&
344+
isOpenClawAbortableWrapper(error) &&
345+
error instanceof Error &&
346+
error.cause === input.runAbortController.signal.reason,
338347
readYieldState: input.lifecycle.readYieldState,
339348
stopAcceptingSteerMessages,
340349
takePendingMidTurnPrecheckRequest: contextGuards.takePendingMidTurnPrecheckRequest,
341350
},
342351
});
343352

344-
// Queued subscription handlers (block-reply delivery, tool events) are
345-
// fire-and-forget during the turn; the pending-events join below is the only
346-
// place the run waits for them. One hung handler (e.g. a stuck delivery
347-
// dispatch lane) must not dead-end the turn until the run budget — 48h by
348-
// default — so the join is bounded and settlement proceeds with a recorded
349-
// warning instead of producing no visible outcome at all.
350-
await joinWithRunLivenessDeadline({
351-
joinWork: waitForPendingEvents,
352-
runAbortSignal: input.runAbortController.signal,
353-
onTimeout: () => {
354-
log.warn(
355-
`pending subscription events did not settle within ${RUN_LIVENESS_JOIN_TIMEOUT_MS}ms; ` +
356-
`proceeding to stream settlement: runId=${attempt.runId}`,
357-
);
358-
},
359-
});
353+
// Only a failure-free run-budget terminal may publish buffered text.
354+
const isFailureFreeRunBudgetTimeout = (): boolean => {
355+
const terminal = readTerminal();
356+
return terminal.timedOutByRunBudget && !terminal.failed;
357+
};
358+
const runBudgetTimeoutTerminal = isFailureFreeRunBudgetTimeout();
359+
const drainPendingEventsBounded = () =>
360+
joinWithRunLivenessDeadline({
361+
// Partial-reply callbacks cannot mutate the buffer and may be stalled
362+
// on transport; timeout salvage needs only the serialized event chain.
363+
joinWork: () => waitForPendingEvents({ includePartialReplies: false }),
364+
onTimeout: () => {
365+
log.warn(
366+
`pending subscription events did not settle within ${RUN_LIVENESS_JOIN_TIMEOUT_MS}ms; ` +
367+
`proceeding to stream settlement: runId=${attempt.runId}`,
368+
);
369+
},
370+
});
371+
if (runBudgetTimeoutTerminal) {
372+
// The timeout already aborted the signal; drain without racing it.
373+
await drainPendingEventsBounded();
374+
} else {
375+
await joinWithRunLivenessDeadline({
376+
joinWork: waitForPendingEvents,
377+
runAbortSignal: input.runAbortController.signal,
378+
onTimeout: () => {
379+
log.warn(
380+
`pending subscription events did not settle within ${RUN_LIVENESS_JOIN_TIMEOUT_MS}ms; ` +
381+
`proceeding to stream settlement: runId=${attempt.runId}`,
382+
);
383+
},
384+
});
385+
// A timeout can fire during the abort-aware join and resolve it before
386+
// its queue drains. Re-read terminal ownership, then drain if eligible.
387+
if (isFailureFreeRunBudgetTimeout()) {
388+
await drainPendingEventsBounded();
389+
}
390+
}
391+
// Ownership can change during the drain; publish only after the final read.
392+
const salvageTerminal = readTerminal();
393+
if (salvageTerminal.timedOutByRunBudget && !salvageTerminal.failed) {
394+
subscription.flushPartialAssistantText();
395+
}
360396
const beforeAgentFinalizeRevisionReason = getBeforeAgentFinalizeRevisionReason();
361397
const beforeAgentFinalizeRevisionEntryId = getBeforeAgentFinalizeRevisionEntryId();
362398
let rewoundBeforeAgentFinalizeRevision = false;

‎src/agents/embedded-agent-runner/run/attempt-spawn-workspace.test-support.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ function createSubscriptionMock(): SubscriptionMock {
138138
setTerminalLifecycleMeta: () => {},
139139
waitForCompactionRetry: async () => {},
140140
waitForPendingEvents: async () => {},
141+
flushPartialAssistantText: () => {},
141142
getAcceptedSessionSpawns: () => [],
142143
getMessagingToolSentTexts: () => [] as string[],
143144
getMessagingToolSentMediaUrls: () => [] as string[],

0 commit comments

Comments
 (0)