Skip to content

Commit 4716cbf

Browse files
authored
refactor(agents): avoid unnecessary failure classification (#134008)
1 parent 43e9a3d commit 4716cbf

10 files changed

Lines changed: 141 additions & 108 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1864,7 +1864,7 @@ src/agents/embedded-agent-utils.ts 3
18641864
src/agents/exec-auto-reviewer.ts 1
18651865
src/agents/exec-defaults.ts 2
18661866
src/agents/execution-auth-binding.ts 1
1867-
src/agents/failover-error.ts 15
1867+
src/agents/failover-error.ts 12
18681868
src/agents/failover/retry-evidence.ts 1
18691869
src/agents/failover/signal-details.ts 1
18701870
src/agents/fallback-skip-cache.ts 1

‎qa/scenarios/channels/provider-http-503-visible-failure.yaml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,8 @@ flow:
8484
timeoutMs:
8585
expr: liveTurnTimeoutMs(env, 180000)
8686
- assert:
87-
expr: "!outbound.deleted && outbound.conversation.id === config.conversationId && outbound.conversation.kind === 'channel' && outbound.isError === true && outbound.text === config.expectedReply"
88-
message: expected one classified provider failure on the original conversation
87+
expr: "!outbound.deleted && outbound.accountId === env.transport.accountId && outbound.conversation.id === config.conversationId && outbound.conversation.kind === 'channel' && outbound.isError === true && outbound.text === config.expectedReply"
88+
message: expected one classified provider failure on the original account and conversation
8989
- call: sleep
9090
args:
9191
- expr: liveTurnTimeoutMs(env, 8000)

‎src/agents/command/lifecycle.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { normalizeAgentRunTerminalDeliverySnapshot } from "../agent-run-terminal
55
import type { AgentRunTerminalOutcome } from "../agent-run-terminal-outcome.js";
66
import { normalizeAgentRunTerminalReceipt } from "../agent-run-terminal-receipt.js";
77
import type { EmbeddedAgentRunEntryTerminal } from "../embedded-agent-runner/run-entry.js";
8-
import { describeFailoverError } from "../failover-error.js";
8+
import { getFailoverErrorCode } from "../failover/error.js";
99
import { renderFailoverCodeUserCopy } from "../failover/user-copy.js";
1010
import {
1111
AGENT_RUN_SUPERSEDED_STOP_REASON,
@@ -18,7 +18,7 @@ import type { AgentAttemptResult } from "./runtime-loaders.js";
1818
const log = createSubsystemLogger("agents/agent-command");
1919

2020
const formatLifecycleError = (error: unknown): string =>
21-
renderFailoverCodeUserCopy(describeFailoverError(error).code) ?? formatErrorMessage(error);
21+
renderFailoverCodeUserCopy(getFailoverErrorCode(error)) ?? formatErrorMessage(error);
2222

2323
function resolveTerminalLogLevel(
2424
outcome: AgentRunTerminalOutcome,

‎src/agents/embedded-agent-runner/run/auth-controller.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,9 @@ import {
2020
isFailoverErrorMessage,
2121
type FailoverReason,
2222
} from "../../embedded-agent-helpers.js";
23-
import {
24-
describeFailoverError,
25-
FailoverError,
26-
resolveFailoverStatus,
27-
} from "../../failover-error.js";
23+
import { FailoverError, resolveFailoverStatus } from "../../failover-error.js";
2824
import { shouldUseTransientCooldownProbeSlot } from "../../failover-policy.js";
25+
import { getFailoverErrorCode } from "../../failover/error.js";
2926
import { renderAuthProfileFailoverCopy } from "../../failover/user-copy.js";
3027
import {
3128
getApiKeyForModelCore,
@@ -502,7 +499,7 @@ export function createEmbeddedRunAuthController(params: {
502499
model: modelId,
503500
authMode,
504501
status: resolveFailoverStatus(reason),
505-
code: failoverParams.error ? describeFailoverError(failoverParams.error).code : undefined,
502+
code: failoverParams.error ? getFailoverErrorCode(failoverParams.error) : undefined,
506503
authProfileFailure: { allInCooldown: failoverParams.allInCooldown },
507504
cause: failoverParams.error,
508505
});

‎src/agents/failover-error.ts‎

Lines changed: 2 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
getErrorMessage,
2121
isFailoverError,
2222
isTimeoutError,
23+
readDirectErrorCode,
2324
readDirectErrorMessage,
2425
type CliTimeoutContext,
2526
} from "./failover/error.js";
@@ -174,32 +175,6 @@ function getStatusCode(err: unknown): number | undefined {
174175
return findErrorProperty(err, readDirectStatusCode);
175176
}
176177

177-
function readDirectErrorCode(err: unknown): string | undefined {
178-
if (!err || typeof err !== "object") {
179-
return undefined;
180-
}
181-
const directCode = (err as { code?: unknown }).code;
182-
if (typeof directCode === "string") {
183-
const trimmed = directCode.trim();
184-
return trimmed ? trimmed : undefined;
185-
}
186-
const detailCode = (err as { detail?: { code?: unknown } }).detail?.code;
187-
if (typeof detailCode === "string") {
188-
const trimmed = detailCode.trim();
189-
return trimmed ? trimmed : undefined;
190-
}
191-
const status = (err as { status?: unknown }).status;
192-
if (typeof status !== "string" || /^\d+$/.test(status)) {
193-
return undefined;
194-
}
195-
const trimmed = status.trim();
196-
return trimmed ? trimmed : undefined;
197-
}
198-
199-
function getErrorCode(err: unknown): string | undefined {
200-
return findErrorProperty(err, readDirectErrorCode);
201-
}
202-
203178
function isStableProviderErrorType(value: string): boolean {
204179
if (
205180
/^(?:api|authentication|invalid_request|not_found|overloaded|permission|rate_limit|server)_error$/i.test(
@@ -397,7 +372,7 @@ function normalizeErrorSignal(err: unknown, providerHint?: string): FailoverSign
397372
const message = getErrorMessage(err);
398373
return {
399374
status: getStatusCode(err),
400-
code: getErrorCode(err),
375+
code: findErrorProperty(err, readDirectErrorCode),
401376
errorType: getErrorType(err),
402377
message: message || undefined,
403378
provider: getProvider(err) ?? providerHint,

‎src/agents/failover/error.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,36 @@ export function findErrorProperty<T>(
126126
);
127127
}
128128

129+
export function readDirectErrorCode(err: unknown): string | undefined {
130+
if (!err || typeof err !== "object") {
131+
return undefined;
132+
}
133+
// SAFETY: The object guard permits probing code; its value remains unknown.
134+
const directCode = (err as { code?: unknown }).code;
135+
if (typeof directCode === "string") {
136+
const trimmed = directCode.trim();
137+
return trimmed ? trimmed : undefined;
138+
}
139+
// SAFETY: Optional chaining handles absent details; only string codes are accepted.
140+
const detailCode = (err as { detail?: { code?: unknown } }).detail?.code;
141+
if (typeof detailCode === "string") {
142+
const trimmed = detailCode.trim();
143+
return trimmed ? trimmed : undefined;
144+
}
145+
// SAFETY: The object guard permits probing status; its type is checked below.
146+
const status = (err as { status?: unknown }).status;
147+
if (typeof status !== "string" || /^\d+$/.test(status)) {
148+
return undefined;
149+
}
150+
const trimmed = status.trim();
151+
return trimmed ? trimmed : undefined;
152+
}
153+
154+
export function getFailoverErrorCode(err: unknown): string | undefined {
155+
// A typed failure owns its code, including absence; only raw errors search causes.
156+
return isFailoverError(err) ? err.code : findErrorProperty(err, readDirectErrorCode);
157+
}
158+
129159
export function readDirectErrorMessage(err: unknown): string | undefined {
130160
if (err instanceof Error) {
131161
return err.message || undefined;

‎src/agents/session-model-auto-revert.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,10 @@ export function createAgentPatchedSessionModelRunGuard(params: {
166166
let failure: { error?: unknown; reason?: FailoverReason } = {};
167167
let reconciled = false;
168168
const captureFailure = (error: unknown, reason?: string) => {
169+
// Only the patch captured when this guard was created can be reconciled.
170+
if (markerTs === undefined) {
171+
return false;
172+
}
169173
const classifiedReason = reason
170174
? (reason as FailoverReason)
171175
: resolveFailoverReasonFromError(error);

‎src/agents/tools/sessions-tool.test.ts‎

Lines changed: 52 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { GatewayClientRequestError } from "../../gateway/client.js";
1616
import { isAgentSessionModelPatchOrigin } from "../../gateway/session-model-patch-origin.js";
1717
import { beginSessionWorkAdmission } from "../../sessions/session-lifecycle-admission.js";
1818
import { withTestDir } from "../../test-helpers/temp-dir.js";
19+
import * as failoverErrors from "../failover-error.js";
1920
import { createAgentPatchedSessionModelRunGuard } from "../session-model-auto-revert.js";
2021
import { withGatewayToolCallerIdentity } from "./gateway-caller-context.js";
2122
import type { AgentToolGatewayRequestCaller } from "./in-process-gateway.js";
@@ -606,28 +607,26 @@ describe("sessions tool", () => {
606607
session: { store: storePath },
607608
agents: { defaults: { model: { primary: "openai/good" } } },
608609
};
609-
await upsertSessionEntryCore(
610-
{ agentId: "main", sessionKey, storePath },
611-
{
612-
sessionId: "session-main",
613-
updatedAt: 1,
614-
model: "good",
615-
modelProvider: "openai",
616-
modelOverride: "good",
617-
providerOverride: "openai",
618-
modelOverrideSource: "auto",
619-
modelOverrideFallbackOriginProvider: "openai",
620-
modelOverrideFallbackOriginModel: "primary",
621-
authProfileOverride: "good-profile",
622-
authProfileOverrideSource: "user",
623-
thinkingLevel: "high",
624-
},
625-
);
610+
const sessionScope = { agentId: "main", sessionKey, storePath };
611+
await upsertSessionEntryCore(sessionScope, {
612+
sessionId: "session-main",
613+
updatedAt: 1,
614+
model: "good",
615+
modelProvider: "openai",
616+
modelOverride: "good",
617+
providerOverride: "openai",
618+
modelOverrideSource: "auto",
619+
modelOverrideFallbackOriginProvider: "openai",
620+
modelOverrideFallbackOriginModel: "primary",
621+
authProfileOverride: "good-profile",
622+
authProfileOverrideSource: "user",
623+
thinkingLevel: "high",
624+
});
626625
const callGateway = vi.fn(
627626
async (request: { method: string; params: Record<string, unknown> }) => {
628627
expect(request.method).toBe("sessions.patch");
629628
expect(isAgentSessionModelPatchOrigin()).toBe(true);
630-
await patchSessionEntryCore({ agentId: "main", sessionKey, storePath }, () => ({
629+
await patchSessionEntryCore(sessionScope, () => ({
631630
label: request.params.label as string,
632631
model: "bad",
633632
modelProvider: "broken",
@@ -662,12 +661,9 @@ describe("sessions tool", () => {
662661
config: cfg,
663662
callGateway: callGateway as never,
664663
});
665-
const currentRunGuard = createAgentPatchedSessionModelRunGuard({
666-
cfg,
667-
agentId: "main",
668-
sessionKey,
669-
storePath,
670-
});
664+
const guardParams = { cfg, ...sessionScope };
665+
const currentRunGuard = createAgentPatchedSessionModelRunGuard(guardParams);
666+
const failedCurrentRunGuard = createAgentPatchedSessionModelRunGuard(guardParams);
671667

672668
await tool.execute("patch-model", {
673669
action: "patch",
@@ -683,7 +679,7 @@ describe("sessions tool", () => {
683679
model: "broken/bad",
684680
},
685681
});
686-
expect(loadSessionEntry({ agentId: "main", sessionKey, storePath })).toMatchObject({
682+
expect(loadSessionEntry(sessionScope)).toMatchObject({
687683
label: "Research",
688684
modelFallback: {
689685
prevModel: "good",
@@ -697,18 +693,36 @@ describe("sessions tool", () => {
697693
},
698694
});
699695
await currentRunGuard.finish(true);
700-
expect(loadSessionEntry({ agentId: "main", sessionKey, storePath })).toHaveProperty(
701-
"modelFallback",
702-
);
696+
expect(loadSessionEntry(sessionScope)).toHaveProperty("modelFallback");
697+
698+
const failure = { status: 404, message: "No endpoints found for broken/bad." };
699+
const entryBeforeFailure = loadSessionEntry(sessionScope);
700+
const transcriptScope = { ...sessionScope, sessionId: "session-main" };
701+
const transcriptBeforeFailure = await loadTranscriptEvents(transcriptScope);
702+
const classifyFailure = vi
703+
.spyOn(failoverErrors, "resolveFailoverReasonFromError")
704+
.mockImplementation(() => {
705+
throw new Error("An unarmed model-patch guard must not classify failures");
706+
});
707+
try {
708+
expect(failedCurrentRunGuard.captureFallbackFailure([])).toBeUndefined();
709+
expect(failedCurrentRunGuard.captureFailure(failure)).toBe(false);
710+
expect(
711+
failedCurrentRunGuard.captureFallbackFailure([
712+
{ error: failure.message, reason: "model_not_found" },
713+
]),
714+
).toBe(false);
715+
await failedCurrentRunGuard.fail(failure);
716+
expect(classifyFailure).not.toHaveBeenCalled();
717+
} finally {
718+
classifyFailure.mockRestore();
719+
}
720+
expect(loadSessionEntry(sessionScope)).toEqual(entryBeforeFailure);
721+
expect(await loadTranscriptEvents(transcriptScope)).toEqual(transcriptBeforeFailure);
703722

704-
const runGuard = createAgentPatchedSessionModelRunGuard({
705-
cfg,
706-
agentId: "main",
707-
sessionKey,
708-
storePath,
709-
});
710-
await runGuard.fail({ status: 404, message: "No endpoints found for broken/bad." });
711-
expect(loadSessionEntry({ agentId: "main", sessionKey, storePath })).toMatchObject({
723+
const runGuard = createAgentPatchedSessionModelRunGuard(guardParams);
724+
await runGuard.fail(failure);
725+
expect(loadSessionEntry(sessionScope)).toMatchObject({
712726
model: "good",
713727
modelProvider: "openai",
714728
modelOverrideSource: "auto",
@@ -717,15 +731,8 @@ describe("sessions tool", () => {
717731
authProfileOverride: "good-profile",
718732
thinkingLevel: "high",
719733
});
720-
expect(loadSessionEntry({ agentId: "main", sessionKey, storePath })).not.toHaveProperty(
721-
"modelFallback",
722-
);
723-
const events = await loadTranscriptEvents({
724-
agentId: "main",
725-
sessionId: "session-main",
726-
sessionKey,
727-
storePath,
728-
});
734+
expect(loadSessionEntry(sessionScope)).not.toHaveProperty("modelFallback");
735+
const events = await loadTranscriptEvents(transcriptScope);
729736
expect(events).toContainEqual(
730737
expect.objectContaining({
731738
message: expect.objectContaining({
Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,56 @@
11
import { describe, expect, it, vi } from "vitest";
22
import { FailoverError } from "../../agents/failover-error.js";
33
import { renderFailoverCodeUserCopy } from "../../agents/failover/user-copy.js";
4+
import * as providerFailover from "../../plugins/provider-failover.js";
45
import { createAgentLifecycleTerminalBackstop } from "./agent-lifecycle-terminal.js";
56

67
const { emitAgentEvent } = vi.hoisted(() => ({ emitAgentEvent: vi.fn() }));
78

89
vi.mock("../../infra/agent-events.js", () => ({ emitAgentEvent }));
910

1011
describe("createAgentLifecycleTerminalBackstop", () => {
11-
it("publishes bounded selected-profile recovery from typed failures", () => {
12-
const profileId = "openai:private-profile";
13-
const rawCause = `Codex app-server auth profile "${profileId}" was not found`;
14-
const terminal = createAgentLifecycleTerminalBackstop({
15-
runId: "missing-selected-profile",
16-
sessionKey: "agent:main:test",
17-
getLifecycleGeneration: () => "test-generation",
18-
resolveTerminationFields: () => ({}),
19-
});
12+
it.each(["typed", "raw"] as const)(
13+
"publishes bounded selected-profile recovery from %s failures without discovering providers",
14+
(kind) => {
15+
const classifyProvider = vi
16+
.spyOn(providerFailover, "classifyProviderFailoverSignalWithPlugin")
17+
.mockImplementation(() => {
18+
throw new Error("Terminal presentation must not discover providers");
19+
});
20+
emitAgentEvent.mockClear();
21+
try {
22+
const profileId = "openai:private-profile";
23+
const rawCause = `Codex app-server auth profile "${profileId}" was not found`;
24+
const terminal = createAgentLifecycleTerminalBackstop({
25+
runId: "missing-selected-profile",
26+
sessionKey: "agent:main:test",
27+
getLifecycleGeneration: () => "test-generation",
28+
resolveTerminationFields: () => ({}),
29+
});
2030

21-
terminal.emit(
22-
"error",
23-
new FailoverError(rawCause, {
24-
reason: "auth",
25-
code: "selected_auth_profile_unavailable",
26-
profileId,
27-
cause: new Error(rawCause),
28-
}),
29-
);
31+
const error =
32+
kind === "typed"
33+
? new FailoverError(rawCause, {
34+
reason: "auth",
35+
code: "selected_auth_profile_unavailable",
36+
profileId,
37+
cause: new Error(rawCause),
38+
})
39+
: Object.assign(new Error(rawCause), {
40+
code: "selected_auth_profile_unavailable",
41+
});
42+
terminal.emit("error", error);
3043

31-
const event = emitAgentEvent.mock.calls[0]?.[0];
32-
expect(event.data.error).toBe(renderFailoverCodeUserCopy("selected_auth_profile_unavailable"));
33-
expect(JSON.stringify(event)).not.toContain(profileId);
34-
expect(JSON.stringify(event)).not.toContain(rawCause);
35-
});
44+
const event = emitAgentEvent.mock.calls[0]?.[0];
45+
expect(event.data.error).toBe(
46+
renderFailoverCodeUserCopy("selected_auth_profile_unavailable"),
47+
);
48+
expect(JSON.stringify(event)).not.toContain(profileId);
49+
expect(JSON.stringify(event)).not.toContain(rawCause);
50+
expect(classifyProvider).not.toHaveBeenCalled();
51+
} finally {
52+
classifyProvider.mockRestore();
53+
}
54+
},
55+
);
3656
});

‎src/auto-reply/reply/agent-lifecycle-terminal.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { readStringValue } from "@openclaw/normalization-core/string-coerce";
2-
import { describeFailoverError } from "../../agents/failover-error.js";
2+
import { getFailoverErrorCode } from "../../agents/failover/error.js";
33
import { renderFailoverCodeUserCopy } from "../../agents/failover/user-copy.js";
44
import { AGENT_RUN_RESTART_ABORT_STOP_REASON } from "../../agents/run-termination.js";
55
import { emitAgentEvent } from "../../infra/agent-events.js";
@@ -102,7 +102,7 @@ export function createAgentLifecycleTerminalBackstop(params: {
102102
data.stopReason = AGENT_RUN_RESTART_ABORT_STOP_REASON;
103103
} else if (phase === "error") {
104104
data.error =
105-
renderFailoverCodeUserCopy(describeFailoverError(resultOrError).code) ??
105+
renderFailoverCodeUserCopy(getFailoverErrorCode(resultOrError)) ??
106106
formatErrorMessage(resultOrError);
107107
Object.assign(data, terminationFields);
108108
} else {

0 commit comments

Comments
 (0)