Skip to content

Commit c162314

Browse files
committed
perf(gateway): skip inactive session recovery stores
1 parent 8b994fc commit c162314

8 files changed

Lines changed: 140 additions & 3 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ Docs: https://docs.openclaw.ai
5858

5959
### Fixes
6060

61+
- **Gateway multi-agent startup:** skip session restart-recovery writer scans for agent databases without running sessions, avoiding per-agent startup delay from unrelated auth or model-catalog state while preserving recovery and corruption handling for durable stores.
6162
- **Control UI archived session deletion:** send archive-gated delete requests from Sessions-page row and mixed-selection actions so write-scoped operators can remove archived threads while active-session deletion remains admin-only. Thanks @shakkernerd.
6263
- **Control UI command recovery:** keep delayed detached and immediate command failures scoped to their submitting session, preserving failed drafts and attachments for that pane without overwriting the active session. Fixes #116846. Thanks @shakkernerd.
6364
- **Microsoft Teams message-tool replies:** keep automatic live previews from duplicating a message already delivered to the current Teams conversation, while preserving distinct follow-up text and cross-conversation sends. Fixes #116397. (#116398) Thanks @a-tokyo.

‎src/agents/main-session-restart-recovery-shared.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import {
44
type InternalSessionEntry as SessionEntry,
55
resolveAllAgentSessionStoreTargetsSync,
66
} from "../config/sessions.js";
7-
import type { SessionTranscriptTurnExpectedState } from "../config/sessions/session-accessor.js";
7+
import {
8+
hasSessionEntriesByStatusReadOnly,
9+
type SessionTranscriptTurnExpectedState,
10+
} from "../config/sessions/session-accessor.js";
811
import type { OpenClawConfig } from "../config/types.openclaw.js";
912
import { createSubsystemLogger } from "../logging/subsystem.js";
1013
import { isMainRestartRecoveryCandidate } from "./main-session-recovery-state.js";
@@ -90,14 +93,18 @@ export async function resolveRestartRecoveryStorePaths(params: {
9093
}): Promise<string[]> {
9194
const storePaths = new Set<string>();
9295
const stateDir = params.stateDir ?? resolveStateDir(process.env);
96+
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
9397
for (const sessionsDir of await resolveAgentSessionDirs(stateDir)) {
9498
storePaths.add(path.join(sessionsDir, "sessions.json"));
9599
}
96100
if (params.cfg) {
97-
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
98101
for (const target of resolveAllAgentSessionStoreTargetsSync(params.cfg, { env })) {
99102
storePaths.add(path.resolve(target.storePath));
100103
}
101104
}
102-
return [...storePaths].toSorted((a, b) => a.localeCompare(b));
105+
// Agent databases also hold auth and model-catalog state. Enter the writer
106+
// lane only when the session owner proves that a running row may need repair.
107+
return [...storePaths]
108+
.filter((storePath) => hasSessionEntriesByStatusReadOnly({ env, storePath }, ["running"]))
109+
.toSorted((a, b) => a.localeCompare(b));
103110
}

‎src/agents/main-session-restart-recovery.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ import {
4444
isSessionWorkAdmissionActive,
4545
runExclusiveSessionLifecycleMutation,
4646
} from "../sessions/session-lifecycle-admission.js";
47+
import {
48+
closeOpenClawAgentDatabasesForTest,
49+
openOpenClawAgentDatabase,
50+
} from "../state/openclaw-agent-db.js";
4751
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
4852
import { createOutboundTestPlugin, createTestRegistry } from "../test-utils/channel-plugins.js";
4953
import { createDeferred } from "../test-utils/deferred.js";
@@ -2006,6 +2010,60 @@ describe("main-session-restart-recovery", () => {
20062010
expect(store["agent:main:already-marked"]?.abortedLastRun).toBe(false);
20072011
});
20082012

