Skip to content

Commit 90ddeb4

Browse files
authored
refactor(agents): absorb overflow, retry, and matcher duplicates into the failover substrate (#121817)
* refactor(ai): centralize context overflow matching * refactor(agents): add retry evidence and guarded status facets * refactor(agents): absorb assistant retry and key matchers * chore(plugin-sdk): refresh failover closure hashes * fix(agents): consume retry evidence at altitude zero * test(agents): narrow retry corpus provider fixtures * test(agents): keep retry corpus sorting immutable
1 parent aba8f10 commit 90ddeb4

29 files changed

Lines changed: 1182 additions & 423 deletions

‎docs/.generated/plugin-sdk-api-baseline.jsonl‎

Lines changed: 65 additions & 65 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/ai/src/utils/overflow.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { describe, expect, it } from "vitest";
22
import type { AssistantMessage } from "../types.js";
3-
import { isConfiguredContextSizeOverflowError, isContextOverflow } from "./overflow.js";
3+
import {
4+
isConfiguredContextSizeOverflowError,
5+
isContextOverflow,
6+
matchesContextOverflowMessage,
7+
} from "./overflow.js";
48

59
function errorMessage(message: string): AssistantMessage {
610
return {
@@ -64,6 +68,25 @@ describe("provider overflow messages", () => {
6468
});
6569
});
6670

71+
describe("scoped overflow messages", () => {
72+
it("recognizes the provider input-length wording in the strict failover scope", () => {
73+
expect(
74+
matchesContextOverflowMessage(
75+
"input length 14295 tokens exceeds the model limit",
76+
"failover-explicit",
77+
),
78+
).toBe(true);
79+
});
80+
81+
it.each(["too many tokens per day", "token limit exceeded for your billing plan"])(
82+
"keeps the broad assistant fallback out of strict failover matching: %s",
83+
(message) => {
84+
expect(matchesContextOverflowMessage(message, "assistant-error")).toBe(true);
85+
expect(matchesContextOverflowMessage(message, "failover-explicit")).toBe(false);
86+
},
87+
);
88+
});
89+
6790
describe("bodyless HTTP errors", () => {
6891
it("does not treat an ambiguous 400 as context overflow", () => {
6992
expect(isContextOverflow(errorMessage("400 status code (no body)"), 262_144)).toBe(false);

‎packages/ai/src/utils/overflow.ts‎

Lines changed: 68 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ export function isConfiguredContextSizeOverflowError(errorMessage: string): bool
1010
}
1111

1212
/**
13-
* Regex patterns to detect context overflow errors from different providers.
13+
* Canonical scoped patterns for context overflow errors from different providers.
1414
*
1515
* These patterns match error messages returned when the input exceeds
1616
* the model's context window.
@@ -41,7 +41,7 @@ export function isConfiguredContextSizeOverflowError(errorMessage: string): bool
4141
* input filling the context window.
4242
* - Ollama: Some deployments truncate silently, others return errors like "prompt too long; exceeded max context length by X tokens"
4343
*/
44-
const OVERFLOW_PATTERNS = [
44+
const ASSISTANT_OVERFLOW_PATTERNS = [
4545
/prompt is too long/i, // Anthropic token overflow
4646
/request_too_large/i, // Anthropic request byte-size overflow (HTTP 413)
4747
/input is too long for requested model/i, // Amazon Bedrock
@@ -70,9 +70,72 @@ const OVERFLOW_PATTERNS = [
7070
/^413\s*(?:status code)?\s*\(no body\)/i, // Cerebras: 413 with no body
7171
];
7272

73+
const FAILOVER_EXPLICIT_OVERFLOW_PATTERNS = [
74+
/request_too_large/i, // Anthropic request byte-size overflow
75+
/context_overflow/i,
76+
CONFIGURED_CONTEXT_SIZE_OVERFLOW_RE, // DS4 server
77+
/invalid_argument[\s\S]*maximum number of tokens/i, // Google/Vertex
78+
/request exceeds the maximum size/i, // Anthropic
79+
/context length exceeded/i,
80+
/maximum context length/i,
81+
/prompt is too long/i,
82+
/prompt too long/i,
83+
/exceeds model context window/i,
84+
/model token limit/i,
85+
/input exceeds[\s\S]*maximum number of tokens/i,
86+
/^(?=[\s\S]*context window)(?=[\s\S]*ran out of (?:room|space))/i, // Codex
87+
/request size exceeds[\s\S]*context window/i,
88+
/context overflow:/i,
89+
/exceed context limit/i,
90+
/exceeds the model'?s maximum context/i,
91+
/max_tokens[\s\S]*exceed[\s\S]*context/i,
92+
/input length[\s\S]*exceed[\s\S]*context/i,
93+
/413[\s\S]*too large/i,
94+
/context_window_exceeded/i,
95+
// FIXED(refactor-06): PR 2 removed the embedded-429 false positive; this is provider overflow.
96+
/input length [\d,]+\s+tokens? exceeds the model limit/i,
97+
/上下文过长|上下文超出|上下文长度超|超出最大上下文|请压缩上下文/,
98+
];
99+
100+
const PROVIDER_FALLBACK_OVERFLOW_PATTERNS = [
101+
/\binput token count exceeds the maximum number of input tokens\b/i, // AWS Bedrock
102+
/\binput is too long for this model\b/i, // AWS Bedrock stream errors
103+
/\binput exceeds the maximum number of tokens\b/i, // Google Vertex / Gemini
104+
/\bollama error:\s*context length exceeded(?:,\s*too many tokens)?\b/i,
105+
/\btotal tokens?.*exceeds? (?:the )?(?:model(?:'s)? )?(?:max|maximum|limit)/i, // Cohere
106+
/\b(?:request|prompt) \(\d[\d,]*\s*tokens?\) exceeds (?:the )?available context size\b/i, // llama.cpp
107+
/\binput (?:is )?too long for (?:the )?model\b/i,
108+
];
109+
110+
const CONTEXT_OVERFLOW_PATTERN_SCOPES = {
111+
"assistant-error": ASSISTANT_OVERFLOW_PATTERNS,
112+
"failover-explicit": FAILOVER_EXPLICIT_OVERFLOW_PATTERNS,
113+
"provider-fallback": PROVIDER_FALLBACK_OVERFLOW_PATTERNS,
114+
"failover-hint": [
115+
/context.*overflow|context window.*(too (?:large|long)|exceed|over|limit|max(?:imum)?|requested|sent|tokens)|prompt.*(too (?:large|long)|exceed|over|limit|max(?:imum)?)|(?:request|input).*(?:context|window|length|token).*(too (?:large|long)|exceed|over|limit|max(?:imum)?)/i,
116+
],
117+
"context-window-too-small": [/context window.*(too small|minimum is)/i],
118+
"tpm-rate-limit-hint": [/\btpm\b|tokens per minute/i],
119+
"rate-limit-hint": [
120+
/rate limit|too many requests|requests per (?:minute|hour|day)|quota|throttl|429\b|tokens per day/i,
121+
],
122+
} as const;
123+
124+
export type ContextOverflowMessageScope = keyof typeof CONTEXT_OVERFLOW_PATTERN_SCOPES;
125+
126+
/** Match one canonical context-overflow wording scope without applying caller policy. */
127+
export function matchesContextOverflowMessage(
128+
errorMessage: string,
129+
scope: ContextOverflowMessageScope,
130+
): boolean {
131+
return CONTEXT_OVERFLOW_PATTERN_SCOPES[scope].some((pattern: RegExp) =>
132+
pattern.test(errorMessage),
133+
);
134+
}
135+
73136
/**
74137
* Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).
75-
* Error messages matching unknown of these are excluded from overflow detection
138+
* Error messages matching any of these are excluded from overflow detection
76139
* even if they also match an OVERFLOW_PATTERN.
77140
*
78141
* Example: Bedrock formats throttling errors as "ThrottlingException: Too many tokens,
@@ -142,7 +205,7 @@ function resolveContextInputTokens(message: AssistantMessage): number | undefine
142205
* 1. Send a request that exceeds the model's context window
143206
* 2. Check the errorMessage in the response
144207
* 3. Create a regex pattern that matches the error
145-
* 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or
208+
* 4. The pattern should be added to the appropriate canonical scope in this file, or
146209
* check the errorMessage yourself before calling this function
147210
*
148211
* @param message - The assistant message to check
@@ -156,7 +219,7 @@ export function isContextOverflow(message: AssistantMessage, contextWindow?: num
156219
const errorMessage = message.errorMessage;
157220
// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)
158221
const isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(errorMessage));
159-
if (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(errorMessage))) {
222+
if (!isNonOverflow && matchesContextOverflowMessage(errorMessage, "assistant-error")) {
160223
return true;
161224
}
162225
}

‎src/agents/api-key-rotation.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,26 @@ describe("executeWithApiKeyRotation", () => {
264264
expect(sleep).not.toHaveBeenCalled();
265265
});
266266

267+
it.each(["model gpt-5.5-preview-0429 not found", "429 insufficient_quota"])(
268+
"does not rotate keys for %s",
269+
async (message) => {
270+
const execute = vi.fn(async () => {
271+
throw new Error(message);
272+
});
273+
274+
await expect(
275+
executeWithApiKeyRotation({
276+
provider: "openai",
277+
apiKeys: ["key-1", "key-2"],
278+
execute,
279+
}),
280+
).rejects.toThrow(message);
281+
282+
expect(execute).toHaveBeenCalledOnce();
283+
expect(execute).toHaveBeenCalledWith("key-1");
284+
},
285+
);
286+
267287
it("does not rotate keys for transient 500 after same-key retry exhaustion", async () => {
268288
const sleep = vi.fn(async () => undefined);
269289
const execute = vi.fn(async () => {

‎src/agents/embedded-agent-runner/compact-reasons.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,36 @@ describe("classifyCompactionReason", () => {
7272
it("keeps unclassified provider errors in the stable unknown bucket", () => {
7373
expect(classifyCompactionReason("No API provider registered for api: ollama")).toBe("unknown");
7474
});
75+
76+
it.each([
77+
["HTTP 400 invalid request", "provider_error_4xx"],
78+
["error, status code: 400, message: invalid request", "provider_error_4xx"],
79+
["Provider API error (429): too many requests", "provider_error_4xx"],
80+
["OpenAI API error (500): upstream failed", "provider_error_5xx"],
81+
["503 service unavailable", "provider_error_5xx"],
82+
])("classifies guarded provider status %s", (reason, expected) => {
83+
expect(classifyCompactionReason(reason)).toBe(expected);
84+
});
85+
86+
it.each([402, 404, 408, 413, 501, 521, 524, 529])(
87+
"does not expand the established provider bucket set to HTTP %i",
88+
(status) => {
89+
expect(classifyCompactionReason(`HTTP ${status} provider response`)).toBe("unknown");
90+
},
91+
);
92+
93+
it.each([
94+
"request id req-4291 failed",
95+
"input length 14295 tokens exceeds the model limit",
96+
"model model-x-500-preview not found",
97+
])("ignores embedded status-like numbers: %s", (reason) => {
98+
// FIXED(refactor-06): numeric payload text is not an HTTP status.
99+
expect(classifyCompactionReason(reason)).toBe("unknown");
100+
});
101+
102+
it("preserves timeout precedence over its HTTP status bucket", () => {
103+
expect(classifyCompactionReason("504 Gateway Timeout")).toBe("timeout");
104+
});
75105
});
76106

77107
describe("isBenignCompactionSkipReason", () => {

‎src/agents/embedded-agent-runner/compact-reasons.ts‎

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@
33
*/
44
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
55
import { sanitizeForLog } from "../../../packages/terminal-core/src/ansi.js";
6+
import { extractFailoverHttpStatus } from "../failover/retry-evidence.js";
67

78
const MAX_COMPACTION_REASON_DETAIL_CHARS = 100;
9+
const COMPACTION_PROVIDER_4XX = new Set([400, 401, 403, 429]);
10+
const COMPACTION_PROVIDER_5XX = new Set([500, 502, 503, 504]);
811

912
export const DEFERRED_CONTEXT_ENGINE_COMPACTION_REASON =
1013
"deferred to background context-engine maintenance";
@@ -60,20 +63,11 @@ export function classifyCompactionReason(reason?: string): string {
6063
if (text.includes("timed out") || text.includes("timeout")) {
6164
return "timeout";
6265
}
63-
if (
64-
text.includes("400") ||
65-
text.includes("401") ||
66-
text.includes("403") ||
67-
text.includes("429")
68-
) {
66+
const status = extractFailoverHttpStatus(reason, { includeLabeledStatus: true });
67+
if (status !== undefined && COMPACTION_PROVIDER_4XX.has(status)) {
6968
return "provider_error_4xx";
7069
}
71-
if (
72-
text.includes("500") ||
73-
text.includes("502") ||
74-
text.includes("503") ||
75-
text.includes("504")
76-
) {
70+
if (status !== undefined && COMPACTION_PROVIDER_5XX.has(status)) {
7771
return "provider_error_5xx";
7872
}
7973
return "unknown";

‎src/agents/embedded-agent-runner/run.overflow-compaction.harness.ts‎

Lines changed: 13 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/**
22
* Test harness mocks for embedded-run overflow compaction coverage.
33
*/
4-
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
4+
import { matchesContextOverflowMessage } from "@openclaw/ai/internal/runtime";
55
import { type Mock, vi } from "vitest";
66
import type { ThinkLevel } from "../../auto-reply/thinking.js";
77
import type { ContextEngineSessionTarget } from "../../context-engine/types.js";
@@ -20,6 +20,7 @@ import type {
2020
} from "../../plugins/types.js";
2121
import { resetCommandQueueStateForTest } from "../../process/command-queue.test-support.js";
2222
import type { AuthProfileStore } from "../auth-profiles/types.js";
23+
import { extractObservedOverflowTokenCount } from "../embedded-agent-helpers/context-overflow-observation.js";
2324
import type { FailoverReason } from "../failover/signal.js";
2425
import { clearAgentHarnesses, registerAgentHarness } from "../harness/registry.js";
2526
import type { ResolvedProviderAuth } from "../model-auth-runtime-shared.js";
@@ -335,10 +336,7 @@ export const mockedClassifyAssistantFailoverReason = vi.fn(
335336
(assistant?: { errorMessage?: string | null }): FailoverReason | null =>
336337
mockedClassifyFailoverReason(assistant?.errorMessage ?? ""),
337338
);
338-
const mockedExtractObservedOverflowTokenCount = vi.fn((msg?: string) => {
339-
const match = msg?.match(/prompt is too long:\s*([\d,]+)\s+tokens\s*>\s*[\d,]+\s+maximum/i);
340-
return match?.[1] ? Number(match[1].replaceAll(",", "")) : undefined;
341-
});
339+
const mockedExtractObservedOverflowTokenCount = vi.fn(extractObservedOverflowTokenCount);
342340
export const mockedFormatAssistantErrorText = vi.fn(() => "");
343341
const mockedIsAuthAssistantError = vi.fn(() => false);
344342
const mockedIsBillingAssistantError = vi.fn(() => false);
@@ -348,15 +346,15 @@ const mockedIsFailoverErrorMessage = vi.fn(() => false);
348346
const mockedIsGenericUnknownStreamErrorMessage = vi.fn((raw: string) =>
349347
/^\s*an unknown error occurred\.?\s*$/i.test(raw),
350348
);
351-
export const mockedIsLikelyContextOverflowError = vi.fn((msg?: string) => {
352-
const lower = normalizeLowercaseStringOrEmpty(msg ?? "");
349+
function matchesCanonicalOverflowFixture(msg?: string): boolean {
350+
const raw = msg ?? "";
353351
return (
354-
lower.includes("request_too_large") ||
355-
lower.includes("context window exceeded") ||
356-
(lower.includes("context window") && lower.includes("ran out of room")) ||
357-
lower.includes("prompt is too long")
352+
matchesContextOverflowMessage(raw, "failover-explicit") ||
353+
matchesContextOverflowMessage(raw, "provider-fallback") ||
354+
matchesContextOverflowMessage(raw, "failover-hint")
358355
);
359-
});
356+
}
357+
export const mockedIsLikelyContextOverflowError = vi.fn(matchesCanonicalOverflowFixture);
360358
const mockedParseImageSizeError = vi.fn(() => null);
361359
const mockedParseImageDimensionError = vi.fn(() => null);
362360
export const mockedIsRateLimitAssistantError = vi.fn<MockAssistantErrorProbe>(() => false);
@@ -574,10 +572,7 @@ function resetRunOverflowCompactionHarnessMocks(): void {
574572
mockedIsBillingAssistantError.mockReset();
575573
mockedIsBillingAssistantError.mockReturnValue(false);
576574
mockedExtractObservedOverflowTokenCount.mockReset();
577-
mockedExtractObservedOverflowTokenCount.mockImplementation((msg?: string) => {
578-
const match = msg?.match(/prompt is too long:\s*([\d,]+)\s+tokens\s*>\s*[\d,]+\s+maximum/i);
579-
return match?.[1] ? Number(match[1].replaceAll(",", "")) : undefined;
580-
});
575+
mockedExtractObservedOverflowTokenCount.mockImplementation(extractObservedOverflowTokenCount);
581576
mockedIsCompactionFailureError.mockReset();
582577
mockedIsCompactionFailureError.mockReturnValue(false);
583578
mockedIsFailoverAssistantError.mockReset();
@@ -589,15 +584,7 @@ function resetRunOverflowCompactionHarnessMocks(): void {
589584
/^\s*an unknown error occurred\.?\s*$/i.test(raw),
590585
);
591586
mockedIsLikelyContextOverflowError.mockReset();
592-
mockedIsLikelyContextOverflowError.mockImplementation((msg?: string) => {
593-
const lower = normalizeLowercaseStringOrEmpty(msg ?? "");
594-
return (
595-
lower.includes("request_too_large") ||
596-
lower.includes("context window exceeded") ||
597-
(lower.includes("context window") && lower.includes("ran out of room")) ||
598-
lower.includes("prompt is too long")
599-
);
600-
});
587+
mockedIsLikelyContextOverflowError.mockImplementation(matchesCanonicalOverflowFixture);
601588
mockedParseImageSizeError.mockReset();
602589
mockedParseImageSizeError.mockReturnValue(null);
603590
mockedParseImageDimensionError.mockReset();
@@ -721,15 +708,7 @@ export function resetSharedRunIntegrationHarnessMocks(): void {
721708
mockedIsFailoverAssistantError.mockReset();
722709
mockedIsFailoverAssistantError.mockReturnValue(false);
723710
mockedIsLikelyContextOverflowError.mockReset();
724-
mockedIsLikelyContextOverflowError.mockImplementation((msg?: string) => {
725-
const lower = normalizeLowercaseStringOrEmpty(msg ?? "");
726-
return (
727-
lower.includes("request_too_large") ||
728-
lower.includes("context window exceeded") ||
729-
(lower.includes("context window") && lower.includes("ran out of room")) ||
730-
lower.includes("prompt is too long")
731-
);
732-
});
711+
mockedIsLikelyContextOverflowError.mockImplementation(matchesCanonicalOverflowFixture);
733712
mockedIsRateLimitAssistantError.mockReset();
734713
mockedIsRateLimitAssistantError.mockReturnValue(false);
735714
mockedResolveAuthProfileOrder.mockReset();

‎src/agents/embedded-agent-runner/run/assistant-failover.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import { sanitizeForLog } from "../../../../packages/terminal-core/src/ansi.js";
55
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
66
import type { AssistantMessage } from "../../../llm/types.js";
7-
import { classifyRateLimitWindow } from "../../../llm/utils/rate-limit-window.js";
87
import {
98
projectAgentRunAttemptTerminal,
109
type AgentRunAttemptTerminal,
@@ -17,6 +16,7 @@ import {
1716
type FailoverReason,
1817
} from "../../embedded-agent-helpers.js";
1918
import { FailoverError, resolveFailoverStatus } from "../../failover-error.js";
19+
import { classifyRateLimitWindow } from "../../failover/retry-evidence.js";
2020
import {
2121
mergeRetryFailoverReason,
2222
resolveRunFailoverDecision,

0 commit comments

Comments
 (0)