Skip to content

Commit a056ebc

Browse files
committed
fix(agents): stop fallback on stale gateway lifecycle
1 parent 7fba71e commit a056ebc

5 files changed

Lines changed: 101 additions & 3 deletions

File tree

‎src/agents/failover-error.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* Exercises raw error coercion, remediation hints, timeout/auth/billing/rate-limit cases.
44
*/
55
import { describe, expect, it } from "vitest";
6+
import { createAgentRunStaleLifecycleError } from "../infra/agent-lifecycle-error.js";
67
import { classifyFailoverSignal } from "./embedded-agent-helpers/errors.js";
78
import {
89
buildFailoverRemediationHint,
@@ -1416,6 +1417,17 @@ describe("failover-error", () => {
14161417
).toBe(true);
14171418
});
14181419

1420+
it("returns true for stale gateway lifecycle ownership loss", () => {
1421+
const staleLifecycle = createAgentRunStaleLifecycleError();
1422+
expect(isNonProviderRuntimeCoordinationError(staleLifecycle)).toBe(true);
1423+
expect(
1424+
isNonProviderRuntimeCoordinationError(new Error("wrapper", { cause: staleLifecycle })),
1425+
).toBe(true);
1426+
const abortWrapper = new Error("request was aborted", { cause: staleLifecycle });
1427+
abortWrapper.name = "AbortError";
1428+
expect(isNonProviderRuntimeCoordinationError(abortWrapper)).toBe(true);
1429+
});
1430+
14191431
it("returns true when the coordination error is nested via cause", () => {
14201432
const wrapped = new Error("wrapper", { cause: makeSessionLockError() });
14211433
expect(isNonProviderRuntimeCoordinationError(wrapped)).toBe(true);
@@ -1459,6 +1471,13 @@ describe("failover-error", () => {
14591471
cause: { result: { reason: "missing_tool_result" } },
14601472
}),
14611473
).toBe(false);
1474+
expect(
1475+
isNonProviderRuntimeCoordinationError({
1476+
status: 503,
1477+
message: "upstream overloaded",
1478+
cause: createAgentRunStaleLifecycleError(),
1479+
}),
1480+
).toBe(false);
14621481
expect(isNonProviderRuntimeCoordinationError(null)).toBe(false);
14631482
expect(isNonProviderRuntimeCoordinationError(undefined)).toBe(false);
14641483
});

