Skip to content

Commit afd1a36

Browse files
authored
perf(agents): reuse loaded provider hooks during error handling (#133970)
* perf(agents): reuse loaded provider hooks during error handling * test(agents): prepare release fixtures before provider error handling Use real durable session writer admission in fault sequences, preserve attempt session identity, and close the fixture's database owners after assertions. Complete the empty provider-hook mock for thrown harness errors and retain fresh source/compiled provider proof through explicit preparation.
1 parent 3fd6fcd commit afd1a36

14 files changed

Lines changed: 247 additions & 84 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ Docs: https://docs.openclaw.ai
7171

7272
### Fixes
7373

74+
- Provider error handling: reuse prepared or already loaded provider hooks instead of cold-loading plugins during error classification, avoiding long stalls in failure reporting and model fallback.
7475
- **Subagent completion:** recognize visible final answers delivered to internal and nested parent sessions, preventing false delivery failures while preserving external channel delivery checks.
7576
- Codex/Linux: wait for a live app-server process to expose its startup command line within the existing inspection deadline, preserving process identity checks and preventing intermittent startup failures.
7677
- **Cloud session lifecycle:** prevent archive, delete, and restart recovery from deadlocking behind an earlier worker move, keep work admission closed through cleanup, and preserve the same successor for concurrent recovery requests.

‎docs/plugins/sdk-provider-plugins.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,7 @@ catalog, API-key auth, and dynamic model resolution.
777777

778778
Runtime fallback notes:
779779

780+
- Error classification uses the prepared provider owner or already loaded provider hooks. `matchesContextOverflowError` and `classifyFailoverReason` never trigger plugin discovery while handling an error; provider preparation owns loading those hooks.
780781
- `normalizeConfig` resolves one owning plugin per provider id (bundled providers first, then the matched runtime plugin) and calls only that hook - there is no scan across other providers. Google's own `normalizeConfig` hook is what normalizes `google` / `google-vertex` / `google-antigravity` config entries; it is not a separate core fallback.
781782
- `resolveConfigApiKey` uses the provider hook when exposed. Amazon Bedrock keeps AWS env-marker resolution in its provider plugin; runtime auth itself still uses the AWS SDK default chain when configured with `auth: "aws-sdk"`.
782783
- `resolveThinkingProfile(ctx)` receives the selected `provider`, `modelId`, optional merged `reasoning` catalog hint, and optional merged model `compat` facts. Use `compat` only to select the provider's thinking UI/profile.

‎src/agents/admitted-run-context.test-support.ts‎

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,24 +25,19 @@ export function withTestAdmittedRunContext<T extends { runId: string }>(
2525
};
2626
}
2727

28-
/** Adapts a production runner only at a test boundary; production stays fail-closed. */
29-
export function wrapRunWithTestAdmission<P extends { runId: string }, R>(
30-
run: (params: P) => R,
31-
): (params: Omit<P, "admittedRunContext" | "preparedRunAdmission">) => R {
32-
return (params) =>
33-
run({
34-
...params,
35-
admittedRunContext: createTestAdmittedRunContext(params.runId),
36-
} as unknown as P);
37-
}
38-
3928
/** Exercises the real post-selection admission boundary without enabling audit collection. */
4029
export function wrapRunWithTestPreparedAdmission<P extends { runId: string }, R>(
41-
run: (params: P) => R,
42-
): (params: Omit<P, "admittedRunContext" | "preparedRunAdmission">) => R {
43-
return (params) =>
44-
run({
45-
...params,
46-
preparedRunAdmission: createTestPreparedRunAdmission(params.runId),
47-
} as unknown as P);
30+
run: (params: P) => Promise<R>,
31+
): (params: Omit<P, "admittedRunContext" | "preparedRunAdmission">) => Promise<R> {
32+
return async (params) => {
33+
// Fixtures reset modules before loading runners; authority must use that same
34+
// module instance and remain owned until the complete runner call settles.
35+
const { prepareSystemAgentRunAdmission } = await import("./admitted-run-context.js");
36+
const admission = prepareSystemAgentRunAdmission({}, params.runId, "test", "runner-fixture");
37+
try {
38+
return await run({ ...params, preparedRunAdmission: admission } as unknown as P);
39+
} finally {
40+
admission.close();
41+
}
42+
};
4843
}

