Skip to content

Commit ee454f3

Browse files
committed
test(agents): harden silent fallback proof
1 parent b40d7f7 commit ee454f3

3 files changed

Lines changed: 205 additions & 218 deletions

File tree

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
3+
import { FailoverError } from "../../failover-error.js";
4+
import { runWithModelFallback } from "../../model-fallback-runner.js";
5+
import {
6+
buildEmbeddedRunnerAssistant,
7+
makeEmbeddedRunnerAttempt,
8+
} from "../../test-helpers/embedded-agent-runner-e2e-fixtures.js";
9+
import { handleEmbeddedAssistantFailure } from "./assistant-failure.js";
10+
import { resolveEmbeddedRunAttemptTerminalState } from "./terminal-outcome.js";
11+
12+
const CREDENTIAL_FILE_ENOENT_MESSAGE =
13+
"ENOENT: no such file or directory, open '/home/operator/.claude/.credentials.json'";
14+
15+
type AssistantFailureInput = Parameters<typeof handleEmbeddedAssistantFailure>[0];
16+
17+
function makeExhaustedCredentialFailureInput(options?: { replaySafe?: boolean }) {
18+
const replaySafe = options?.replaySafe !== false;
19+
const assistant = buildEmbeddedRunnerAssistant({
20+
provider: "anthropic",
21+
model: "mock-1",
22+
stopReason: "error",
23+
errorMessage: CREDENTIAL_FILE_ENOENT_MESSAGE,
24+
});
25+
const attempt = makeEmbeddedRunnerAttempt({
26+
lastAssistant: assistant,
27+
currentAttemptAssistant: assistant,
28+
toolMetas: replaySafe ? [] : [{ toolName: "write", replaySafe: false }],
29+
});
30+
const advanceAttemptAuthProfile = vi.fn(async () => true);
31+
const maybeMarkAuthProfileFailure = vi.fn(async () => {});
32+
const traceAttempts: AssistantFailureInput["traceAttempts"] = [];
33+
const input: AssistantFailureInput = {
34+
runParams: {
35+
sessionId: "session:credential-enoent",
36+
runId: "run:credential-enoent",
37+
config: undefined,
38+
} as AssistantFailureInput["runParams"],
39+
attempt,
40+
attemptAssistant: assistant,
41+
currentAttemptAssistant: assistant,
42+
terminalState: resolveEmbeddedRunAttemptTerminalState({
43+
attempt,
44+
assistant,
45+
}),
46+
activeErrorContext: { provider: "anthropic", model: "mock-1" },
47+
provider: "anthropic",
48+
modelId: "mock-1",
49+
model: "mock-1",
50+
thinkLevel: "off",
51+
getThinkLevel: () => "off",
52+
attemptedThinking: new Set(["off"]),
53+
fallbackConfigured: true,
54+
pluginHarnessOwnsTransport: false,
55+
canRestartForLiveSwitch: false,
56+
authProfileId: "anthropic:p1",
57+
authProfileStore: {
58+
version: 1,
59+
profiles: {
60+
"anthropic:p1": {
61+
type: "api_key",
62+
provider: "anthropic",
63+
key: "test-key",
64+
},
65+
"anthropic:p2": {
66+
type: "api_key",
67+
provider: "anthropic",
68+
key: "test-key-2",
69+
},
70+
},
71+
usageStats: {
72+
"anthropic:p1": { lastUsed: 1 },
73+
"anthropic:p2": { lastUsed: 2 },
74+
},
75+
},
76+
runtimeAuthRetry: false,
77+
maybeRefreshRuntimeAuthForAuthError: vi.fn(async () => false),
78+
resolveAuthProfileFailureReason: () => null,
79+
emptyErrorRetries: 3,
80+
overloadProfileRotations: 0,
81+
overloadProfileRotationLimit: 1,
82+
rateLimitProfileRotations: 0,
83+
rateLimitProfileRotationLimit: 1,
84+
sameModelIdleTimeoutRetries: 0,
85+
previousRetryFailoverReason: null,
86+
maybeMarkAuthProfileFailure,
87+
maybeEscalateRateLimitProfileFallback: vi.fn(),
88+
maybeRetrySameModelRateLimit: vi.fn(async () => false),
89+
maybeBackoffBeforeOverloadFailover: vi.fn(async () => {}),
90+
advanceAttemptAuthProfile,
91+
traceAttempts,
92+
suspendForFailure: vi.fn(),
93+
suspensionSessionId: "session:credential-enoent",
94+
agentDir: "/tmp/openclaw-assistant-failure-test",
95+
isProbeSession: false,
96+
};
97+
return {
98+
advanceAttemptAuthProfile,
99+
input,
100+
maybeMarkAuthProfileFailure,
101+
traceAttempts,
102+
};
103+
}
104+
105+
describe("handleEmbeddedAssistantFailure", () => {
106+
it("falls back after exhausted replay-safe credential-file retries without touching auth state", async () => {
107+
const fixture = makeExhaustedCredentialFailureInput();
108+
109+
await expect(handleEmbeddedAssistantFailure(fixture.input)).rejects.toMatchObject({
110+
reason: "unknown",
111+
provider: "anthropic",
112+
model: "mock-1",
113+
rawError: CREDENTIAL_FILE_ENOENT_MESSAGE,
114+
});
115+
116+
expect(fixture.advanceAttemptAuthProfile).not.toHaveBeenCalled();
117+
expect(fixture.maybeMarkAuthProfileFailure).not.toHaveBeenCalled();
118+
expect(fixture.input.authProfileStore.usageStats).toEqual({
119+
"anthropic:p1": { lastUsed: 1 },
120+
"anthropic:p2": { lastUsed: 2 },
121+
});
122+
expect(fixture.traceAttempts).toEqual([
123+
{
124+
provider: "anthropic",
125+
model: "mock-1",
126+
result: "fallback_model",
127+
reason: "unknown",
128+
stage: "assistant",
129+
},
130+
]);
131+
});
132+
133+
it("does not fallback credential-file ENOENT after replay-unsafe tool activity", async () => {
134+
const fixture = makeExhaustedCredentialFailureInput({ replaySafe: false });
135+
136+
const outcome = await handleEmbeddedAssistantFailure(fixture.input);
137+
138+
expect(outcome.action).toBe("proceed");
139+
expect(fixture.advanceAttemptAuthProfile).not.toHaveBeenCalled();
140+
expect(fixture.maybeMarkAuthProfileFailure).not.toHaveBeenCalled();
141+
expect(fixture.traceAttempts).toEqual([]);
142+
});
143+
144+
it("does not cache an exact credential-file failure from a fallback candidate", async () => {
145+
const previous = process.env.OPENCLAW_FALLBACK_SKIP_TTL_MS;
146+
process.env.OPENCLAW_FALLBACK_SKIP_TTL_MS = "60000";
147+
try {
148+
const config = {
149+
agents: {
150+
defaults: {
151+
model: {
152+
primary: "openai/mock-0",
153+
fallbacks: ["anthropic/mock-1", "groq/mock-2"],
154+
},
155+
},
156+
},
157+
} satisfies OpenClawConfig;
158+
const calls: string[] = [];
159+
const run = async (provider: string, model: string) => {
160+
calls.push(`${provider}/${model}`);
161+
if (provider === "openai") {
162+
throw new FailoverError("primary rate limited", {
163+
provider,
164+
model,
165+
reason: "rate_limit",
166+
});
167+
}
168+
if (provider === "anthropic") {
169+
await handleEmbeddedAssistantFailure(makeExhaustedCredentialFailureInput().input);
170+
}
171+
return "ok";
172+
};
173+
174+
for (let turn = 0; turn < 2; turn += 1) {
175+
const result = await runWithModelFallback({
176+
cfg: config,
177+
provider: "openai",
178+
model: "mock-0",
179+
sessionId: "session:credential-enoent-no-skip",
180+
skipAuthProfileRuntime: true,
181+
run,
182+
});
183+
expect(result.result).toBe("ok");
184+
}
185+
186+
expect(calls).toEqual([
187+
"openai/mock-0",
188+
"anthropic/mock-1",
189+
"groq/mock-2",
190+
"openai/mock-0",
191+
"anthropic/mock-1",
192+
"groq/mock-2",
193+
]);
194+
} finally {
195+
if (previous === undefined) {
196+
delete process.env.OPENCLAW_FALLBACK_SKIP_TTL_MS;
197+
} else {
198+
process.env.OPENCLAW_FALLBACK_SKIP_TTL_MS = previous;
199+
}
200+
}
201+
});
202+
});

0 commit comments

Comments
 (0)