‎src/agents/failover-error.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
*/
66
import { parseStrictNonNegativeInteger } from "@openclaw/normalization-core/number-coercion";
77
import { formatCliCommand } from "../cli/command-format.js";
8+
import { isAgentRunStaleLifecycleError } from "../infra/agent-lifecycle-error.js";
89
import { readErrorName } from "../infra/errors.js";
910
import {
1011
classifyFailoverSignal,
@@ -496,6 +497,22 @@ function hasMissingToolResultFailure(err: unknown): boolean {
496497
return findErrorProperty(err, readMissingToolResultMarker) === true;
497498
}
498499

500+
function hasStaleAgentRunLifecycleFailure(err: unknown): boolean {
501+
return (
502+
findErrorProperty(err, (candidate) =>
503+
isAgentRunStaleLifecycleError(candidate) ? true : undefined,
504+
) === true
505+
);
506+
}
507+
508+
function hasDirectProviderFailureIdentity(err: unknown): boolean {
509+
if (isFailoverError(err)) {
510+
return true;
511+
}
512+
const signal = normalizeDirectErrorSignal(err);
513+
return Boolean(signal.status || signal.code || signal.errorType || signal.provider);
514+
}
515+
499516
/**
500517
* True when the error is a local runtime coordination/tool-execution error
501518
* rather than a provider/model failure. The model fallback chain must abort on
@@ -899,6 +916,13 @@ export function resolveModelFallbackError(
899916
if (err instanceof AgentHarnessSessionSupersededError) {
900917
return { kind: "coordination", error: err };
901918
}
919+
const staleLifecycleFailure = hasStaleAgentRunLifecycleFailure(err);
920+
if (
921+
staleLifecycleFailure &&
922+
(isAgentRunStaleLifecycleError(err) || !hasDirectProviderFailureIdentity(err))
923+
) {
924+
return { kind: "coordination", error: err };
925+
}
902926
// A direct takeover remains a coordination failure unless the dedicated
903927
// cleanup wrapper owns a preserved prompt error. Its message alone must not
904928
// reclassify session-state loss as a provider failure.
@@ -912,7 +936,8 @@ export function resolveModelFallbackError(
912936
if (
913937
hasSessionWriteLockContention(err) ||
914938
hasEmbeddedAttemptSessionTakeover(err) ||
915-
hasMissingToolResultFailure(err)
939+
hasMissingToolResultFailure(err) ||
940+
staleLifecycleFailure
916941
) {
917942
return { kind: "coordination", error: err };
918943
}

‎src/agents/model-fallback.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { expectDefined } from "@openclaw/normalization-core";
55
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
66
import { TranscriptNotContinuableError } from "../../packages/agent-core/src/errors.js";
77
import type { OpenClawConfig } from "../config/config.js";
8+
import { createAgentRunStaleLifecycleError } from "../infra/agent-lifecycle-error.js";
89
import {
910
onTrustedInternalDiagnosticEvent,
1011
resetDiagnosticEventsForTest,
@@ -1927,6 +1928,38 @@ describe("runWithModelFallback", () => {
19271928
expect(run).toHaveBeenCalledTimes(1);
19281929
});
19291930

1931+
it("aborts the fallback chain on stale gateway lifecycle errors (#116418)", async () => {
1932+
const cfg = makeCfg({
1933+
agents: {
1934+
defaults: {
1935+
model: {
1936+
primary: "ollama/qwen3:0.6b",
1937+
fallbacks: ["minimax/MiniMax-M3"],
1938+
},
1939+
},
1940+
},
1941+
});
1942+
const lifecycleError = createAgentRunStaleLifecycleError();
1943+
const wrappedLifecycleError = new Error("request was aborted", { cause: lifecycleError });
1944+
wrappedLifecycleError.name = "AbortError";
1945+
const run = vi.fn().mockRejectedValue(wrappedLifecycleError);
1946+
const onFallbackStep = vi.fn();
1947+
1948+
await expect(
1949+
runWithModelFallback({
1950+
cfg,
1951+
provider: "ollama",
1952+
model: "qwen3:0.6b",
1953+
run,
1954+
onFallbackStep,
1955+
}),
1956+
).rejects.toBe(wrappedLifecycleError);
1957+
expect(run).toHaveBeenCalledTimes(1);
1958+
expect(onFallbackStep).not.toHaveBeenCalledWith(
1959+
expect.objectContaining({ decision: "candidate_failed" }),
1960+
);
1961+
});
1962+
19301963
it("aborts the fallback chain on transcript continuation failures without candidate_failed attribution", async () => {
19311964
const cfg = makeCfg({
19321965
agents: {

‎src/infra/agent-events.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ import { randomUUID } from "node:crypto";
44
import type { VerboseLevel } from "../auto-reply/thinking.js";
55
import { resolveGlobalSingleton } from "../shared/global-singleton.js";
66
import { notifyListeners, registerListener } from "../shared/listeners.js";
7-
import { createAbortError } from "./abort-signal.js";
87
import { hasInvalidLifecycleStartTimestamp } from "./agent-event-lifecycle.js";
8+
import { createAgentRunStaleLifecycleError } from "./agent-lifecycle-error.js";
99
import { clearAgentRunUsage, resetAgentRunUsageForTest } from "./agent-run-usage.js";
1010

1111
/** Approval event phase for request/resolution transitions. */
@@ -194,7 +194,7 @@ export function assertAgentRunLifecycleGenerationCurrent(lifecycleGeneration: st
194194
if (isAgentEventLifecycleGenerationCurrent(lifecycleGeneration)) {
195195
return;
196196
}
197-
throw createAbortError("Agent run belongs to a stale gateway lifecycle");
197+
throw createAgentRunStaleLifecycleError();
198198
}
199199

200200
/** Captures immutable lifecycle ownership for one admitted execution. */

‎src/infra/agent-lifecycle-error.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const AGENT_RUN_STALE_LIFECYCLE_ERROR = "Agent run belongs to a stale gateway lifecycle";
2+
const AGENT_RUN_STALE_LIFECYCLE_ERROR_CODE = "ERR_STALE_GATEWAY_LIFECYCLE";
3+
4+
export function createAgentRunStaleLifecycleError(): Error {
5+
const error = new Error(AGENT_RUN_STALE_LIFECYCLE_ERROR) as Error & { code: string };
6+
error.name = "AbortError";
7+
error.code = AGENT_RUN_STALE_LIFECYCLE_ERROR_CODE;
8+
return error;
9+
}
10+
11+
export function isAgentRunStaleLifecycleError(value: unknown): boolean {
12+
try {
13+
return (
14+
value instanceof Error &&
15+
"code" in value &&
16+
value.code === AGENT_RUN_STALE_LIFECYCLE_ERROR_CODE
17+
);
18+
} catch {
19+
return false;
20+
}
21+
}

0 commit comments

Comments
 (0)