Skip to content

Commit c43166a

Browse files
authored
perf(gateway): stop rescanning migrated session stores at startup (#128513)
1 parent cc2993c commit c43166a

9 files changed

Lines changed: 214 additions & 18 deletions

‎src/config/sessions/session-canonical-key.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ import {
1010
normalizeMainKey,
1111
parseAgentSessionKey,
1212
} from "../../routing/session-key.js";
13+
import {
14+
OPENCLAW_AGENT_SCHEMA_VERSION,
15+
type OpenClawAgentDatabaseOptions,
16+
} from "../../state/openclaw-agent-db-contract.js";
17+
import { withOpenClawAgentDatabaseReadOnly } from "../../state/openclaw-agent-db-readonly.js";
1318
import type { DB as OpenClawAgentKyselyDatabase } from "../../state/openclaw-agent-db.generated.js";
1419
import { parseSqliteSessionEntryRecord } from "./session-entry-json.js";
1520
import { projectCanonicalSessionEntryShape } from "./store-entry-shape.js";
@@ -22,7 +27,7 @@ import type { SessionEntry } from "./types.js";
2227
const SESSION_CANONICAL_KEY_REPAIR_COMMAND = "openclaw doctor --fix";
2328
type CanonicalSessionDatabase = Pick<
2429
OpenClawAgentKyselyDatabase,
25-
"session_key_contract" | "session_nodes" | "session_windows"
30+
"schema_meta" | "session_key_contract" | "session_nodes" | "session_windows"
2631
>;
2732
const validatedDatabases = new WeakSet<DatabaseSync>();
2833

@@ -261,3 +266,28 @@ export function setCanonicalSqliteSessionMainKey(
261266
);
262267
validatedDatabases.delete(database.db);
263268
}
269+
270+
/** Checks the startup contract without joining the writable database lifecycle. */
271+
export function isCanonicalSqliteSessionMainKeyCurrent(
272+
options: OpenClawAgentDatabaseOptions,
273+
mainKey: string | undefined,
274+
): boolean {
275+
const canonicalMainKey = normalizeMainKey(mainKey);
276+
const result = withOpenClawAgentDatabaseReadOnly((database) => {
277+
const db = getNodeSqliteKysely<CanonicalSessionDatabase>(database.db);
278+
const schema = executeSqliteQueryTakeFirstSync(
279+
database.db,
280+
db.selectFrom("schema_meta").select("schema_version").where("meta_key", "=", "primary"),
281+
);
282+
if (schema?.schema_version !== OPENCLAW_AGENT_SCHEMA_VERSION) {
283+
return false;
284+
}
285+
return (
286+
executeSqliteQueryTakeFirstSync(
287+
database.db,
288+
db.selectFrom("session_key_contract").select("main_key").where("id", "=", 1),
289+
)?.main_key === canonicalMainKey
290+
);
291+
}, options);
292+
return result.found && result.value;
293+
}

‎src/config/sessions/startup-migration.registry-recovery.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,50 @@ afterEach(() => {
2828
closeOpenClawStateDatabaseForTest();
2929
});
3030

