From 073013a61b9f2da17147b7845e030836fbd5f218 Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 4 Dec 2026 15:19:52 +0100 Subject: [PATCH 1/2] fix(gemini): repair streams that end with an unframed final event (#2682) The @google/genai SDK reader ends an SSE stream that closed without a final event delimiter with 'Incomplete JSON segment at the end', even when every complete event was already delivered. createMessage surfaced that as a hard provider error, losing the streamed response. Two repairs, modelled by GeminiStreamEnd.tla (spec + 4 cfgs in the same commit; base passes, each sabotage fails its named invariant): - a zero-delivery unframed end on the first attempt retries the request once, because a redo is clean before the first yield; - an unframed end after delivered events completes the stream with the events already yielded instead of failing the turn. Aborts surface before any tolerance; unrelated stream errors are untouched. Tests red-verified on the pre-fix tree. TLC: GeminiStreamEnd.cfg pass (35 states); Raw fails UnframedEndCompletes, RetryOff fails ZeroDeliveryRetried, AbortMasked fails AbortSurfaces, SwallowAll fails OtherErrorsSurface. Gates: test:core 5316 passed, test:api 6427 passed, gemini.spec.ts 117 passed, tsc --noEmit, eslint --max-warnings=0, prettier --check. Closes #2682 --- .../tla/GeminiStreamEnd.AbortMasked.cfg | 6 + docs/architecture/tla/GeminiStreamEnd.Raw.cfg | 6 + .../tla/GeminiStreamEnd.RetryOff.cfg | 6 + .../tla/GeminiStreamEnd.SwallowAll.cfg | 6 + docs/architecture/tla/GeminiStreamEnd.cfg | 6 + docs/architecture/tla/GeminiStreamEnd.tla | 100 +++++++ src/api/providers/__tests__/gemini.spec.ts | 154 ++++++++++ src/api/providers/gemini.ts | 277 ++++++++++-------- 8 files changed, 444 insertions(+), 117 deletions(-) create mode 100644 docs/architecture/tla/GeminiStreamEnd.AbortMasked.cfg create mode 100644 docs/architecture/tla/GeminiStreamEnd.Raw.cfg create mode 100644 docs/architecture/tla/GeminiStreamEnd.RetryOff.cfg create mode 100644 docs/architecture/tla/GeminiStreamEnd.SwallowAll.cfg create mode 100644 docs/architecture/tla/GeminiStreamEnd.cfg create mode 100644 docs/architecture/tla/GeminiStreamEnd.tla diff --git a/docs/architecture/tla/GeminiStreamEnd.AbortMasked.cfg b/docs/architecture/tla/GeminiStreamEnd.AbortMasked.cfg new file mode 100644 index 00000000000..0639224a136 --- /dev/null +++ b/docs/architecture/tla/GeminiStreamEnd.AbortMasked.cfg @@ -0,0 +1,6 @@ +CONSTANT TolerateUnframed = TRUE +CONSTANT AbortFirst = FALSE +CONSTANT TolerateAnyError = FALSE +CONSTANT RetryZero = TRUE +SPECIFICATION Spec +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried diff --git a/docs/architecture/tla/GeminiStreamEnd.Raw.cfg b/docs/architecture/tla/GeminiStreamEnd.Raw.cfg new file mode 100644 index 00000000000..129203aeed2 --- /dev/null +++ b/docs/architecture/tla/GeminiStreamEnd.Raw.cfg @@ -0,0 +1,6 @@ +CONSTANT TolerateUnframed = FALSE +CONSTANT AbortFirst = TRUE +CONSTANT TolerateAnyError = FALSE +CONSTANT RetryZero = TRUE +SPECIFICATION Spec +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried diff --git a/docs/architecture/tla/GeminiStreamEnd.RetryOff.cfg b/docs/architecture/tla/GeminiStreamEnd.RetryOff.cfg new file mode 100644 index 00000000000..26d20e30a01 --- /dev/null +++ b/docs/architecture/tla/GeminiStreamEnd.RetryOff.cfg @@ -0,0 +1,6 @@ +CONSTANT TolerateUnframed = TRUE +CONSTANT AbortFirst = TRUE +CONSTANT TolerateAnyError = FALSE +CONSTANT RetryZero = FALSE +SPECIFICATION Spec +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried diff --git a/docs/architecture/tla/GeminiStreamEnd.SwallowAll.cfg b/docs/architecture/tla/GeminiStreamEnd.SwallowAll.cfg new file mode 100644 index 00000000000..84514a61553 --- /dev/null +++ b/docs/architecture/tla/GeminiStreamEnd.SwallowAll.cfg @@ -0,0 +1,6 @@ +CONSTANT TolerateUnframed = TRUE +CONSTANT AbortFirst = TRUE +CONSTANT TolerateAnyError = TRUE +CONSTANT RetryZero = TRUE +SPECIFICATION Spec +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried diff --git a/docs/architecture/tla/GeminiStreamEnd.cfg b/docs/architecture/tla/GeminiStreamEnd.cfg new file mode 100644 index 00000000000..aabf36e9af9 --- /dev/null +++ b/docs/architecture/tla/GeminiStreamEnd.cfg @@ -0,0 +1,6 @@ +CONSTANT TolerateUnframed = TRUE +CONSTANT AbortFirst = TRUE +CONSTANT TolerateAnyError = FALSE +CONSTANT RetryZero = TRUE +SPECIFICATION Spec +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried diff --git a/docs/architecture/tla/GeminiStreamEnd.tla b/docs/architecture/tla/GeminiStreamEnd.tla new file mode 100644 index 00000000000..93ae3a7f606 --- /dev/null +++ b/docs/architecture/tla/GeminiStreamEnd.tla @@ -0,0 +1,100 @@ +---- MODULE GeminiStreamEnd ---- +\* Source: the SDK stream iterator that GeminiHandler.createMessage consumes +\* (models.generateContentStream). Sink: the createMessage completion decision +\* after the consumption loop. +\* Failure: a stream that ends while its final event is still unframed raised +\* a hard provider error, so delivered events were lost behind 'Incomplete +\* JSON segment at the end' (issue 2682), and a first-attempt end with no +\* delivered event failed instead of retrying the clean request. +\* Invariants: UnframedEndCompletes, AbortSurfaces, OtherErrorsSurface, +\* ZeroDeliveryRetried. +\* Expect Raw to fail UnframedEndCompletes, RetryOff to fail ZeroDeliveryRetried, +\* AbortMasked to fail AbortSurfaces and SwallowAll to fail OtherErrorsSurface. +\* Result: fixed passes in 35 states; Raw (23), RetryOff (12), AbortMasked (16) +\* and SwallowAll (18) each fail exactly the invariant named above. Each +\* sabotage run takes less than 1 second; the whole gate runs in seconds. +\* Findings: no model failure beyond the pinned defects. A RetryOff run first +\* passed vacuously because the invariant read the RetryZero constant; the +\* invariant is now an unconditional unreachability claim. +\* False alarms: none. The retry restarts the settlement, so a second unframed +\* end still surfaces; OtherErrorsSurface stays unconditional on purpose. +\* The provider test replays every invariant sentence on the real handler. +\* Review: 0 covered, 0 added, 0 gap (first round). +\* Cost: about 15 minutes of agent work; each TLC run takes less than 1 second. +\* The SDK settlement names are oracles; the delivered event values are +\* outside this model (Task consumes them). +EXTENDS Naturals + +CONSTANTS TolerateUnframed, AbortFirst, TolerateAnyError, RetryZero + +VARIABLES settlement, aborted, delivered, attempts, outcome +vars == <> + +Settlements == {"clean", "unframed", "otherError"} +Outcomes == {"completed", "providerError", "abortError", "none"} + +\* The sink decision is a pure policy over how the iterator settled, whether +\* the request was aborted, whether an event was delivered, and the attempt. +Surface(settle, ab, del, att) == + \* An abort check that runs first never lets tolerance mask the abort. + IF AbortFirst /\ ab THEN "abortError" + \* A tolerance broad enough to cover every error is the SwallowAll defect. + ELSE IF TolerateAnyError /\ settle # "clean" THEN "completed" + \* A tolerance applied before the abort check masks it (AbortMasked defect). + ELSE IF ~AbortFirst /\ TolerateUnframed /\ settle = "unframed" THEN "completed" + ELSE IF ab THEN "abortError" + ELSE IF settle = "clean" THEN "completed" + \* The fix: an unframed end still delivered every complete event. + ELSE IF settle = "unframed" /\ TolerateUnframed /\ del THEN "completed" + ELSE "providerError" + +\* A zero-delivery unframed end on the first attempt retries the request: +\* nothing was yielded, so a redo is clean. +CanRetry == RetryZero /\ settlement = "unframed" /\ ~aborted /\ ~delivered /\ attempts = 0 + +Init == /\ settlement \in Settlements + /\ aborted \in BOOLEAN + /\ delivered = FALSE + /\ attempts = 0 + /\ outcome = "none" + +Deliver == /\ outcome = "none" /\ ~delivered + /\ delivered' = TRUE + /\ UNCHANGED <> + +Settle == /\ outcome = "none" /\ ~CanRetry + /\ outcome' = Surface(settlement, aborted, delivered, attempts) + /\ UNCHANGED <> + +Retry == /\ CanRetry /\ outcome = "none" + /\ attempts' = 1 + /\ settlement' \in Settlements + /\ delivered' = FALSE + /\ UNCHANGED <> + +\* A settled outcome is terminal; the stuttering step keeps TLC's deadlock +\* check meaningful for states that are stuck before settling. +Termination == outcome # "none" /\ UNCHANGED vars + +Next == Deliver \/ Settle \/ Retry \/ Termination + +Spec == Init /\ [][Next]_vars + +UnframedEndCompletes == + (outcome # "none" /\ settlement = "unframed" /\ ~aborted /\ delivered) => + outcome = "completed" + +AbortSurfaces == (outcome # "none" /\ aborted) => outcome = "abortError" + +OtherErrorsSurface == + (outcome # "none" /\ settlement = "otherError" /\ ~aborted) => + outcome = "providerError" + +\* A settled zero-delivery unframed end on the first attempt must be +\* unreachable: the policy retries it instead of failing it. The claim is +\* unconditional, so switching RetryZero off in a sabotage run violates it. +ZeroDeliveryRetried == + ~(outcome # "none" /\ settlement = "unframed" /\ ~aborted /\ + ~delivered /\ attempts = 0) + +==== diff --git a/src/api/providers/__tests__/gemini.spec.ts b/src/api/providers/__tests__/gemini.spec.ts index 9a2ed7d3c21..60c9a019ae1 100644 --- a/src/api/providers/__tests__/gemini.spec.ts +++ b/src/api/providers/__tests__/gemini.spec.ts @@ -1887,4 +1887,158 @@ describe("GeminiHandler", () => { expect(pulls).toBe(2) }) }) + + describe("createMessage stream end truncation (issue #2682)", () => { + const messages: Anthropic.Messages.MessageParam[] = [ + { + role: "user", + content: "Hello", + }, + ] + + // The @google/genai SDK reader throws this exact message when the SSE + // stream closes while its final event is still unframed (no trailing + // delimiter), even though every complete event was already delivered. + const INCOMPLETE_JSON_SEGMENT = "Incomplete JSON segment at the end" + + function makePartsChunk(parts: Array>) { + return { + candidates: [ + { + content: { parts }, + }, + ], + } + } + + function makeUsageChunk() { + return { + candidates: [{ finishReason: "STOP" }], + usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 5 }, + } + } + + function startStreamWith(generator: AsyncGenerator, signal?: AbortSignal) { + handler["client"].models.generateContentStream = vi.fn().mockReturnValue(generator) + return handler.createMessage( + "You are a helpful assistant", + messages, + makeCreateMessageMetadata({ abortSignal: signal }), + ) + } + + async function* settlementStream( + settlement: string, + abortedController?: AbortController, + ): AsyncGenerator { + yield makePartsChunk([{ text: "first chunk" }]) + if (abortedController) { + abortedController.abort() + } + if (settlement === "unframed") { + throw new Error(INCOMPLETE_JSON_SEGMENT) + } + if (settlement === "otherError") { + throw new Error("connection reset while reading the response body") + } + } + + it("completes the stream when the SDK ends with an unframed final event, keeping delivered text and usage", async () => { + async function* truncated(): AsyncGenerator { + yield makePartsChunk([{ text: "surviving content" }]) + yield makeUsageChunk() + throw new Error(INCOMPLETE_JSON_SEGMENT) + } + + const chunks = await collectStream(startStreamWith(truncated())) + expect( + chunks.filter((c) => c.type === "text").map((c) => (c as { type: "text"; text: string }).text), + ).toStrictEqual(["surviving content"]) + expect(chunks.some((c) => c.type === "usage")).toBe(true) + expect(mockCaptureException).not.toHaveBeenCalled() + }) + + it.each([ + { settlement: "clean", aborted: false }, + { settlement: "clean", aborted: true }, + { settlement: "unframed", aborted: false }, + { settlement: "unframed", aborted: true }, + { settlement: "otherError", aborted: false }, + { settlement: "otherError", aborted: true }, + ])( + "surfaces the contract outcome for a $settlement stream end with abort=$aborted", + async ({ settlement, aborted }) => { + const controller = new AbortController() + const stream = startStreamWith( + settlementStream(settlement, aborted ? controller : undefined), + controller.signal, + ) + + if (!aborted) { + if (settlement === "otherError") { + // An unrelated stream error still surfaces as a provider error. + await expect(collectStream(stream)).rejects.toThrow() + return + } + const chunks = await collectStream(stream) + expect(chunks.some((c) => c.type === "text")).toBe(true) + return + } + + const error = await collectStream(stream).catch((e: unknown) => e) + expect(error).toBeInstanceOf(Error) + expect((error as Error).name).toBe("AbortError") + expect((error as Error).message).toBe("The Gemini request was aborted") + }, + ) + + it("still fails on an unrelated mid-stream error", async () => { + await expect(collectStream(startStreamWith(settlementStream("otherError")))).rejects.toThrow() + // The surfaced failure is the provider error, not a silent completion. + expect(mockCaptureException).toHaveBeenCalledTimes(1) + const capturedError = mockCaptureException.mock.calls[0][0] + expect(capturedError).toBeInstanceOf(ApiProviderError) + }) + + // A non-generator iterable: the ESLint require-yield rule rejects a + // generator that only throws. + function streamThatThrowsImmediately(error: Error): AsyncIterable { + return { + [Symbol.asyncIterator]() { + return { + next: async (): Promise> => { + throw error + }, + } + }, + } + } + + it("retries the request once when an unframed end delivers nothing", async () => { + const secondAttempt = asyncStreamFrom([makePartsChunk([{ text: "retried content" }])]) + const mockStream = vi + .fn() + .mockReturnValueOnce(streamThatThrowsImmediately(new Error(INCOMPLETE_JSON_SEGMENT))) + .mockReturnValueOnce(secondAttempt) + handler["client"].models.generateContentStream = mockStream + + const chunks = await collectStream(handler.createMessage("You are a helpful assistant", messages)) + expect( + chunks.filter((c) => c.type === "text").map((c) => (c as { type: "text"; text: string }).text), + ).toStrictEqual(["retried content"]) + expect(mockStream).toHaveBeenCalledTimes(2) + }) + + it("surfaces the error after a second unframed end that again delivers nothing", async () => { + const mockStream = vi + .fn() + .mockImplementation(() => streamThatThrowsImmediately(new Error(INCOMPLETE_JSON_SEGMENT))) + handler["client"].models.generateContentStream = mockStream + + await expect( + collectStream(handler.createMessage("You are a helpful assistant", messages)), + ).rejects.toThrow() + expect(mockStream).toHaveBeenCalledTimes(2) + }) + }) }) diff --git a/src/api/providers/gemini.ts b/src/api/providers/gemini.ts index e3e02430e50..5d356f01d0a 100644 --- a/src/api/providers/gemini.ts +++ b/src/api/providers/gemini.ts @@ -234,6 +234,11 @@ function assertSecureGeminiBaseUrl(baseUrl: string, modelId: string, operation: ) } +// The @google/genai SDK reader ends an SSE stream that closed without a +// final event delimiter with this exact message, even though every +// complete event was already delivered (issue #2682). +const INCOMPLETE_JSON_SEGMENT = "Incomplete JSON segment at the end" + export class GeminiHandler extends BaseProvider implements SingleCompletionHandler { protected options: ApiHandlerOptions @@ -436,150 +441,188 @@ export class GeminiHandler extends BaseProvider implements SingleCompletionHandl } try { - const result = await this.client.models.generateContentStream(params) - - let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined - let pendingGroundingMetadata: GroundingMetadata | undefined - let finalResponse: { responseId?: string } | undefined - // Gemini provides no call ID, so one is synthesized here. The // request-unique component keeps persisted pending-action IDs (#1714) // distinct across requests even though the counter restarts at zero. + // The ID stays stable across the retry attempt below. const toolCallRequestId = crypto.randomUUID() - let toolCallCounter = 0 - for await (const chunk of result) { - // Stop consuming buffered chunks once the request is aborted (the - // SDK iterator may keep delivering buffered content after abort). - if (requestSignal?.aborted) { - break - } + // The SDK reader ends an SSE stream that closed without a final event + // delimiter with 'Incomplete JSON segment at the end' (issue #2682). + // Two repairs keep the response alive: an end that delivered nothing + // retries the request once, because a redo is clean before the first + // yield; an end after delivered events completes with them instead of + // failing the turn and losing what was already streamed. + for (let attempt = 0; ; attempt++) { + let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined + let pendingGroundingMetadata: GroundingMetadata | undefined + let finalResponse: { responseId?: string } | undefined + let toolCallCounter = 0 + let deliveredEvents = 0 - // Track the final structured response (per SDK pattern: candidate.finishReason) - if (chunk.candidates && chunk.candidates[0]?.finishReason) { - finalResponse = chunk as { responseId?: string } - } - // Process candidates and their parts to separate thoughts from content - if (chunk.candidates && chunk.candidates.length > 0) { - const candidate = chunk.candidates[0] + try { + const result = await this.client.models.generateContentStream(params) - if (candidate.groundingMetadata) { - pendingGroundingMetadata = candidate.groundingMetadata - } + for await (const chunk of result) { + // Stop consuming buffered chunks once the request is aborted (the + // SDK iterator may keep delivering buffered content after abort). + if (requestSignal?.aborted) { + break + } - if (candidate.content && candidate.content.parts) { - for (const part of candidate.content.parts as Array<{ - thought?: boolean - text?: string - thoughtSignature?: string - functionCall?: { name: string; args: Record } - }>) { - // Capture thought signatures so they can be persisted into API history. - const thoughtSignature = part.thoughtSignature - // Persist thought signatures so they can be round-tripped in the next step. - // Gemini 3 requires this during tool calling; other Gemini thinking models - // benefit from it for continuity. - if (includeThoughtSignatures && thoughtSignature) { - this.lastThoughtSignature = thoughtSignature + // Track the final structured response (per SDK pattern: candidate.finishReason) + if (chunk.candidates && chunk.candidates[0]?.finishReason) { + finalResponse = chunk as { responseId?: string } + } + // Process candidates and their parts to separate thoughts from content + if (chunk.candidates && chunk.candidates.length > 0) { + const candidate = chunk.candidates[0] + + if (candidate.groundingMetadata) { + pendingGroundingMetadata = candidate.groundingMetadata } - if (part.thought) { - // This is a thinking/reasoning part - if (part.text) { - // Re-check before emitting: the consumer may have aborted - // while processing a previously yielded part of this chunk. - throwIfAborted(requestSignal) - yield { type: "reasoning", text: part.text } - } - } else if (part.functionCall) { - // Gemini sends complete function calls in a single chunk - // Emit as partial chunks for consistent handling with NativeToolCallParser - const callId = `${part.functionCall.name}-${toolCallRequestId}-${toolCallCounter}` - const args = JSON.stringify(part.functionCall.args) - - // Emit name first - throwIfAborted(requestSignal) - yield { - type: "tool_call_partial", - index: toolCallCounter, - id: callId, - name: part.functionCall.name, - arguments: undefined, + if (candidate.content && candidate.content.parts) { + for (const part of candidate.content.parts as Array<{ + thought?: boolean + text?: string + thoughtSignature?: string + functionCall?: { name: string; args: Record } + }>) { + // Capture thought signatures so they can be persisted into API history. + const thoughtSignature = part.thoughtSignature + // Persist thought signatures so they can be round-tripped in the next step. + // Gemini 3 requires this during tool calling; other Gemini thinking models + // benefit from it for continuity. + if (includeThoughtSignatures && thoughtSignature) { + this.lastThoughtSignature = thoughtSignature + } + + if (part.thought) { + // This is a thinking/reasoning part + if (part.text) { + // Re-check before emitting: the consumer may have aborted + // while processing a previously yielded part of this chunk. + throwIfAborted(requestSignal) + deliveredEvents++ + yield { type: "reasoning", text: part.text } + } + } else if (part.functionCall) { + // Gemini sends complete function calls in a single chunk + // Emit as partial chunks for consistent handling with NativeToolCallParser + const callId = `${part.functionCall.name}-${toolCallRequestId}-${toolCallCounter}` + const args = JSON.stringify(part.functionCall.args) + + // Emit name first + throwIfAborted(requestSignal) + deliveredEvents++ + yield { + type: "tool_call_partial", + index: toolCallCounter, + id: callId, + name: part.functionCall.name, + arguments: undefined, + } + + // Then emit arguments + throwIfAborted(requestSignal) + deliveredEvents++ + yield { + type: "tool_call_partial", + index: toolCallCounter, + id: callId, + name: undefined, + arguments: args, + } + + toolCallCounter++ + } else { + // This is regular content + if (part.text) { + throwIfAborted(requestSignal) + deliveredEvents++ + yield { type: "text", text: part.text } + } + } } + } + } - // Then emit arguments - throwIfAborted(requestSignal) - yield { - type: "tool_call_partial", - index: toolCallCounter, - id: callId, - name: undefined, - arguments: args, - } + // Fallback to the original text property if no candidates structure + // (no pre-yield guard here: this is the only yield of a fallback + // chunk, and the top-of-loop check runs without a suspension point + // before it). + else if (chunk.text) { + deliveredEvents++ + yield { type: "text", text: chunk.text } + } - toolCallCounter++ - } else { - // This is regular content - if (part.text) { - throwIfAborted(requestSignal) - yield { type: "text", text: part.text } - } - } + if (chunk.usageMetadata) { + lastUsageMetadata = chunk.usageMetadata } } + } catch (error) { + if (isRequestAborted(error, metadata?.abortSignal)) { + // Abort normalization stays in the outer catch; never retry or + // complete a cancelled stream. + throw error + } + const unframedEnd = error instanceof Error && error.message === INCOMPLETE_JSON_SEGMENT + if (unframedEnd && deliveredEvents === 0 && attempt === 0) { + // Nothing was yielded to the caller, so the request can be + // redone cleanly instead of surfacing a truncated stream. + continue + } + if (!unframedEnd || deliveredEvents === 0) { + throw error + } + // An unframed end after delivered events completes the stream: + // every complete event was already yielded above. } - // Fallback to the original text property if no candidates structure - // (no pre-yield guard here: this is the only yield of a fallback - // chunk, and the top-of-loop check runs without a suspension point - // before it). - else if (chunk.text) { - yield { type: "text", text: chunk.text } - } + // An aborted request must surface as an AbortError, not as a normal + // stream completion: the top-of-loop break (or a swallowed mid-stream + // abort) ends the loop without throwing otherwise. + throwIfAborted(requestSignal) - if (chunk.usageMetadata) { - lastUsageMetadata = chunk.usageMetadata + if (finalResponse?.responseId) { + // Capture responseId so Task.addToApiConversationHistory can store it + // alongside the assistant message in api_history.json. + this.lastResponseId = finalResponse.responseId } - } - - // An aborted request must surface as an AbortError, not as a normal - // stream completion: the top-of-loop break (or a swallowed mid-stream - // abort) ends the loop without throwing otherwise. - throwIfAborted(requestSignal) - if (finalResponse?.responseId) { - // Capture responseId so Task.addToApiConversationHistory can store it - // alongside the assistant message in api_history.json. - this.lastResponseId = finalResponse.responseId - } - - if (pendingGroundingMetadata) { - const sources = this.extractGroundingSources(pendingGroundingMetadata) - if (sources.length > 0) { - yield { type: "grounding", sources } + if (pendingGroundingMetadata) { + const sources = this.extractGroundingSources(pendingGroundingMetadata) + if (sources.length > 0) { + yield { type: "grounding", sources } + } } - } - if (lastUsageMetadata) { - const inputTokens = lastUsageMetadata.promptTokenCount ?? 0 - const outputTokens = lastUsageMetadata.candidatesTokenCount ?? 0 - const cacheReadTokens = lastUsageMetadata.cachedContentTokenCount - const reasoningTokens = lastUsageMetadata.thoughtsTokenCount - - yield { - type: "usage", - inputTokens, - outputTokens, - cacheReadTokens, - reasoningTokens, - totalCost: this.calculateCost({ - info, + if (lastUsageMetadata) { + const inputTokens = lastUsageMetadata.promptTokenCount ?? 0 + const outputTokens = lastUsageMetadata.candidatesTokenCount ?? 0 + const cacheReadTokens = lastUsageMetadata.cachedContentTokenCount + const reasoningTokens = lastUsageMetadata.thoughtsTokenCount + + yield { + type: "usage", inputTokens, outputTokens, cacheReadTokens, reasoningTokens, - }), + totalCost: this.calculateCost({ + info, + inputTokens, + outputTokens, + cacheReadTokens, + reasoningTokens, + }), + } } + + // The attempt loop only ever runs one pass past a tolerated end: a + // clean or completed stream breaks here; a retry continues above. + break } } catch (error) { // Aborted request: covers both the external signal and SDK-native From c0cf1661c81ee62c9427028187d51cc6d922656e Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 4 Dec 2026 16:30:55 +0100 Subject: [PATCH 2/2] fix(gemini): reset thought signature per attempt; model mid-retry aborts CodeRabbit round 1 on PR #2836: - gemini.ts: reset lastThoughtSignature at the start of each attempt so a signature-only part from a discarded attempt cannot be saved with the successful response (red-verified regression test). - gemini.spec.ts: settlement cases for reasoning, tool-call and fallback-text delivery before an unframed end; each asserts the output sequence and exactly one SDK request (red-verified under a sabotaged retry guard). - GeminiStreamEnd.tla: Abort action makes cancellation reachable on any attempt so AbortSurfaces checks the Retry-then-Abort ordering; sig/sigAt plus RetryClearsSig model the per-attempt signature reset with the new SigNotCarried invariant and a SigLeak sabotage cfg. Ratchet: 1 covered, 2 added, 0 gap (threads 4801273323, 4801273340, 4801273350). - TLC: base passes in 94 states; Raw/RetryOff/AbortMasked/SwallowAll/SigLeak each fail exactly UnframedEndCompletes/ZeroDeliveryRetried/AbortSurfaces/ OtherErrorsSurface/SigNotCarried. --- .../tla/GeminiStreamEnd.AbortMasked.cfg | 3 +- docs/architecture/tla/GeminiStreamEnd.Raw.cfg | 3 +- .../tla/GeminiStreamEnd.RetryOff.cfg | 3 +- .../tla/GeminiStreamEnd.SigLeak.cfg | 7 ++ .../tla/GeminiStreamEnd.SwallowAll.cfg | 3 +- docs/architecture/tla/GeminiStreamEnd.cfg | 3 +- docs/architecture/tla/GeminiStreamEnd.tla | 69 +++++++++++---- src/api/providers/__tests__/gemini.spec.ts | 88 +++++++++++++++++++ src/api/providers/gemini.ts | 7 ++ 9 files changed, 165 insertions(+), 21 deletions(-) create mode 100644 docs/architecture/tla/GeminiStreamEnd.SigLeak.cfg diff --git a/docs/architecture/tla/GeminiStreamEnd.AbortMasked.cfg b/docs/architecture/tla/GeminiStreamEnd.AbortMasked.cfg index 0639224a136..6d6a2f36861 100644 --- a/docs/architecture/tla/GeminiStreamEnd.AbortMasked.cfg +++ b/docs/architecture/tla/GeminiStreamEnd.AbortMasked.cfg @@ -2,5 +2,6 @@ CONSTANT TolerateUnframed = TRUE CONSTANT AbortFirst = FALSE CONSTANT TolerateAnyError = FALSE CONSTANT RetryZero = TRUE +CONSTANT RetryClearsSig = TRUE SPECIFICATION Spec -INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried SigNotCarried diff --git a/docs/architecture/tla/GeminiStreamEnd.Raw.cfg b/docs/architecture/tla/GeminiStreamEnd.Raw.cfg index 129203aeed2..981c4bf8325 100644 --- a/docs/architecture/tla/GeminiStreamEnd.Raw.cfg +++ b/docs/architecture/tla/GeminiStreamEnd.Raw.cfg @@ -2,5 +2,6 @@ CONSTANT TolerateUnframed = FALSE CONSTANT AbortFirst = TRUE CONSTANT TolerateAnyError = FALSE CONSTANT RetryZero = TRUE +CONSTANT RetryClearsSig = TRUE SPECIFICATION Spec -INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried SigNotCarried diff --git a/docs/architecture/tla/GeminiStreamEnd.RetryOff.cfg b/docs/architecture/tla/GeminiStreamEnd.RetryOff.cfg index 26d20e30a01..40e6a7658d8 100644 --- a/docs/architecture/tla/GeminiStreamEnd.RetryOff.cfg +++ b/docs/architecture/tla/GeminiStreamEnd.RetryOff.cfg @@ -2,5 +2,6 @@ CONSTANT TolerateUnframed = TRUE CONSTANT AbortFirst = TRUE CONSTANT TolerateAnyError = FALSE CONSTANT RetryZero = FALSE +CONSTANT RetryClearsSig = TRUE SPECIFICATION Spec -INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried SigNotCarried diff --git a/docs/architecture/tla/GeminiStreamEnd.SigLeak.cfg b/docs/architecture/tla/GeminiStreamEnd.SigLeak.cfg new file mode 100644 index 00000000000..a3a760fee8b --- /dev/null +++ b/docs/architecture/tla/GeminiStreamEnd.SigLeak.cfg @@ -0,0 +1,7 @@ +CONSTANT TolerateUnframed = TRUE +CONSTANT AbortFirst = TRUE +CONSTANT TolerateAnyError = FALSE +CONSTANT RetryZero = TRUE +CONSTANT RetryClearsSig = FALSE +SPECIFICATION Spec +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried SigNotCarried diff --git a/docs/architecture/tla/GeminiStreamEnd.SwallowAll.cfg b/docs/architecture/tla/GeminiStreamEnd.SwallowAll.cfg index 84514a61553..8ac39cebeb7 100644 --- a/docs/architecture/tla/GeminiStreamEnd.SwallowAll.cfg +++ b/docs/architecture/tla/GeminiStreamEnd.SwallowAll.cfg @@ -2,5 +2,6 @@ CONSTANT TolerateUnframed = TRUE CONSTANT AbortFirst = TRUE CONSTANT TolerateAnyError = TRUE CONSTANT RetryZero = TRUE +CONSTANT RetryClearsSig = TRUE SPECIFICATION Spec -INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried SigNotCarried diff --git a/docs/architecture/tla/GeminiStreamEnd.cfg b/docs/architecture/tla/GeminiStreamEnd.cfg index aabf36e9af9..4fc882ed677 100644 --- a/docs/architecture/tla/GeminiStreamEnd.cfg +++ b/docs/architecture/tla/GeminiStreamEnd.cfg @@ -2,5 +2,6 @@ CONSTANT TolerateUnframed = TRUE CONSTANT AbortFirst = TRUE CONSTANT TolerateAnyError = FALSE CONSTANT RetryZero = TRUE +CONSTANT RetryClearsSig = TRUE SPECIFICATION Spec -INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried +INVARIANTS UnframedEndCompletes AbortSurfaces OtherErrorsSurface ZeroDeliveryRetried SigNotCarried diff --git a/docs/architecture/tla/GeminiStreamEnd.tla b/docs/architecture/tla/GeminiStreamEnd.tla index 93ae3a7f606..5daf3fe2e3d 100644 --- a/docs/architecture/tla/GeminiStreamEnd.tla +++ b/docs/architecture/tla/GeminiStreamEnd.tla @@ -7,31 +7,44 @@ \* JSON segment at the end' (issue 2682), and a first-attempt end with no \* delivered event failed instead of retrying the clean request. \* Invariants: UnframedEndCompletes, AbortSurfaces, OtherErrorsSurface, -\* ZeroDeliveryRetried. +\* ZeroDeliveryRetried, SigNotCarried. \* Expect Raw to fail UnframedEndCompletes, RetryOff to fail ZeroDeliveryRetried, -\* AbortMasked to fail AbortSurfaces and SwallowAll to fail OtherErrorsSurface. -\* Result: fixed passes in 35 states; Raw (23), RetryOff (12), AbortMasked (16) -\* and SwallowAll (18) each fail exactly the invariant named above. Each -\* sabotage run takes less than 1 second; the whole gate runs in seconds. +\* AbortMasked to fail AbortSurfaces, SwallowAll to fail OtherErrorsSurface and +\* SigLeak to fail SigNotCarried. +\* Result: fixed passes in 94 states; Raw (33), RetryOff (14), AbortMasked +\* (19), SwallowAll (22) and SigLeak (81) each fail exactly the invariant +\* named above. Each sabotage run takes less than 1 second; the whole gate +\* runs in seconds. \* Findings: no model failure beyond the pinned defects. A RetryOff run first \* passed vacuously because the invariant read the RetryZero constant; the -\* invariant is now an unconditional unreachability claim. +\* invariant is now an unconditional unreachability claim. A probe run confirmed +\* the new ordering: Retry, then Abort on attempt 1, settles to abortError, +\* so AbortSurfaces checks cancellation after a retry (thread 4801273323). \* False alarms: none. The retry restarts the settlement, so a second unframed \* end still surfaces; OtherErrorsSurface stays unconditional on purpose. \* The provider test replays every invariant sentence on the real handler. -\* Review: 0 covered, 0 added, 0 gap (first round). -\* Cost: about 15 minutes of agent work; each TLC run takes less than 1 second. -\* The SDK settlement names are oracles; the delivered event values are -\* outside this model (Task consumes them). +\* Review: 1 covered, 2 added, 0 gap (PR 2836 CodeRabbit round 1). +\* Added: thread 4801273323 - the Abort action makes cancellation reachable +\* while outcome is "none" on any attempt, so AbortSurfaces checks an abort +\* after Retry advanced attempts to 1 as well. +\* Added: thread 4801273350 - sig, sigAt and RetryClearsSig model the per +\* attempt thought-signature reset; SigNotCarried fails when the retry keeps +\* a discarded attempt's signature. +\* Covered: thread 4801273340 - the delivered flag abstracts every delivery +\* kind; the handler tests cover reasoning, tool-call and fallback text. +\* Cost: about 30 minutes of agent work; each TLC run takes less than 1 second. +\* The SDK settlement names are oracles; the delivered event values and the +\* signature strings are outside this model (Task consumes them). EXTENDS Naturals -CONSTANTS TolerateUnframed, AbortFirst, TolerateAnyError, RetryZero +CONSTANTS TolerateUnframed, AbortFirst, TolerateAnyError, RetryZero, RetryClearsSig -VARIABLES settlement, aborted, delivered, attempts, outcome -vars == <> +VARIABLES settlement, aborted, delivered, attempts, outcome, sig, sigAt +vars == <> Settlements == {"clean", "unframed", "otherError"} Outcomes == {"completed", "providerError", "abortError", "none"} +SigAttempts == {0, 1, "unset"} \* The sink decision is a pure policy over how the iterator settled, whether \* the request was aborted, whether an event was delivered, and the attempt. @@ -57,26 +70,46 @@ Init == /\ settlement \in Settlements /\ delivered = FALSE /\ attempts = 0 /\ outcome = "none" + /\ sig = FALSE + /\ sigAt = "unset" Deliver == /\ outcome = "none" /\ ~delivered /\ delivered' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> + +\* A signature-only part stores a signature without delivering an event. A +\* part that both signs and delivers is Deliver then Sign in some order; the +\* invariant reads both the same way. +Sign == /\ outcome = "none" + /\ sig' = TRUE + /\ sigAt' = attempts + /\ UNCHANGED <> Settle == /\ outcome = "none" /\ ~CanRetry /\ outcome' = Surface(settlement, aborted, delivered, attempts) - /\ UNCHANGED <> + /\ UNCHANGED <> + +\* Cancellation fires while a request is in flight, on any attempt: it stays +\* reachable after Retry advanced attempts to 1 (review 4801273323). +Abort == /\ outcome = "none" + /\ aborted' = TRUE + /\ UNCHANGED <> +\* The retry must drop attempt state: the delivered counter and the stored +\* signature both belong to the discarded attempt (review 4801273350). Retry == /\ CanRetry /\ outcome = "none" /\ attempts' = 1 /\ settlement' \in Settlements /\ delivered' = FALSE + /\ sig' = IF RetryClearsSig THEN FALSE ELSE sig + /\ sigAt' = IF RetryClearsSig THEN "unset" ELSE sigAt /\ UNCHANGED <> \* A settled outcome is terminal; the stuttering step keeps TLC's deadlock \* check meaningful for states that are stuck before settling. Termination == outcome # "none" /\ UNCHANGED vars -Next == Deliver \/ Settle \/ Retry \/ Termination +Next == Deliver \/ Settle \/ Retry \/ Sign \/ Abort \/ Termination Spec == Init /\ [][Next]_vars @@ -97,4 +130,8 @@ ZeroDeliveryRetried == ~(outcome # "none" /\ settlement = "unframed" /\ ~aborted /\ ~delivered /\ attempts = 0) +\* A settled completion never uses a signature captured on a discarded +\* attempt: the retry must reset the stored value (review 4801273350). +SigNotCarried == ~(outcome = "completed" /\ sig /\ sigAt # attempts) + ==== diff --git a/src/api/providers/__tests__/gemini.spec.ts b/src/api/providers/__tests__/gemini.spec.ts index 60c9a019ae1..f584c0cf2a3 100644 --- a/src/api/providers/__tests__/gemini.spec.ts +++ b/src/api/providers/__tests__/gemini.spec.ts @@ -1958,6 +1958,64 @@ describe("GeminiHandler", () => { expect(mockCaptureException).not.toHaveBeenCalled() }) + // Every delivery counter must keep the end tolerated: reasoning, + // tool-call, and fallback-text parts all increment deliveredEvents, + // so each completes instead of retrying after content was yielded. + it.each([ + { + kind: "reasoning" as const, + chunk: makePartsChunk([{ thought: true, text: "thinking out loud" }]), + expected: [{ type: "reasoning", text: "thinking out loud" }], + }, + { + kind: "tool call" as const, + chunk: makePartsChunk([{ functionCall: { name: "read_file", args: { path: "x.ts" } } }]), + expected: [ + { type: "tool_call_partial", index: 0, name: "read_file", arguments: undefined }, + { type: "tool_call_partial", index: 0, name: undefined, arguments: '{"path":"x.ts"}' }, + ], + }, + { + kind: "fallback text" as const, + chunk: { text: "fallback content" }, + expected: [{ type: "text", text: "fallback content" }], + }, + ])( + "completes the stream when $kind delivery precedes an unframed end, without a retry", + async ({ chunk, expected }) => { + async function* delivered(): AsyncGenerator { + yield chunk + yield makeUsageChunk() + throw new Error(INCOMPLETE_JSON_SEGMENT) + } + // A second return value only exists to catch a wrongful retry: + // a delivered event must keep the SDK called exactly once. + const mockStream = vi.fn().mockReturnValueOnce(delivered()).mockReturnValueOnce(asyncStreamFrom([])) + handler["client"].models.generateContentStream = mockStream + + const chunks = await collectStream( + handler.createMessage("You are a helpful assistant", messages, makeCreateMessageMetadata()), + ) + const deliveredChunks = chunks.filter((c) => c.type !== "usage") + if (expected[0].type === "tool_call_partial") { + // Tool-call chunks carry a request-unique generated id: project + // the stable fields for the strict sequence assert. + expect( + deliveredChunks.map((c) => ({ + type: c.type, + index: (c as { index: number }).index, + name: (c as { name?: string }).name, + arguments: (c as { arguments?: string }).arguments, + })), + ).toStrictEqual(expected) + } else { + expect(deliveredChunks).toStrictEqual(expected) + } + expect(chunks.some((c) => c.type === "usage")).toBe(true) + expect(mockStream).toHaveBeenCalledTimes(1) + }, + ) + it.each([ { settlement: "clean", aborted: false }, { settlement: "clean", aborted: true }, @@ -2040,5 +2098,35 @@ describe("GeminiHandler", () => { ).rejects.toThrow() expect(mockStream).toHaveBeenCalledTimes(2) }) + + it("does not keep a discarded attempt's thought signature when the unsigned retry succeeds", async () => { + // Signature capture requires tools in the metadata + // (includeThoughtSignatures). A signature-only part sets the stored + // signature without counting as a delivered event, so this stream + // both captures one and retries. The surviving attempt succeeds + // without any signature part: the discarded value must not be + // returned for the new assistant message. + const toolMetadata: ApiHandlerCreateMessageMetadata = { + ...makeCreateMessageMetadata(), + tools: [{ type: "function", function: { name: "read_file", description: "", parameters: {} } }], + } + + async function* sigOnlyThenUnframed(): AsyncGenerator { + yield makePartsChunk([{ thoughtSignature: "discarded-sig" }]) + throw new Error(INCOMPLETE_JSON_SEGMENT) + } + const unsignedRetry = asyncStreamFrom([makePartsChunk([{ text: "clean retry" }]), makeUsageChunk()]) + const mockStream = vi.fn().mockReturnValueOnce(sigOnlyThenUnframed()).mockReturnValueOnce(unsignedRetry) + handler["client"].models.generateContentStream = mockStream + + const chunks = await collectStream( + handler.createMessage("You are a helpful assistant", messages, toolMetadata), + ) + expect( + chunks.filter((c) => c.type === "text").map((c) => (c as { type: "text"; text: string }).text), + ).toStrictEqual(["clean retry"]) + expect(mockStream).toHaveBeenCalledTimes(2) + expect(handler.getThoughtSignature()).toBeUndefined() + }) }) }) diff --git a/src/api/providers/gemini.ts b/src/api/providers/gemini.ts index 5d356f01d0a..eb0d298b2fd 100644 --- a/src/api/providers/gemini.ts +++ b/src/api/providers/gemini.ts @@ -459,6 +459,13 @@ export class GeminiHandler extends BaseProvider implements SingleCompletionHandl let finalResponse: { responseId?: string } | undefined let toolCallCounter = 0 let deliveredEvents = 0 + // A discarded attempt's captured signature must not survive + // the retry: a signature-only part never counts as a + // delivered event, so the retry reset above does not + // cover it. Reset it alongside the per-attempt counters, + // or the failed attempt's value is saved with the + // successful response's message. + this.lastThoughtSignature = undefined try { const result = await this.client.models.generateContentStream(params)