Skip to content
73 changes: 73 additions & 0 deletions docs/plans/2026-07-11-dashscope-invalid-stream-retry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# DashScope Invalid Stream Retry Implementation Plan

> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

**Goal:** Make Qwen Code tolerate up to four consecutive transient invalid model streams before surfacing `InvalidStreamError`.

**Architecture:** Keep the existing provider-independent `InvalidStreamError` validation and retry path. Increase only its independent retry budget, preserving the existing linear delay and abort behavior; prove the change with stream factories that return a fresh async generator for every attempt.

**Tech Stack:** TypeScript, Vitest, fake timers, Qwen Code core streaming pipeline.

### Task 1: Add the regression test

**Files:**

- Modify: `packages/core/src/core/geminiChat.test.ts`

**Step 1: Write the failing test**

Add a test under `sendMessageStream with retries` that returns four fresh invalid streams followed by a valid response. Assert five generator calls, four retry telemetry events, a successful response chunk, and clean two-turn history.

**Step 2: Run the focused test to verify it fails**

Run: `cd packages/core && npx vitest run src/core/geminiChat.test.ts -t "should recover after four consecutive invalid streams"`

Expected: FAIL because the current two-retry budget stops after three calls.

### Task 2: Increase the invalid-stream retry budget

**Files:**

- Modify: `packages/core/src/core/geminiChat.ts`
- Modify: `packages/core/src/core/geminiChat.test.ts`

**Step 1: Implement the minimal change**

Change `INVALID_STREAM_RETRY_CONFIG.maxRetries` from `2` to `4`.

**Step 2: Update the persistent-failure assertions**

Update the existing persistent invalid-content test to expect five total stream calls and four retry telemetry events.

**Step 3: Run focused tests to verify they pass**

Run: `cd packages/core && npx vitest run src/core/geminiChat.test.ts -t "sendMessageStream with retries"`

Expected: PASS.

### Task 3: Verify the change

**Files:**

- Verify: `packages/core/src/core/geminiChat.ts`
- Verify: `packages/core/src/core/geminiChat.test.ts`

**Step 1: Run the full affected test file**

Run: `cd packages/core && npx vitest run src/core/geminiChat.test.ts`

Expected: PASS.

**Step 2: Run repository checks**

Run: `npm run lint`, `npm run typecheck`, and `npm run build` from the worktree root.

Expected: all commands exit successfully.

**Step 3: Review the diff**

Check that the change is limited to the retry budget, its regression coverage, and these planning artifacts.

**Step 4: Commit**

Run: `git add docs/plans/2026-07-11-dashscope-invalid-stream-retry.md packages/core/src/core/geminiChat.ts packages/core/src/core/geminiChat.test.ts && git commit -m "fix(core): tolerate repeated invalid model streams"`
90 changes: 87 additions & 3 deletions packages/core/src/core/geminiChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4607,12 +4607,20 @@ describe('GeminiChat', async () => {
);
await expectStreamExhaustion(stream);

// Should be called 3 times (1 initial + 2 transient retries)
// Should be called 5 times (1 initial + 4 transient retries)
expect(
mockContentGenerator.generateContentStream,
).toHaveBeenCalledTimes(3);
expect(mockLogContentRetry).toHaveBeenCalledTimes(2);
).toHaveBeenCalledTimes(5);
expect(mockLogContentRetry).toHaveBeenCalledTimes(4);
expect(mockLogContentRetryFailure).toHaveBeenCalledTimes(1);
expect(mockLogContentRetryFailure).toHaveBeenCalledWith(
mockConfig,
expect.objectContaining({
total_attempts: 5,
final_error_type: 'NO_FINISH_REASON',
model: 'test-model',
}),
);

// History should still contain the user message.
const history = chat.getHistory();
Expand All @@ -4626,6 +4634,82 @@ describe('GeminiChat', async () => {
}
});

Comment thread
yiliang114 marked this conversation as resolved.
Resolved
it('should recover after four consecutive invalid streams', async () => {
vi.useFakeTimers();
try {
let callCount = 0;
vi.mocked(
mockContentGenerator.generateContentStream,
).mockImplementation(async () => {
callCount++;
if (callCount <= 4) {
return (async function* () {
yield {
candidates: [
{
content: { parts: [] },
finishReason: 'STOP',
},
],
} as unknown as GenerateContentResponse;
})();
}

return (async function* () {
yield {
candidates: [
{
content: { parts: [{ text: 'Recovered response' }] },
finishReason: 'STOP',
},
],
} as unknown as GenerateContentResponse;
})();
});

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'test' },
'prompt-id-four-invalid-streams',
);
const events = await collectStreamWithFakeTimers(stream, 25_000);

expect(
mockContentGenerator.generateContentStream,
).toHaveBeenCalledTimes(5);
expect(mockLogContentRetry).toHaveBeenCalledTimes(4);
for (const [index, retryDelayMs] of [
2000, 4000, 6000, 8000,
].entries()) {
expect(mockLogContentRetry).toHaveBeenNthCalledWith(
index + 1,
mockConfig,
expect.objectContaining({
attempt_number: index,
error_type: 'NO_RESPONSE_TEXT',
retry_delay_ms: retryDelayMs,
model: 'test-model',
}),
);
}
expect(mockLogContentRetryFailure).not.toHaveBeenCalled();
expect(
events.some(
(event) =>
event.type === StreamEventType.CHUNK &&
event.value.candidates?.[0]?.content?.parts?.[0]?.text ===
'Recovered response',
),
).toBe(true);
expect(chat.getHistory()).toEqual([
{ role: 'user', parts: [{ text: 'test' }] },
{ role: 'model', parts: [{ text: 'Recovered response' }] },
]);
} finally {
vi.useRealTimers();
}
});

it('should retry usage-only empty streams and succeed on a later attempt', async () => {
vi.useFakeTimers();
try {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/core/geminiChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ const INVALID_CONTENT_RETRY_OPTIONS: ContentRetryOptions = {
// reason. All are retried with an independent budget (similar to rate-limit
// retries) so they do not consume each other's retry budgets.
const INVALID_STREAM_RETRY_CONFIG = {
maxRetries: 2,
maxRetries: 4,
initialDelayMs: 2000,
};

Expand Down
Loading