-
Notifications
You must be signed in to change notification settings - Fork 273
[Fix] Billed requests with no response when the provider errors mid-stream #1597
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
Draft
zoomote
wants to merge
11
commits into
main
Choose a base branch
from
fix/mid-stream-retry-limit-2s556ff4rta7j
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
79bf036
fix: bound mid-stream API retries and surface failures after retry limit
roomote ee1209b
test: model mid-stream retry lifecycle
roomote c701b82
fix: close retry lifecycle gaps
roomote 24d86f8
test: cover retry failure boundaries
roomote 34b2113
refactor: simplify retry message ownership
roomote 26e0547
test: scope retry mutation exclusions
roomote 45d13f2
test: isolate retry protocol mutations
roomote 48a86e1
refactor: make retry ownership explicit
roomote 4ea1fe5
refactor: centralize retry ownership defaults
roomote f852ba2
fix: remove exact request on approved retry
roomote 23613e5
test: cover exact retry message lookup
roomote 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| import { providerIdentifiers, RooCodeEventName, type ClineMessage } from "@roo-code/types" | ||
| import * as assert from "assert" | ||
|
|
||
| import { setDefaultSuiteTimeout } from "./test-utils" | ||
| import { isCompletedAsk, waitFor } from "./utils" | ||
|
|
||
| const PROBE = "mid-stream-retry-e2e:" | ||
|
|
||
| function installMidStreamFailureInterceptor(requests: { count: number }): () => void { | ||
| const originalFetch = globalThis.fetch | ||
|
|
||
| globalThis.fetch = async function (input: RequestInfo | URL, init?: RequestInit): Promise<Response> { | ||
| const body = typeof init?.body === "string" ? init.body : "" | ||
| if (body.includes(PROBE)) { | ||
| requests.count++ | ||
| return makePartialFailureResponse() | ||
| } | ||
| return originalFetch.call(globalThis, input, init as RequestInit) | ||
| } as typeof globalThis.fetch | ||
|
|
||
| return () => { | ||
| globalThis.fetch = originalFetch | ||
| } | ||
| } | ||
|
|
||
| function makePartialFailureResponse(): Response { | ||
| const encoder = new TextEncoder() | ||
| let emitted = false | ||
| const stream = new ReadableStream<Uint8Array>({ | ||
| pull(controller) { | ||
| if (!emitted) { | ||
| emitted = true | ||
| controller.enqueue( | ||
| encoder.encode( | ||
| `data: ${JSON.stringify({ | ||
| id: "mid-stream-failure", | ||
| object: "chat.completion.chunk", | ||
| model: "openai/gpt-4.1", | ||
| choices: [ | ||
| { index: 0, delta: { role: "assistant", content: "partial" }, finish_reason: null }, | ||
| ], | ||
| })}\n\n`, | ||
| ), | ||
| ) | ||
| return | ||
| } | ||
| controller.error(new Error("mid-stream provider failure")) | ||
| }, | ||
| }) | ||
|
|
||
| return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } }) | ||
| } | ||
|
|
||
| suite("Mid-stream retry", function () { | ||
| setDefaultSuiteTimeout(this) | ||
|
|
||
| let restoreFetch: (() => void) | undefined | ||
| const requests = { count: 0 } | ||
|
|
||
| suiteSetup(async () => { | ||
| restoreFetch = installMidStreamFailureInterceptor(requests) | ||
| const aimockUrl = process.env.AIMOCK_URL | ||
| await globalThis.api.setConfiguration({ | ||
| apiProvider: providerIdentifiers.openrouter, | ||
| openRouterApiKey: "mock-key", | ||
| openRouterModelId: "openai/gpt-4.1", | ||
| requestDelaySeconds: 1, | ||
| ...(aimockUrl && { openRouterBaseUrl: `${aimockUrl}/v1` }), | ||
| }) | ||
| }) | ||
|
|
||
| suiteTeardown(async () => { | ||
| restoreFetch?.() | ||
| restoreFetch = undefined | ||
| await globalThis.api.clearCurrentTask() | ||
| }) | ||
|
|
||
| test("bounds partial-stream retries and surfaces the failure prompt", async () => { | ||
| requests.count = 0 | ||
| const messages: ClineMessage[] = [] | ||
| const handler = ({ message }: { message: ClineMessage }) => messages.push(message) | ||
| globalThis.api.on(RooCodeEventName.Message, handler) | ||
|
|
||
| try { | ||
| await globalThis.api.startNewTask({ | ||
| configuration: { mode: "ask", autoApprovalEnabled: false }, | ||
| text: `${PROBE} fail after a partial provider response`, | ||
| }) | ||
|
|
||
| await waitFor( | ||
| () => messages.some((message) => isCompletedAsk(message) && message.ask === "api_req_failed"), | ||
| { timeout: 60_000 }, | ||
| ) | ||
| assert.strictEqual(requests.count, 4, "Should make one initial request and three automatic retries") | ||
| assert.ok( | ||
| messages.some((message) => message.type === "say" && message.say === "api_req_retry_delayed"), | ||
| "Should expose automatic retry backoff to the user", | ||
| ) | ||
|
|
||
| await new Promise((resolve) => setTimeout(resolve, 250)) | ||
| assert.strictEqual(requests.count, 4, "Waiting at the retry prompt must not issue another billed request") | ||
| } finally { | ||
| globalThis.api.off(RooCodeEventName.Message, handler) | ||
| } | ||
| }) | ||
| }) | ||
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,162 @@ | ||
| import assert from "node:assert/strict" | ||
|
|
||
| import { decideMidStreamFailure, MAX_MID_STREAM_RETRIES } from "../src/core/task/midStreamRetry" | ||
|
|
||
| type Phase = "requesting" | "backoff" | "awaiting-user" | "stopped" | "succeeded" | ||
|
|
||
| interface ModelState { | ||
| phase: Phase | ||
| stopReason?: "decline" | "backoff-abort" | "prompt-abort" | ||
| retryAttempt: number | ||
| requests: number | ||
| announcements: number | ||
| roundsApproved: number | ||
| } | ||
|
|
||
| interface Transition { | ||
| name: string | ||
| next: ModelState | ||
| } | ||
|
|
||
| interface TraceStep { | ||
| action: string | ||
| state: ModelState | ||
| } | ||
|
|
||
| const MAX_APPROVED_ROUNDS = 1 | ||
| const MAX_DEPTH = 16 | ||
| const MAX_STATES = 100 | ||
| const expectedActions = ["fail", "retry", "approve", "decline", "abort-backoff", "abort-prompt", "succeed"] as const | ||
| const landmarks = { | ||
| "automatic-budget-exhausted": (state: ModelState) => | ||
| state.phase === "awaiting-user" && state.requests === MAX_MID_STREAM_RETRIES + 1, | ||
| "approved-round-reset": (state: ModelState) => | ||
| state.roundsApproved === 1 && state.phase === "requesting" && state.retryAttempt === 0, | ||
| "declined-after-approved-round": (state: ModelState) => | ||
| state.roundsApproved === 1 && state.stopReason === "decline", | ||
| "backoff-cancelled": (state: ModelState) => state.stopReason === "backoff-abort", | ||
| "prompt-cancelled": (state: ModelState) => state.stopReason === "prompt-abort", | ||
| } satisfies Record<string, (state: ModelState) => boolean> | ||
|
|
||
| function initialState(): ModelState { | ||
| return { phase: "requesting", retryAttempt: 0, requests: 1, announcements: 0, roundsApproved: 0 } | ||
| } | ||
|
|
||
| function transitions(state: ModelState): Transition[] { | ||
| if (state.phase === "requesting") { | ||
| const decision = decideMidStreamFailure(state.retryAttempt) | ||
| return [ | ||
| { name: "fail", next: { ...state, phase: decision === "retry" ? "backoff" : "awaiting-user" } }, | ||
| { name: "succeed", next: { ...state, phase: "succeeded" } }, | ||
| ] | ||
| } | ||
| if (state.phase === "backoff") { | ||
| return [ | ||
| { | ||
| name: "retry", | ||
| next: { | ||
| ...state, | ||
| phase: "requesting", | ||
| retryAttempt: state.retryAttempt + 1, | ||
| requests: state.requests + 1, | ||
| announcements: state.announcements + 1, | ||
| }, | ||
| }, | ||
| { name: "abort-backoff", next: { ...state, phase: "stopped", stopReason: "backoff-abort" } }, | ||
| ] | ||
| } | ||
| if (state.phase === "awaiting-user") { | ||
| const result: Transition[] = [ | ||
| { name: "decline", next: { ...state, phase: "stopped", stopReason: "decline" } }, | ||
| { name: "abort-prompt", next: { ...state, phase: "stopped", stopReason: "prompt-abort" } }, | ||
| ] | ||
| if (state.roundsApproved < MAX_APPROVED_ROUNDS) { | ||
| result.push({ | ||
| name: "approve", | ||
| next: { | ||
| ...state, | ||
| phase: "requesting", | ||
| retryAttempt: 0, | ||
| requests: state.requests + 1, | ||
| roundsApproved: state.roundsApproved + 1, | ||
| }, | ||
| }) | ||
| } | ||
| return result | ||
| } | ||
| return [] | ||
| } | ||
|
|
||
| function invariantViolations(state: ModelState): string[] { | ||
| const violations: string[] = [] | ||
| if (state.announcements !== state.requests - 1 - state.roundsApproved) { | ||
| violations.push("every automatic retry must have exactly one user-visible announcement") | ||
| } | ||
| if (state.retryAttempt > MAX_MID_STREAM_RETRIES) { | ||
| violations.push("an automatic retry exceeded the configured retry budget") | ||
| } | ||
| if (state.phase === "awaiting-user" && state.retryAttempt !== MAX_MID_STREAM_RETRIES) { | ||
| violations.push("user input must be requested exactly when the automatic retry budget is exhausted") | ||
| } | ||
| return violations | ||
| } | ||
|
|
||
| function canonical(state: ModelState): string { | ||
| return JSON.stringify(state) | ||
| } | ||
|
|
||
| function formatCounterexample(message: string, trace: TraceStep[]): string { | ||
| return [ | ||
| `Mid-stream retry invariant failed: ${message}`, | ||
| `Bounds: depth=${MAX_DEPTH}, states=${MAX_STATES}, approvedRounds=${MAX_APPROVED_ROUNDS}`, | ||
| ...trace.map((step, index) => `${index}. ${step.action} ${JSON.stringify(step.state)}`), | ||
| ].join("\n") | ||
| } | ||
|
|
||
| function runModelCheck(): number { | ||
| const start = initialState() | ||
| const queue: Array<{ state: ModelState; trace: TraceStep[] }> = [ | ||
| { state: start, trace: [{ action: "initial", state: start }] }, | ||
| ] | ||
| const visited = new Set([canonical(start)]) | ||
| const reachedActions = new Set<string>() | ||
| const reachedLandmarks = new Set<string>() | ||
| const frontier: ModelState[] = [] | ||
|
|
||
| for (let index = 0; index < queue.length; index++) { | ||
| const node = queue[index]! | ||
| for (const [name, predicate] of Object.entries(landmarks)) { | ||
| if (predicate(node.state)) reachedLandmarks.add(name) | ||
| } | ||
| const violations = invariantViolations(node.state) | ||
| if (violations.length) throw new Error(formatCounterexample(violations.join("; "), node.trace)) | ||
| if (node.trace.length - 1 === MAX_DEPTH) { | ||
| frontier.push(node.state) | ||
| continue | ||
| } | ||
| for (const transition of transitions(node.state)) { | ||
| reachedActions.add(transition.name) | ||
| const key = canonical(transition.next) | ||
| if (visited.has(key)) continue | ||
| visited.add(key) | ||
| queue.push({ | ||
| state: transition.next, | ||
| trace: [...node.trace, { action: transition.name, state: transition.next }], | ||
| }) | ||
| if (visited.size > MAX_STATES) throw new Error(`Mid-stream retry model exceeded ${MAX_STATES} states`) | ||
| } | ||
| } | ||
|
|
||
| const unreachableActions = expectedActions.filter((action) => !reachedActions.has(action)) | ||
| assert.deepEqual(unreachableActions, [], `Unreachable actions: ${unreachableActions.join(", ")}`) | ||
| const missingLandmarks = Object.keys(landmarks).filter((name) => !reachedLandmarks.has(name)) | ||
| assert.deepEqual(missingLandmarks, [], `Unreachable landmarks: ${missingLandmarks.join(", ")}`) | ||
| const unexploredSuccessor = frontier.flatMap(transitions).find((next) => !visited.has(canonical(next.next))) | ||
| assert.equal(unexploredSuccessor, undefined, "Increase MAX_DEPTH to cover unseen successors") | ||
| return visited.size | ||
| } | ||
|
|
||
| const checkedStates = runModelCheck() | ||
| console.log( | ||
| `Mid-stream retry model check passed: ${checkedStates} reachable states, ${expectedActions.length}/${expectedActions.length} actions reachable, ${Object.keys(landmarks).length}/${Object.keys(landmarks).length} landmarks reached, depth <= ${MAX_DEPTH}`, | ||
| ) |
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.
Uh oh!
There was an error while loading. Please reload this page.