Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
2 changes: 1 addition & 1 deletion packages/cli/src/config/settingsSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1735,7 +1735,7 @@ const SETTINGS_SCHEMA = {
requiresRestart: false,
default: undefined as number | undefined,
description:
'Maximum inactivity between streamed chunks for OpenAI-compatible models, in milliseconds. Set to 0 to disable the idle guard. For provider-backed models, configure this field in the selected modelProviders entry.',
'Maximum inactivity between streamed chunks for OpenAI-compatible and Anthropic models, in milliseconds. Set to 0 to disable the idle guard. For provider-backed models, configure this field in the selected modelProviders entry.',
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
minimum: 0,
maximum: 2_147_483_647,
parentKey: 'generationConfig',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ import type { GenerateContentParameters } from '@google/genai';
import { FinishReason, GenerateContentResponse } from '@google/genai';
import type { ContentGeneratorConfig } from '../contentGenerator.js';
import {
DEFAULT_STREAM_IDLE_TIMEOUT_MS,
DEFAULT_TIMEOUT,
DISABLED_REQUEST_TIMEOUT_MS,
QWEN_STREAM_IDLE_TIMEOUT_MS_ENV,
QWEN_STREAM_MAX_LIFETIME_MS_ENV,
} from '../openaiContentGenerator/constants.js';

const mockReportAnthropicRequest = vi.hoisted(() => vi.fn());
Expand Down Expand Up @@ -5001,6 +5004,330 @@ describe('AnthropicContentGenerator', () => {
});
});

