Skip to content

Commit a947730

Browse files
authored
fix(sessions): scope legacy-main owner notice to real legacy rows (#126551)
* fix(sessions): scope legacy-main owner notice to real legacy rows resolveArmingDecision returns owner-unresolved purely from config, before any session store is read, so the unresolved-owner notice and the agents-create gate both fired without checking whether any legacy `main` rows exist. A new explicit-ownership fleet with zero session data printed "legacy main rows have no unambiguous configured owner" on every startup, and `agents create main` dead-ended: it told operators to run `openclaw doctor --fix`, which cannot resolve anything when there is nothing to migrate. Probe the candidate stores in the unresolved-owner branch and report no-legacy-rows when every store proves clean. Unreadable stores, legacy JSON stores, and genuine read failures still fail open and keep the notice, so the precaution survives exactly where absence cannot be proven. The main-creation gate now blocks an unarmed run only when the scan did not prove the fleet clean; armed runs still require a completed ledger. Store scanning moves to legacy-main-session-key-scan.ts: the probe and the armed claim reader share one normalization-aware key predicate, so a store holding `agent:Main:...` or another key that normalizes to `main` cannot be misread as clean, and the migration module stays under the max-lines limit. * test(gateway): stop compaction read-error mocks depending on factory order src/gateway/server.sessions.compaction-read-errors.test.ts captured the real loadTranscriptEvents as a side effect of its vi.mock factory, then required it in beforeEach. The factory runs on first import of the mocked module, so once a shard shares a worker (--isolate=false) the field could still be unset and all five tests failed with "transcript reader mock was not initialized". Resolve the real reader with vi.importActual in beforeAll instead, so the default implementation no longer depends on whether the factory has run. Pre-existing on main: 0a8226c fails the same checks-node-compact-small-4 shard with the identical five tests. Not reproducible locally, including with the exact 25-file shard composition; CI on Linux runners is the verification. * test(gateway): load the mocked transcript reader deterministically src/gateway/server.sessions.compaction-read-errors.test.ts captures the real loadTranscriptEvents as a side effect of its vi.mock factory and requires it in beforeEach. The factory only runs when the mocked module is first imported, and nothing in this file imported it directly, so once a shard shares a worker (--isolate=false) the capture could still be unset and all five tests failed with "transcript reader mock was not initialized". Import the mocked module for its side effect so the factory always runs. Resolving the reader with vi.importActual instead was wrong: that returns a separately instantiated, unmocked copy that does not share the module-level SQLite state the harness sets up, so it read no events, compaction no-opped successfully and the three rejection tests failed on response.ok. Capturing through importOriginal keeps the harness's own module instance. Pre-existing on main: 0a8226c fails the same checks-node-compact-small-4 shard with the identical five tests.
1 parent f612675 commit a947730

7 files changed

Lines changed: 230 additions & 64 deletions

‎src/agents/agent-create.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,27 @@ describe("createAgent", () => {
256256
});
257257
});
258258

