Skip to content

Commit 70e6aa1

Browse files
MarvintheboredPeetiegonzalezclaudeobviyus
authored
fix: /models stops working after an unrelated config edit and never recovers (#128608)
* fix: /models stops working after an unrelated config edit and never recovers A config transaction whose reload plan is empty publishes the new runtime config but never advances the prepared model owner's config stamp. Owners are stamped with a hash of the whole config, so a key with no bearing on models leaves every strict-policy catalog read rejected for the life of the gateway process. Advance the model-neutral config stamp in place on no-op publications instead of rebuilding the prepared generation, which the planner has already determined is unnecessary. Existing leases keep their immutable snapshot, auth bindings carry onto the restamped snapshot, pending builds restamp at commit, and read-only owners are untouched. Deferred startup publication now resolves its config inside the serialized refresh so a no-op commit landing mid-startup cannot publish an already-stale stamp. Related: #128515 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(gateway): rebuild prepared owners from the committed runtime config The no-op commit path resolves secrets and commits prepared.config, but the rebuild that follows used the source-derived candidate. Where resolution returns a different object -- secrets.providers.* edits, which are exactly the changes that must rebuild rather than restamp -- the rebuilt owner carries an identity no reader supplies, so every strict catalog read rejects it and the failure this change removes reappears on its own fallback path. Reuse the config the runtime-commit hook already receives, cleared per transaction so a rebuild cannot inherit one committed by an earlier one. Co-Authored-By: Claude Opus 5 <[email protected]> * test(gateway): cover the resolved-config auth rewarm The ownership scenario returned the config secrets activation received, so a rebuild against the source candidate looked correct. Let activation resolve to a distinct object and assert by identity which config the rebuild used -- deep equality matches either object and proves nothing. Fails without the committed-config selection, passes with it. Co-Authored-By: Claude Opus 5 <[email protected]> * fix(gateway): preserve prepared runtime options on auth rewarm --------- Co-authored-by: Marvinthebored <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 0022cd2 commit 70e6aa1

12 files changed

Lines changed: 642 additions & 61 deletions

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,3 +63,18 @@ export function getPreparedModelRuntimeAuthMaterializations(
6363
): readonly RuntimeAuthMaterialization[] {
6464
return materializationsBySnapshot.get(snapshot) ?? [];
6565
}
66+
67+
export function copyPreparedModelRuntimeAuthBindings(source: object, target: object): void {
68+
const authStore = authStoreBySnapshot.get(source);
69+
const authLoader = authLoaderBySnapshot.get(source);
70+
const materializations = materializationsBySnapshot.get(source);
71+
if (authStore) {
72+
authStoreBySnapshot.set(target, authStore);
73+
}
74+
if (authLoader) {
75+
authLoaderBySnapshot.set(target, authLoader);
76+
}
77+
if (materializations) {
78+
materializationsBySnapshot.set(target, materializations);
79+
}
80+
}
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
// Preserve module setup before modules that consume it.
2+
// oxfmt-ignore
3+
import {
4+
getPreparedModelRuntimeMocks,
5+
resetPreparedModelRuntimeHarness,
6+
} from "./prepared-model-runtime.test-harness.js";
7+
import { beforeEach, describe, expect, it, vi } from "vitest";
8+
import { createDeferred } from "../../test/helpers/promise.js";
9+
import {
10+
getPreparedModelRuntimeAuthMaterializations,
11+
getPreparedModelRuntimeAuthStore,
12+
loadPreparedModelRuntimeAuth,
13+
setPreparedModelRuntimeAuthMaterializations,
14+
} from "./prepared-model-runtime-auth.js";
15+
import {
16+
advancePreparedModelRuntimeConfig,
17+
loadPublishedGatewayReplyDispatchRuntime,
18+
prepareModelRuntimeSnapshot,
19+
refreshPreparedModelRuntimeSnapshots,
20+
} from "./prepared-model-runtime.js";
21+
22+
const mocks = getPreparedModelRuntimeMocks();
23+
24+
describe("prepared model runtime config stamps", () => {
25+
beforeEach(() => {
26+
resetPreparedModelRuntimeHarness();
27+
mocks.configuredAgentIds = ["default"];
28+
});
29+
30+
it("advances without rebuilding or mutating existing readers", async () => {
31+
const initialConfig = {};
32+
const nextConfig = { gateway: { reload: { mode: "hot" as const } } };
33+
await refreshPreparedModelRuntimeSnapshots(initialConfig, { gatewayLifecycle: true });
34+
const input = {
35+
agentId: "default",
36+
agentDir: "/tmp/unused-agent",
37+
inheritedAuthDir: "/tmp/unused-agent",
38+
config: initialConfig,
39+
};
40+
const existingReader = await prepareModelRuntimeSnapshot(input);
41+
const materializations = [
42+
{
43+
provider: "test",
44+
modelId: "model",
45+
modelApi: "responses",
46+
modelBaseUrl: "https://example.test",
47+
requestTransportOverrides: "none" as const,
48+
authMode: "api_key",
49+
runtimeOwnerId: "test-owner",
50+
},
51+
];
52+
setPreparedModelRuntimeAuthMaterializations(existingReader, materializations);
53+
const authStore = getPreparedModelRuntimeAuthStore(existingReader);
54+
const loadedAuth = await loadPreparedModelRuntimeAuth(existingReader, { providerIds: [] });
55+
56+
advancePreparedModelRuntimeConfig(nextConfig);
57+
58+
const advanced = await prepareModelRuntimeSnapshot({ ...input, config: nextConfig });
59+
expect(advanced).not.toBe(existingReader);
60+
expect(advanced.config).toBe(nextConfig);
61+
expect(existingReader.config).toBe(initialConfig);
62+
expect(getPreparedModelRuntimeAuthStore(advanced)).toBe(authStore);
63+
expect(getPreparedModelRuntimeAuthMaterializations(advanced)).toBe(materializations);
64+
await expect(loadPreparedModelRuntimeAuth(advanced, { providerIds: [] })).resolves.toEqual(
65+
loadedAuth,
66+
);
67+
expect(mocks.ensureOpenClawModelsJson).toHaveBeenCalledOnce();
68+
await expect(
69+
loadPublishedGatewayReplyDispatchRuntime({ agentId: "default" }),
70+
).resolves.toMatchObject({ config: nextConfig });
71+
});
72+
73+
it("resolves startup config inside the serialized publication", async () => {
74+
const initialConfig = {};
75+
const nextConfig = { gateway: { reload: { mode: "hot" as const } } };
76+
let currentConfig = initialConfig;
77+
78+
const publication = refreshPreparedModelRuntimeSnapshots(() => currentConfig, {
79+
gatewayLifecycle: true,
80+
});
81+
currentConfig = nextConfig;
82+
advancePreparedModelRuntimeConfig(nextConfig);
83+
await publication;
84+
85+
await expect(
86+
prepareModelRuntimeSnapshot({
87+
agentId: "default",
88+
agentDir: "/tmp/unused-agent",
89+
inheritedAuthDir: "/tmp/unused-agent",
90+
config: nextConfig,
91+
}),
92+
).resolves.toMatchObject({ config: nextConfig });
93+
await expect(
94+
loadPublishedGatewayReplyDispatchRuntime({ agentId: "default" }),
95+
).resolves.toMatchObject({ config: nextConfig });
96+
});
97+
98+
it("drops an async startup config supplier superseded before it resolves", async () => {
99+
const staleConfig = {};
100+
const nextConfig = { gateway: { reload: { mode: "hot" as const } } };
101+
const supplierReady = createDeferred();
102+
const stalePublication = refreshPreparedModelRuntimeSnapshots(async () => {
103+
await supplierReady.promise;
104+
return staleConfig;
105+
});
106+
const nextPublication = refreshPreparedModelRuntimeSnapshots(nextConfig, {
107+
gatewayLifecycle: true,
108+
});
109+
110+
supplierReady.resolve();
111+
await Promise.all([stalePublication, nextPublication]);
112+
113+
expect(mocks.ensureOpenClawModelsJson).toHaveBeenCalledOnce();
114+
await expect(
115+
prepareModelRuntimeSnapshot({
116+
agentId: "default",
117+
agentDir: "/tmp/unused-agent",
118+
inheritedAuthDir: "/tmp/unused-agent",
119+
config: nextConfig,
120+
}),
121+
).resolves.toMatchObject({ config: nextConfig });
122+
});
123+
124+
it("drops a publication whose lifecycle claim is lost during async config resolution", async () => {
125+
const initialConfig = {};
126+
const staleConfig = { gateway: { reload: { mode: "off" as const } } };
127+
const nextConfig = { gateway: { reload: { mode: "hot" as const } } };
128+
await refreshPreparedModelRuntimeSnapshots(initialConfig, { gatewayLifecycle: true });
129+
const supplierStarted = createDeferred();
130+
const releaseSupplier = createDeferred();
131+
let claimCurrent = true;
132+
const stalePublication = refreshPreparedModelRuntimeSnapshots(
133+
async () => {
134+
supplierStarted.resolve();
135+
await releaseSupplier.promise;
136+
return staleConfig;
137+
},
138+
{
139+
gatewayLifecycle: true,
140+
isPublicationCurrent: () => claimCurrent,
141+
},
142+
);
143+
144+
await supplierStarted.promise;
145+
claimCurrent = false;
146+
releaseSupplier.resolve();
147+
await stalePublication;
148+
await refreshPreparedModelRuntimeSnapshots(nextConfig, { gatewayLifecycle: true });
149+
150+
expect(mocks.ensureOpenClawModelsJson).toHaveBeenCalledTimes(2);
151+
await expect(
152+
prepareModelRuntimeSnapshot({
153+
agentId: "default",
154+
agentDir: "/tmp/unused-agent",
155+
inheritedAuthDir: "/tmp/unused-agent",
156+
config: nextConfig,
157+
}),
158+
).resolves.toMatchObject({ config: nextConfig });
159+
await expect(
160+
loadPublishedGatewayReplyDispatchRuntime({ agentId: "default" }),
161+
).resolves.toMatchObject({ config: nextConfig });
162+
});
163+
164+
it("keeps an in-flight auth publication on the advanced stamp", async () => {
165+
const initialConfig = {};
166+
const nextConfig = { gateway: { reload: { mode: "hot" as const } } };
167+
await refreshPreparedModelRuntimeSnapshots(initialConfig, { gatewayLifecycle: true });
168+
let finishAuthRefresh: (() => void) | undefined;
169+
mocks.ensureOpenClawModelsJson.mockImplementationOnce(
170+
async () =>
171+
await new Promise<{ agentDir: string; wrote: false }>((resolve) => {
172+
finishAuthRefresh = () => resolve({ agentDir: "/tmp/unused-agent", wrote: false });
173+
}),
174+
);
175+
176+
mocks.mutationListener?.({ affectsInheritedStores: true });
177+
await vi.waitFor(() => expect(finishAuthRefresh).toBeDefined());
178+
advancePreparedModelRuntimeConfig(nextConfig);
179+
finishAuthRefresh?.();
180+
181+
await expect(
182+
prepareModelRuntimeSnapshot({
183+
agentId: "default",
184+
agentDir: "/tmp/unused-agent",
185+
inheritedAuthDir: "/tmp/unused-agent",
186+
config: nextConfig,
187+
}),
188+
).resolves.toMatchObject({ config: nextConfig });
189+
expect(mocks.ensureOpenClawModelsJson).toHaveBeenCalledTimes(2);
190+
});
191+
});

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

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { resolveSelectedAgentHarnessRuntime } from "./harness/runtime-plugin-loa
1515
import { resolveLegacyInheritedAuthDir } from "./legacy-inherited-auth-dir.js";
1616
import { resolveModelCandidateChain } from "./model-fallback-candidates.js";
1717
import { resolveDefaultModelForAgent } from "./model-selection-config.js";
18+
import { copyPreparedModelRuntimeAuthBindings } from "./prepared-model-runtime-auth.js";
1819
import {
1920
startSerializedSnapshotBuild,
2021
startSerializedSnapshotBuildBatch,
@@ -212,6 +213,30 @@ export function preparedModelRuntimeConfigsMatch(
212213
}
213214
}
214215

216+
function stampPreparedModelRuntimeSnapshotConfig(
217+
snapshot: PreparedModelRuntimeSnapshot,
218+
config: OpenClawConfig,
219+
): PreparedModelRuntimeSnapshot {
220+
if (snapshot.config === config) {
221+
return snapshot;
222+
}
223+
const stamped = Object.freeze({ ...snapshot, config });
224+
copyPreparedModelRuntimeAuthBindings(snapshot, stamped);
225+
return stamped;
226+
}
227+
228+
export function advancePreparedModelRuntimeOwnerConfig(
229+
owner: PreparedModelRuntimeOwner,
230+
config: OpenClawConfig,
231+
): void {
232+
owner.input = { ...owner.input, config };
233+
if (owner.snapshot) {
234+
// Existing leases retain their immutable snapshot. New readers receive the same prepared
235+
// generation with only its planner-approved, model-neutral config stamp advanced.
236+
owner.snapshot = stampPreparedModelRuntimeSnapshotConfig(owner.snapshot, config);
237+
}
238+
}
239+
215240
export function normalizeOptionalDir(dirname: string | undefined): string | undefined {
216241
return dirname ? path.resolve(dirname) : undefined;
217242
}
@@ -549,7 +574,12 @@ export async function publishPreparedModelRuntimeOwnerBatch(params: {
549574
`prepared model runtime snapshot missing after auth refresh for ${candidate.input.agentDir}`,
550575
);
551576
}
552-
candidate.owner.snapshot = result.snapshot;
577+
const snapshot = stampPreparedModelRuntimeSnapshotConfig(
578+
result.snapshot,
579+
candidate.owner.input.config,
580+
);
581+
candidate.owner.snapshot = snapshot;
582+
results.set(candidate.owner, { ...result, snapshot });
553583
candidate.owner.pluginGeneration = result.pluginGeneration;
554584
candidate.owner.pending = undefined;
555585
candidate.owner.needsRefresh = false;
@@ -635,12 +665,13 @@ export async function publishModelRuntimeSnapshot(
635665
`prepared model runtime publication was superseded for ${input.agentDir}`,
636666
);
637667
}
638-
owner.snapshot = result.snapshot;
668+
const snapshot = stampPreparedModelRuntimeSnapshotConfig(result.snapshot, owner.input.config);
669+
owner.snapshot = snapshot;
639670
owner.pluginGeneration = result.pluginGeneration;
640671
owner.pendingPluginGeneration = undefined;
641672
owner.pending = undefined;
642673
owner.needsRefresh = false;
643-
return result.snapshot;
674+
return snapshot;
644675
} catch (error) {
645676
const refreshError = toStringifiedError(error);
646677
if (owner.generation === generation) {

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

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
PreparedModelRuntimePublicationSupersededError,
1313
createPreparedModelRuntimeOwner,
1414
createPreparedModelRuntimeReplacement,
15+
advancePreparedModelRuntimeOwnerConfig,
1516
effectiveEnvironmentFingerprint,
1617
hasSameLifecycleInput,
1718
listConfiguredOwnerInputs,
@@ -78,6 +79,18 @@ const replyDispatchPublication = new PreparedReplyDispatchPublicationOwner({
7879
});
7980
export const loadPublishedGatewayReplyDispatchRuntime = replyDispatchPublication.load;
8081

82+
/** Advances model-neutral config identity without rebuilding prepared generation artifacts. */
83+
export function advancePreparedModelRuntimeConfig(config: OpenClawConfig): void {
84+
for (const owner of owners.values()) {
85+
// Read-only owners include the config hash in their map key and remain bound to their lease.
86+
if (owner.input.readOnly) {
87+
continue;
88+
}
89+
advancePreparedModelRuntimeOwnerConfig(owner, config);
90+
}
91+
replyDispatchPublication.advanceConfig(config);
92+
}
93+
8194
/** Resolves a published owner or activates a standalone lifecycle owner. */
8295
export async function loadPreparedModelRuntimeSnapshot(
8396
rawInput: PreparedModelRuntimeInput,
@@ -414,7 +427,7 @@ export function rejectPendingPreparedModelRuntimeReplacement(
414427
async function refreshPreparedModelRuntimeSnapshotsNow(
415428
config: OpenClawConfig,
416429
options: PreparedModelRuntimeRefreshOptions,
417-
publicationEpoch: number,
430+
isPublicationCurrent: () => boolean,
418431
): Promise<void> {
419432
retainedGatewayRunOwners.clear(owners);
420433
const { defaultWorkspaceDir: workspace, allowGatewaySubagentBinding: bindings } = options;
@@ -479,10 +492,10 @@ async function refreshPreparedModelRuntimeSnapshotsNow(
479492
owners,
480493
agentBuildCompletions,
481494
buildTimeoutMs: modelRuntimeBuildTimeoutMs,
482-
isPublicationCurrent: () => publicationEpoch === refreshRequestEpoch,
495+
isPublicationCurrent,
483496
// Config replacement is one transaction. Per-owner auth supersession may retire individual
484497
// candidates, while a newer config epoch stops every remaining build in this publication.
485-
isBuildCurrent: () => publicationEpoch === refreshRequestEpoch,
498+
isBuildCurrent: isPublicationCurrent,
486499
onBuildStats: options.onBuildStats,
487500
pluginMetadataSnapshot: options.pluginMetadataSnapshot,
488501
registerEntriesAfterBuildStart: true,
@@ -491,33 +504,38 @@ async function refreshPreparedModelRuntimeSnapshotsNow(
491504

492505
/** Serializes config/plugin publications so only the latest completed refresh retires owners. */
493506
export function refreshPreparedModelRuntimeSnapshots(
494-
config: OpenClawConfig,
507+
config: OpenClawConfig | (() => OpenClawConfig | Promise<OpenClawConfig>),
495508
options: PreparedModelRuntimeRefreshOptions = {},
496509
): Promise<void> {
510+
if (options.isPublicationCurrent?.() === false) {
511+
return Promise.resolve();
512+
}
497513
// Stale synchronously. Queued publication must never leave the prior generation request-visible.
498514
markPreparedModelRuntimeSnapshotsStale(undefined, { waitForReplacement: true });
499515
const requestEpoch = refreshRequestEpoch;
500516
const replacement = pendingModelRuntimeReplacement;
517+
const isPublicationCurrent = () =>
518+
requestEpoch === refreshRequestEpoch && options.isPublicationCurrent?.() !== false;
501519
return enqueuePreparedModelRuntimePublication(async () => {
502-
if (requestEpoch !== refreshRequestEpoch) {
520+
if (!isPublicationCurrent()) {
521+
return;
522+
}
523+
const currentConfig = typeof config === "function" ? await config() : config;
524+
if (!isPublicationCurrent()) {
503525
return;
504526
}
505-
await refreshPreparedModelRuntimeSnapshotsNow(config, options, requestEpoch);
506-
if (requestEpoch !== refreshRequestEpoch) {
527+
await refreshPreparedModelRuntimeSnapshotsNow(currentConfig, options, isPublicationCurrent);
528+
if (!isPublicationCurrent()) {
507529
return;
508530
}
509531
await drainPendingAuthMutations();
510-
if (requestEpoch !== refreshRequestEpoch) {
532+
if (!isPublicationCurrent()) {
511533
return;
512534
}
513535
replyDispatchPublication.rebuild(owners.values());
514536
}).then(
515537
() => {
516-
if (
517-
requestEpoch === refreshRequestEpoch &&
518-
replacement &&
519-
pendingModelRuntimeReplacement === replacement
520-
) {
538+
if (isPublicationCurrent() && replacement && pendingModelRuntimeReplacement === replacement) {
521539
pendingModelRuntimeReplacement = undefined;
522540
replacement.resolve();
523541
// Publication listeners may synchronously read the committed owner. Clear the lifecycle
@@ -527,7 +545,7 @@ export function refreshPreparedModelRuntimeSnapshots(
527545
},
528546
(error: unknown) => {
529547
const refreshError = toStringifiedError(error);
530-
if (requestEpoch === refreshRequestEpoch) {
548+
if (isPublicationCurrent()) {
531549
// Candidate and queued auth builds may finish independently. A failed transaction must
532550
// leave no owner from its partially published generation request-visible.
533551
for (const owner of owners.values()) {
@@ -538,11 +556,7 @@ export function refreshPreparedModelRuntimeSnapshots(
538556
owner.pluginGeneration = undefined;
539557
}
540558
}
541-
if (
542-
requestEpoch === refreshRequestEpoch &&
543-
replacement &&
544-
pendingModelRuntimeReplacement === replacement
545-
) {
559+
if (isPublicationCurrent() && replacement && pendingModelRuntimeReplacement === replacement) {
546560
pendingModelRuntimeReplacement = undefined;
547561
replacement.reject(refreshError);
548562
notifyPreparedModelRuntimePublication({ phase: "failed", error: refreshError });

0 commit comments

Comments
 (0)