// Issue #9005 finding 4: the OpenAI wire wraps its stream in an idle
// watchdog plus a non-resetting lifetime cap (openaiContentGenerator
// `withStreamGuards`), while the Anthropic wire had neither — a stream that
// returns 200 and then goes silent (or drip-feeds `thinking_delta` frames
// forever, which keep resetting any idle-only timer) hangs the CLI until
// the process is killed. These tests pin the Anthropic wire to the same
// guards, mirroring the OpenAI pipeline's watchdog suite.
describe('stream watchdog guards (issue #9005 finding 4)', () => {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
// A manually gated SSE event source: events arrive only when pushed, so
// tests can model a stream that goes silent or is drip-fed. Mirrors the
// `gatedStream` helper in openaiContentGenerator/pipeline.test.ts.
function gatedEventStream() {
let resolveNext: ((r: IteratorResult<unknown>) => void) | null = null;
const buffered: unknown[] = [];
let ended = false;
let returned = false;
const deliver = (r: IteratorResult<unknown>) => {
const r2 = resolveNext;
resolveNext = null;
r2?.(r);
};
return {
push(event: unknown) {
if (resolveNext) deliver({ done: false, value: event });
else buffered.push(event);
},
end() {
ended = true;
if (resolveNext) deliver({ done: true, value: undefined as never });
},
wasReturned() {
return returned;
},
stream: {
[Symbol.asyncIterator]() {
return {
next(): Promise<IteratorResult<unknown>> {
if (buffered.length) {
return Promise.resolve({
done: false,
value: buffered.shift()!,
});
}
if (ended) {
return Promise.resolve({
done: true,
value: undefined as never,
});
}
return new Promise((res) => {
resolveNext = res;
});
},
return(): Promise<IteratorResult<unknown>> {
returned = true;
ended = true;
if (resolveNext) {
deliver({ done: true, value: undefined as never });
}
return Promise.resolve({
done: true,
value: undefined as never,
});
},
};
},
},
};
}

const buildGenerator = async (guardConfig: {
streamIdleTimeoutMs?: number;
streamMaxLifetimeMs?: number;
}) => {
const { AnthropicContentGenerator } = await importGenerator();
return new AnthropicContentGenerator(
{
model: 'claude-test',
apiKey: 'test-key',
timeout: 10_000,
maxRetries: 2,
samplingParams: { max_tokens: 100 },
schemaCompliance: 'auto',
...(guardConfig.streamIdleTimeoutMs !== undefined
? { streamIdleTimeoutMs: guardConfig.streamIdleTimeoutMs }
: {}),
...(guardConfig.streamMaxLifetimeMs !== undefined
? { streamMaxLifetimeMs: guardConfig.streamMaxLifetimeMs }
: {}),
},
mockConfig,
);
};

const streamRequest = {
model: 'models/ignored',
contents: 'Hello',
} as unknown as GenerateContentParameters;

// Drain the stream and capture whatever it ends with. Without the guards a
// silent/drip-fed source never settles, so callers race the result
// against a sentinel instead of awaiting it directly — a missing
// watchdog then fails the assertion instead of hanging the test.
const consumeUntilSettled = (
stream: AsyncGenerator<GenerateContentResponse>,
) =>
(async () => {
for await (const _chunk of stream) {
/* drain */
}
})().catch((e: unknown) => e);

beforeEach(() => {
// Ignore ambient QWEN_STREAM_* knobs from the dev/CI shell so the
// explicit-config tests aren't silently overridden.
vi.stubEnv(QWEN_STREAM_IDLE_TIMEOUT_MS_ENV, undefined);
vi.stubEnv(QWEN_STREAM_MAX_LIFETIME_MS_ENV, undefined);
vi.useFakeTimers();
});

afterEach(() => {
vi.useRealTimers();
vi.unstubAllEnvs();
});

it('aborts and throws a retryable ETIMEDOUT when the stream is silent past the idle timeout', async () => {
const gated = gatedEventStream(); // never pushes → silent
anthropicState.createImpl.mockResolvedValue(gated.stream);
const generator = await buildGenerator({
streamIdleTimeoutMs: 1000,
streamMaxLifetimeMs: 0,
});
const stream = await generator.generateContentStream(streamRequest);
const captured = consumeUntilSettled(stream);
await vi.advanceTimersByTimeAsync(1000);
await vi.advanceTimersByTimeAsync(0);
const sentinel = Symbol('idle-watchdog-did-not-fire');
const err = await Promise.race([captured, Promise.resolve(sentinel)]);
expect(err).toMatchObject({
name: 'StreamInactivityTimeoutError',
code: 'ETIMEDOUT',
idleMs: 1000,
chunksReceived: 0,
});
expect((err as Error).message).toContain('QWEN_STREAM_IDLE_TIMEOUT_MS');
expect(gated.wasReturned()).toBe(true);
});

it('uses the shared default idle timeout when no override is configured', async () => {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
const gated = gatedEventStream(); // never pushes → silent
anthropicState.createImpl.mockResolvedValue(gated.stream);
const generator = await buildGenerator({});
const stream = await generator.generateContentStream(streamRequest);
const captured = consumeUntilSettled(stream);
await vi.advanceTimersByTimeAsync(DEFAULT_STREAM_IDLE_TIMEOUT_MS);
await vi.advanceTimersByTimeAsync(0);
const sentinel = Symbol('default-idle-watchdog-did-not-fire');
const err = await Promise.race([captured, Promise.resolve(sentinel)]);
expect(err).toMatchObject({
name: 'StreamInactivityTimeoutError',
code: 'ETIMEDOUT',
idleMs: DEFAULT_STREAM_IDLE_TIMEOUT_MS,
chunksReceived: 0,
});
});

it('does not interrupt a stream whose events keep arriving inside the idle window', async () => {
const gated = gatedEventStream();
anthropicState.createImpl.mockResolvedValue(gated.stream);
const generator = await buildGenerator({
streamIdleTimeoutMs: 1000,
streamMaxLifetimeMs: 0,
});
const stream = await generator.generateContentStream(streamRequest);
let done = false;
let error: unknown;
const texts: string[] = [];
const consume = (async () => {
for await (const chunk of stream) {
for (const candidate of chunk.candidates ?? []) {
for (const part of candidate.content?.parts ?? []) {
if (part.text) texts.push(part.text);
}
}
}
})().then(
() => (done = true),
(e: unknown) => (error = e),
);
gated.push({
type: 'message_start',
message: {
id: 'msg-1',
model: 'claude-test',
usage: { input_tokens: 1 },
},
});
gated.push({
type: 'content_block_start',
index: 0,
content_block: { type: 'text', text: '' },
});
gated.push({
type: 'content_block_delta',
index: 0,
delta: { type: 'text_delta', text: 'hel' },
});
await vi.advanceTimersByTimeAsync(500); // < 1000ms idle window
gated.push({
type: 'content_block_delta',
index: 0,
delta: { type: 'text_delta', text: 'lo' },
});
await vi.advanceTimersByTimeAsync(500);
gated.push({ type: 'content_block_stop', index: 0 });
gated.push({
type: 'message_delta',
delta: { stop_reason: 'end_turn' },
usage: { output_tokens: 1 },
});
gated.push({ type: 'message_stop' });
gated.end();
await vi.advanceTimersByTimeAsync(0);
await consume;
expect(error).toBeUndefined();
expect(done).toBe(true);
expect(texts).toEqual(['hel', 'lo']);
});

it('caps total stream lifetime when thinking deltas keep resetting the idle watchdog', async () => {
// The issue #9005 finding-4 shape: adaptive thinking emits long runs of
// `thinking_delta` frames, each resetting an idle-only timer, while the
// message never completes (the #8597 drip-fed hang). The lifetime cap
// does not reset.
const gated = gatedEventStream(); // drip-fed, never ends
anthropicState.createImpl.mockResolvedValue(gated.stream);
const generator = await buildGenerator({
streamIdleTimeoutMs: 1000,
streamMaxLifetimeMs: 3000,
});
const stream = await generator.generateContentStream(streamRequest);
const captured = consumeUntilSettled(stream);
gated.push({
type: 'message_start',
message: {
id: 'msg-1',
model: 'claude-test',
usage: { input_tokens: 1 },
},
});
await vi.advanceTimersByTimeAsync(500);
gated.push({
type: 'content_block_start',
index: 0,
content_block: { type: 'thinking', thinking: '' },
});
await vi.advanceTimersByTimeAsync(500);
for (let i = 0; i < 4; i++) {
gated.push({
type: 'content_block_delta',
index: 0,
delta: { type: 'thinking_delta', thinking: 't' },
});
await vi.advanceTimersByTimeAsync(500); // each drip resets the 1s idle watchdog
}
await vi.advanceTimersByTimeAsync(1000); // now past the 3000ms cap
await vi.advanceTimersByTimeAsync(0);
const sentinel = Symbol('lifetime-cap-did-not-fire');
const err = await Promise.race([captured, Promise.resolve(sentinel)]);
expect(err).toMatchObject({
name: 'StreamLifetimeExceededError',
code: 'ETIMEDOUT',
maxLifetimeMs: 3000,
chunksReceived: 6,
});
expect((err as Error).message).toContain('QWEN_STREAM_MAX_LIFETIME_MS');
expect(gated.wasReturned()).toBe(true);
});

it('leaves streams unguarded when both timeouts are disabled (<= 0)', async () => {
const gated = gatedEventStream();
anthropicState.createImpl.mockResolvedValue(gated.stream);
const generator = await buildGenerator({
streamIdleTimeoutMs: 0,
streamMaxLifetimeMs: 0,
});
const stream = await generator.generateContentStream(streamRequest);
let done = false;
let error: unknown;
const consume = (async () => {
for await (const _chunk of stream) {
/* drain */
}
})().then(
() => (done = true),
(e: unknown) => (error = e),
);
gated.push({
type: 'content_block_start',
index: 0,
content_block: { type: 'text', text: '' },
});
// A silence far beyond the default idle timeout — survivable only
// when the guards are explicitly disabled.
await vi.advanceTimersByTimeAsync(DEFAULT_STREAM_IDLE_TIMEOUT_MS + 1000);
gated.push({
type: 'content_block_delta',
index: 0,
delta: { type: 'text_delta', text: 'still here' },
});
gated.push({ type: 'content_block_stop', index: 0 });
gated.push({
type: 'message_delta',
delta: { stop_reason: 'end_turn' },
usage: { output_tokens: 1 },
});
gated.end();
await vi.advanceTimersByTimeAsync(0);
await consume;
expect(error).toBeUndefined();
expect(done).toBe(true);
});
});

describe('tool_choice mapping from Gemini toolConfig', () => {
async function sendWithToolConfig(
mode: string | undefined,
Expand Down
Loading
Loading