Skip to content

Commit 79e6755

Browse files
authored
fix(agents): prevent reloads from losing queued replies or restoring stale credentials (#128138)
* fix(agents): fence retired prepared runtime generations * test(agents): prove queued turns survive credential reload
1 parent c0197b6 commit 79e6755

8 files changed

Lines changed: 389 additions & 24 deletions

File tree

‎src/agents/prepared-model-runtime-generation-scope.ts‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import { AsyncLocalStorage } from "node:async_hooks";
22
import { resolveGlobalSingleton } from "../shared/global-singleton.js";
3-
import type { PreparedModelRuntimePluginGeneration } from "./prepared-model-runtime.types.js";
3+
import type {
4+
PreparedModelRuntimePluginGeneration,
5+
PreparedModelRuntimeSnapshot,
6+
} from "./prepared-model-runtime.types.js";
7+
8+
type PreparedModelRuntimeGenerationScope = Readonly<{
9+
generation: PreparedModelRuntimePluginGeneration;
10+
borrowSnapshot?: () => PreparedModelRuntimeSnapshot | undefined;
11+
}>;
412

513
// Global singleton keeps one scope instance across lazy module boundaries so a
614
// wrapped turn and the nested embedded runner always share the same store.
@@ -9,15 +17,22 @@ const PREPARED_MODEL_RUNTIME_PLUGIN_GENERATION_SCOPE_KEY: unique symbol = Symbol
917
);
1018

1119
const preparedModelRuntimePluginGenerationScope = resolveGlobalSingleton<
12-
AsyncLocalStorage<PreparedModelRuntimePluginGeneration | undefined>
20+
AsyncLocalStorage<PreparedModelRuntimeGenerationScope | undefined>
1321
>(PREPARED_MODEL_RUNTIME_PLUGIN_GENERATION_SCOPE_KEY, () => new AsyncLocalStorage());
1422

1523
/** Keeps the exact admitted generation available to nested embedded agent runs. */
1624
export function withPreparedModelRuntimePluginGenerationScope<T>(
1725
generation: PreparedModelRuntimePluginGeneration,
1826
run: () => T,
27+
borrowSnapshot?: () => PreparedModelRuntimeSnapshot | undefined,
1928
): T {
20-
return preparedModelRuntimePluginGenerationScope.run(generation, run);
29+
const inherited = preparedModelRuntimePluginGenerationScope.getStore();
30+
const borrow =
31+
borrowSnapshot ?? (inherited?.generation === generation ? inherited.borrowSnapshot : undefined);
32+
return preparedModelRuntimePluginGenerationScope.run(
33+
{ generation, ...(borrow ? { borrowSnapshot: borrow } : {}) },
34+
run,
35+
);
2136
}
2237