259+
it("creates main when an unarmed scan proves every legacy store clean", async () => {
260+
mocks.config = { agents: { entries: { robby: { id: "robby" } } } };
261+
mocks.migrateLegacyMainSessionKeys.mockResolvedValueOnce({
262+
armed: false,
263+
changes: [],
264+
complete: true,
265+
ledgerComplete: false,
266+
legacyAgentId: "main",
267+
mainKey: "main",
268+
outcomes: [{ kind: "no-legacy-rows", detail: "no configured owner" }],
269+
warnings: [],
270+
});
271+
272+
await expect(createAgent({ name: "main" })).resolves.toMatchObject({
273+
status: "created",
274+
agentId: "main",
275+
});
276+
expect(mocks.resolveSharedAuthStoreOwnership).toHaveBeenCalledOnce();
277+
expect(mocks.transformConfigFileWithRetry).toHaveBeenCalledOnce();
278+
});
279+
259280
it("defaults the workspace through the agent-scoped resolver", async () => {
260281
const result = await createAgent({ name: "Researcher" });
261282

‎src/agents/agent-create.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,10 @@ async function evaluateMainCreationGate(
176176
legacyAgentId: BOOTSTRAP_AGENT_ID,
177177
mode: "detect",
178178
});
179-
if (!migration.armed || !migration.ledgerComplete) {
179+
// An unarmed scan can proceed only when every candidate store proved collision-free.
180+
const provenClean = migration.outcomes.every((outcome) => outcome.kind === "no-legacy-rows");
181+
const blocked = migration.armed ? !migration.ledgerComplete : !provenClean;
182+
if (blocked) {
180183
const details = migration.outcomes.map(describeLegacySessionOutcome).join("; ");
181184
return createError(
182185
"legacy-session-migration-required",
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import { executeSqliteQuerySync } from "../../infra/kysely-sync.js";
2+
import { normalizeAgentId, parseAgentSessionKey } from "../../routing/session-key.js";
3+
import { withOpenClawAgentDatabaseReadOnly } from "../../state/openclaw-agent-db-readonly.js";
4+
import { readClaim } from "./legacy-main-session-migration-operations.js";
5+
import type { PhysicalStore, SessionClaim } from "./legacy-main-session-migration.contract.js";
6+
import { getSessionKysely } from "./session-accessor.sqlite-scope.js";
7+
8+
/** Returns the stored `agent:<id>:` prefix when the key is owned by the legacy agent. */
9+
function legacyAgentKeyPrefix(key: string, legacyAgentId: string): string | null {
10+
const parsed = parseAgentSessionKey(key);
11+
if (!parsed || normalizeAgentId(parsed.agentId) !== legacyAgentId) {
12+
return null;
13+
}
14+
const prefix = `agent:${parsed.agentId}:`;
15+
return key.startsWith(prefix) ? prefix : null;
16+
}
17+
18+
function canonicalKeyFor(key: string, legacyAgentId: string, ownerAgentId: string): string | null {
19+
const prefix = legacyAgentKeyPrefix(key, legacyAgentId);
20+
return prefix ? `agent:${ownerAgentId}:${key.slice(prefix.length)}` : null;
21+
}
22+
23+
export function storeHasLegacyAgentSessionKey(params: {
24+
legacyAgentId: string;
25+
store: PhysicalStore;
26+
env: NodeJS.ProcessEnv;
27+
}): boolean {
28+
const result = withOpenClawAgentDatabaseReadOnly(
29+
(database) =>
30+
executeSqliteQuerySync(
31+
database.db,
32+
getSessionKysely(database.db).selectFrom("session_nodes").select("session_key"),
33+
).rows.some((row) => legacyAgentKeyPrefix(row.session_key, params.legacyAgentId) !== null),
34+
{ agentId: params.store.databaseAgentId, env: params.env, path: params.store.path },
35+
);
36+
// A missing database, schema, or table proves absence exactly as the armed claim
37+
// reader does below; only genuine read failures throw and let the caller fail open.
38+
return result.found ? result.value : false;
39+
}
40+
41+
export function readClaimsFromStore(params: {
42+
legacyAgentId: string;
43+
ownerAgentId: string;
44+
store: PhysicalStore;
45+
env: NodeJS.ProcessEnv;
46+
}): { canonical: SessionClaim[]; legacy: SessionClaim[] } {
47+
const result = withOpenClawAgentDatabaseReadOnly(
48+
(database) => {
49+
const keys = executeSqliteQuerySync(
50+
database.db,
51+
getSessionKysely(database.db).selectFrom("session_nodes").select("session_key"),
52+
).rows.map((row) => row.session_key);
53+
const legacy: SessionClaim[] = [];
54+
const canonical: SessionClaim[] = [];
55+
for (const key of keys) {
56+
const canonicalKey = canonicalKeyFor(key, params.legacyAgentId, params.ownerAgentId);
57+
if (canonicalKey) {
58+
const claim = readClaim(database, params.store, key, canonicalKey);
59+
if (claim) {
60+
legacy.push(claim);
61+
}
62+
continue;
63+
}
64+
const parsed = parseAgentSessionKey(key);
65+
if (parsed && normalizeAgentId(parsed.agentId) === params.ownerAgentId) {
66+
const claim = readClaim(database, params.store, key, key);
67+
if (claim) {
68+
canonical.push(claim);
69+
}
70+
}
71+
}
72+
return { canonical, legacy };
73+
},
74+
{ agentId: params.store.databaseAgentId, env: params.env, path: params.store.path },
75+
);
76+
return result.found ? result.value : { canonical: [], legacy: [] };
77+
}

‎src/config/sessions/legacy-main-session-migration.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,11 @@ describe("legacy main session migration", () => {
559559
const unresolved = createFixture({
560560
agents: { ownership: "explicit", entries: { ops: {}, research: {} } },
561561
});
562+
seedClaim({
563+
databaseAgentId: "main",
564+
databasePath: databasePath(unresolved.stateDir, "main"),
565+
key: "agent:main:chat",
566+
});
562567
const perAgentPinned = createFixture({
563568
agents: {
564569
ownership: "explicit",
@@ -592,6 +597,49 @@ describe("legacy main session migration", () => {
592597
expect(notArmed.warnings[0]).toContain("agents.defaults.sessionStore.agentId");
593598
});
594599

600+
it("proves an unresolved-owner store clean when it has no legacy rows", async () => {
601+
const fixture = createFixture({
602+
agents: { ownership: "explicit", entries: { ops: {}, research: {} } },
603+
});
604+
605+
const result = await migrateLegacyMainSessionKeys({
606+
cfg: fixture.cfg,
607+
env: fixture.env,
608+
mode: "detect",
609+
});
610+
611+
expect(result).toMatchObject({
612+
armed: false,
613+
complete: true,
614+
ledgerComplete: false,
615+
outcomes: [{ kind: "no-legacy-rows", detail: "no configured owner" }],
616+
warnings: [],
617+
});
618+
});
619+
620+
it("keeps unresolved ownership advisory when a candidate store is unreadable", async () => {
621+
const unreadablePath = path.join(tempDirs.make("unresolved-unreadable-"), "sessions.sqlite");
622+
fs.symlinkSync(`${unreadablePath}.missing`, unreadablePath);
623+
const fixture = createFixture({
624+
agents: { ownership: "explicit", entries: { ops: {}, research: {} } },
625+
session: { store: unreadablePath },
626+
});
627+
628+
const result = await migrateLegacyMainSessionKeys({
629+
cfg: fixture.cfg,
630+
env: fixture.env,
631+
mode: "automatic",
632+
});
633+
634+
expect(result).toMatchObject({
635+
armed: false,
636+
complete: false,
637+
ledgerComplete: false,
638+
outcomes: [{ kind: "not-armed", detail: "owner-unresolved" }],
639+
});
640+
expect(result.warnings[0]).toContain("agents.defaults.sessionStore.agentId");
641+
});
642+
595643
it("uses an explicit migration owner for retired main rows in per-agent stores", async () => {
596644
const fixture = createFixture({
597645
agents: {

‎src/config/sessions/legacy-main-session-migration.ts‎

Lines changed: 49 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,20 @@ import {
88
executeSqliteQueryTakeFirstSync,
99
getNodeSqliteKysely,
1010
} from "../../infra/kysely-sync.js";
11-
import {
12-
normalizeAgentId,
13-
normalizeMainKey,
14-
parseAgentSessionKey,
15-
} from "../../routing/session-key.js";
16-
import { withOpenClawAgentDatabaseReadOnly } from "../../state/openclaw-agent-db-readonly.js";
11+
import { normalizeAgentId, normalizeMainKey } from "../../routing/session-key.js";
1712
import { isSameOpenClawAgentDatabasePath } from "../../state/openclaw-agent-db-registry.js";
1813
import { withExistingOpenClawStateDatabaseReadOnly } from "../../state/openclaw-state-db-readonly.js";
1914
import type { DB as OpenClawStateKyselyDatabase } from "../../state/openclaw-state-db.generated.js";
2015
import { runOpenClawStateWriteTransaction } from "../../state/openclaw-state-db.js";
2116
import { resolveStateDir } from "../paths.js";
2217
import type { OpenClawConfig } from "../types.openclaw.js";
18+
import {
19+
readClaimsFromStore,
20+
storeHasLegacyAgentSessionKey,
21+
} from "./legacy-main-session-key-scan.js";
2322
import {
2423
claimsMatch,
2524
processIdenticalClaims,
26-
readClaim,
2725
repairDivergentClaims,
2826
samePhysicalStore,
2927
warningForDivergence,
@@ -36,11 +34,11 @@ import type {
3634
SessionClaim,
3735
} from "./legacy-main-session-migration.contract.js";
3836
import { resolveSessionStorePathCore } from "./paths.js";
39-
import { getSessionKysely } from "./session-accessor.sqlite-scope.js";
4037
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
4138
import {
4239
resolveAllAgentSessionStoreCandidateTargetsSync,
4340
resolveAgentSessionStoreTargetsSync,
41+
resolveSessionStoreCompatibilityAgentId,
4442
} from "./targets.js";
4543

4644
const SOURCE_KEY = "legacy-main-session-keys";
@@ -82,15 +80,6 @@ function resolveArmingDecision(cfg: OpenClawConfig, legacyAgentId: string): Armi
8280
return { armed: false, reason: "owner-unresolved" };
8381
}
8482

85-
function canonicalKeyFor(key: string, legacyAgentId: string, ownerAgentId: string): string | null {
86-
const parsed = parseAgentSessionKey(key);
87-
if (!parsed || normalizeAgentId(parsed.agentId) !== legacyAgentId) {
88-
return null;
89-
}
90-
const prefix = `agent:${parsed.agentId}:`;
91-
return key.startsWith(prefix) ? `agent:${ownerAgentId}:${key.slice(prefix.length)}` : null;
92-
}
93-
9483
function addPhysicalStore(stores: PhysicalStore[], candidate: PhysicalStore): void {
9584
if (!stores.some((store) => samePhysicalStore(store, candidate))) {
9685
stores.push(candidate);
@@ -160,7 +149,7 @@ function resolvePhysicalStores(params: {
160149
env: NodeJS.ProcessEnv;
161150
legacyAgentId: string;
162151
mode: LegacyMainSessionMigrationMode;
163-
ownerAgentId: string;
152+
ownerAgentId?: string;
164153
}): ResolvedPhysicalStores {
165154
const logicalTargets = [
166155
...resolveAllAgentSessionStoreCandidateTargetsSync(params.cfg, { env: params.env }),
@@ -172,14 +161,17 @@ function resolvePhysicalStores(params: {
172161
env: params.env,
173162
}),
174163
},
175-
{
164+
];
165+
if (params.ownerAgentId) {
166+
logicalTargets.push({
176167
agentId: params.ownerAgentId,
177168
storePath: resolveSessionStorePathCore(params.cfg.session?.store, {
178169
agentId: params.ownerAgentId,
179170
env: params.env,
180171
}),
181-
},
182-
];
172+
});
173+
}
174+
const defaultAgentId = params.ownerAgentId ?? resolveSessionStoreCompatibilityAgentId(params.cfg);
183175
const stores: PhysicalStore[] = [];
184176
const jsonPaths = new Set<string>();
185177
const unreadable: LegacyMainSessionMigrationOutcome[] = [];
@@ -190,7 +182,7 @@ function resolvePhysicalStores(params: {
190182
}
191183
const resolved = resolveSqliteTargetFromSessionStorePath(target.storePath, {
192184
agentId: target.agentId,
193-
defaultAgentId: params.ownerAgentId,
185+
defaultAgentId,
194186
env: params.env,
195187
});
196188
const physical: PhysicalStore = {
@@ -229,47 +221,6 @@ function resolveSourceLayout(resolved: ResolvedPhysicalStores): string[] {
229221
].toSorted();
230222
}
231223

232-
function readClaimsFromStore(params: {
233-
legacyAgentId: string;
234-
ownerAgentId: string;
235-
store: PhysicalStore;
236-
env: NodeJS.ProcessEnv;
237-
}): { canonical: SessionClaim[]; legacy: SessionClaim[] } {
238-
if (inspectPath(params.store.path) === "missing") {
239-
return { canonical: [], legacy: [] };
240-
}
241-
const result = withOpenClawAgentDatabaseReadOnly(
242-
(database) => {
243-
const keys = executeSqliteQuerySync(
244-
database.db,
245-
getSessionKysely(database.db).selectFrom("session_nodes").select("session_key"),
246-
).rows.map((row) => row.session_key);
247-
const legacy: SessionClaim[] = [];
248-
const canonical: SessionClaim[] = [];
249-
for (const key of keys) {
250-
const canonicalKey = canonicalKeyFor(key, params.legacyAgentId, params.ownerAgentId);
251-
if (canonicalKey) {
252-
const claim = readClaim(database, params.store, key, canonicalKey);
253-
if (claim) {
254-
legacy.push(claim);
255-
}
256-
continue;
257-
}
258-
const parsed = parseAgentSessionKey(key);
259-
if (parsed && normalizeAgentId(parsed.agentId) === params.ownerAgentId) {
260-
const claim = readClaim(database, params.store, key, key);
261-
if (claim) {
262-
canonical.push(claim);
263-
}
264-
}
265-
}
266-
return { canonical, legacy };
267-
},
268-
{ agentId: params.store.databaseAgentId, env: params.env, path: params.store.path },
269-
);
270-
return result.found ? result.value : { canonical: [], legacy: [] };
271-
}
272-
273224
function readLedger(env: NodeJS.ProcessEnv): { report: LedgerReport; status: string } | undefined {
274225
return (
275226
withExistingOpenClawStateDatabaseReadOnly(
@@ -420,6 +371,38 @@ async function migrateLegacyMainSessionKeysInternal(params: {
420371
warnings: [] as string[],
421372
};
422373
if (!arming.armed) {
374+
if (arming.reason === "owner-unresolved") {
375+
// Owner guidance is useful only when legacy rows may exist; unreadable or JSON
376+
// candidates fail open because they cannot prove the fleet is clean.
377+
let rowsMayExist: boolean;
378+
try {
379+
const resolved = resolvePhysicalStores({
380+
cfg: params.cfg,
381+
env,
382+
legacyAgentId,
383+
mode: params.mode,
384+
});
385+
rowsMayExist =
386+
resolved.unreadable.length > 0 ||
387+
resolved.jsonPaths.length > 0 ||
388+
resolved.stores.some(
389+
(store) =>
390+
inspectPath(store.path) === "present" &&
391+
storeHasLegacyAgentSessionKey({ env, legacyAgentId, store }),
392+
);
393+
} catch {
394+
rowsMayExist = true;
395+
}
396+
if (!rowsMayExist) {
397+
return {
398+
...base,
399+
armed: false,
400+
complete: true,
401+
ledgerComplete: false,
402+
outcomes: [{ kind: "no-legacy-rows", detail: "no configured owner" }],
403+
};
404+
}
405+
}
423406
const unresolved = arming.reason === "owner-unresolved";
424407
return {
425408
...base,
@@ -497,6 +480,9 @@ async function migrateLegacyMainSessionKeysInternal(params: {
497480
const allCanonical: SessionClaim[] = [];
498481
for (const store of resolved.stores) {
499482
try {
483+
if (inspectPath(store.path) === "missing") {
484+
continue;
485+
}
500486
const claims = readClaimsFromStore({ env, legacyAgentId, ownerAgentId, store });
501487
allLegacy.push(...claims.legacy);
502488
allCanonical.push(...claims.canonical);

‎src/gateway/server.sessions.compaction-read-errors.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ import {
44
appendTranscriptMessage,
55
upsertSessionEntryCore,
66
} from "../config/sessions/session-accessor.js";
7+
// Force the mocked module to load here: the factory below captures the real reader as a
8+
// side effect, and beforeEach needs that capture. Without this import the factory only ran
9+
// if some other module in the graph pulled it in first, which is not guaranteed once a
10+
// shard shares a worker (--isolate=false).
11+
import "../config/sessions/session-accessor.sqlite-read.js";
712
import { rpcReq } from "./test-helpers.js";
813
import {
914
sessionStoreEntry,

0 commit comments

Comments
 (0)