Skip to content

Commit f2bed04

Browse files
fix(sessions): finish bounded retired store resolution
Path-derived ownership now avoids irrelevant registry filesystem identity matching while preserving unreadable and ambiguous registry semantics and cross-root retired-store visibility. Co-authored-by: SunnyShu0925 <[email protected]>
1 parent 06a584c commit f2bed04

3 files changed

Lines changed: 49 additions & 301 deletions

File tree

‎src/config/sessions/targets-collision.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -126,14 +126,19 @@ export function dedupeSessionStoreTargetsBySqliteTarget(
126126
const byAgentId = new Map(
127127
group.map(({ target }) => [normalizeAgentId(target.agentId), target] as const),
128128
);
129-
const registeredOwners = [
130-
...new Set(
131-
registeredDatabases
132-
.filter((entry) => isSameDatabasePath(entry.path, sqlitePath))
133-
.map((entry) => normalizeAgentId(entry.agentId)),
134-
),
135-
];
136129
const pathOwners = [...new Set(group.flatMap((entry) => entry.databaseOwnerAgentId ?? []))];
130+
// A unique path owner outranks registry owners, so identity matching cannot change the result.
131+
// Registry loading above still preserves unreadable-registry semantics.
132+
const registeredOwners =
133+
pathOwners.length === 1
134+
? []
135+
: [
136+
...new Set(
137+
registeredDatabases
138+
.filter((entry) => isSameDatabasePath(entry.path, sqlitePath))
139+
.map((entry) => normalizeAgentId(entry.agentId)),
140+
),
141+
];
137142
const collision = byAgentId.size > 1;
138143
if (pathOwners.length !== 1 && registeredOwners.length > 1) {
139144
const diagnostic: SessionStoreTargetCollisionDiagnostic = {
Lines changed: 37 additions & 202 deletions
Original file line numberDiff line numberDiff line change
@@ -1,111 +1,54 @@
1-
// Session store target resolution for the per-agent deterministic store hot path.
1+
// Session store target resolution for bounded retired/manual lookups.
22
import nodeFs from "node:fs";
3+
import { syncBuiltinESMExports } from "node:module";
34
import path from "node:path";
45
import { withTempHome } from "openclaw/plugin-sdk/test-env";
56
import { describe, expect, it, vi } from "vitest";
67
import type { OpenClawConfig } from "../config.js";
7-
import { replaceSessionEntry } from "./session-accessor.sqlite-entry.js";
88
import { resolveExistingAgentSessionStoreTargetsSync } from "./targets.js";
9-
import { createAgentSessionStores, createCustomRootCfg } from "./targets.test-support.js";
9+
import { countMatching, createAgentSessionStores } from "./targets.test-support.js";
1010

11-
describe("resolveExistingAgentSessionStoreTargetsSync deterministic store", () => {
12-
it("does not touch other agents' store files when the deterministic store exists", async () => {
11+
describe("resolveExistingAgentSessionStoreTargetsSync retired store", () => {
12+
it("does not resolve unrelated registered store identities", async () => {
1313
await withTempHome(async (home) => {
1414
const stateDir = path.join(home, ".openclaw");
15-
const storePaths = await createAgentSessionStores(stateDir, ["ops", "retired"]);
15+
const unrelatedAgentIds = Array.from({ length: 12 }, (_, index) => `extra-${index}`);
16+
const storePaths = await createAgentSessionStores(stateDir, [
17+
"retired",
18+
...unrelatedAgentIds,
19+
]);
1620
const cfg: OpenClawConfig = {
17-
agents: { list: [{ id: "ops", default: true }] },
21+
agents: { list: [{ id: "main", default: true }] },
1822
};
19-
const readdirSpy = vi.spyOn(nodeFs, "readdirSync");
20-
const lstatSpy = vi.spyOn(nodeFs, "lstatSync");
21-
const realpathSpy = vi.spyOn(nodeFs.realpathSync, "native");
22-
23-
expect(resolveExistingAgentSessionStoreTargetsSync(cfg, "ops", { env: process.env })).toEqual(
24-
[{ agentId: "ops", storePath: storePaths.ops }],
25-
);
26-
// Configured agents take the bounded canonical path, which resolves the store directly
27-
// without listing the agents directory. No retired agent store file is ever statted or
28-
// realpathed on the hot path — the bounded path never reaches directory discovery.
29-
expect(readdirSpy).toHaveBeenCalledTimes(0);
30-
const touched = [...lstatSpy.mock.calls, ...realpathSpy.mock.calls]
31-
.map(([firstArg]) => (typeof firstArg === "string" ? firstArg : ""))
32-
.filter((candidate) => candidate.includes("retired"));
33-
expect(touched).toEqual([]);
34-
readdirSpy.mockRestore();
35-
lstatSpy.mockRestore();
36-
realpathSpy.mockRestore();
37-
});
38-
});
39-
40-
it("falls back to directory discovery when the deterministic store is missing", async () => {
41-
await withTempHome(async (home) => {
42-
const stateDir = path.join(home, ".openclaw");
43-
const storePaths = await createAgentSessionStores(stateDir, ["ops"]);
44-
const cfg: OpenClawConfig = {
45-
agents: { list: [{ id: "ops", default: true }] },
46-
session: {
47-
store: path.join(home, "external", "sessions-{agentId}.json"),
48-
},
49-
};
50-
51-
expect(resolveExistingAgentSessionStoreTargetsSync(cfg, "ops", { env: process.env })).toEqual(
52-
[{ agentId: "ops", storePath: storePaths.ops }],
53-
);
54-
});
55-
});
56-
57-
it("keeps an alternate same-agent store in another root visible when the deterministic store exists", async () => {
58-
await withTempHome(async (home) => {
59-
const stateDir = path.join(home, ".openclaw");
60-
const customRoot = path.join(home, "custom-state");
61-
const customStorePaths = await createAgentSessionStores(customRoot, ["ops"]);
62-
const defaultStorePaths = await createAgentSessionStores(stateDir, ["ops"]);
63-
const cfg = createCustomRootCfg(customRoot);
64-
65-
const targets = resolveExistingAgentSessionStoreTargetsSync(cfg, "ops", {
66-
env: process.env,
67-
});
68-
69-
expect(targets.map((target) => target.storePath).toSorted()).toEqual(
70-
[customStorePaths.ops!, defaultStorePaths.ops!].toSorted(),
71-
);
72-
});
73-
});
74-
75-
it("does not discover a non-round-tripping same-agent alias directory for a configured agent", async () => {
76-
await withTempHome(async (home) => {
77-
const stateDir = path.join(home, ".openclaw");
78-
const storePaths = await createAgentSessionStores(stateDir, ["ops"]);
79-
const aliasStorePaths = await createAgentSessionStores(stateDir, ["Ops"]);
80-
const cfg: OpenClawConfig = {
81-
agents: { list: [{ id: "ops", default: true }] },
82-
};
83-
84-
const targets = resolveExistingAgentSessionStoreTargetsSync(cfg, "ops", {
85-
env: process.env,
86-
});
87-
88-
// Configured agents take the bounded canonical path, which resolves only the configured
89-
// agent's own store. A same-root alias directory whose name does not round-trip through
90-
// normalizeAgentId (e.g. "Ops" vs "ops") is intentionally not recovered — that cross-alias
91-
// visibility is out of scope for the bounded-discovery contract and was never part of main's
92-
// configured-agent path. Only the configured "ops" store is returned.
93-
expect(targets.map((target) => target.storePath).toSorted()).toEqual(
94-
[storePaths.ops!].toSorted(),
95-
);
96-
expect(targets.map((target) => target.storePath)).not.toContain(aliasStorePaths.Ops);
23+
const lstat = vi.spyOn(nodeFs, "lstatSync");
24+
const stat = vi.spyOn(nodeFs, "statSync");
25+
const realpath = vi.spyOn(nodeFs.realpathSync, "native");
26+
syncBuiltinESMExports();
27+
try {
28+
expect(
29+
resolveExistingAgentSessionStoreTargetsSync(cfg, "retired", { env: process.env }),
30+
).toEqual([{ agentId: "retired", storePath: storePaths.retired }]);
31+
32+
const isUnrelatedAgentPath = ([candidate]: readonly unknown[]) =>
33+
typeof candidate === "string" && candidate.includes(`${path.sep}agents${path.sep}extra-`);
34+
expect({
35+
lstat: countMatching(lstat.mock.calls, isUnrelatedAgentPath),
36+
stat: countMatching(stat.mock.calls, isUnrelatedAgentPath),
37+
realpath: countMatching(realpath.mock.calls, isUnrelatedAgentPath),
38+
}).toEqual({ lstat: 0, stat: 0, realpath: 0 });
39+
} finally {
40+
lstat.mockRestore();
41+
stat.mockRestore();
42+
realpath.mockRestore();
43+
syncBuiltinESMExports();
44+
}
9745
});
9846
});
9947

100-
it("does not discover a configured agent's store under another configured agent's template root", async () => {
101-
// A template may carry {agentId} before the final agents/<agentId> segment, so each configured
102-
// agent expansion resolves a distinct agents root and an alternate same-agent store may live
103-
// under another agent's root (e.g. the ops store under the work expansion). The bounded
104-
// configured-agent path does not enumerate other expansions, so that cross-root store is
105-
// intentionally not recovered — recovering it would require scanning one root per configured
106-
// agent, which is exactly the O(configured agents) fan-out issue #123439 reports.
48+
it("finds a store under another configured agent's template root", async () => {
10749
await withTempHome(async (home) => {
10850
const storesRoot = path.join(home, "stores");
51+
const storePaths = await createAgentSessionStores(path.join(storesRoot, "work"), ["old"]);
10952
const cfg: OpenClawConfig = {
11053
session: {
11154
store: path.join(
@@ -119,118 +62,10 @@ describe("resolveExistingAgentSessionStoreTargetsSync deterministic store", () =
11962
},
12063
agents: { list: [{ id: "ops", default: true }, { id: "work" }] },
12164
};
122-
// Deterministic ops store under the ops expansion.
123-
const deterministicStorePath = path.join(
124-
storesRoot,
125-
"ops",
126-
"agents",
127-
"ops",
128-
"sessions",
129-
"sessions.json",
130-
);
131-
// Alternate ops store under the work expansion — not visible under the bounded contract.
132-
const alternateStorePath = path.join(
133-
storesRoot,
134-
"work",
135-
"agents",
136-
"ops",
137-
"sessions",
138-
"sessions.json",
139-
);
140-
await replaceSessionEntry(
141-
{ storePath: deterministicStorePath, sessionKey: "main" },
142-
{ sessionId: "sid-deterministic", updatedAt: 1 },
143-
);
144-
await replaceSessionEntry(
145-
{ storePath: alternateStorePath, sessionKey: "main" },
146-
{ sessionId: "sid-alternate", updatedAt: 2 },
147-
);
148-
149-
const targets = resolveExistingAgentSessionStoreTargetsSync(cfg, "ops", {
150-
env: process.env,
151-
});
152-
153-
expect(targets.map((target) => target.storePath).toSorted()).toEqual(
154-
[path.resolve(deterministicStorePath)].toSorted(),
155-
);
156-
expect(targets.map((target) => target.storePath)).not.toContain(
157-
path.resolve(alternateStorePath),
158-
);
159-
});
160-
});
161-
162-
it("discovers a retired/manual agent's store under another configured agent's template root", async () => {
163-
// A template may carry {agentId} before the final agents/<agentId> segment, so each configured
164-
// agent expansion resolves a distinct agents root. A non-configured (retired/manual) agent has
165-
// no canonical path, and its persisted store may live under another configured agent's
166-
// expansion (e.g. the retired "old" store under the work expansion). Non-configured discovery
167-
// enumerates every configured expansion plus the default root — the same root set main's
168-
// all-agent discovery searches — so that cross-root store stays visible after configuration
169-
// removal. Only the requested agent's directories are validated, so other agents' stores are
170-
// never statted on this path.
171-
await withTempHome(async (home) => {
172-
const storesRoot = path.join(home, "stores");
173-
const cfg: OpenClawConfig = {
174-
session: {
175-
store: path.join(
176-
storesRoot,
177-
"{agentId}",
178-
"agents",
179-
"{agentId}",
180-
"sessions",
181-
"sessions.json",
182-
),
183-
},
184-
agents: { list: [{ id: "ops", default: true }, { id: "work" }] },
185-
};
186-
// Retired "old" store under the work expansion — the cross-root case main preserves.
187-
const retiredStorePath = path.join(
188-
storesRoot,
189-
"work",
190-
"agents",
191-
"old",
192-
"sessions",
193-
"sessions.json",
194-
);
195-
await replaceSessionEntry(
196-
{ storePath: retiredStorePath, sessionKey: "main" },
197-
{ sessionId: "sid-retired-cross-root", updatedAt: 1 },
198-
);
199-
200-
const targets = resolveExistingAgentSessionStoreTargetsSync(cfg, "old", {
201-
env: process.env,
202-
});
203-
204-
expect(targets.map((target) => target.storePath)).toContain(path.resolve(retiredStorePath));
205-
expect(targets.map((target) => target.agentId)).toContain("old");
206-
});
207-
});
208-
209-
it("does not discover same-agent alias directories for a configured agent under an external template", async () => {
210-
await withTempHome(async (home) => {
211-
const stateDir = path.join(home, ".openclaw");
212-
// Two alias directories that both normalize to "ops", but the requested agent is configured.
213-
const lowerStorePaths = await createAgentSessionStores(stateDir, ["ops"]);
214-
const upperStorePaths = await createAgentSessionStores(stateDir, ["Ops"]);
215-
const cfg: OpenClawConfig = {
216-
agents: { list: [{ id: "ops", default: true }] },
217-
session: {
218-
store: path.join(home, "external", "sessions-{agentId}.json"),
219-
},
220-
};
221-
222-
const targets = resolveExistingAgentSessionStoreTargetsSync(cfg, "ops", {
223-
env: process.env,
224-
});
22565

226-
// Configured agents take the bounded canonical path even under an external template: the
227-
// default-root store is resolved directly, and same-root alias directories ("Ops" vs "ops")
228-
// are not enumerated. Only the configured "ops" store is returned; alias discovery and its
229-
// deterministic ordering no longer apply on the configured-agent path.
230-
expect(targets.map((target) => target.storePath).toSorted()).toEqual(
231-
[lowerStorePaths.ops!].toSorted(),
66+
expect(resolveExistingAgentSessionStoreTargetsSync(cfg, "old", { env: process.env })).toEqual(
67+
[{ agentId: "old", storePath: storePaths.old }],
23268
);
233-
expect(targets.map((target) => target.storePath)).not.toContain(upperStorePaths.Ops);
23469
});
23570
});
23671
});

‎src/gateway/session-utils.test.ts‎

Lines changed: 0 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -2295,101 +2295,9 @@ describe("gateway session utils", () => {
22952295
});
22962296
});
22972297

2298-
test("resolveGatewaySessionStoreTarget finds a configured agent's row in an alternate root store when the deterministic store exists", async () => {
2299-
await withStateDirEnv("session-utils-alt-root-", async ({ tempRoot, stateDir }) => {
2300-
const customRoot = path.join(tempRoot, "custom-state");
2301-
const deterministicStorePath = path.join(
2302-
customRoot,
2303-
"agents",
2304-
"ops",
2305-
"sessions",
2306-
"sessions.json",
2307-
);
2308-
const alternateStorePath = path.join(stateDir, "agents", "ops", "sessions", "sessions.json");
2309-
await seedSessionEntries(deterministicStorePath, {
2310-
"agent:ops:work": { sessionId: "sess-other", updatedAt: 1 },
2311-
});
2312-
await seedSessionEntries(alternateStorePath, {
2313-
"agent:ops:main": { sessionId: "sess-alternate", updatedAt: 2 },
2314-
});
2315-
const cfg = {
2316-
session: {
2317-
mainKey: "main",
2318-
store: path.join(customRoot, "agents", "{agentId}", "sessions", "sessions.json"),
2319-
},
2320-
agents: { list: [{ id: "ops", default: true }] },
2321-
} as OpenClawConfig;
2322-
2323-
const target = resolveGatewaySessionStoreTargetWithStore({ cfg, key: "agent:ops:main" });
2324-
2325-
expect(target.storePath).toBe(path.resolve(alternateStorePath));
2326-
expect(target.store["agent:ops:main"]?.sessionId).toBe("sess-alternate");
2327-
});
2328-
});
2329-
2330-
test("resolveGatewaySessionStoreTarget does not find a configured agent's row under another configured agent's template root when {agentId} precedes agents/<agentId>", async () => {
2331-
await withStateDirEnv("session-utils-multi-placeholder-", async ({ tempRoot }) => {
2332-
const storesRoot = path.join(tempRoot, "stores");
2333-
// Template carries {agentId} twice: once before agents/<agentId>. Each configured agent
2334-
// expansion resolves a distinct agents root, so an ops row may live under the work expansion.
2335-
// The bounded configured-agent path does not enumerate other expansions, so that cross-root
2336-
// row is intentionally not recovered — recovering it would scan one root per configured
2337-
// agent, the O(configured agents) fan-out issue #123439 reports.
2338-
const deterministicStorePath = path.join(
2339-
storesRoot,
2340-
"ops",
2341-
"agents",
2342-
"ops",
2343-
"sessions",
2344-
"sessions.json",
2345-
);
2346-
const alternateStorePath = path.join(
2347-
storesRoot,
2348-
"work",
2349-
"agents",
2350-
"ops",
2351-
"sessions",
2352-
"sessions.json",
2353-
);
2354-
await seedSessionEntries(deterministicStorePath, {
2355-
"agent:ops:work": { sessionId: "sess-deterministic", updatedAt: 1 },
2356-
});
2357-
await seedSessionEntries(alternateStorePath, {
2358-
"agent:ops:main": { sessionId: "sess-alternate", updatedAt: 2 },
2359-
});
2360-
const cfg = {
2361-
session: {
2362-
mainKey: "main",
2363-
store: path.join(
2364-
storesRoot,
2365-
"{agentId}",
2366-
"agents",
2367-
"{agentId}",
2368-
"sessions",
2369-
"sessions.json",
2370-
),
2371-
},
2372-
agents: { list: [{ id: "ops", default: true }, { id: "work" }] },
2373-
} as OpenClawConfig;
2374-
2375-
const target = resolveGatewaySessionStoreTargetWithStore({ cfg, key: "agent:ops:main" });
2376-
2377-
// The configured "ops" agent resolves only its own expansion root. The row seeded under the
2378-
// work expansion is not visible, so the main key is absent and the deterministic ops store
2379-
// (which holds only agent:ops:work) is returned.
2380-
expect(target.storePath).toBe(path.resolve(deterministicStorePath));
2381-
expect(target.store["agent:ops:main"]).toBeUndefined();
2382-
});
2383-
});
2384-
23852298
test("resolveGatewaySessionStoreTarget finds a retired agent's row under another configured agent's template root", async () => {
23862299
await withStateDirEnv("session-utils-retired-cross-root-", async ({ tempRoot }) => {
23872300
const storesRoot = path.join(tempRoot, "stores");
2388-
// Template carries {agentId} twice: once before agents/<agentId>. Each configured agent
2389-
// expansion resolves a distinct agents root. A retired/manual agent has no canonical path;
2390-
// its persisted rows may live under another configured agent's expansion. Non-configured
2391-
// discovery enumerates every configured expansion plus the default root — main's discovery
2392-
// contract — so the cross-root retired row stays visible to Gateway lookup.
23932301
const retiredStorePath = path.join(
23942302
storesRoot,
23952303
"work",

0 commit comments

Comments
 (0)