Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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;
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 comment says "Delegate to classifyError for all other cases", but isSchemaDepthError and isInvalidArgumentError checks (~10 lines above) still precede the delegation. These checks are not inside classifyError — a future maintainer who trusts the comment may remove them, creating a gap.

Update the comment to clarify these two message-level guards are independent safety nets not covered by classifyError.

Also: the if (status === 400) return false; check above is now redundant dead code (classifyError already rejects 400). Either remove it or add a comment noting it's a safety net.

— deepseek-v4-pro via Qwen Code /review

},

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] classifyError(error) returns {retryable, reason, status} but only .retryable is consumed. The classification reason is silently discarded, making retry decisions un-debuggable. Consider logging the reason when retrying:

Suggested change
},
const classification = classifyError(error);
if (classification.retryable) {
debugLogger.warn(
`Retrying: ${classification.reason}`,
error instanceof Error ? error : undefined,
);
}
return classification.retryable;

— deepseek-v4-pro via Qwen Code /review

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] classifyError(error) 返回 {retryable, reason, status},但 reason 仅在 retryable=true 时记录。当 retryable=false 时(例如 "Deterministic request error: HTTP 400"),reason 被静默丢弃,导致排查时无法理解为何某个请求未被重试。建议同时记录非重试路径的 reason:

Suggested change
},
const classification = classifyError(error);
if (classification.retryable) {
debugLogger.debug(
`geminiChat retrying: status=${classification.status ?? 'none'}, reason=${classification.reason}`,
);
} else {
debugLogger.debug(
`geminiChat NOT retrying: status=${classification.status ?? 'none'}, reason=${classification.reason}`,
);
}
return classification.retryable;

— deepseek-v4-pro via Qwen Code /review

authType: this.config.getContentGeneratorConfig()?.authType,
persistentMode: isUnattendedMode(),
Expand Down
96 changes: 96 additions & 0 deletions packages/core/src/tools/mcp-client-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,102 @@ describe('McpClientManager', () => {
expect(secondClient.disconnect).toHaveBeenCalledOnce();
});

it('should not spawn duplicate clients when discoverMcpToolsForServer is called concurrently for the same server', async () => {
// Simulate a slow connect to create a window where a second call could race.
let connectCallCount = 0;
const connectDelays: Array<(value: void) => void> = [];

const mockedClient = {
connect: vi.fn().mockImplementation(() => {
connectCallCount++;
return new Promise<void>((resolve) => {
connectDelays.push(resolve);
});
}),
discover: vi.fn().mockResolvedValue(undefined),
disconnect: vi.fn().mockResolvedValue(undefined),
getStatus: vi.fn(),
};

vi.mocked(McpClient).mockReturnValue(mockedClient as unknown as McpClient);

const mockConfig = {
isTrustedFolder: () => true,
getMcpServers: () => ({ 'test-server': {} }),
getMcpServerCommand: () => undefined,
getPromptRegistry: () => ({}) as PromptRegistry,
getWorkspaceContext: () => ({}) as WorkspaceContext,
getDebugMode: () => false,
} as unknown as Config;
const manager = new McpClientManager(mockConfig, {} as ToolRegistry);

// Fire two concurrent discoveries for the same server.
const p1 = manager.discoverMcpToolsForServer(
'test-server',
{} as unknown as Config,
);
const p2 = manager.discoverMcpToolsForServer(
'test-server',
{} as unknown as Config,
);

// Let both settle (the second should have been a no-op).
// Resolve the single in-flight connect.
connectDelays[0]?.();
await p1;
await p2;

// Only one connect call should have been made — the concurrent second
// call must have bailed out early.
expect(connectCallCount).toBe(1);
expect(mockedClient.connect).toHaveBeenCalledOnce();
expect(mockedClient.discover).toHaveBeenCalledOnce();
});

it('should clean up in-flight tracking after discovery completes', async () => {
const mockedClient = {
connect: vi.fn().mockResolvedValue(undefined),
discover: vi.fn().mockResolvedValue(undefined),
disconnect: vi.fn().mockResolvedValue(undefined),
getStatus: vi.fn(),
};

vi.mocked(McpClient).mockReturnValue(mockedClient as unknown as McpClient);

const mockConfig = {
isTrustedFolder: () => true,
getMcpServers: () => ({ 'test-server': {} }),
getMcpServerCommand: () => undefined,
getPromptRegistry: () => ({}) as PromptRegistry,
getWorkspaceContext: () => ({}) as WorkspaceContext,
getDebugMode: () => false,
} as unknown as Config;
const manager = new McpClientManager(mockConfig, {} as ToolRegistry);

await manager.discoverMcpToolsForServer(
'test-server',
{} as unknown as Config,
);

// After completion, a second call should proceed (not be skipped).
const secondClient = {
connect: vi.fn().mockResolvedValue(undefined),
discover: vi.fn().mockResolvedValue(undefined),
disconnect: vi.fn().mockResolvedValue(undefined),
getStatus: vi.fn(),
};
vi.mocked(McpClient).mockReturnValue(secondClient as unknown as McpClient);

await manager.discoverMcpToolsForServer(
'test-server',
{} as unknown as Config,
);

// The second call should have created a new client and connected.
expect(secondClient.connect).toHaveBeenCalledOnce();
expect(secondClient.discover).toHaveBeenCalledOnce();
});

it('should no-op when discovering an unknown server', async () => {
const mockedMcpClient = {
connect: vi.fn(),
Expand Down
23 changes: 23 additions & 0 deletions packages/core/src/tools/mcp-client-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export class McpClientManager {
private healthCheckTimers: Map<string, NodeJS.Timeout> = new Map();
private consecutiveFailures: Map<string, number> = new Map();
private isReconnecting: Map<string, boolean> = new Map();
private inFlightDiscoveries: Set<string> = new Set();

constructor(
config: Config,
Expand Down Expand Up @@ -157,6 +158,16 @@ export class McpClientManager {
return;
}

// Prevent concurrent re-discovery of the same server to avoid spawning
// duplicate MCP child processes. If a discovery/reconnection is already
// in progress for this server, bail out early.
if (this.inFlightDiscoveries.has(serverName)) {
debugLogger.debug(
`Discovery already in flight for server '${serverName}', skipping.`,
);
return;
}

// Ensure we don't leak an existing connection for this server.
const existingClient = this.clients.get(serverName);
if (existingClient) {
Expand All @@ -168,10 +179,17 @@ export class McpClientManager {
);
} finally {
this.clients.delete(serverName);
this.stopHealthCheck(serverName);
this.eventEmitter?.emit('mcp-client-update', this.clients);
}
}

// Track this discovery in-flight to prevent races.
const discoveryDone = () => {
this.inFlightDiscoveries.delete(serverName);
};
this.inFlightDiscoveries.add(serverName);

// For SDK MCP servers, pass the sendSdkMcpMessage callback.
const sdkCallback = isSdkMcpServerConfig(serverConfig)
? this.sendSdkMcpMessage
Expand Down Expand Up @@ -202,7 +220,11 @@ export class McpClientManager {
error,
)}`,
);
// Remove the failed client so a subsequent discovery can retry cleanly.
this.clients.delete(serverName);
this.stopHealthCheck(serverName);
} finally {
discoveryDone();
this.eventEmitter?.emit('mcp-client-update', this.clients);
}
}
Expand Down Expand Up @@ -231,6 +253,7 @@ export class McpClientManager {
this.clients.clear();
this.consecutiveFailures.clear();
this.isReconnecting.clear();
this.inFlightDiscoveries.clear();
}

/**
Expand Down
Loading
Loading