31+
it("does not create a missing configured agent database during startup maintenance", async () => {
32+
const root = fs.realpathSync.native(tempDirs.make("openclaw-startup-missing-agent-db-"));
33+
const stateDir = path.join(root, "state");
34+
const storePath = path.join(stateDir, "agents", "idle", "sessions", "sessions.json");
35+
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
36+
const cfg: OpenClawConfig = {
37+
agents: { entries: { idle: { default: true } } },
38+
session: { store: path.join(stateDir, "agents", "{agentId}", "sessions", "sessions.json") },
39+
};
40+
const sqlitePath = resolveSqliteTargetFromSessionStorePath(storePath, {
41+
agentId: "idle",
42+
env,
43+
}).path;
44+
const migrateManagedWorktreeCanonicalWorkspaces = vi.fn(async () => 0);
45+
const sweepOrphanSessionStoreTemps = vi.fn(async () => 0);
46+
47+
await runSessionStartupMigration({
48+
cfg,
49+
env,
50+
log: { info: vi.fn(), warn: vi.fn() },
51+
deps: {
52+
migrateLegacyMainSessionKeys: vi.fn(async () => ({
53+
armed: false,
54+
changes: [],
55+
complete: false,
56+
ledgerComplete: false,
57+
legacyAgentId: "main",
58+
mainKey: "main",
59+
outcomes: [{ kind: "not-armed" as const }],
60+
warnings: [],
61+
})),
62+
migrateManagedWorktreeCanonicalWorkspaces,
63+
migrateOrphanedSessionKeys: vi.fn(async () => ({ changes: [], warnings: [] })),
64+
prepareLegacySessionSurfaces: () => EMPTY_LEGACY_SESSION_SURFACES,
65+
resolveAllAgentSessionStoreTargetsSync: () => [{ agentId: "idle", storePath }],
66+
sweepOrphanSessionStoreTemps,
67+
},
68+
});
69+
70+
expect(fs.existsSync(sqlitePath)).toBe(false);
71+
expect(migrateManagedWorktreeCanonicalWorkspaces).not.toHaveBeenCalled();
72+
expect(sweepOrphanSessionStoreTemps).toHaveBeenCalledWith({ storePath });
73+
});
74+
3175
it("re-registers durable lineage children before configured-only runtime reads", async () => {
3276
const root = fs.realpathSync.native(tempDirs.make("openclaw-startup-registry-recovery-"));
3377
const stateDir = path.join(root, "state");

‎src/config/sessions/startup-migration.ts‎

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import fs from "node:fs";
12
import { resolveAgentSessionDirs } from "../../agents/session-dirs.js";
23
import { migrateOrphanedSessionKeys } from "../../infra/state-migrations.session-store.js";
34
import type { PreparedLegacySessionSurfaces } from "../../plugins/legacy-session-surfaces.types.js";
5+
import { listOpenClawRegisteredAgentDatabases } from "../../state/openclaw-agent-db-registry.js";
46
import {
57
closeOpenClawAgentDatabaseByPath,
68
isOpenClawAgentDatabaseOpen,
@@ -9,7 +11,10 @@ import {
911
import { resolveStateDir } from "../paths.js";
1012
import type { OpenClawConfig } from "../types.openclaw.js";
1113
import { migrateLegacyMainSessionKeys } from "./legacy-main-session-migration.js";
12-
import { setCanonicalSqliteSessionMainKey } from "./session-canonical-key.js";
14+
import {
15+
isCanonicalSqliteSessionMainKeyCurrent,
16+
setCanonicalSqliteSessionMainKey,
17+
} from "./session-canonical-key.js";
1318
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
1419
import { sweepOrphanSessionStoreTemps } from "./store-temp-cleanup.js";
1520
import { resolveAllAgentSessionStoreTargetsSync } from "./targets.js";
@@ -22,6 +27,12 @@ type PrepareLegacySessionSurfaces = (params: {
2227
env?: NodeJS.ProcessEnv;
2328
}) => PreparedLegacySessionSurfaces;
2429

30+
type SessionSqliteDatabaseExists = (params: {
31+
agentId: string;
32+
env?: NodeJS.ProcessEnv;
33+
path?: string;
34+
}) => boolean;
35+
2536
/** Runs best-effort session migration and orphan-temp cleanup before runtime reads. */
2637
export async function runSessionStartupMigration(params: {
2738
cfg: OpenClawConfig;
@@ -33,6 +44,7 @@ export async function runSessionStartupMigration(params: {
3344
prepareLegacySessionSurfaces?: PrepareLegacySessionSurfaces;
3445
migrateManagedWorktreeCanonicalWorkspaces?: typeof migrateManagedWorktreeCanonicalWorkspaces;
3546
resolveAllAgentSessionStoreTargetsSync?: typeof resolveAllAgentSessionStoreTargetsSync;
47+
sessionSqliteDatabaseExists?: SessionSqliteDatabaseExists;
3648
sweepOrphanSessionStoreTemps?: typeof sweepOrphanSessionStoreTemps;
3749
};
3850
}): Promise<boolean> {
@@ -64,7 +76,11 @@ export async function runSessionStartupMigration(params: {
6476
const result = await migrate({
6577
cfg: params.cfg,
6678
env,
67-
legacySessionSurfaces: prepareSurfaces({ config: params.cfg, env }),
79+
legacySessionSurfaces: () =>
80+
prepareSurfaces({
81+
config: params.cfg,
82+
env,
83+
}),
6884
});
6985
if (result.changes.length > 0) {
7086
params.log.info(
@@ -109,17 +125,45 @@ export async function runSessionStartupMigration(params: {
109125
}
110126

111127
const sweepTemps = params.deps?.sweepOrphanSessionStoreTemps ?? sweepOrphanSessionStoreTemps;
128+
const databaseExists =
129+
params.deps?.sessionSqliteDatabaseExists ??
130+
((input: Parameters<SessionSqliteDatabaseExists>[0]) =>
131+
input.path !== undefined && fs.existsSync(input.path));
112132
try {
113133
let removedFiles = 0;
114134
let migratedWorktreeSessions = 0;
135+
const registeredDatabases = new Set(
136+
listOpenClawRegisteredAgentDatabases({ env }).map(
137+
(entry) => `${entry.agentId}\0${entry.path}`,
138+
),
139+
);
115140
for (const target of targets) {
116141
const path = resolveSqliteTargetFromSessionStorePath(target.storePath, {
117142
agentId: target.agentId,
118143
env: params.env,
119144
}).path;
145+
if (
146+
!databaseExists({
147+
agentId: target.agentId,
148+
...(params.env ? { env: params.env } : {}),
149+
path,
150+
})
151+
) {
152+
removedFiles += await sweepTemps({ storePath: target.storePath });
153+
continue;
154+
}
120155
const alreadyOpen = isOpenClawAgentDatabaseOpen(path);
121-
const database = openOpenClawAgentDatabase({ agentId: target.agentId, path });
122-
setCanonicalSqliteSessionMainKey(database, params.cfg.session?.mainKey);
156+
const isRegistered = registeredDatabases.has(`${target.agentId}\0${path}`);
157+
if (
158+
!isRegistered ||
159+
!isCanonicalSqliteSessionMainKeyCurrent(
160+
{ agentId: target.agentId, env, path },
161+
params.cfg.session?.mainKey,
162+
)
163+
) {
164+
const database = openOpenClawAgentDatabase({ agentId: target.agentId, env, path });
165+
setCanonicalSqliteSessionMainKey(database, params.cfg.session?.mainKey);
166+
}
123167
const migrateWorktreeSessions =
124168
params.deps?.migrateManagedWorktreeCanonicalWorkspaces ??
125169
migrateManagedWorktreeCanonicalWorkspaces;
@@ -135,7 +179,7 @@ export async function runSessionStartupMigration(params: {
135179
`session: managed-worktree workspace migration failed for ${target.agentId}; continuing: ${String(error)}`,
136180
);
137181
}
138-
if (!alreadyOpen) {
182+
if (!alreadyOpen && isOpenClawAgentDatabaseOpen(path)) {
139183
closeOpenClawAgentDatabaseByPath(path);
140184
}
141185
removedFiles += await sweepTemps({ storePath: target.storePath });

‎src/config/sessions/startup-migration.worktree-workspace.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ it("backfills a nested requested workspace once instead of using the agent defau
3232
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
3333
const storePath = path.join(stateDir, "agents", "main", "sessions", "sessions.json");
3434
const sessionKey = "agent:main:dashboard:legacy-worktree";
35+
const ordinarySessionKey = "agent:main:dashboard:ordinary";
3536
const cfg: OpenClawConfig = {
3637
agents: { list: [{ id: "main", default: true, workspace: agentWorkspace }] },
3738
session: { store: storePath },
@@ -58,6 +59,16 @@ it("backfills a nested requested workspace once instead of using the agent defau
5859
worktree: { id: "legacy", branch: "openclaw/legacy", repoRoot },
5960
},
6061
);
62+
await replaceSessionEntry(
63+
{ agentId: "main", env, sessionKey: ordinarySessionKey, storePath },
64+
{ sessionId: "ordinary-session", updatedAt: 20 },
65+
);
66+
const ordinaryBefore = loadSessionEntry({
67+
agentId: "main",
68+
env,
69+
sessionKey: ordinarySessionKey,
70+
storePath,
71+
});
6172

6273
const runMigration = async () =>
6374
await migrateManagedWorktreeCanonicalWorkspaces({
@@ -74,4 +85,7 @@ it("backfills a nested requested workspace once instead of using the agent defau
7485

7586
await runMigration();
7687
expect(loadSessionEntry({ agentId: "main", env, sessionKey, storePath })).toEqual(first);
88+
expect(
89+
loadSessionEntry({ agentId: "main", env, sessionKey: ordinarySessionKey, storePath }),
90+
).toEqual(ordinaryBefore);
7791
});

‎src/config/sessions/worktree-workspace-migration.ts‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
import path from "node:path";
2+
import { sql } from "kysely";
23
import { resolveAgentWorkspaceDir } from "../../agents/agent-scope.js";
34
import { listRegistryWorktreesForMigration } from "../../agents/worktrees/registry.js";
5+
import { executeSqliteQuerySync } from "../../infra/kysely-sync.js";
46
import { resolveProjectRegistry } from "../../projects/project-registry.js";
7+
import { withOpenClawAgentDatabaseReadOnly } from "../../state/openclaw-agent-db-readonly.js";
58
import type { OpenClawConfig } from "../types.openclaw.js";
6-
import { listSessionEntriesReadOnly, patchSessionEntryCore } from "./session-accessor.js";
9+
import { patchSessionEntryCore } from "./session-accessor.js";
10+
import { parseReadableSqliteSessionEntryRow } from "./session-accessor.sqlite-entry-store.js";
11+
import {
12+
getSessionKysely,
13+
resolveSqliteScope,
14+
toDatabaseOptions,
15+
} from "./session-accessor.sqlite-scope.js";
716
import type { SessionEntry } from "./types.js";
817

918
function isInside(root: string, target: string): boolean {
@@ -48,6 +57,40 @@ function resolveLegacyCanonicalWorkspace(params: {
4857
return agentWorkspace && agentWorkspace === recordedRepoRoot ? agentWorkspace : undefined;
4958
}
5059

60+
function listLegacyWorktreeSessionEntries(params: {
61+
agentId: string;
62+
env: NodeJS.ProcessEnv;
63+
storePath: string;
64+
}): Array<{ entry: SessionEntry; sessionKey: string }> {
65+
const resolved = resolveSqliteScope({ ...params, sessionKey: "" });
66+
const result = withOpenClawAgentDatabaseReadOnly((database) => {
67+
const db = getSessionKysely(database.db);
68+
const rows = executeSqliteQuerySync(
69+
database.db,
70+
db
71+
.selectFrom("session_nodes")
72+
.selectAll()
73+
.where(
74+
/* kysely-allow-raw: Startup migration targets the retired JSON shape without materializing every session. */
75+
sql<boolean>`session_nodes.entry_valid != 1 OR (
76+
json_valid(session_nodes.entry_json)
77+
AND json_type(session_nodes.entry_json, '$.worktree') = 'object'
78+
AND (
79+
json_type(session_nodes.entry_json, '$.worktree.canonicalWorkspaceDir') IS NULL
80+
OR json_extract(session_nodes.entry_json, '$.worktree.canonicalWorkspaceDir') = ''
81+
)
82+
)`,
83+
)
84+
.orderBy("session_key", "asc"),
85+
).rows;
86+
return rows.flatMap((row) => {
87+
const entry = parseReadableSqliteSessionEntryRow(database, row);
88+
return entry ? [{ entry, sessionKey: row.session_key }] : [];
89+
});
90+
}, toDatabaseOptions(resolved));
91+
return result.found ? result.value : [];
92+
}
93+
5194
export async function migrateManagedWorktreeCanonicalWorkspaces(params: {
5295
agentId: string;
5396
cfg: OpenClawConfig;
@@ -57,11 +100,10 @@ export async function migrateManagedWorktreeCanonicalWorkspaces(params: {
57100
const env = params.env ?? process.env;
58101
const worktrees = listRegistryWorktreesForMigration(env);
59102
let migrated = 0;
60-
for (const { entry, sessionKey } of listSessionEntriesReadOnly({
103+
for (const { entry, sessionKey } of listLegacyWorktreeSessionEntries({
61104
agentId: params.agentId,
62105
env,
63106
storePath: params.storePath,
64-
readConsistency: "latest",
65107
})) {
66108
const canonicalWorkspaceDir = resolveLegacyCanonicalWorkspace({
67109
agentId: params.agentId,

‎src/gateway/server-startup-session-migration.test-support.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,9 @@ function makeDeps(
5656
.mockResolvedValue(0),
5757
runDoctorSessionSqlite,
5858
reconcileSessionTranscriptIndexes,
59-
sessionSqliteDatabaseExists: vi.fn<SessionSqliteDatabaseExists>().mockReturnValue(true),
59+
sessionSqliteDatabaseExists: vi
60+
.fn<SessionSqliteDatabaseExists>()
61+
.mockImplementation((params) => params.path === undefined),
6062
};
6163
}
6264

‎src/gateway/server-startup-session-migration.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ type SessionSqliteStartupFailureReportWriter = (
3333
type SessionSqliteDatabaseExists = (params: {
3434
agentId: string;
3535
env?: NodeJS.ProcessEnv;
36+
path?: string;
3637
}) => boolean;
3738

3839
type SessionMigrationDeps = Parameters<typeof runSessionStartupMigration>[0]["deps"] & {

‎src/infra/state-migrations.orphan-keys.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,21 @@ describe("migrateOrphanedSessionKeys", () => {
727727
});
728728
});
729729

730+
it("does not prepare channel migration surfaces without a legacy store", async () => {
731+
await withStateFixture(async ({ stateDir }) => {
732+
const prepareLegacySessionSurfaces = vi.fn(() => EMPTY_LEGACY_SESSION_SURFACES);
733+
734+
const result = await migrateOrphanedSessionKeys({
735+
cfg: OPS_WORK_CONFIG,
736+
env: { OPENCLAW_STATE_DIR: stateDir },
737+
legacySessionSurfaces: prepareLegacySessionSurfaces,
738+
});
739+
740+
expect(result).toEqual({ changes: [], warnings: [] });
741+
expect(prepareLegacySessionSurfaces).not.toHaveBeenCalled();
742+
});
743+
});
744+
730745
it("is idempotent — running twice produces same result", async () => {
731746
await withStateFixture(async ({ stateDir }) => {
732747
const storePath = opsSessionStorePath(stateDir);

0 commit comments

Comments
 (0)