Skip to content

Commit d8f55fa

Browse files
authored
fix(gateway): refresh model catalog after auth changes (#134361)
* fix(models): refresh catalog content after credential-identity changes * refactor(agents): split auth-profile mutation lineage out of runtime-snapshots Split the max-lines boundary by moving persisted mutation lineage out of runtime snapshots; behavior is unchanged. * refactor(agents): annotate the moved test-api global assertion for the safety ratchet * test(agents): type the catalog worker mock and shrink the assertion baseline * perf(agents): bound auth publication provider facts * perf(gateway): keep auth status off catalog discovery * fix(agents): reject retired catalog owners * test(gateway): resolve the auth-status handler result before racing it * fix(models): gate catalog refresh by read intent * test(models): prove deferred catalog reads stay static * test(models): type the unscoped catalog-refresh row context
1 parent 74e8d74 commit d8f55fa

31 files changed

Lines changed: 741 additions & 292 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1667,7 +1667,6 @@ src/agents/auth-profiles/policy.ts 1
16671667
src/agents/auth-profiles/portability.ts 1
16681668
src/agents/auth-profiles/profiles.ts 1
16691669
src/agents/auth-profiles/repair.ts 1
1670-
src/agents/auth-profiles/runtime-snapshots.ts 1
16711670
src/agents/auth-profiles/source-check.ts 1
16721671
src/agents/auth-profiles/sqlite.ts 2
16731672
src/agents/auth-profiles/state.ts 5

‎extensions/memory-lancedb/embeddings.lifecycle.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@ import type { MemoryConfig } from "./config.js";
1313
const providerMocks = vi.hoisted(() => ({
1414
getMemoryEmbeddingProvider: vi.fn(),
1515
authMutationListeners: new Set<
16-
(event: { agentDir?: string; affectsInheritedStores: boolean }) => void
16+
(event: {
17+
agentDir?: string;
18+
affectsInheritedStores: boolean;
19+
profileSetChanged: boolean;
20+
}) => void
1721
>(),
1822
}));
1923

@@ -206,6 +210,7 @@ describe("memory-lancedb provider lifecycle", () => {
206210
listener?.({
207211
agentDir: "/tmp/agent-private/../agent-private",
208212
affectsInheritedStores: false,
213+
profileSetChanged: false,
209214
});
210215

211216
await embed(embeddings, "other", "other warm provider");

‎src/agents/auth-profiles/external-oauth.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,11 @@ describe("auth external oauth helpers", () => {
323323
expect(getRuntimeAuthProfileStoreSnapshot(agentDir)?.profiles["openai:default"]?.type).toBe(
324324
"oauth",
325325
);
326-
expect(listener).toHaveBeenCalledWith({ agentDir, affectsInheritedStores: false });
326+
expect(listener).toHaveBeenCalledWith({
327+
agentDir,
328+
affectsInheritedStores: false,
329+
profileSetChanged: true,
330+
});
327331
} finally {
328332
unregister();
329333
}
Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
import { resolveSharedAuthStorePath, type AuthProfileOwnerScope } from "./path-resolve.js";
2+
import { resolveAuthProfileDatabasePath } from "./sqlite.js";
3+
4+
type PersistedMutationRecord = {
5+
credentialRevision: number;
6+
credentialRevisionKnown: boolean;
7+
profileSetRevision: number;
8+
profileSetRevisionKnown: boolean;
9+
stateRevision: number;
10+
stateRevisionKnown: boolean;
11+
mutationFloor: number;
12+
profileRevisions: Map<string, number>;
13+
};
14+
15+
const persistedMutationRecords = new Map<string, PersistedMutationRecord>();
16+
let persistedMutationRevision = 0;
17+
let evictedOwnerMutationFloor = 0;
18+
const MAX_PERSISTED_MUTATION_OWNERS = 256;
19+
const MAX_PERSISTED_MUTATION_PROFILES_PER_OWNER = 256;
20+
21+
export type RuntimeAuthProfileStoreMutationToken = {
22+
revision: number;
23+
known: boolean;
24+
};
25+
26+
export type RuntimeAuthProfileStoreMutationOwner =
27+
| { kind: "resolved"; databasePath: string; sharedDatabasePath: string }
28+
| { kind: "unresolved"; databasePath: string; scope: AuthProfileOwnerScope };
29+
30+
// Runtime snapshots are keyed by the canonical database path so default-agent
31+
// and per-agent stores do not overwrite each other.
32+
export function resolveRuntimeStoreKey(agentDir?: string): string {
33+
return agentDir ? resolveAuthProfileDatabasePath(agentDir) : resolveSharedAuthStorePath();
34+
}
35+
36+
function maxMutationRevision(record: PersistedMutationRecord): number {
37+
return Math.max(
38+
record.credentialRevision,
39+
record.profileSetRevision,
40+
record.stateRevision,
41+
record.mutationFloor,
42+
...record.profileRevisions.values(),
43+
);
44+
}
45+
46+
function getOrCreatePersistedMutationRecord(ownerKey: string): PersistedMutationRecord {
47+
const existing = persistedMutationRecords.get(ownerKey);
48+
if (existing) {
49+
// Mutations, rather than reads, drive LRU recency so observation cannot
50+
// retain dormant owners forever.
51+
persistedMutationRecords.delete(ownerKey);
52+
persistedMutationRecords.set(ownerKey, existing);
53+
return existing;
54+
}
55+
const record: PersistedMutationRecord = {
56+
credentialRevision: evictedOwnerMutationFloor,
57+
credentialRevisionKnown: evictedOwnerMutationFloor === 0,
58+
profileSetRevision: evictedOwnerMutationFloor,
59+
profileSetRevisionKnown: evictedOwnerMutationFloor === 0,
60+
stateRevision: evictedOwnerMutationFloor,
61+
stateRevisionKnown: evictedOwnerMutationFloor === 0,
62+
mutationFloor: evictedOwnerMutationFloor,
63+
profileRevisions: new Map(),
64+
};
65+
persistedMutationRecords.set(ownerKey, record);
66+
while (persistedMutationRecords.size > MAX_PERSISTED_MUTATION_OWNERS) {
67+
const oldestOwnerKey = persistedMutationRecords.keys().next().value;
68+
if (oldestOwnerKey === undefined) {
69+
break;
70+
}
71+
const oldest = persistedMutationRecords.get(oldestOwnerKey);
72+
persistedMutationRecords.delete(oldestOwnerKey);
73+
if (oldest) {
74+
// A floor trades false-positive rollback fences for bounded memory; it
75+
// must never let an evicted persisted mutation look unchanged.
76+
evictedOwnerMutationFloor = Math.max(evictedOwnerMutationFloor, maxMutationRevision(oldest));
77+
}
78+
}
79+
record.mutationFloor = Math.max(record.mutationFloor, evictedOwnerMutationFloor);
80+
return record;
81+
}
82+
83+
function setProfileMutationRevision(
84+
record: PersistedMutationRecord,
85+
profileId: string,
86+
revision: number,
87+
): void {
88+
record.profileRevisions.delete(profileId);
89+
record.profileRevisions.set(profileId, revision);
90+
while (record.profileRevisions.size > MAX_PERSISTED_MUTATION_PROFILES_PER_OWNER) {
91+
const oldestProfileId = record.profileRevisions.keys().next().value;
92+
if (oldestProfileId === undefined) {
93+
break;
94+
}
95+
const oldestRevision = record.profileRevisions.get(oldestProfileId) ?? 0;
96+
record.profileRevisions.delete(oldestProfileId);
97+
record.mutationFloor = Math.max(record.mutationFloor, oldestRevision);
98+
}
99+
}
100+
101+
function getPersistedMutationRecord(ownerKey: string): PersistedMutationRecord | undefined {
102+
return persistedMutationRecords.get(ownerKey);
103+
}
104+
105+
export function recordRuntimeAuthProfileStorePersistedMutation(
106+
ownerKey: string,
107+
mutation: {
108+
credentialsChanged: boolean;
109+
profileSetChanged?: boolean;
110+
stateChanged: boolean;
111+
profileIds: Iterable<string>;
112+
},
113+
): void {
114+
persistedMutationRevision += 1;
115+
const record = getOrCreatePersistedMutationRecord(ownerKey);
116+
if (mutation.profileSetChanged) {
117+
record.profileSetRevision = persistedMutationRevision;
118+
record.profileSetRevisionKnown = true;
119+
}
120+
if (mutation.credentialsChanged) {
121+
record.credentialRevision = persistedMutationRevision;
122+
record.credentialRevisionKnown = true;
123+
for (const profileId of mutation.profileIds) {
124+
setProfileMutationRevision(record, profileId, persistedMutationRevision);
125+
}
126+
}
127+
if (mutation.stateChanged) {
128+
record.stateRevision = persistedMutationRevision;
129+
record.stateRevisionKnown = true;
130+
}
131+
}
132+
133+
function combineMutationTokens(
134+
tokens: RuntimeAuthProfileStoreMutationToken[],
135+
): RuntimeAuthProfileStoreMutationToken {
136+
return {
137+
revision: Math.max(0, ...tokens.map((token) => token.revision)),
138+
known: tokens.every((token) => token.known),
139+
};
140+
}
141+
142+
/** Bounded persisted credential lineage; unknown means its exact token was evicted. */
143+
export function getRuntimeAuthProfileStoreCredentialMutationToken(
144+
agentDir?: string,
145+
profileId?: string,
146+
options?: { includeMain?: boolean; owner?: RuntimeAuthProfileStoreMutationOwner },
147+
): RuntimeAuthProfileStoreMutationToken {
148+
const requestedKey = options?.owner?.databasePath ?? resolveRuntimeStoreKey(agentDir);
149+
if (!profileId) {
150+
const record = getPersistedMutationRecord(requestedKey);
151+
return record
152+
? { revision: record.credentialRevision, known: record.credentialRevisionKnown }
153+
: { revision: evictedOwnerMutationFloor, known: evictedOwnerMutationFloor === 0 };
154+
}
155+
if (options?.includeMain && options.owner?.kind === "unresolved") {
156+
return { revision: 0, known: false };
157+
}
158+
const mainKey = !options?.includeMain
159+
? requestedKey
160+
: options.owner?.kind === "resolved"
161+
? options.owner.sharedDatabasePath
162+
: resolveRuntimeStoreKey(undefined);
163+
const keys =
164+
requestedKey === mainKey || options?.includeMain !== true
165+
? [requestedKey]
166+
: [requestedKey, mainKey];
167+
return combineMutationTokens(
168+
keys.map((key) => {
169+
const record = getPersistedMutationRecord(key);
170+
if (!record) {
171+
return { revision: evictedOwnerMutationFloor, known: evictedOwnerMutationFloor === 0 };
172+
}
173+
const revision = record.profileRevisions.get(profileId);
174+
return revision === undefined
175+
? { revision: record.mutationFloor, known: record.mutationFloor === 0 }
176+
: { revision, known: true };
177+
}),
178+
);
179+
}
180+
181+
/** Persisted token for profile-id additions and removals in one owner store. */
182+
export function getRuntimeAuthProfileStoreProfileSetMutationToken(
183+
agentDir?: string,
184+
databasePath?: string,
185+
): RuntimeAuthProfileStoreMutationToken {
186+
const ownerKey = databasePath ?? resolveRuntimeStoreKey(agentDir);
187+
const record = getPersistedMutationRecord(ownerKey);
188+
return record
189+
? { revision: record.profileSetRevision, known: record.profileSetRevisionKnown }
190+
: { revision: evictedOwnerMutationFloor, known: evictedOwnerMutationFloor === 0 };
191+
}
192+
193+
/** Persisted mutation token for non-secret selection state in one owner store. */
194+
export function getRuntimeAuthProfileStoreStateMutationToken(
195+
agentDir?: string,
196+
options?: { includeMain?: boolean; owner?: RuntimeAuthProfileStoreMutationOwner },
197+
): RuntimeAuthProfileStoreMutationToken {
198+
const requestedKey = options?.owner?.databasePath ?? resolveRuntimeStoreKey(agentDir);
199+
if (options?.includeMain && options.owner?.kind === "unresolved") {
200+
return { revision: 0, known: false };
201+
}
202+
const mainKey = !options?.includeMain
203+
? requestedKey
204+
: options.owner?.kind === "resolved"
205+
? options.owner.sharedDatabasePath
206+
: resolveRuntimeStoreKey(undefined);
207+
const keys =
208+
requestedKey === mainKey || options?.includeMain !== true
209+
? [requestedKey]
210+
: [requestedKey, mainKey];
211+
return combineMutationTokens(
212+
keys.map((key) => {
213+
const record = getPersistedMutationRecord(key);
214+
return record
215+
? { revision: record.stateRevision, known: record.stateRevisionKnown }
216+
: { revision: evictedOwnerMutationFloor, known: evictedOwnerMutationFloor === 0 };
217+
}),
218+
);
219+
}
220+
221+
const testing = {
222+
MAX_PERSISTED_MUTATION_OWNERS,
223+
MAX_PERSISTED_MUTATION_PROFILES_PER_OWNER,
224+
getPersistedMutationRecordCounts(): { owners: number; profiles: number } {
225+
return {
226+
owners: persistedMutationRecords.size,
227+
profiles: Math.max(
228+
0,
229+
...Array.from(persistedMutationRecords.values(), (record) => record.profileRevisions.size),
230+
),
231+
};
232+
},
233+
resetPersistedMutationLineage(): void {
234+
persistedMutationRecords.clear();
235+
persistedMutationRevision = 0;
236+
evictedOwnerMutationFloor = 0;
237+
},
238+
};
239+
if (process.env.VITEST || process.env.NODE_ENV === "test") {
240+
// SAFETY: test-only publication; globalThis is written as an open symbol-keyed bag.
241+
(globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw.runtimeAuthSnapshotsTestApi")] =
242+
testing;
243+
}

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db
1616
import { withEnvAsync } from "../../test-utils/env.js";
1717
import { AUTH_STORE_VERSION } from "./constants.js";
1818
import { testing as externalAuthTesting } from "./external-auth.test-support.js";
19+
import {
20+
getRuntimeAuthProfileStoreCredentialMutationToken,
21+
getRuntimeAuthProfileStoreStateMutationToken,
22+
} from "./mutation-lineage.js";
1923
import { resolveApiKeyForProfile } from "./oauth.js";
2024
import { loadPersistedAuthProfileStore } from "./persisted.js";
2125
import {
@@ -34,9 +38,7 @@ import {
3438
import {
3539
clearRuntimeAuthProfileStoreSnapshots,
3640
getRuntimeAuthProfileStoreSnapshotCore as getInternalRuntimeAuthProfileStoreSnapshot,
37-
getRuntimeAuthProfileStoreCredentialMutationToken,
3841
getRuntimeAuthProfileStoreCredentialsRevision,
39-
getRuntimeAuthProfileStoreStateMutationToken,
4042
listOwnedRuntimeAuthProfileStoreSnapshots,
4143
replaceRuntimeAuthProfileStoreSnapshots,
4244
} from "./runtime-snapshots.js";

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import "./runtime-snapshots.js";
1+
import "./mutation-lineage.js";
22

33
type RuntimeSnapshotsTestApi = {
44
MAX_PERSISTED_MUTATION_OWNERS: number;

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,9 @@ describe("runtime auth profile snapshots", () => {
106106
runtimeOwnerId: "codex",
107107
});
108108

109-
expect(listener).toHaveBeenCalledWith({ affectsInheritedStores: true });
109+
expect(listener).toHaveBeenCalledWith({
110+
affectsInheritedStores: true,
111+
});
110112
} finally {
111113
unregister();
112114
clearRuntimeAuthProfileStoreSnapshots();
@@ -203,10 +205,12 @@ describe("runtime auth profile snapshots", () => {
203205
expect(listener).toHaveBeenNthCalledWith(1, {
204206
agentDir,
205207
affectsInheritedStores: false,
208+
profileSetChanged: true,
206209
});
207210
expect(listener).toHaveBeenNthCalledWith(2, {
208211
agentDir,
209212
affectsInheritedStores: false,
213+
profileSetChanged: true,
210214
});
211215
} finally {
212216
unregister();
@@ -234,6 +238,7 @@ describe("runtime auth profile snapshots", () => {
234238
expect(listener).toHaveBeenCalledOnce();
235239
expect(listener).toHaveBeenCalledWith({
236240
affectsInheritedStores: true,
241+
profileSetChanged: false,
237242
});
238243
} finally {
239244
unregister();
@@ -264,7 +269,10 @@ describe("runtime auth profile snapshots", () => {
264269
]);
265270

266271
expect(listener).toHaveBeenCalledOnce();
267-
expect(listener).toHaveBeenCalledWith({ affectsInheritedStores: true });
272+
expect(listener).toHaveBeenCalledWith({
273+
affectsInheritedStores: true,
274+
profileSetChanged: false,
275+
});
268276
} finally {
269277
unregister();
270278
clearRuntimeAuthProfileStoreSnapshots();
@@ -285,10 +293,12 @@ describe("runtime auth profile snapshots", () => {
285293
expect(listener).toHaveBeenNthCalledWith(1, {
286294
agentDir,
287295
affectsInheritedStores: false,
296+
profileSetChanged: false,
288297
});
289298
expect(listener).toHaveBeenNthCalledWith(2, {
290299
agentDir,
291300
affectsInheritedStores: false,
301+
profileSetChanged: false,
292302
});
293303
} finally {
294304
unregister();

0 commit comments

Comments
 (0)