2013+
it("does not create empty agent databases while scanning startup recovery", async () => {
2014+
const agentIds = Array.from({ length: 12 }, (_, index) => `agent-${index + 1}`);
2015+
const databasePaths = await Promise.all(
2016+
agentIds.map(async (agentId) => {
2017+
await makeSessionsDir(agentId);
2018+
return path.join(tmpDir, "agents", agentId, "agent", "openclaw-agent.sqlite");
2019+
}),
2020+
);
2021+
2022+
await expect(markStartupOrphanedMainSessionsForRecovery({ stateDir: tmpDir })).resolves.toEqual(
2023+
{ marked: 0, skipped: 0 },
2024+
);
2025+
for (const databasePath of databasePaths) {
2026+
await expect(fs.stat(databasePath)).rejects.toMatchObject({ code: "ENOENT" });
2027+
}
2028+
});
2029+
2030+
it("does not enter the writer lane for agent databases without running sessions", async () => {
2031+
const agentIds = Array.from({ length: 12 }, (_, index) => `agent-${index + 1}`);
2032+
const env = { ...process.env, OPENCLAW_STATE_DIR: tmpDir };
2033+
for (const agentId of agentIds) {
2034+
openOpenClawAgentDatabase({
2035+
agentId,
2036+
env,
2037+
path: path.join(tmpDir, "agents", agentId, "agent", "openclaw-agent.sqlite"),
2038+
});
2039+
}
2040+
closeOpenClawAgentDatabasesForTest();
2041+
const applySessionEntryReplacements = vi.spyOn(
2042+
sessionAccessor,
2043+
"applySessionEntryReplacements",
2044+
);
2045+
2046+
try {
2047+
await expect(
2048+
markStartupOrphanedMainSessionsForRecovery({ stateDir: tmpDir }),
2049+
).resolves.toEqual({ marked: 0, skipped: 0 });
2050+
expect(applySessionEntryReplacements).not.toHaveBeenCalled();
2051+
} finally {
2052+
applySessionEntryReplacements.mockRestore();
2053+
}
2054+
});
2055+
2056+
it("keeps corrupt existing agent databases on the startup recovery error path", async () => {
2057+
await makeSessionsDir();
2058+
const databasePath = path.join(tmpDir, "agents", "main", "agent", "openclaw-agent.sqlite");
2059+
await fs.mkdir(path.dirname(databasePath), { recursive: true });
2060+
await fs.writeFile(databasePath, "not a sqlite database");
2061+
2062+
await expect(
2063+
markStartupOrphanedMainSessionsForRecovery({ stateDir: tmpDir }),
2064+
).rejects.toThrow();
2065+
});
2066+
20092067
it.each([
20102068
["current owner before delayed stale registration", "current-first"],
20112069
["stale owner before current registration", "stale-first"],

‎src/config/sessions/session-accessor.entry.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { clearPluginOwnedSessionState } from "./plugin-host-cleanup.js";
1212
import {
1313
countSqliteSessionEntryRowsReadOnly as countSessionEntryRowsReadOnly,
1414
copySqliteSessionOwnedStateForCanonicalRepair as copySessionOwnedStateForCanonicalRepair,
15+
hasSqliteSessionEntriesByStatusReadOnly as hasSessionEntriesByStatusReadOnly,
1516
listSqliteSessionGenerationIdsForCanonicalRepair as listSessionGenerationIdsForCanonicalRepair,
1617
listSqliteSessionChildEntriesReadOnly as listSessionChildEntriesReadOnly,
1718
listSqliteSessionEntries,
@@ -61,6 +62,7 @@ export { clearPluginOwnedSessionState };
6162
export {
6263
countSessionEntryRowsReadOnly,
6364
copySessionOwnedStateForCanonicalRepair,
65+
hasSessionEntriesByStatusReadOnly,
6466
listSessionGenerationIdsForCanonicalRepair,
6567
listSessionChildEntriesReadOnly,
6668
listSessionEntriesReadOnly,

‎src/config/sessions/session-accessor.readonly.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@ import { cleanupTempDirs, makeTempDir } from "../../../test/helpers/temp-dir.js"
44
import {
55
closeOpenClawAgentDatabasesForTest,
66
isOpenClawAgentDatabaseOpen,
7+
openOpenClawAgentDatabase,
78
resolveOpenClawAgentSqlitePath,
89
} from "../../state/openclaw-agent-db.js";
910
import {
1011
closeOpenClawStateDatabaseForTest,
1112
openOpenClawStateDatabase,
1213
} from "../../state/openclaw-state-db.js";
1314
import {
15+
hasSessionEntriesByStatusReadOnly,
1416
listSessionEntries,
1517
listSessionEntriesReadOnly,
1618
resolveTranscriptSessionKeyBySessionId,
@@ -68,6 +70,42 @@ describe("session accessor readonly listing", () => {
6870
expect(countRegisteredAgentDatabases(env)).toBe(0);
6971
});
7072

73+
it("probes lifecycle status without creating or registering a missing database", () => {
74+
const stateDir = makeTempDir(tempDirs, "openclaw-session-readonly-status-missing-");
75+
const env = { OPENCLAW_STATE_DIR: stateDir };
76+
const agentId = "worker-1";
77+
const databasePath = resolveOpenClawAgentSqlitePath({ agentId, env });
78+
clearRegisteredAgentDatabases(env);
79+
80+
expect(hasSessionEntriesByStatusReadOnly({ agentId, env }, ["running"])).toBe(false);
81+
expect(fs.existsSync(databasePath)).toBe(false);
82+
expect(countRegisteredAgentDatabases(env)).toBe(0);
83+
});
84+
85+
it("distinguishes non-session agent state from a running session row", async () => {
86+
const stateDir = makeTempDir(tempDirs, "openclaw-session-readonly-status-existing-");
87+
const env = { OPENCLAW_STATE_DIR: stateDir };
88+
const agentId = "worker-1";
89+
const databasePath = resolveOpenClawAgentSqlitePath({ agentId, env });
90+
openOpenClawAgentDatabase({ agentId, env, path: databasePath });
91+
closeOpenClawAgentDatabasesForTest();
92+
clearRegisteredAgentDatabases(env);
93+
94+
expect(hasSessionEntriesByStatusReadOnly({ agentId, env }, ["running"])).toBe(false);
95+
expect(countRegisteredAgentDatabases(env)).toBe(0);
96+
97+
await upsertSessionEntry(
98+
{ agentId, env, sessionKey: "agent:worker-1:main" },
99+
{ sessionId: "session-1", status: "running", updatedAt: 10 },
100+
);
101+
closeOpenClawAgentDatabasesForTest();
102+
clearRegisteredAgentDatabases(env);
103+
104+
expect(hasSessionEntriesByStatusReadOnly({ agentId, env }, ["running"])).toBe(true);
105+
expect(hasSessionEntriesByStatusReadOnly({ agentId, env }, ["done"])).toBe(false);
106+
expect(countRegisteredAgentDatabases(env)).toBe(0);
107+
});
108+
71109
it("resolves a missing session identity without creating or registering a database", () => {
72110
const stateDir = makeTempDir(tempDirs, "openclaw-session-readonly-missing-identity-");
73111
const env = { OPENCLAW_STATE_DIR: stateDir };

‎src/config/sessions/session-accessor.sqlite-entry.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,35 @@ export function countSqliteSessionEntryRowsReadOnly(scope: SessionEntryListScope
297297
return result.found ? result.value : 0;
298298
}
299299

300+
/**
301+
* Proves whether a durable store has a row in one of the requested lifecycle states.
302+
* Unknown existing schemas stay eligible so the writable owner can surface or repair them.
303+
*/
304+
export function hasSqliteSessionEntriesByStatusReadOnly(
305+
scope: Partial<Omit<SessionAccessScope, "sessionKey">>,
306+
statuses: readonly SessionEntryStatus[],
307+
): boolean {
308+
const selectedStatuses = [...new Set(statuses)];
309+
if (selectedStatuses.length === 0) {
310+
return false;
311+
}
312+
const resolved = resolveSqliteScope({ ...scope, sessionKey: "" });
313+
const result = withOpenClawAgentDatabaseReadOnly((database) => {
314+
const db = getSessionKysely(database.db);
315+
return Boolean(
316+
executeSqliteQueryTakeFirstSync(
317+
database.db,
318+
db
319+
.selectFrom("session_nodes")
320+
.select("session_key")
321+
.where("status", "in", selectedStatuses)
322+
.limit(1),
323+
),
324+
);
325+
}, toDatabaseOptions(resolved));
326+
return result.found ? result.value : result.reason !== "database-missing";
327+
}
328+
300329
function listSqliteSessionEntriesFromDatabase(
301330
database: Pick<OpenClawAgentDatabase, "agentId" | "db" | "path">,
302331
resolved: ResolvedSqliteScope,

‎src/config/sessions/session-accessor.sqlite.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Stable SQLite accessor surface. Domain owners live in the focused modules below.
22
export {
33
countSqliteSessionEntryRowsReadOnly,
4+
hasSqliteSessionEntriesByStatusReadOnly,
45
listSqliteSessionEntries,
56
listSqliteSessionChildEntriesReadOnly,
67
listSqliteSessionEntriesReadOnly,

‎src/config/sessions/session-accessor.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ export type {
121121
export {
122122
countSessionEntryRowsReadOnly,
123123
copySessionOwnedStateForCanonicalRepair,
124+
hasSessionEntriesByStatusReadOnly,
124125
listSessionGenerationIdsForCanonicalRepair,
125126
clearPluginOwnedSessionState,
126127
listSessionChildEntriesReadOnly,

0 commit comments

Comments
 (0)