mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-12-02 18:20:01 +08:00
fix(core): implement context-aware silent retries and availability TTL for capacity errors (#28761) (#28790)
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { ModelAvailabilityService } from './modelAvailabilityService.js';
|
||||
|
||||
describe('ModelAvailabilityService', () => {
|
||||
@@ -210,4 +210,64 @@ describe('ModelAvailabilityService', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Capacity TTL expiration', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('recovers terminal status for capacity after the TTL expires', () => {
|
||||
service.markTerminal(model, 'capacity');
|
||||
|
||||
// Before TTL expiration, model is unavailable
|
||||
expect(service.snapshot(model)).toEqual({
|
||||
available: false,
|
||||
reason: 'capacity',
|
||||
});
|
||||
|
||||
// Fast forward 29 seconds (default is 30s)
|
||||
vi.advanceTimersByTime(29000);
|
||||
expect(service.snapshot(model)).toEqual({
|
||||
available: false,
|
||||
reason: 'capacity',
|
||||
});
|
||||
|
||||
// Fast forward past 30 seconds
|
||||
vi.advanceTimersByTime(1001);
|
||||
expect(service.snapshot(model)).toEqual({
|
||||
available: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('allows custom TTL parameter in snapshot', () => {
|
||||
service.markTerminal(model, 'capacity');
|
||||
|
||||
// Check with a custom 5s TTL
|
||||
expect(service.snapshot(model, 5000)).toEqual({
|
||||
available: false,
|
||||
reason: 'capacity',
|
||||
});
|
||||
|
||||
// Advance 6 seconds
|
||||
vi.advanceTimersByTime(6000);
|
||||
expect(service.snapshot(model, 5000)).toEqual({
|
||||
available: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not expire terminal status for non-capacity reasons (e.g. quota)', () => {
|
||||
service.markTerminal(model, 'quota');
|
||||
|
||||
// Even after advance, quota remains terminal
|
||||
vi.advanceTimersByTime(60000);
|
||||
expect(service.snapshot(model)).toEqual({
|
||||
available: false,
|
||||
reason: 'quota',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,7 +17,11 @@ export type UnavailabilityReason =
|
||||
export type ModelHealthStatus = 'terminal' | 'sticky_retry';
|
||||
|
||||
type HealthState =
|
||||
| { status: 'terminal'; reason: TerminalUnavailabilityReason }
|
||||
| {
|
||||
status: 'terminal';
|
||||
reason: TerminalUnavailabilityReason;
|
||||
markedAt?: number;
|
||||
}
|
||||
| {
|
||||
status: 'sticky_retry';
|
||||
reason: TurnUnavailabilityReason;
|
||||
@@ -44,11 +48,32 @@ import { normalizeModelId } from '../utils/modelUtils.js';
|
||||
export class ModelAvailabilityService {
|
||||
private readonly health = new Map<ModelId, HealthState>();
|
||||
|
||||
private getHealth(
|
||||
model: ModelId,
|
||||
ttlMs: number = 30000,
|
||||
): HealthState | undefined {
|
||||
const state = this.health.get(model);
|
||||
if (
|
||||
state &&
|
||||
state.status === 'terminal' &&
|
||||
state.reason === 'capacity' &&
|
||||
state.markedAt !== undefined
|
||||
) {
|
||||
const elapsed = Date.now() - state.markedAt;
|
||||
if (elapsed >= ttlMs) {
|
||||
this.clearState(model);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
markTerminal(modelId: ModelId, reason: TerminalUnavailabilityReason) {
|
||||
const model = normalizeModelId(modelId);
|
||||
this.setState(model, {
|
||||
status: 'terminal',
|
||||
reason,
|
||||
markedAt: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -59,7 +84,7 @@ export class ModelAvailabilityService {
|
||||
|
||||
markRetryOncePerTurn(modelId: ModelId, attempts: number = 1) {
|
||||
const model = normalizeModelId(modelId);
|
||||
const currentState = this.health.get(model);
|
||||
const currentState = this.getHealth(model);
|
||||
// Do not override a terminal failure with a transient one.
|
||||
if (currentState?.status === 'terminal') {
|
||||
return;
|
||||
@@ -82,15 +107,15 @@ export class ModelAvailabilityService {
|
||||
|
||||
consumeStickyAttempt(modelId: ModelId) {
|
||||
const model = normalizeModelId(modelId);
|
||||
const state = this.health.get(model);
|
||||
const state = this.getHealth(model);
|
||||
if (state?.status === 'sticky_retry') {
|
||||
this.setState(model, { ...state, consumed: true });
|
||||
}
|
||||
}
|
||||
|
||||
snapshot(modelId: ModelId): ModelAvailabilitySnapshot {
|
||||
snapshot(modelId: ModelId, ttlMs: number = 30000): ModelAvailabilitySnapshot {
|
||||
const model = normalizeModelId(modelId);
|
||||
const state = this.health.get(model);
|
||||
const state = this.getHealth(model, ttlMs);
|
||||
|
||||
if (!state) {
|
||||
return { available: true };
|
||||
@@ -114,7 +139,7 @@ export class ModelAvailabilityService {
|
||||
const model = normalizeModelId(modelId);
|
||||
const snapshot = this.snapshot(model);
|
||||
if (snapshot.available) {
|
||||
const state = this.health.get(model);
|
||||
const state = this.getHealth(model);
|
||||
// A sticky model is being attempted, so note that.
|
||||
const attempts =
|
||||
state?.status === 'sticky_retry' ? state.attempts : undefined;
|
||||
|
||||
@@ -938,4 +938,121 @@ describe('retryWithBackoff', () => {
|
||||
expect(mockService.markTerminal).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Capacity Exhaustion Context-Aware Retries (Option 2)', () => {
|
||||
it('should retry automatically when onPersistent429 is undefined (unattended runs)', async () => {
|
||||
const capacityError = new TerminalQuotaError(
|
||||
'Resource has been exhausted (e.g. MODEL_CAPACITY_EXHAUSTED).',
|
||||
{
|
||||
code: 429,
|
||||
message: 'MODEL_CAPACITY_EXHAUSTED',
|
||||
details: [
|
||||
{
|
||||
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
|
||||
reason: 'MODEL_CAPACITY_EXHAUSTED',
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
'MODEL_CAPACITY_EXHAUSTED',
|
||||
);
|
||||
|
||||
const fn = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(capacityError)
|
||||
.mockResolvedValue('success');
|
||||
|
||||
const promise = retryWithBackoff(fn, {
|
||||
maxAttempts: 3,
|
||||
initialDelayMs: 1,
|
||||
maxDelayMs: 2,
|
||||
onPersistent429: undefined, // unattended mode
|
||||
});
|
||||
|
||||
await vi.runAllTimersAsync();
|
||||
const result = await promise;
|
||||
expect(result).toBe('success');
|
||||
expect(fn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should silently retry up to 2 times and succeed on the 3rd attempt in interactive mode without calling onPersistent429', async () => {
|
||||
const capacityError = new TerminalQuotaError(
|
||||
'Resource has been exhausted (e.g. MODEL_CAPACITY_EXHAUSTED).',
|
||||
{
|
||||
code: 429,
|
||||
message: 'MODEL_CAPACITY_EXHAUSTED',
|
||||
details: [
|
||||
{
|
||||
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
|
||||
reason: 'MODEL_CAPACITY_EXHAUSTED',
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
'MODEL_CAPACITY_EXHAUSTED',
|
||||
);
|
||||
|
||||
const fn = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(capacityError)
|
||||
.mockRejectedValueOnce(capacityError)
|
||||
.mockResolvedValue('success');
|
||||
|
||||
const onPersistent429 = vi.fn().mockResolvedValue(null);
|
||||
|
||||
const promise = retryWithBackoff(fn, {
|
||||
maxAttempts: 5,
|
||||
initialDelayMs: 1,
|
||||
maxDelayMs: 2,
|
||||
onPersistent429, // interactive mode
|
||||
});
|
||||
|
||||
await vi.runAllTimersAsync();
|
||||
const result = await promise;
|
||||
expect(result).toBe('success');
|
||||
expect(fn).toHaveBeenCalledTimes(3);
|
||||
expect(onPersistent429).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should silently retry up to 2 times and invoke onPersistent429 on the 3rd failure in interactive mode', async () => {
|
||||
const capacityError = new TerminalQuotaError(
|
||||
'Resource has been exhausted (e.g. MODEL_CAPACITY_EXHAUSTED).',
|
||||
{
|
||||
code: 429,
|
||||
message: 'MODEL_CAPACITY_EXHAUSTED',
|
||||
details: [
|
||||
{
|
||||
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
|
||||
reason: 'MODEL_CAPACITY_EXHAUSTED',
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
'MODEL_CAPACITY_EXHAUSTED',
|
||||
);
|
||||
|
||||
const fn = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(capacityError)
|
||||
.mockRejectedValueOnce(capacityError)
|
||||
.mockRejectedValueOnce(capacityError)
|
||||
.mockResolvedValue('success');
|
||||
|
||||
const onPersistent429 = vi.fn().mockResolvedValue(null);
|
||||
|
||||
const promise = retryWithBackoff(fn, {
|
||||
maxAttempts: 5,
|
||||
initialDelayMs: 1,
|
||||
maxDelayMs: 2,
|
||||
onPersistent429, // interactive mode
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
expect(promise).rejects.toThrow(TerminalQuotaError),
|
||||
vi.runAllTimersAsync(),
|
||||
]);
|
||||
expect(fn).toHaveBeenCalledTimes(3);
|
||||
expect(onPersistent429).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -294,6 +294,8 @@ export async function retryWithBackoff<T>(
|
||||
getAvailabilityContext?.()?.policy.maxAttempts ?? maxAttempts;
|
||||
|
||||
let attempt = 0;
|
||||
let capacityAttempts = 0;
|
||||
const MAX_SILENT_CAPACITY_ATTEMPTS = 3;
|
||||
let currentDelay = initialDelayMs;
|
||||
const throwIfAborted = () => {
|
||||
if (signal?.aborted) {
|
||||
@@ -337,7 +339,7 @@ export async function retryWithBackoff<T>(
|
||||
}
|
||||
throwIfAborted();
|
||||
|
||||
const classifiedError = classifyGoogleError(error);
|
||||
let classifiedError = classifyGoogleError(error);
|
||||
|
||||
const errorCode = getErrorStatus(error);
|
||||
|
||||
@@ -345,25 +347,76 @@ export async function retryWithBackoff<T>(
|
||||
classifiedError instanceof TerminalQuotaError ||
|
||||
classifiedError instanceof ModelNotFoundError
|
||||
) {
|
||||
if (onPersistent429) {
|
||||
try {
|
||||
const fallbackModel = await onPersistent429(
|
||||
authType,
|
||||
classifiedError,
|
||||
);
|
||||
if (fallbackModel) {
|
||||
attempt = 0; // Reset attempts and retry with the new model.
|
||||
currentDelay = initialDelayMs;
|
||||
continue;
|
||||
// Fall back to automatic retry for capacity exhaustion in unattended/non-interactive mode,
|
||||
// or allow up to 3 silent retries in interactive mode before prompting the fallback dialog.
|
||||
const isCapacityExceeded =
|
||||
classifiedError instanceof TerminalQuotaError &&
|
||||
(classifiedError.reason === 'MODEL_CAPACITY_EXHAUSTED' ||
|
||||
classifiedError.reason === 'MODEL_CAPACITY_EXCEEDED' ||
|
||||
/exhausted your capacity|capacity exceeded|MODEL_CAPACITY_EXHAUSTED/i.test(
|
||||
classifiedError.message,
|
||||
));
|
||||
|
||||
let useSilentRetry = false;
|
||||
let silentDelayMs: number | undefined;
|
||||
|
||||
if (
|
||||
classifiedError instanceof TerminalQuotaError &&
|
||||
isCapacityExceeded
|
||||
) {
|
||||
if (!onPersistent429) {
|
||||
// Unattended mode: always retry up to standard maxAttempts
|
||||
useSilentRetry = true;
|
||||
silentDelayMs = classifiedError.retryDelayMs;
|
||||
} else {
|
||||
// Interactive mode: allow up to 3 silent retries with progressive backoff before calling fallback handler
|
||||
capacityAttempts++;
|
||||
if (capacityAttempts < MAX_SILENT_CAPACITY_ATTEMPTS) {
|
||||
useSilentRetry = true;
|
||||
silentDelayMs =
|
||||
classifiedError.retryDelayMs !== undefined
|
||||
? classifiedError.retryDelayMs
|
||||
: capacityAttempts === 1
|
||||
? 1000
|
||||
: 3000; // 1s on attempt 1, 3s on attempt 2
|
||||
}
|
||||
} catch (fallbackError) {
|
||||
debugLogger.warn('Fallback to Flash model failed:', fallbackError);
|
||||
}
|
||||
}
|
||||
// Terminal/not_found already recorded; nothing else to mark here.
|
||||
throw classifiedError instanceof Error
|
||||
? enrichQuotaError(classifiedError, authType)
|
||||
: classifiedError; // Throw if no fallback or fallback failed.
|
||||
|
||||
if (useSilentRetry && classifiedError instanceof TerminalQuotaError) {
|
||||
const retryable = new RetryableQuotaError(
|
||||
classifiedError.message,
|
||||
classifiedError.cause,
|
||||
);
|
||||
if (silentDelayMs !== undefined) {
|
||||
retryable.retryDelayMs = silentDelayMs;
|
||||
currentDelay = silentDelayMs;
|
||||
}
|
||||
classifiedError = retryable;
|
||||
} else {
|
||||
if (onPersistent429) {
|
||||
try {
|
||||
const fallbackModel = await onPersistent429(
|
||||
authType,
|
||||
classifiedError,
|
||||
);
|
||||
if (fallbackModel) {
|
||||
attempt = 0; // Reset attempts and retry with the new model.
|
||||
currentDelay = initialDelayMs;
|
||||
continue;
|
||||
}
|
||||
} catch (fallbackError) {
|
||||
debugLogger.warn(
|
||||
'Fallback to Flash model failed:',
|
||||
fallbackError,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Terminal/not_found already recorded; nothing else to mark here.
|
||||
throw classifiedError instanceof Error
|
||||
? enrichQuotaError(classifiedError, authType)
|
||||
: classifiedError; // Throw if no fallback or fallback failed.
|
||||
}
|
||||
}
|
||||
|
||||
// Handle ValidationRequiredError - user needs to verify before proceeding
|
||||
|
||||
Reference in New Issue
Block a user