Skip to content

Commit 0c7b560

Browse files
authored
fix(gateway): avoid repeated session root scans in configured lists (#124384)
* fix(gateway): stop configured session rediscovery * fix(gateway): reuse prepared child store targets * refactor(gateway): own prepared session targets * test(gateway): prove session registry recovery
1 parent 0e65272 commit 0c7b560

13 files changed

Lines changed: 396 additions & 214 deletions

‎src/config/sessions/combined-store-gateway.ts‎

Lines changed: 81 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
// Gateway callers need canonical per-agent keys even when stores are split by `{agentId}`.
33

44
import { expectDefined } from "@openclaw/normalization-core";
5+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
56
import { listAgentEntries } from "../../agents/agent-scope.js";
67
import {
8+
resolveSessionStoreAgentId,
79
resolveSessionStoreKey,
810
resolveStoredSessionKeyForAgentStore,
911
} from "../../gateway/session-store-key.js";
@@ -12,7 +14,10 @@ import {
1214
normalizeAgentId,
1315
parseAgentSessionKey,
1416
} from "../../routing/session-key.js";
15-
import { listOpenIncognitoAgentDatabases } from "../../state/openclaw-agent-db.js";
17+
import {
18+
listOpenClawRegisteredAgentDatabases,
19+
listOpenIncognitoAgentDatabases,
20+
} from "../../state/openclaw-agent-db.js";
1621
import { resolveSessionStoreCompatibilityAgentId } from "../legacy.default-agent-owner.js";
1722
import type { OpenClawConfig } from "../types.openclaw.js";
1823
import { resolveSessionStorePathCore } from "./paths.js";
@@ -173,6 +178,33 @@ function mergeOpenIncognitoStores(params: {
173178
return storePaths;
174179
}
175180

181+
function filterCombinedStoreToConfiguredAgents(params: {
182+
cfg: OpenClawConfig;
183+
configuredAgentIds: ReadonlySet<string>;
184+
store: Record<string, SessionEntry>;
185+
}): void {
186+
const isConfiguredSessionKey = (key: string | undefined) => {
187+
const normalizedKey = normalizeOptionalString(key);
188+
if (!normalizedKey) {
189+
return false;
190+
}
191+
const canonicalKey = resolveSessionStoreKey({ cfg: params.cfg, sessionKey: normalizedKey });
192+
const agentId = resolveSessionStoreAgentId(params.cfg, canonicalKey);
193+
return params.configuredAgentIds.has(normalizeAgentId(agentId));
194+
};
195+
for (const [key, entry] of Object.entries(params.store)) {
196+
const keep =
197+
key === "global" ||
198+
key === "unknown" ||
199+
isConfiguredSessionKey(key) ||
200+
isConfiguredSessionKey(entry.spawnedBy) ||
201+
isConfiguredSessionKey(entry.parentSessionKey);
202+
if (!keep) {
203+
delete params.store[key];
204+
}
205+
}
206+
}
207+
176208
function resolveGatewaySessionStoreTargets(
177209
cfg: OpenClawConfig,
178210
opts: GatewaySessionStoreOptions,
@@ -188,16 +220,45 @@ function resolveGatewaySessionStoreTargets(
188220
opts.configuredAgentsOnly === true && !requestedAgentId
189221
? new Set(listConfiguredSessionStoreAgentIds(cfg))
190222
: undefined;
191-
const allowedIncognitoAgentIds = requestedAgentId
192-
? new Set([requestedAgentId])
193-
: configuredAgentIds;
194223
const incognitoTargets =
195224
opts.includeIncognito === false
196225
? []
197226
: listOpenIncognitoAgentDatabases().filter(
198-
(target) => !allowedIncognitoAgentIds || allowedIncognitoAgentIds.has(target.agentId),
227+
(target) => !requestedAgentId || target.agentId === requestedAgentId,
199228
);
200229

230+
if (configuredAgentIds) {
231+
const incognitoTargetKeys = new Set(
232+
incognitoTargets.map((target) => `${target.agentId}\0${target.storePath}`),
233+
);
234+
const candidates = dedupeSessionStoreTargetsBySqliteTarget(
235+
[
236+
...listOpenClawRegisteredAgentDatabases().map(({ agentId, path }) => ({
237+
agentId,
238+
storePath: path,
239+
})),
240+
...resolveSessionStoreTargets(cfg, { allAgents: true }),
241+
...incognitoTargets,
242+
],
243+
{
244+
defaultAgentId,
245+
onDiagnostic: (diagnostic) => diagnostics.push(diagnostic.message),
246+
},
247+
);
248+
return {
249+
configuredAgentIds,
250+
defaultAgentId,
251+
diagnostics,
252+
durableTargets: candidates.filter(
253+
(target) => !incognitoTargetKeys.has(`${target.agentId}\0${target.storePath}`),
254+
),
255+
incognitoTargets: candidates.filter((target) =>
256+
incognitoTargetKeys.has(`${target.agentId}\0${target.storePath}`),
257+
),
258+
storeConfig,
259+
};
260+
}
261+
201262
if (storeConfig && !isStorePathTemplate(storeConfig)) {
202263
const ownerIds = [
203264
...new Set([
@@ -230,9 +291,7 @@ function resolveGatewaySessionStoreTargets(
230291

231292
const durableTargets = requestedAgentId
232293
? resolveAgentSessionStoreTargetsSync(cfg, requestedAgentId)
233-
: opts.configuredAgentsOnly === true
234-
? resolveSessionStoreTargets(cfg, { allAgents: true })
235-
: resolveAllAgentSessionStoreTargetsSync(cfg);
294+
: resolveAllAgentSessionStoreTargetsSync(cfg);
236295
return {
237296
configuredAgentIds,
238297
defaultAgentId,
@@ -273,6 +332,7 @@ export function loadCombinedSessionStoreForGatewayCore(
273332
): {
274333
diagnostics?: string[];
275334
durableStorePath?: string;
335+
durableTargets: Array<{ agentId: string; storePath: string }>;
276336
storePath: string;
277337
store: Record<string, SessionEntry>;
278338
} {
@@ -288,53 +348,6 @@ export function loadCombinedSessionStoreForGatewayCore(
288348
requestedAgentId,
289349
storeConfig,
290350
} = resolveGatewaySessionStoreTargets(cfg, opts);
291-
if (storeConfig && !isStorePathTemplate(storeConfig)) {
292-
const combined: Record<string, SessionEntry> = {};
293-
for (const { agentId, storePath } of durableTargets) {
294-
const store = loadGatewayStoreEntries({ agentId, projection, storePath });
295-
for (const { sessionKey: key, entry } of store) {
296-
const canonicalKey = resolveStoredSessionKeyForAgentStore({
297-
cfg,
298-
agentId,
299-
sessionKey: key,
300-
});
301-
if (key !== canonicalKey) {
302-
throw canonicalSessionKeyMigrationRequiredError(
303-
`non-canonical persisted row resolves to session key ${canonicalKey}`,
304-
);
305-
}
306-
const canonicalAgentId = normalizeAgentId(
307-
parseAgentSessionKey(canonicalKey)?.agentId ?? agentId,
308-
);
309-
if (configuredAgentIds && !configuredAgentIds.has(canonicalAgentId)) {
310-
continue;
311-
}
312-
if (requestedAgentId && canonicalAgentId !== requestedAgentId) {
313-
continue;
314-
}
315-
mergeSessionEntryIntoCombined({
316-
cfg,
317-
combined,
318-
entry,
319-
agentId: canonicalAgentId,
320-
canonicalKey,
321-
});
322-
}
323-
}
324-
const durableStorePath = resolveCombinedDatabasePath(durableTargets, defaultAgentId);
325-
const incognitoStorePaths = mergeOpenIncognitoStores({
326-
cfg,
327-
combined,
328-
projection,
329-
targets: incognitoTargets,
330-
});
331-
return {
332-
diagnostics,
333-
durableStorePath,
334-
storePath: incognitoStorePaths.length > 0 ? "(multiple)" : durableStorePath,
335-
store: combined,
336-
};
337-
}
338351
const combined: Record<string, SessionEntry> = {};
339352
for (const target of durableTargets) {
340353
const agentId = target.agentId;
@@ -354,9 +367,6 @@ export function loadCombinedSessionStoreForGatewayCore(
354367
const canonicalAgentId = normalizeAgentId(
355368
parseAgentSessionKey(canonicalKey)?.agentId ?? agentId,
356369
);
357-
if (configuredAgentIds && !configuredAgentIds.has(canonicalAgentId)) {
358-
continue;
359-
}
360370
if (requestedAgentId && canonicalAgentId !== requestedAgentId) {
361371
continue;
362372
}
@@ -376,12 +386,24 @@ export function loadCombinedSessionStoreForGatewayCore(
376386
projection,
377387
targets: incognitoTargets,
378388
});
389+
if (configuredAgentIds) {
390+
filterCombinedStoreToConfiguredAgents({ cfg, configuredAgentIds, store: combined });
391+
}
379392

380393
const durableStorePaths = durableTargets.map((target) => target.storePath);
381394
const durableStorePath = resolveCombinedDatabasePath(durableTargets, defaultAgentId);
395+
if (storeConfig && !isStorePathTemplate(storeConfig)) {
396+
return {
397+
diagnostics,
398+
durableStorePath,
399+
durableTargets,
400+
storePath: incognitoStorePaths.length > 0 ? "(multiple)" : durableStorePath,
401+
store: combined,
402+
};
403+
}
382404
const storePath = resolveCombinedStorePath(
383405
[...durableStorePaths, ...incognitoStorePaths],
384406
storeConfig,
385407
);
386-
return { diagnostics, durableStorePath, storePath, store: combined };
408+
return { diagnostics, durableStorePath, durableTargets, storePath, store: combined };
387409
}
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
import { afterEach, expect, it, vi } from "vitest";
4+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
5+
import * as sessionDirs from "../../agents/session-dirs.js";
6+
import { EMPTY_LEGACY_SESSION_SURFACES } from "../../plugins/legacy-session-surfaces.types.js";
7+
import { unregisterOpenClawAgentDatabase } from "../../state/openclaw-agent-db-registry.js";
8+
import {
9+
closeOpenClawAgentDatabasesForTest,
10+
listOpenClawRegisteredAgentDatabases,
11+
} from "../../state/openclaw-agent-db.js";
12+
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
13+
import { withEnvAsync } from "../../test-utils/env.js";
14+
import type { OpenClawConfig } from "../types.openclaw.js";
15+
import { loadCombinedSessionStoreForGatewayCore } from "./combined-store-gateway.js";
16+
import { replaceSessionEntry } from "./session-accessor.js";
17+
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
18+
import { runSessionStartupMigration } from "./startup-migration.js";
19+
20+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
21+
22+
afterEach(() => {
23+
closeOpenClawAgentDatabasesForTest();
24+
closeOpenClawStateDatabaseForTest();
25+
});
26+
27+
it("re-registers durable lineage children before configured-only runtime reads", async () => {
28+
const root = fs.realpathSync.native(tempDirs.make("openclaw-startup-registry-recovery-"));
29+
const stateDir = path.join(root, "state");
30+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
31+
const env = { ...process.env };
32+
const storeTemplate = path.join(stateDir, "agents", "{agentId}", "sessions", "sessions.json");
33+
const cfg: OpenClawConfig = {
34+
agents: { entries: { ops: { default: true } } },
35+
session: { store: storeTemplate },
36+
};
37+
const mainKey = "agent:ops:main";
38+
const childKey = "agent:codex:subagent:upgrade-child";
39+
const storePathFor = (agentId: string) => storeTemplate.replace("{agentId}", agentId);
40+
41+
await replaceSessionEntry(
42+
{ agentId: "ops", env, sessionKey: mainKey, storePath: storePathFor("ops") },
43+
{ sessionId: "session-ops", updatedAt: 20 },
44+
);
45+
await replaceSessionEntry(
46+
{ agentId: "codex", env, sessionKey: childKey, storePath: storePathFor("codex") },
47+
{ sessionId: "session-codex", spawnedBy: mainKey, updatedAt: 30 },
48+
);
49+
await replaceSessionEntry(
50+
{
51+
agentId: "local",
52+
env,
53+
sessionKey: "agent:local:main",
54+
storePath: storePathFor("local"),
55+
},
56+
{ sessionId: "session-local", updatedAt: 10 },
57+
);
58+
59+
const childDatabasePath = resolveSqliteTargetFromSessionStorePath(storePathFor("codex"), {
60+
agentId: "codex",
61+
env,
62+
}).path;
63+
closeOpenClawAgentDatabasesForTest();
64+
unregisterOpenClawAgentDatabase({ agentId: "codex", env, path: childDatabasePath });
65+
66+
expect(fs.existsSync(childDatabasePath)).toBe(true);
67+
expect(
68+
listOpenClawRegisteredAgentDatabases({ env }).some(
69+
(entry) => entry.agentId === "codex" && entry.path === childDatabasePath,
70+
),
71+
).toBe(false);
72+
73+
await runSessionStartupMigration({
74+
cfg,
75+
env,
76+
log: { info: vi.fn(), warn: vi.fn() },
77+
deps: {
78+
migrateLegacyMainSessionKeys: vi.fn(async () => ({
79+
armed: false,
80+
changes: [],
81+
complete: false,
82+
ledgerComplete: false,
83+
legacyAgentId: "main",
84+
mainKey: "main",
85+
outcomes: [{ kind: "not-armed" as const }],
86+
warnings: [],
87+
})),
88+
migrateOrphanedSessionKeys: vi.fn(async () => ({ changes: [], warnings: [] })),
89+
prepareLegacySessionSurfaces: () => EMPTY_LEGACY_SESSION_SURFACES,
90+
sweepOrphanSessionStoreTemps: vi.fn(async () => 0),
91+
},
92+
});
93+
94+
expect(listOpenClawRegisteredAgentDatabases({ env })).toContainEqual(
95+
expect.objectContaining({ agentId: "codex", path: childDatabasePath }),
96+
);
97+
98+
const enumerateAgentDirs = vi.spyOn(sessionDirs, "resolveAgentSessionDirsFromAgentsDirSync");
99+
try {
100+
const store = loadCombinedSessionStoreForGatewayCore(cfg, {
101+
configuredAgentsOnly: true,
102+
}).store;
103+
expect(store[mainKey]?.sessionId).toBe("session-ops");
104+
expect(store[childKey]?.sessionId).toBe("session-codex");
105+
expect(store["agent:local:main"]).toBeUndefined();
106+
expect(enumerateAgentDirs).not.toHaveBeenCalled();
107+
} finally {
108+
enumerateAgentDirs.mockRestore();
109+
}
110+
});
111+
});

0 commit comments

Comments
 (0)