Skip to content

Commit 77f7560

Browse files
fix(gateway): prevent chat metadata from blocking concurrent RPCs (#119369)
* fix(gateway): serve chat metadata from prepared snapshots * fix(gateway): make chat metadata replacement atomic * fix(gateway): keep metadata contract cycle-free * fix(gateway): settle coalesced metadata replacement * fix(gateway): retry invalidated metadata projections * fix(gateway): terminate unowned metadata invalidation
1 parent dca3ed1 commit 77f7560

26 files changed

Lines changed: 1497 additions & 363 deletions

‎src/agents/auth-profiles.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ export {
6060
clearRuntimeAuthProfileStoreSnapshots,
6161
ensureAuthProfileStore,
6262
ensureAuthProfileStoreWithoutExternalProfiles,
63+
getPreparedRuntimeAuthProfileStoreSnapshot,
6364
getRuntimeAuthProfileStoreSnapshot,
6465
hasAuthProfileStoreSourceForProvider,
6566
hasAnyAuthProfileStoreSource,

‎src/agents/auth-profiles/runtime-snapshots.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { describe, expect, it, vi } from "vitest";
88
import {
99
clearRuntimeAuthProfileStoreSnapshot,
1010
clearRuntimeAuthProfileStoreSnapshots,
11+
getPreparedRuntimeAuthProfileStoreSnapshot,
1112
getRuntimeAuthProfileStoreSnapshot,
1213
getRuntimeAuthProfileStoreCredentialsRevision,
1314
noteRuntimeAuthProfileStorePersistedMutation,
@@ -206,6 +207,45 @@ describe("runtime auth profile snapshots", () => {
206207
}
207208
});
208209

210+
it("merges inherited and agent prepared stores without persisted fallback", () => {
211+
const inheritedAuthDir = "/tmp/openclaw-auth-runtime-inherited";
212+
const agentDir = "/tmp/openclaw-auth-runtime-agent";
213+
try {
214+
setRuntimeAuthProfileStoreSnapshot(
215+
{
216+
...createStore("inherited"),
217+
profiles: {
218+
...createStore("inherited").profiles,
219+
"anthropic:default": {
220+
type: "api_key",
221+
provider: "anthropic",
222+
key: "inherited-key",
223+
},
224+
},
225+
},
226+
inheritedAuthDir,
227+
);
228+
setRuntimeAuthProfileStoreSnapshot(createStore("agent"), agentDir);
229+
230+
const prepared = getPreparedRuntimeAuthProfileStoreSnapshot(agentDir, inheritedAuthDir);
231+
232+
expectOpenAICodexSnapshotCredential(prepared, { access: "agent" });
233+
expect(prepared?.profiles["anthropic:default"]).toMatchObject({
234+
type: "api_key",
235+
provider: "anthropic",
236+
key: "inherited-key",
237+
});
238+
expect(
239+
getPreparedRuntimeAuthProfileStoreSnapshot(
240+
"/tmp/openclaw-auth-runtime-missing",
241+
"/tmp/openclaw-auth-runtime-also-missing",
242+
),
243+
).toBeUndefined();
244+
} finally {
245+
clearRuntimeAuthProfileStoreSnapshots();
246+
}
247+
});
248+
209249
it("clears one agent snapshot without disturbing other stores", () => {
210250
const firstAgentDir = "/tmp/openclaw-auth-runtime-snapshot-first";
211251
const secondAgentDir = "/tmp/openclaw-auth-runtime-snapshot-second";

‎src/agents/auth-profiles/runtime-snapshots.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import path from "node:path";
55
*/
66
import { isDeepStrictEqual } from "node:util";
77
import { cloneAuthProfileStore } from "./clone.js";
8+
import { mergeAuthProfileStores } from "./persisted.js";
89
import { resolveAuthProfileDatabasePath } from "./sqlite.js";
910
import type { AuthProfileStore, RuntimeAuthProfileStore } from "./types.js";
1011

@@ -223,6 +224,27 @@ export function getRuntimeAuthProfileStoreSnapshot(
223224
return store ? cloneAuthProfileStore(store) : undefined;
224225
}
225226

227+
/**
228+
* Reads the effective prepared auth store without falling back to persisted storage.
229+
* Lifecycle consumers use this after auth publication so request paths never reopen SQLite.
230+
*/
231+
export function getPreparedRuntimeAuthProfileStoreSnapshot(
232+
agentDir?: string,
233+
inheritedAuthDir?: string,
234+
): AuthProfileStore | undefined {
235+
const inherited = getRuntimeAuthProfileStoreSnapshot(inheritedAuthDir);
236+
const requested = getRuntimeAuthProfileStoreSnapshot(agentDir);
237+
if (!agentDir || resolveRuntimeStoreKey(agentDir) === resolveRuntimeStoreKey(inheritedAuthDir)) {
238+
return requested ?? inherited;
239+
}
240+
if (inherited && requested) {
241+
return mergeAuthProfileStores(inherited, requested, {
242+
preserveBaseRuntimeExternalProfiles: true,
243+
});
244+
}
245+
return requested ?? inherited;
246+
}
247+
226248
/** Lists cloned live snapshots for transactional rollback composition. */
227249
export function listRuntimeAuthProfileStoreSnapshots(): Array<{
228250
agentDir: string;

‎src/agents/auth-profiles/store.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
import {
4444
clearRuntimeAuthProfileStoreSnapshot as clearRuntimeAuthProfileStoreSnapshotImpl,
4545
clearRuntimeAuthProfileStoreSnapshots as clearRuntimeAuthProfileStoreSnapshotsImpl,
46+
getPreparedRuntimeAuthProfileStoreSnapshot as getPreparedRuntimeAuthProfileStoreSnapshotImpl,
4647
getRuntimeAuthProfileStoreSnapshot as getRuntimeAuthProfileStoreSnapshotImpl,
4748
getRuntimeAuthProfileStoreSnapshotRevision,
4849
noteRuntimeAuthProfileStorePersistedMutation,
@@ -1317,6 +1318,14 @@ export function getRuntimeAuthProfileStoreSnapshot(
13171318
return getRuntimeAuthProfileStoreSnapshotImpl(agentDir);
13181319
}
13191320

1321+
/** Return the lifecycle-published effective auth store without persisted fallback reads. */
1322+
export function getPreparedRuntimeAuthProfileStoreSnapshot(
1323+
agentDir?: string,
1324+
inheritedAuthDir?: string,
1325+
): AuthProfileStore | undefined {
1326+
return getPreparedRuntimeAuthProfileStoreSnapshotImpl(agentDir, inheritedAuthDir);
1327+
}
1328+
13201329
/** Replace runtime auth-profile snapshots, used by tests and prepared runtimes. */
13211330
export function replaceRuntimeAuthProfileStoreSnapshots(
13221331
entries: Array<{ agentDir?: string; store: AuthProfileStore }>,

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

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -111,37 +111,44 @@ function resolveInputs(params: LoadPreparedModelCatalogParams = {}): {
111111
};
112112
}
113113

114-
/** Returns the configured catalog for the current generation without starting discovery. */
115-
export function getPreparedModelCatalogSnapshot(
114+
/** Returns the configured lifecycle owner for the current generation without starting discovery. */
115+
export function getPreparedModelCatalogOwnerSnapshot(
116116
params: LoadPreparedModelCatalogParams = {},
117-
): ModelCatalogSnapshot | undefined {
117+
): PreparedModelRuntimeSnapshot | undefined {
118118
const { activationExact, activationFull, exact, full } = resolveInputs(params);
119119
const publishedFull = getPreparedModelRuntimeSnapshot(full);
120120
if (publishedFull && preparedModelRuntimeConfigsMatch(publishedFull.config, full.config)) {
121-
return publishedFull.modelCatalog;
121+
return publishedFull;
122122
}
123123
if (activationFull && activationFull.workspaceDir !== full.workspaceDir) {
124124
const activatedFull = getPreparedModelRuntimeSnapshot(activationFull);
125125
if (activatedFull && preparedModelRuntimeConfigsMatch(activatedFull.config, full.config)) {
126-
return activatedFull.modelCatalog;
126+
return activatedFull;
127127
}
128128
}
129129
if (exact === full) {
130130
return undefined;
131131
}
132132
const publishedExact = getPreparedModelRuntimeSnapshot(exact);
133133
if (publishedExact && preparedModelRuntimeConfigsMatch(publishedExact.config, exact.config)) {
134-
return publishedExact.modelCatalog;
134+
return publishedExact;
135135
}
136136
if (!activationExact || activationExact.workspaceDir === exact.workspaceDir) {
137137
return undefined;
138138
}
139139
const activatedExact = getPreparedModelRuntimeSnapshot(activationExact);
140140
return activatedExact && preparedModelRuntimeConfigsMatch(activatedExact.config, exact.config)
141-
? activatedExact.modelCatalog
141+
? activatedExact
142142
: undefined;
143143
}
144144

145+
/** Returns the configured catalog for the current generation without starting discovery. */
146+
export function getPreparedModelCatalogSnapshot(
147+
params: LoadPreparedModelCatalogParams = {},
148+
): ModelCatalogSnapshot | undefined {
149+
return getPreparedModelCatalogOwnerSnapshot(params)?.modelCatalog;
150+
}
151+
145152
async function resolvePreparedModelCatalogOwnerSnapshotWithPolicy(
146153
params: LoadPreparedModelCatalogParams,
147154
configPolicy: PreparedModelCatalogConfigPolicy,

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

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@ import {
44
acquireAgentRunPreparedModelRuntime,
55
acquireReadOnlyPreparedModelRuntime,
66
activateStandalonePreparedModelRuntime,
7+
getPreparedModelRuntimeSnapshot,
78
markPreparedModelRuntimeSnapshotsStale,
89
prepareModelRuntimeSnapshot,
910
publishPreparedModelRuntimeSnapshot,
11+
rejectPendingPreparedModelRuntimeReplacement,
12+
registerPreparedModelRuntimePublicationListener,
1013
refreshPreparedModelRuntimeSnapshots,
1114
} from "./prepared-model-runtime.js";
1215
import {
@@ -33,6 +36,100 @@ describe("prepared model runtime snapshots", () => {
3336
expect(mocks.ensureOpenClawModelsJson).not.toHaveBeenCalled();
3437
});
3538

39+
it("publishes invalidation before the replacement generation", async () => {
40+
mocks.configuredAgentIds = ["default"];
41+
const events: string[] = [];
42+
const unregister = registerPreparedModelRuntimePublicationListener((event) => {
43+
events.push(event.phase);
44+
});
45+
46+
await refreshPreparedModelRuntimeSnapshots({}, { gatewayLifecycle: true });
47+
unregister();
48+
await refreshPreparedModelRuntimeSnapshots({});
49+
50+
expect(events).toEqual(["invalidated", "published"]);
51+
});
52+
53+
it("makes the replacement owner readable before announcing publication", async () => {
54+
mocks.configuredAgentIds = ["default"];
55+
const initialConfig = {};
56+
const replacementConfig = { agents: { defaults: { model: "openai/gpt-5.5" } } };
57+
await refreshPreparedModelRuntimeSnapshots(initialConfig, { gatewayLifecycle: true });
58+
let publishedOwner: ReturnType<typeof getPreparedModelRuntimeSnapshot>;
59+
const unregister = registerPreparedModelRuntimePublicationListener((event) => {
60+
if (event.phase === "published") {
61+
publishedOwner = getPreparedModelRuntimeSnapshot({
62+
agentId: "default",
63+
agentDir: "/tmp/unused-agent",
64+
inheritedAuthDir: "/tmp/unused-agent",
65+
config: replacementConfig,
66+
});
67+
}
68+
});
69+
70+
await refreshPreparedModelRuntimeSnapshots(replacementConfig);
71+
unregister();
72+
73+
expect(publishedOwner).toMatchObject({ config: replacementConfig });
74+
});
75+
76+
it("announces invalidation from the direct stale owner boundary", async () => {
77+
mocks.configuredAgentIds = ["default"];
78+
await refreshPreparedModelRuntimeSnapshots({}, { gatewayLifecycle: true });
79+
const events: string[] = [];
80+
const unregister = registerPreparedModelRuntimePublicationListener((event) => {
81+
events.push(event.phase);
82+
});
83+
84+
markPreparedModelRuntimeSnapshotsStale("test direct reload stale edge", {
85+
waitForReplacement: true,
86+
});
87+
unregister();
88+
89+
expect(events).toEqual(["invalidated"]);
90+
});
91+
92+
it("terminates direct invalidation when no replacement owns it", async () => {
93+
mocks.configuredAgentIds = ["default"];
94+
await refreshPreparedModelRuntimeSnapshots({}, { gatewayLifecycle: true });
95+
const events: Array<{ phase: string; error?: Error }> = [];
96+
const unregister = registerPreparedModelRuntimePublicationListener((event) => {
97+
events.push(event);
98+
});
99+
100+
markPreparedModelRuntimeSnapshotsStale("direct invalidation has no replacement");
101+
unregister();
102+
103+
expect(events).toEqual([
104+
{ phase: "invalidated" },
105+
{
106+
phase: "failed",
107+
error: expect.objectContaining({ message: "direct invalidation has no replacement" }),
108+
},
109+
]);
110+
});
111+
112+
it("announces a failed replacement so lifecycle readers do not wait indefinitely", async () => {
113+
mocks.configuredAgentIds = ["default"];
114+
await refreshPreparedModelRuntimeSnapshots({}, { gatewayLifecycle: true });
115+
const events: Array<{ phase: string; error?: Error }> = [];
116+
const unregister = registerPreparedModelRuntimePublicationListener((event) => {
117+
events.push(event);
118+
});
119+
const replacementError = new Error("replacement aborted");
120+
121+
const gateId = markPreparedModelRuntimeSnapshotsStale("test failed reload", {
122+
waitForReplacement: true,
123+
});
124+
rejectPendingPreparedModelRuntimeReplacement(gateId, replacementError);
125+
unregister();
126+
127+
expect(events).toEqual([
128+
{ phase: "invalidated" },
129+
{ phase: "failed", error: replacementError },
130+
]);
131+
});
132+
36133
it("does not let a read-only draft replace a configured gateway owner", async () => {
37134
mocks.configuredAgentIds = ["default"];
38135
const configured = { agents: { defaults: { model: "openai/gpt-5.5" } } };

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

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,28 @@ let refreshRequestEpoch = 0;
6262
let pendingModelRuntimeReplacement: PreparedModelRuntimeReplacement | undefined;
6363
type AuthMutationEvent = { agentDir?: string; affectsInheritedStores: boolean };
6464
const pendingAuthMutations: AuthMutationEvent[] = [];
65+
type PreparedModelRuntimePublicationEvent =
66+
| { phase: "invalidated" | "published" }
67+
| { phase: "failed"; error: Error };
68+
const publicationListeners = new Set<(event: PreparedModelRuntimePublicationEvent) => void>();
69+
70+
/** Observes committed prepared model/auth generations without starting discovery. */
71+
export function registerPreparedModelRuntimePublicationListener(
72+
listener: (event: PreparedModelRuntimePublicationEvent) => void,
73+
): () => void {
74+
publicationListeners.add(listener);
75+
return () => publicationListeners.delete(listener);
76+
}
77+
78+
function notifyPreparedModelRuntimePublication(event: PreparedModelRuntimePublicationEvent): void {
79+
for (const listener of publicationListeners) {
80+
try {
81+
listener(event);
82+
} catch (error) {
83+
log.warn(`prepared model runtime publication listener failed: ${String(error)}`);
84+
}
85+
}
86+
}
6587

6688
/** Resolves a published owner or activates a standalone lifecycle owner. */
6789
export async function loadPreparedModelRuntimeSnapshot(
@@ -469,6 +491,10 @@ export function markPreparedModelRuntimeSnapshotsStale(
469491
owner.needsRefresh = true;
470492
owner.refreshError = staleError;
471493
}
494+
notifyPreparedModelRuntimePublication({ phase: "invalidated" });
495+
if (!pendingModelRuntimeReplacement) {
496+
notifyPreparedModelRuntimePublication({ phase: "failed", error: staleError });
497+
}
472498
return pendingModelRuntimeReplacement?.gateId;
473499
}
474500

@@ -482,7 +508,9 @@ export function rejectPendingPreparedModelRuntimeReplacement(
482508
return;
483509
}
484510
pendingModelRuntimeReplacement = undefined;
485-
replacement.reject(toError(error));
511+
const replacementError = toError(error);
512+
replacement.reject(replacementError);
513+
notifyPreparedModelRuntimePublication({ phase: "failed", error: replacementError });
486514
}
487515

488516
/** Rebuilds active owners after config/plugin runtime publication. */
@@ -590,6 +618,9 @@ export function refreshPreparedModelRuntimeSnapshots(
590618
) {
591619
pendingModelRuntimeReplacement = undefined;
592620
replacement.resolve();
621+
// Publication listeners may synchronously read the committed owner. Clear the lifecycle
622+
// gate before announcing availability so they cannot observe a false missing generation.
623+
notifyPreparedModelRuntimePublication({ phase: "published" });
593624
}
594625
},
595626
(error: unknown) => {
@@ -611,6 +642,7 @@ export function refreshPreparedModelRuntimeSnapshots(
611642
) {
612643
pendingModelRuntimeReplacement = undefined;
613644
replacement.reject(refreshError);
645+
notifyPreparedModelRuntimePublication({ phase: "failed", error: refreshError });
614646
}
615647
throw refreshError;
616648
},
@@ -681,12 +713,18 @@ function invalidateForAuthMutation(event: AuthMutationEvent): void {
681713
// mutation would immediately stale that initial generation even though no prior owner existed.
682714
return;
683715
}
716+
notifyPreparedModelRuntimePublication({ phase: "invalidated" });
684717
pendingAuthMutations.push(normalizedEvent);
685-
void enqueuePreparedModelRuntimePublication(drainPendingAuthMutations).catch((error: unknown) => {
718+
void enqueuePreparedModelRuntimePublication(async () => {
719+
await drainPendingAuthMutations();
720+
notifyPreparedModelRuntimePublication({ phase: "published" });
721+
}).catch((error: unknown) => {
686722
if (error instanceof PreparedModelRuntimePublicationSupersededError) {
687723
return;
688724
}
689-
log.warn(`auth-triggered model runtime refresh failed: ${String(error)}`);
725+
const refreshError = toError(error);
726+
notifyPreparedModelRuntimePublication({ phase: "failed", error: refreshError });
727+
log.warn(`auth-triggered model runtime refresh failed: ${String(refreshError)}`);
690728
});
691729
}
692730

@@ -703,6 +741,7 @@ function resetPreparedModelRuntimeSnapshotsForTest(): void {
703741
refreshTail = Promise.resolve();
704742
refreshRequestEpoch = 0;
705743
pendingAuthMutations.length = 0;
744+
publicationListeners.clear();
706745
modelRuntimeBuildTimeoutMs = DEFAULT_MODEL_RUNTIME_BUILD_TIMEOUT_MS;
707746
}
708747

‎src/gateway/local-request-context.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,9 @@ function createLocalGatewayRequestContext(
137137
config: params.getRuntimeConfig(),
138138
readOnly: true,
139139
})?.entries,
140+
readChatMetadata: async () => {
141+
throw new Error("Chat metadata is unavailable in local embedded agent gateway context.");
142+
},
140143
getHealthCache: () => null,
141144
refreshHealthSnapshot: async () =>
142145
({}) as Awaited<ReturnType<GatewayRequestContext["refreshHealthSnapshot"]>>,

0 commit comments

Comments
 (0)