Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions packages/core/src/core/geminiChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1700,6 +1700,180 @@ describe('GeminiChat', async () => {
).toHaveBeenCalledTimes(2);
});

it('should retry on 408 Request Timeout errors', async () => {
const error408 = new ApiError({
message: 'Request Timeout',
status: 408,
});

vi.mocked(mockContentGenerator.generateContentStream)
.mockRejectedValueOnce(error408)
.mockResolvedValueOnce(
(async function* () {
yield {
candidates: [
{
content: { parts: [{ text: 'Recovered from 408' }] },
finishReason: 'STOP',
},
],
} as unknown as GenerateContentResponse;
})(),
);

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'test' },
'prompt-id-408-retry',
);

const events: StreamEvent[] = [];
for await (const event of stream) {
events.push(event);
}

// Should be called twice (initial + retry)
expect(
mockContentGenerator.generateContentStream,
).toHaveBeenCalledTimes(2);

// Should have successful content
expect(
events.some(
(e) =>
e.type === StreamEventType.CHUNK &&
e.value.candidates?.[0]?.content?.parts?.[0]?.text ===
'Recovered from 408',
),
).toBe(true);
});

it('should retry on 409 transient conflict errors', async () => {
const error409 = new ApiError({
message: 'Lock contention detected',
status: 409,
});

vi.mocked(mockContentGenerator.generateContentStream)
.mockRejectedValueOnce(error409)
.mockResolvedValueOnce(
(async function* () {
yield {
candidates: [
{
content: { parts: [{ text: 'Recovered from 409' }] },
finishReason: 'STOP',
},
],
} as unknown as GenerateContentResponse;
})(),
);

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'test' },
'prompt-id-409-retry',
);

const events: StreamEvent[] = [];
for await (const event of stream) {
events.push(event);
}

// Should be called twice (initial + retry)
expect(
mockContentGenerator.generateContentStream,
).toHaveBeenCalledTimes(2);

expect(
events.some(
(e) =>
e.type === StreamEventType.CHUNK &&
e.value.candidates?.[0]?.content?.parts?.[0]?.text ===
'Recovered from 409',
),
).toBe(true);
});

it('should NOT retry on 409 deterministic conflict errors', async () => {
const error409 = new ApiError({
message: 'Resource already exists',
status: 409,
});

vi.mocked(mockContentGenerator.generateContentStream).mockRejectedValue(
error409,
);

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'test' },
'prompt-id-409-noretry',
);

await expect(
(async () => {
for await (const _ of stream) {
/* consume stream */
}
})(),
).rejects.toThrow(error409);

// Should only be called once (no retry)
expect(
mockContentGenerator.generateContentStream,
).toHaveBeenCalledTimes(1);
});

it('should retry on network errors (ECONNRESET)', async () => {
const networkError = new Error(
'Connection reset',
) as NodeJS.ErrnoException;
networkError.code = 'ECONNRESET';

vi.mocked(mockContentGenerator.generateContentStream)
.mockRejectedValueOnce(networkError)
.mockResolvedValueOnce(
(async function* () {
yield {
candidates: [
{
content: {
parts: [{ text: 'Recovered from network error' }],
},
finishReason: 'STOP',
},
],
} as unknown as GenerateContentResponse;
})(),
);

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'test' },
'prompt-id-network-retry',
);

const events: StreamEvent[] = [];
for await (const event of stream) {
events.push(event);
}

// Should be called twice (initial + retry)
expect(
mockContentGenerator.generateContentStream,
).toHaveBeenCalledTimes(2);

expect(
events.some(
(e) =>
e.type === StreamEventType.CHUNK &&
e.value.candidates?.[0]?.content?.parts?.[0]?.text ===
'Recovered from network error',
),
).toBe(true);
});

afterEach(() => {
// Reset to default behavior
mockRetryWithBackoff.mockImplementation(async (apiCall) => apiCall());
Expand Down
16 changes: 12 additions & 4 deletions packages/core/src/core/geminiChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ import type {
GenerateContentResponseUsageMetadata,
} from '@google/genai';
import { createUserContent, FinishReason } from '@google/genai';
import { retryWithBackoff, isUnattendedMode } from '../utils/retry.js';
import {
retryWithBackoff,
isUnattendedMode,
classifyError,
} from '../utils/retry.js';
import { getErrorStatus } from '../utils/errors.js';
import { createDebugLogger } from '../utils/debugLogger.js';
import { parseAndFormatApiError } from '../utils/errorParsing.js';
Expand Down Expand Up @@ -713,17 +717,21 @@ export class GeminiChat {
);
const streamResponse = await retryWithBackoff(apiCall, {
shouldRetryOnError: (error: unknown) => {
// Never retry deterministic client errors regardless of classification
if (error instanceof Error) {
if (isSchemaDepthError(error.message)) return false;
if (isInvalidArgumentError(error.message)) return false;
}

const status = getErrorStatus(error);
if (status === 400) return false;

@wenshao wenshao May 4, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The explicit if (status === 400) return false; check before delegating to classifyError is redundant — classifyError already classifies 400 as non-retryable. It creates an asymmetry: 400 is double-checked while 401/403/404/422 are only handled by classifyError. If a maintainer sees the explicit 400 check and removes the 400 handling from classifyError, callers of defaultShouldRetry would lose 400 protection.

Consider removing this explicit check and fully delegating to classifyError. Alternatively, move the message checks (isSchemaDepthError/isInvalidArgumentError) into classifyError as well, making the callback a clean delegation.

Suggested change
if (status === 400) return false;
// Delegate to classifyError for all cases.
return classifyError(error).retryable;

if (status === 429) return true;
if (status && status >= 500 && status < 600) return true;

return false;
// Delegate to classifyError for all other cases. Explicitly accepted
// retryable categories for Gemini streaming: 408 (timeout), 409 (transient
// lock/contention only), 429 (rate limit), 5xx (server errors), network
// transport errors. Deterministic errors (400, 401, 403, 404, 422) are
// handled by classifyError and return retryable=false.
return classifyError(error).retryable;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The shouldRetryOnError callback now delegates entirely to classifyError(error).retryable for non-400 errors, replacing the previous explicit allowlist (status === 429, 5xx) with a return false fallback. While functionally equivalent today, this loses defense-in-depth: any future addition of a retryable category to classifyError (e.g. a new status code or message pattern) will automatically and silently apply to Gemini Chat streaming requests, bypassing Gemini Chat's context-specific judgment (which previously required explicit opt-in for each error type).

Consider adding an allowlist assertion after classifyError, or documenting which error categories are explicitly accepted for Gemini streaming retries.

— deepseek-v4-pro via Qwen Code /review

},
authType: this.config.getContentGeneratorConfig()?.authType,
persistentMode: isUnattendedMode(),
Expand Down
Loading
Loading