‎src/agents/admitted-run-context.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ import {
1414
retainAdmittedRunBeforeToolCallRecovery,
1515
resolveAdmittedRunActiveAssertion,
1616
resolvePreparedRunAdmission,
17+
type PreparedAgentRunAdmission,
1718
} from "./admitted-run-context.js";
19+
import { wrapRunWithTestPreparedAdmission } from "./admitted-run-context.test-support.js";
1820

1921
const enabledConfig = { logging: { audit: { enabled: true, executionIdentity: true } } };
2022
const facts = {
@@ -32,6 +34,37 @@ afterEach(() => {
3234
});
3335

3436
describe("prepared run admission", () => {
37+
it.each([false, true])(
38+
"owns real fixture authority across module resets and runner settlement (reject=%s)",
39+
async (reject) => {
40+
vi.resetModules();
41+
const admissionOwner = await import("./admitted-run-context.js");
42+
const failure = new Error("runner failed");
43+
let assertActive: (() => void) | undefined;
44+
const run = wrapRunWithTestPreparedAdmission(
45+
async (params: { runId: string; preparedRunAdmission: PreparedAgentRunAdmission }) => {
46+
const admitted = await params.preparedRunAdmission.admit("embedded");
47+
expect(await params.preparedRunAdmission.admit("plugin-harness")).toBe(admitted);
48+
expect(admitted).not.toHaveProperty("executionIdentityToken");
49+
assertActive = admissionOwner.resolveAdmittedRunActiveAssertion(admitted);
50+
expect(assertActive).toBeTypeOf("function");
51+
assertActive?.();
52+
if (reject) {
53+
throw failure;
54+
}
55+
return "done";
56+
},
57+
);
58+
const result = run({ runId: `runner-fixture-${reject}` });
59+
if (reject) {
60+
await expect(result).rejects.toBe(failure);
61+
} else {
62+
await expect(result).resolves.toBe("done");
63+
}
64+
expect(() => assertActive?.()).toThrow("no longer active");
65+
},
66+
);
67+
3568
it("creates distinct operational instances without identity while disabled", async () => {
3669
const { runtime, ...admissionFacts } = facts;
3770
const first = await prepareAgentRunAdmission({

‎src/agents/cli-runner.before-agent-reply-cron.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
type DiagnosticEventPayload,
1414
} from "../infra/diagnostic-events.js";
1515
import type { HookRunner } from "../plugins/hooks.js";
16-
import { wrapRunWithTestAdmission } from "./admitted-run-context.test-support.js";
16+
import { wrapRunWithTestPreparedAdmission } from "./admitted-run-context.test-support.js";
1717
import { testing as cliBackendsTesting } from "./cli-backends.test-support.js";
1818
import type { CliOutput } from "./cli-output-contracts.js";
1919
import { CliAuthProfilePreparationError } from "./cli-runner/auth-profile-preparation-error.js";
@@ -189,7 +189,7 @@ beforeEach(() => {
189189

190190
beforeAll(async () => {
191191
const cliRunner = await import("./cli-runner.js");
192-
runCliAgent = wrapRunWithTestAdmission(cliRunner.runCliAgent);
192+
runCliAgent = wrapRunWithTestPreparedAdmission(cliRunner.runCliAgent);
193193
({ restoreCliRunnerTestDeps, setCliRunnerTestDeps } = cliRunner);
194194
});
195195

‎src/agents/embedded-agent-runner.run-embedded-agent.auth-profile-rotation.e2e.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
77
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
88
import type { OpenClawConfig } from "../config/config.js";
99
import { redactIdentifier } from "../logging/redact-identifier.js";
10-
import { wrapRunWithTestAdmission } from "./admitted-run-context.test-support.js";
10+
import { wrapRunWithTestPreparedAdmission } from "./admitted-run-context.test-support.js";
1111
import {
1212
resolveInlineProviderApiKeyUsageId,
1313
type AuthProfileFailureReason,
@@ -116,7 +116,7 @@ const originalFetch = globalThis.fetch;
116116
beforeAll(async () => {
117117
vi.resetModules();
118118
installRunEmbeddedMocks();
119-
runEmbeddedAgent = wrapRunWithTestAdmission(
119+
runEmbeddedAgent = wrapRunWithTestPreparedAdmission(
120120
(await import("./embedded-agent-runner/run.js")).runEmbeddedAgent,
121121
);
122122
({ createDiagnosticLogRecordCapture: createDiagnosticLogRecordCaptureFn } =

‎src/agents/embedded-agent-runner.run-embedded-agent.fault-sequences.e2e.test.ts‎

Lines changed: 57 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import os from "node:os";
44
import path from "node:path";
55
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
66
import type { OpenClawConfig } from "../config/config.js";
7-
import { wrapRunWithTestAdmission } from "./admitted-run-context.test-support.js";
8-
import { ensureAuthProfileStore, saveAuthProfileStore } from "./auth-profiles/store.js";
7+
import { wrapRunWithTestPreparedAdmission } from "./admitted-run-context.test-support.js";
98
import {
109
classifyEmbeddedAgentRunResultForModelFallback,
1110
mergeEmbeddedAgentRunResultForModelFallbackExhaustion,
@@ -23,10 +22,6 @@ import {
2322
installEmbeddedRunnerBaseE2eMocks,
2423
installEmbeddedRunnerFastRunE2eMocks,
2524
} from "./test-helpers/embedded-agent-runner-e2e-mocks.js";
26-
import {
27-
captureRoutingDecisionWork,
28-
createModelRoutingTestAdmission,
29-
} from "./test-helpers/model-routing-decision-e2e-fixtures.js";
3025

3126
type ProviderFault =
3227
| { status: 200; text: string }
@@ -77,6 +72,10 @@ type TestRunEmbeddedAgent = (
7772
let runEmbeddedAgent: TestRunEmbeddedAgent;
7873
let runEmbeddedAgentWithPreparedAdmission: ProductionRunEmbeddedAgent;
7974
let runWithModelFallback: typeof import("./model-fallback-runner.js").runWithModelFallback;
75+
let captureRoutingDecisionWork: typeof import("./test-helpers/model-routing-decision-e2e-fixtures.js").captureRoutingDecisionWork;
76+
let createModelRoutingTestAdmission: typeof import("./test-helpers/model-routing-decision-e2e-fixtures.js").createModelRoutingTestAdmission;
77+
let ensureAuthProfileStore: typeof import("./auth-profiles/store.js").ensureAuthProfileStore;
78+
let saveAuthProfileStore: typeof import("./auth-profiles/store.js").saveAuthProfileStore;
8079

8180
beforeAll(async () => {
8281
vi.resetModules();
@@ -95,8 +94,11 @@ beforeAll(async () => {
9594

9695
runEmbeddedAgentWithPreparedAdmission = (await import("./embedded-agent-runner/run.js"))
9796
.runEmbeddedAgent;
98-
runEmbeddedAgent = wrapRunWithTestAdmission(runEmbeddedAgentWithPreparedAdmission);
97+
runEmbeddedAgent = wrapRunWithTestPreparedAdmission(runEmbeddedAgentWithPreparedAdmission);
9998
({ runWithModelFallback } = await import("./model-fallback-runner.js"));
99+
({ captureRoutingDecisionWork, createModelRoutingTestAdmission } =
100+
await import("./test-helpers/model-routing-decision-e2e-fixtures.js"));
101+
({ ensureAuthProfileStore, saveAuthProfileStore } = await import("./auth-profiles/store.js"));
100102
});
101103

102104
beforeEach(() => {
@@ -139,7 +141,7 @@ async function withScenarioWorkspace<T>(
139141
): Promise<T> {
140142
const rawRoot = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-fault-sequences-"));
141143
const root = await fs.realpath(rawRoot);
142-
const agentDir = path.join(root, "agent");
144+
const agentDir = path.join(root, "agents", "test", "agent");
143145
const workspaceDir = path.join(root, "workspace");
144146
await Promise.all([
145147
fs.mkdir(agentDir, { recursive: true }),
@@ -148,7 +150,18 @@ async function withScenarioWorkspace<T>(
148150
try {
149151
return await run({ agentDir, workspaceDir });
150152
} finally {
151-
await fs.rm(root, { recursive: true, force: true });
153+
const { waitForSessionTranscriptIndexReconcile } =
154+
await import("../config/sessions/session-transcript-reconcile.js");
155+
const { closeOpenClawAgentDatabaseByPath } = await import("../state/openclaw-agent-db.js");
156+
const { closeAuthProfileReadPool } = await import("./auth-profiles/sqlite.js");
157+
const databasePath = path.join(agentDir, "openclaw-agent.sqlite");
158+
try {
159+
await waitForSessionTranscriptIndexReconcile({ agentId: "test", path: databasePath });
160+
} finally {
161+
closeAuthProfileReadPool({ kind: "database", databasePath });
162+
closeOpenClawAgentDatabaseByPath(databasePath);
163+
await fs.rm(root, { recursive: true, force: true });
164+
}
152165
}
153166
}
154167

@@ -233,15 +246,20 @@ function makeAttemptForFault(
233246
function installFaultScript(faults: ProviderFault[], observations: AttemptObservation[]): void {
234247
let index = 0;
235248
runEmbeddedAttemptMock.mockImplementation(async (rawParams: unknown) => {
236-
const params = rawParams as { provider: string; modelId?: string; authProfileId?: string };
249+
const params = rawParams as {
250+
provider: string;
251+
modelId?: string;
252+
authProfileId?: string;
253+
sessionId: string;
254+
};
237255
const fault = faults[index];
238256
if (!fault) {
239257
throw new Error(`unexpected provider attempt ${index + 1}`);
240258
}
241259
index += 1;
242260
const ref = { provider: params.provider, model: params.modelId ?? "unknown" };
243261
observations.push({ ...ref, profileId: params.authProfileId, fault });
244-
return makeAttemptForFault(fault, ref);
262+
return { ...makeAttemptForFault(fault, ref), sessionIdUsed: params.sessionId };
245263
});
246264
}
247265

@@ -251,14 +269,27 @@ async function runScenario(params: {
251269
config: OpenClawConfig;
252270
runId: string;
253271
}): Promise<ScenarioOutcome> {
272+
const { replaceSessionEntry } = await import("../config/sessions/session-accessor.js");
273+
const sessionTarget = {
274+
agentId: "test",
275+
sessionId: `session:${params.runId}`,
276+
sessionKey: `agent:test:${params.runId}`,
277+
storePath: path.join(params.agentDir, "openclaw-agent.sqlite"),
278+
};
254279
try {
280+
// The synthetic attempt skips transcript creation; seed the real row so the
281+
// runner claims its writer normally before entering compaction recovery.
282+
await replaceSessionEntry(sessionTarget, {
283+
sessionId: sessionTarget.sessionId,
284+
updatedAt: Date.now(),
285+
});
255286
const outcome = await runWithModelFallback<EmbeddedAgentRunResult>({
256287
cfg: params.config,
257288
provider: "openai",
258289
model: "mock-1",
259290
runId: params.runId,
260-
sessionId: `session:${params.runId}`,
261-
sessionKey: `agent:test:${params.runId}`,
291+
sessionId: sessionTarget.sessionId,
292+
sessionKey: sessionTarget.sessionKey,
262293
agentDir: params.agentDir,
263294
classifyResult: ({ provider, model, result }) =>
264295
classifyEmbeddedAgentRunResultForModelFallback({ provider, model, result }),
@@ -269,8 +300,9 @@ async function runScenario(params: {
269300
}),
270301
run: async (provider, model, options) =>
271302
await runEmbeddedAgent({
272-
sessionId: `session:${params.runId}`,
273-
sessionKey: `agent:test:${params.runId}`,
303+
sessionId: sessionTarget.sessionId,
304+
sessionKey: sessionTarget.sessionKey,
305+
sessionTarget,
274306
workspaceDir: params.workspaceDir,
275307
agentDir: params.agentDir,
276308
config: params.config,
@@ -305,7 +337,6 @@ async function readUsageStats(agentDir: string) {
305337
}
306338

307339
function expectResult(outcome: ScenarioOutcome): Extract<ScenarioOutcome, { kind: "result" }> {
308-
expect(outcome.kind).toBe("result");
309340
if (outcome.kind !== "result") {
310341
throw outcome.error;
311342
}
@@ -363,9 +394,10 @@ async function expectPreparationInvalidationToDropRoutingWork(
363394
}
364395
return await realMkdir(target, options);
365396
});
397+
let run: ReturnType<ProductionRunEmbeddedAgent> | undefined;
366398
try {
367399
const { decisionWork } = await captureRoutingDecisionWork(async () => {
368-
const run = runEmbeddedAgentWithPreparedAdmission({
400+
run = runEmbeddedAgentWithPreparedAdmission({
369401
preparedRunAdmission: preparedAdmission,
370402
sessionId: `session:${runId}`,
371403
sessionKey: `agent:test:${runId}`,
@@ -379,7 +411,12 @@ async function expectPreparationInvalidationToDropRoutingWork(
379411
runId,
380412
enqueue: async (task) => await task(),
381413
});
382-
await reachedPreparation.promise;
414+
await Promise.race([
415+
reachedPreparation.promise,
416+
run.then(() => {
417+
throw new Error("embedded run settled before attempt preparation");
418+
}),
419+
]);
383420
if (mode === "close") {
384421
preparedAdmission.close();
385422
} else {
@@ -400,6 +437,8 @@ async function expectPreparationInvalidationToDropRoutingWork(
400437
releasePreparation.resolve();
401438
replacementAdmission?.close();
402439
preparedAdmission.close();
440+
// The rejection is observed above; join all run work before restoring its checkpoint.
441+
await Promise.allSettled(run ? [run] : []);
403442
mkdirSpy.mockRestore();
404443
}
405444
});

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -822,6 +822,8 @@ export async function loadRunOverflowCompactionHarness(): Promise<{
822822
// real handle shape without rediscovering every bundled provider plugin.
823823
vi.doMock("../../plugins/provider-hook-runtime.js", () => ({
824824
attachModelProviderRuntimePluginHandle: (model: object) => model,
825+
resolveLoadedProviderPluginsForHooks: vi.fn(() => undefined),
826+
resolveLoadedProviderRuntimePlugin: vi.fn(() => undefined),
825827
resolveProviderRuntimePluginHandle: vi.fn((params: Record<string, unknown>) => params),
826828
resolveProviderHookPlugin: vi.fn(() => undefined),
827829
resolveProviderPluginsForHooks: vi.fn(() => []),

‎src/agents/model-fallback.run-embedded.e2e.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import os from "node:os";
44
import path from "node:path";
55
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
66
import type { OpenClawConfig } from "../config/config.js";
7-
import { wrapRunWithTestAdmission } from "./admitted-run-context.test-support.js";
7+
import { wrapRunWithTestPreparedAdmission } from "./admitted-run-context.test-support.js";
88
import type { AuthProfileFailureReason } from "./auth-profiles.js";
99
import { ensureAuthProfileStore, saveAuthProfileStore } from "./auth-profiles/store.js";
1010
import { classifyEmbeddedAgentRunResultForModelFallback } from "./embedded-agent-runner/result-fallback-classifier.js";
@@ -94,7 +94,7 @@ beforeAll(async () => {
9494
installRunEmbeddedMocks();
9595
runEmbeddedAgentWithPreparedAdmission = (await import("./embedded-agent-runner/run.js"))
9696
.runEmbeddedAgent;
97-
runEmbeddedAgent = wrapRunWithTestAdmission(runEmbeddedAgentWithPreparedAdmission);
97+
runEmbeddedAgent = wrapRunWithTestPreparedAdmission(runEmbeddedAgentWithPreparedAdmission);
9898
({ runWithModelFallback } = await import("./model-fallback-runner.js"));
9999
({ runEmbeddedAgentEntry } = await import("./embedded-agent-runner/run-entry.js"));
100100
});

‎src/agents/test-helpers/embedded-agent-runner-e2e-mocks.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,8 @@ export function installEmbeddedRunnerBaseE2eMocks(options?: {
171171
vi.doMock("../../plugins/provider-hook-runtime.js", () => ({
172172
attachModelProviderRuntimePluginHandle: (model: unknown) => model,
173173
prepareProviderExtraParams: vi.fn(() => undefined),
174+
resolveLoadedProviderPluginsForHooks: vi.fn(() => undefined),
175+
resolveLoadedProviderRuntimePlugin: vi.fn(() => undefined),
174176
resolveProviderExtraParamsForTransport: vi.fn(() => undefined),
175177
resolveProviderHookPlugin: vi.fn(() => undefined),
176178
resolveProviderPluginsForHooks: vi.fn(() => []),

0 commit comments

Comments
 (0)