-
Notifications
You must be signed in to change notification settings - Fork 892
fix(combos): fail over zero-output stream failures, recording each terminal once #2449
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+579
−5
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| import type { ResponsesTerminalStatus } from "../../bridge"; | ||
| import type { RequestLogContext } from "../request-log"; | ||
| import { createSseInspector } from "../relay"; | ||
| import { MAX_CLIENT_SSE_FRAME_BYTES } from "../sse-frame-buffer"; | ||
|
|
||
| const COMBO_STREAM_PREFLIGHT_MAX_BYTES = MAX_CLIENT_SSE_FRAME_BYTES; | ||
|
|
||
| const PRE_OUTPUT_CONTROL_EVENTS = new Set([ | ||
| "response.created", | ||
| "response.in_progress", | ||
| "response.queued", | ||
| "response.heartbeat", | ||
| ]); | ||
|
|
||
| const TERMINAL_EVENTS = new Set([ | ||
| "response.completed", | ||
| "response.failed", | ||
| "response.incomplete", | ||
| ]); | ||
|
|
||
| /** | ||
| * Decide when replaying the request on another combo target would risk duplicating | ||
| * client-visible output or a tool-side effect. Unknown event types commit the child | ||
| * conservatively; only the small Responses lifecycle preamble remains replayable. | ||
| */ | ||
| export function comboStreamPayloadCommitsOutput(payload: unknown): boolean { | ||
| if (!payload || typeof payload !== "object" || Array.isArray(payload)) return true; | ||
| const type = (payload as { type?: unknown }).type; | ||
| if (typeof type !== "string") return true; | ||
| return !PRE_OUTPUT_CONTROL_EVENTS.has(type) && !TERMINAL_EVENTS.has(type); | ||
| } | ||
|
|
||
| function replayBufferedResponse( | ||
| response: Response, | ||
| reader: ReadableStreamDefaultReader<Uint8Array>, | ||
| buffered: Uint8Array[], | ||
| ): Response { | ||
| let index = 0; | ||
| const body = new ReadableStream<Uint8Array>({ | ||
| async pull(controller) { | ||
| if (index < buffered.length) { | ||
| controller.enqueue(buffered[index++]!); | ||
| return; | ||
| } | ||
| try { | ||
| const next = await reader.read(); | ||
| if (next.done) controller.close(); | ||
| else controller.enqueue(next.value); | ||
| } catch (error) { | ||
| try { controller.error(error); } catch { /* consumer already closed */ } | ||
| } | ||
| }, | ||
| cancel(reason) { | ||
| reader.cancel(reason).catch(() => undefined); | ||
| }, | ||
| }); | ||
| return new Response(body, { | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| headers: response.headers, | ||
| }); | ||
| } | ||
|
|
||
| function failedTerminalResponse( | ||
| response: Response, | ||
| terminalPayload: Record<string, unknown>, | ||
| logCtx: RequestLogContext, | ||
| ): Response { | ||
| const nested = terminalPayload.response; | ||
| const terminalResponse = nested && typeof nested === "object" && !Array.isArray(nested) | ||
| ? nested as Record<string, unknown> | ||
| : {}; | ||
| const nestedError = terminalResponse.error; | ||
| const error = nestedError && typeof nestedError === "object" && !Array.isArray(nestedError) | ||
| ? nestedError as Record<string, unknown> | ||
| : { | ||
| type: "upstream_error", | ||
| code: "upstream_server_error", | ||
| message: logCtx.upstreamError ?? "Provider stream failed before producing output", | ||
| }; | ||
| const headers = new Headers(response.headers); | ||
| headers.set("content-type", "application/json"); | ||
| headers.delete("content-length"); | ||
| headers.delete("content-encoding"); | ||
| const usage = terminalResponse.usage; | ||
| return new Response(JSON.stringify({ | ||
| error, | ||
| // The combo classifier needs only the error and optional usage. Do not carry | ||
| // response ids, provider metadata, or future terminal fields into the client | ||
| // error envelope merely because they shared the terminal snapshot. | ||
| response: { | ||
| error, | ||
| ...(usage && typeof usage === "object" && !Array.isArray(usage) ? { usage } : {}), | ||
| }, | ||
| }), { | ||
| status: logCtx.terminalHttpStatus ?? 502, | ||
| headers, | ||
| }); | ||
| } | ||
|
|
||
| export type ComboStreamPreflightResult = | ||
| | { kind: "accepted"; response: Response } | ||
| | { kind: "failed"; response: Response }; | ||
|
|
||
| /** | ||
| * Buffer a combo child's downstream SSE only until the request becomes unsafe to | ||
| * replay or reaches a terminal. This owns exactly one body reader. The aggregate | ||
| * buffer is capped; hitting the cap commits the current target instead of growing | ||
| * memory or guessing that replay is safe. | ||
| */ | ||
| export async function preflightComboStreamResponse( | ||
| response: Response, | ||
| logCtx: RequestLogContext, | ||
| ): Promise<ComboStreamPreflightResult> { | ||
| const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""; | ||
| if (!response.ok || !response.body || !contentType.includes("text/event-stream")) { | ||
| return { kind: "accepted", response }; | ||
| } | ||
|
|
||
| const reader = response.body.getReader(); | ||
| const buffered: Uint8Array[] = []; | ||
| let bufferedBytes = 0; | ||
| let outputCommitted = false; | ||
| let terminalStatus: ResponsesTerminalStatus | undefined; | ||
| let failedPayload: Record<string, unknown> | undefined; | ||
| const inspector = createSseInspector({ | ||
| logCtx, | ||
| onParsedPayload: payload => { | ||
| if (comboStreamPayloadCommitsOutput(payload)) outputCommitted = true; | ||
| if (!payload || typeof payload !== "object" || Array.isArray(payload)) return; | ||
| if ((payload as { type?: unknown }).type === "response.failed") { | ||
| failedPayload = payload as Record<string, unknown>; | ||
| } | ||
| }, | ||
| onTerminal: status => { terminalStatus = status; }, | ||
| }); | ||
|
|
||
| try { | ||
| for (;;) { | ||
| const next = await reader.read(); | ||
| if (next.done) { | ||
| inspector.finish(); | ||
| } else { | ||
| if (bufferedBytes + next.value.byteLength > COMBO_STREAM_PREFLIGHT_MAX_BYTES) { | ||
| // Keep the cap about memory the preflight allocates. The upstream chunk already exists; | ||
| // copying it before committing would transiently exceed the boundary for no | ||
| // replay benefit. Preserve it unsliced behind the already-bounded prefix. | ||
| return { | ||
| kind: "accepted", | ||
| response: replayBufferedResponse(response, reader, [...buffered, next.value]), | ||
| }; | ||
| } | ||
| const retained = next.value.slice(); | ||
| buffered.push(retained); | ||
| bufferedBytes += retained.byteLength; | ||
| inspector.feed(retained); | ||
| } | ||
|
|
||
| if (terminalStatus === "failed" && !outputCommitted && failedPayload) { | ||
| await reader.cancel("retrying zero-output combo stream failure").catch(() => undefined); | ||
| return { kind: "failed", response: failedTerminalResponse(response, failedPayload, logCtx) }; | ||
| } | ||
| if (next.done || terminalStatus !== undefined || outputCommitted | ||
| || bufferedBytes >= COMBO_STREAM_PREFLIGHT_MAX_BYTES) { | ||
| return { kind: "accepted", response: replayBufferedResponse(response, reader, buffered) }; | ||
| } | ||
| } | ||
| } finally { | ||
| inspector.dispose(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use unambiguous wording for
retryable.повторяемый terminalcan mean “repeatable” or “recurring terminal,” not “eligible for a retry.” The runtime retries a classifiedresponse.failedonly before output commitment. Replace this phrase with wording such asтерминальное событие ... для которого разрешена повторная попытка, or retainretryable, so the Russian page does not imply that terminal failures can generally be replayed.Suggested wording
As per path instructions, translated locale pages must stay in sync with the English source.
📝 Committable suggestion
🤖 Prompt for AI Agents
Source: Path instructions