2338
/** Detached queue drains re-admit on the current generation, never a predecessor's scope. */
@@ -29,5 +44,13 @@ export function runOutsidePreparedModelRuntimePluginGenerationScope<T>(run: () =
2944
export function getPreparedModelRuntimePluginGeneration():
3045
| PreparedModelRuntimePluginGeneration
3146
| undefined {
32-
return preparedModelRuntimePluginGenerationScope.getStore();
47+
return preparedModelRuntimePluginGenerationScope.getStore()?.generation;
48+
}
49+
50+
/** Borrows the exact parent snapshot only while its owning turn lease remains open. */
51+
export function getPreparedModelRuntimeBorrowedSnapshot(
52+
generation: PreparedModelRuntimePluginGeneration,
53+
): PreparedModelRuntimeSnapshot | undefined {
54+
const current = preparedModelRuntimePluginGenerationScope.getStore();
55+
return current?.generation === generation ? current.borrowSnapshot?.() : undefined;
3356
}

‎src/agents/prepared-model-runtime-lease.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
/** Agent-run lease admission for lifecycle-owned prepared model runtimes. */
22
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
33
import { isReservedSystemAgentId } from "../system-agent/agent-id.js";
4+
import { getPreparedModelRuntimeBorrowedSnapshot } from "./prepared-model-runtime-generation-scope.js";
45
import {
56
PreparedModelRuntimeOwnerNotPublishedError,
67
PreparedModelRuntimePublicationSupersededError,
78
hasConfiguredOwnerMatching,
89
ownerKey,
910
normalizePreparedModelRuntimeInput,
11+
preparedModelRuntimeConfigsMatch,
1012
publishModelRuntimeSnapshot,
1113
rebindInputToCommittedConfiguredOwner,
14+
resolveConfiguredOwner,
1215
type PreparedModelRuntimeInput,
1316
type PreparedModelRuntimeLease,
1417
type PreparedModelRuntimeOwner,
@@ -78,6 +81,42 @@ export async function acquirePreparedModelRuntimeLeaseFromOwners(
7881
}
7982
continue;
8083
}
84+
if (provenance === "run" && context.getGatewayLifecycleActive() && options.pluginGeneration) {
85+
const configuredOwner = resolveConfiguredOwner(context.owners, input);
86+
if (configuredOwner?.pending) {
87+
await configuredOwner.pending.catch(() => undefined);
88+
continue;
89+
}
90+
if (
91+
configuredOwner &&
92+
(configuredOwner.needsRefresh ||
93+
configuredOwner.pluginGeneration !== options.pluginGeneration)
94+
) {
95+
const borrowed = getPreparedModelRuntimeBorrowedSnapshot(options.pluginGeneration);
96+
if (
97+
!configuredOwner.needsRefresh &&
98+
borrowed &&
99+
borrowed.metadataSnapshot === options.pluginGeneration.pluginMetadataSnapshot &&
100+
preparedModelRuntimeConfigsMatch(borrowed.config, input.config) &&
101+
borrowed.agentId === input.agentId &&
102+
borrowed.agentDir === input.agentDir &&
103+
borrowed.inheritedAuthDir === input.inheritedAuthDir &&
104+
borrowed.workspaceDir === input.workspaceDir &&
105+
(!input.allowGatewaySubagentBinding || borrowed.allowGatewaySubagentBinding) &&
106+
!input.readOnly &&
107+
!input.loadRuntimePlugins &&
108+
!input.skipCredentials &&
109+
!input.env
110+
) {
111+
// A turn may finish under its still-open parent lease after reload. Its historic
112+
// generation must never publish over the configured owner for newly admitted work.
113+
return { snapshot: borrowed, release: () => {} };
114+
}
115+
throw new PreparedModelRuntimeOwnerNotPublishedError(
116+
`prepared model runtime plugin generation was superseded for ${input.agentDir}`,
117+
);
118+
}
119+
}
81120
let existing = context.owners.get(key);
82121
let staleDynamicOwner =
83122
existing?.needsRefresh &&

‎src/agents/prepared-model-runtime.owner-selection.test.ts‎

Lines changed: 154 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import path from "node:path";
1111
import { beforeEach, describe, expect, it, vi } from "vitest";
1212
import { retainLegacyDefaultAgentId } from "../config/legacy.default-agent-owner.js";
1313
import { createEmptyPluginRegistry } from "../plugins/registry-empty.js";
14+
import { withPreparedModelRuntimePluginGenerationScope } from "./prepared-model-runtime-generation-scope.js";
1415
import {
1516
acquireAgentRunPreparedModelRuntime,
1617
acquireReadOnlyPreparedModelRuntime,
@@ -246,7 +247,7 @@ describe("prepared model runtime owner selection", () => {
246247
expect(mocks.ensureOpenClawModelsJson).not.toHaveBeenCalled();
247248
});
248249

249-
it("sequences pending owners by their explicit plugin generation", async () => {
250+
it("rejects unpublished plugin generations while matching pending callers share their owner", async () => {
250251
mocks.configuredAgentIds = ["default"];
251252
const config = {};
252253
await refreshPreparedModelRuntimeSnapshots(config, { gatewayLifecycle: true });
@@ -281,24 +282,170 @@ describe("prepared model runtime owner selection", () => {
281282
});
282283
const pendingB = acquireAgentRunPreparedModelRuntime(input, {
283284
pluginGeneration: generationB,
284-
});
285+
}).catch((error: unknown) => error);
285286
await Promise.resolve();
286287
expect(mocks.ensureOpenClawModelsJson).toHaveBeenCalledTimes(2);
287288
finishGenerationA();
288-
const [leaseA, matchingLeaseA, leaseB] = await Promise.all([
289+
const [leaseA, matchingLeaseA, rejectedGeneration] = await Promise.all([
289290
pendingA,
290291
matchingPendingA,
291292
pendingB,
292293
]);
293294

294295
expect(matchingLeaseA.snapshot).toBe(leaseA.snapshot);
295-
expect(leaseB.snapshot).not.toBe(leaseA.snapshot);
296+
expect(rejectedGeneration).toEqual(
297+
expect.objectContaining({ message: expect.stringContaining("superseded") }),
298+
);
296299
expect(leaseA.snapshot.metadataSnapshot).toBe(generationA!.pluginMetadataSnapshot);
297-
expect(leaseB.snapshot.metadataSnapshot).toBe(generationB.pluginMetadataSnapshot);
300+
await expect(prepareModelRuntimeSnapshot(input)).resolves.toBe(leaseA.snapshot);
298301
leaseA.release();
299302
matchingLeaseA.release();
300-
await expect(prepareModelRuntimeSnapshot(input)).resolves.toBe(leaseB.snapshot);
301-
leaseB.release();
303+
});
304+
305+
it("keeps a committed gateway owner current when an admitted turn resumes on its older generation", async () => {
306+
mocks.configuredAgentIds = ["default"];
307+
const defaults = {
308+
model: "openai/gpt-5",
309+
models: {
310+
"openai/gpt-5": { params: { transport: "sse" as const, openaiWsWarmup: false } },
311+
},
312+
};
313+
const previousConfig = {
314+
agents: { defaults },
315+
messages: { responsePrefix: "previous" },
316+
};
317+
const committedConfig = {
318+
agents: { defaults },
319+
messages: { responsePrefix: "committed" },
320+
};
321+
const publicationOptions = {
322+
allowGatewaySubagentBinding: true,
323+
catalogMode: "static" as const,
324+
gatewayLifecycle: true,
325+
};
326+
const runInput = (config: typeof previousConfig) => ({
327+
agentId: "default",
328+
agentDir: "/tmp/unused-agent",
329+
allowGatewaySubagentBinding: true,
330+
config,
331+
runtimePluginSelections: [{ provider: "openai", modelId: "gpt-5", runtime: "openclaw" }],
332+
workspaceDir: "/tmp/unused-workspace",
333+
});
334+
335+
await refreshPreparedModelRuntimeSnapshots(previousConfig, publicationOptions);
336+
const admitted = await loadPublishedGatewayReplyDispatchRuntime({ agentId: "default" });
337+
const previousSnapshot = getPreparedModelRuntimeSnapshot(runInput(previousConfig));
338+
expect(admitted?.pluginGeneration).toBeDefined();
339+
expect(previousSnapshot).toBeDefined();
340+
341+
const outerLease = await acquireAgentRunPreparedModelRuntime(runInput(previousConfig), {
342+
catalogMode: "static",
343+
pluginGeneration: admitted!.pluginGeneration,
344+
});
345+
expect(outerLease.snapshot).toBe(previousSnapshot);
346+
let outerLeaseActive = true;
347+
348+
await refreshPreparedModelRuntimeSnapshots(committedConfig, publicationOptions);
349+
const committedSnapshot = getPreparedModelRuntimeSnapshot(runInput(committedConfig));
350+
const registryLoads = mocks.loadAgentRuntimePluginRegistryHandle.mock.calls.length;
351+
expect(committedSnapshot).toBeDefined();
352+
expect(committedSnapshot).not.toBe(previousSnapshot);
353+
let releaseDetachedAdmission!: () => void;
354+
const detachedAdmissionGate = new Promise<void>((resolve) => {
355+
releaseDetachedAdmission = resolve;
356+
});
357+
let detachedAdmission!: Promise<unknown>;
358+
359+
try {
360+
await withPreparedModelRuntimePluginGenerationScope(
361+
admitted!.pluginGeneration,
362+
async () => {
363+
const resumed = await withPreparedModelRuntimePluginGenerationScope(
364+
admitted!.pluginGeneration,
365+
async () =>
366+
await acquireAgentRunPreparedModelRuntime(runInput(previousConfig), {
367+
catalogMode: "static",
368+
pluginGeneration: admitted!.pluginGeneration,
369+
}),
370+
);
371+
372+
expect(resumed.snapshot).toBe(previousSnapshot);
373+
expect(getPreparedModelRuntimeSnapshot(runInput(committedConfig))).toBe(
374+
committedSnapshot,
375+
);
376+
expect(mocks.loadAgentRuntimePluginRegistryHandle).toHaveBeenCalledTimes(registryLoads);
377+
resumed.release();
378+
const clonedConfigLease = await acquireAgentRunPreparedModelRuntime(
379+
runInput(structuredClone(previousConfig)),
380+
{ pluginGeneration: admitted!.pluginGeneration },
381+
);
382+
expect(clonedConfigLease.snapshot).toBe(previousSnapshot);
383+
clonedConfigLease.release();
384+
await expect(
385+
acquireAgentRunPreparedModelRuntime(
386+
{ ...runInput(previousConfig), workspaceDir: "/tmp/different-workspace" },
387+
{ pluginGeneration: admitted!.pluginGeneration },
388+
),
389+
).rejects.toThrow("plugin generation was superseded");
390+
await expect(
391+
acquireAgentRunPreparedModelRuntime(runInput(previousConfig), {
392+
pluginGeneration: { ...admitted!.pluginGeneration },
393+
}),
394+
).rejects.toThrow("plugin generation was superseded");
395+
detachedAdmission = detachedAdmissionGate.then(async () =>
396+
acquireAgentRunPreparedModelRuntime(runInput(previousConfig), {
397+
pluginGeneration: admitted!.pluginGeneration,
398+
}),
399+
);
400+
},
401+
() => (outerLeaseActive ? outerLease.snapshot : undefined),
402+
);
403+
} finally {
404+
outerLeaseActive = false;
405+
outerLease.release();
406+
}
407+
releaseDetachedAdmission();
408+
await expect(detachedAdmission).rejects.toThrow("plugin generation was superseded");
409+
410+
await expect(
411+
acquireAgentRunPreparedModelRuntime(runInput(previousConfig), {
412+
pluginGeneration: admitted!.pluginGeneration,
413+
}),
414+
).rejects.toThrow("plugin generation was superseded");
415+
expect(getPreparedModelRuntimeSnapshot(runInput(committedConfig))).toBe(committedSnapshot);
416+
417+
const next = await acquireAgentRunPreparedModelRuntime(runInput(committedConfig));
418+
expect(next.snapshot).toBe(committedSnapshot);
419+
next.release();
420+
});
421+
422+
it("does not let a stale pinned generation replace an owner awaiting auth refresh", async () => {
423+
mocks.configuredAgentIds = ["default"];
424+
const config = {};
425+
await refreshPreparedModelRuntimeSnapshots(config, { gatewayLifecycle: true });
426+
const admitted = await loadPublishedGatewayReplyDispatchRuntime({ agentId: "default" });
427+
expect(admitted).toBeDefined();
428+
429+
mocks.mutationListener?.({ agentDir: "/tmp/unused-agent", affectsInheritedStores: false });
430+
431+
await expect(
432+
acquireAgentRunPreparedModelRuntime(
433+
{
434+
agentId: "default",
435+
agentDir: "/tmp/unused-agent",
436+
config,
437+
workspaceDir: "/tmp/unused-workspace",
438+
},
439+
{ pluginGeneration: { ...admitted!.pluginGeneration } },
440+
),
441+
).rejects.toThrow("plugin generation was superseded");
442+
443+
await vi.waitFor(async () => {
444+
expect(mocks.ensureOpenClawModelsJson).toHaveBeenCalledTimes(2);
445+
await expect(
446+
loadPublishedGatewayReplyDispatchRuntime({ agentId: "default" }),
447+
).resolves.toMatchObject({ config });
448+
});
302449
});
303450

304451
it("bounds retained gateway run owners while reusing recent selections", async () => {

‎src/agents/prepared-model-runtime.owner.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,14 @@ export function hasConfiguredOwnerMatching(
148148
return findConfiguredOwnerCandidates(owners, rawInput).length > 0;
149149
}
150150

151+
export function resolveConfiguredOwner(
152+
owners: Map<string, PreparedModelRuntimeOwner>,
153+
rawInput: PreparedModelRuntimeInput,
154+
): PreparedModelRuntimeOwner | undefined {
155+
const candidates = findConfiguredOwnerCandidates(owners, rawInput);
156+
return candidates.length === 1 ? candidates[0] : undefined;
157+
}
158+
151159
function resolveCommittedConfiguredOwner(
152160
owners: Map<string, PreparedModelRuntimeOwner>,
153161
rawInput: PreparedModelRuntimeInput,

‎src/auto-reply/reply/get-reply-run.prepared-metadata.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,10 @@ describe("runPreparedReply prepared metadata", () => {
103103
config,
104104
agentId: "main",
105105
agentDir: "/tmp/openclaw-reply-agent",
106+
allowGatewaySubagentBinding: true,
106107
workspaceDir,
107108
},
108-
{ pluginGeneration },
109+
{ catalogMode: "static", pluginGeneration },
109110
);
110111
expect(admissionSnapshot).toBe(metadataSnapshot);
111112
expect(executionSnapshot).toBe(metadataSnapshot);

‎src/auto-reply/reply/get-reply-run.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,19 +40,23 @@ export async function runPreparedReply(
4040
config: dispatchRuntime.config,
4141
agentId: dispatchRuntime.agentId,
4242
agentDir: dispatchRuntime.agentDir,
43+
allowGatewaySubagentBinding: true,
4344
workspaceDir: context.workspaceDir,
4445
},
45-
{ pluginGeneration: dispatchRuntime.pluginGeneration },
46+
{ catalogMode: "static", pluginGeneration: dispatchRuntime.pluginGeneration },
4647
);
48+
let leaseActive = true;
4749
try {
4850
return await withPreparedModelRuntimePluginGenerationScope(
4951
dispatchRuntime.pluginGeneration,
5052
() =>
5153
withPluginRuntimeGenerationScope(lease.snapshot, () =>
5254
executePreparedReplyContext(context),
5355
),
56+
() => (leaseActive ? lease.snapshot : undefined),
5457
);
5558
} finally {
59+
leaseActive = false;
5660
lease.release();
5761
}
5862
}

‎test/e2e/qa-lab/runtime/fixtures/worker-inference-generation-provider/index.js‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,6 @@ export default definePluginEntry({
6868
if (typeof sourceCredential !== "string" || !sourceCredential) {
6969
throw new Error("qa worker generation provider requires a direct credential");
7070
}
71-
const runtimeCredential = `qa-worker-runtime-${generation}`;
72-
7371
trace("registered", { registrationMode: api.registrationMode });
7472
api.registerReload({
7573
hotPrefixes: [`plugins.entries.${PLUGIN_ID}.config`],
@@ -101,7 +99,10 @@ export default definePluginEntry({
10199
await waitForBarrierRelease(barrierPath);
102100
trace("auth-prepare-released", { waited: true });
103101
}
104-
trace("auth-ready", { runtimeCredentialGeneration: generation });
102+
const runtimeGeneration =
103+
typeof apiKey === "string" ? apiKey.slice(apiKey.lastIndexOf("-") + 1) : generation;
104+
const runtimeCredential = `qa-worker-runtime-${runtimeGeneration}`;
105+
trace("auth-ready", { runtimeCredentialGeneration: runtimeGeneration });
105106
return { apiKey: runtimeCredential };
106107
},
107108
createStreamFn: ({ model }) => {

0 commit comments

Comments
 (0)