Skip to content

Commit 9b123e2

Browse files
roboclaw-botVACInc
andauthored
fix(sessions): refresh planner stats after bulk cleanup (#133925)
* fix(sessions): refresh planner stats after bulk cleanup Worked on by: - @VACInc Co-authored-by: VACInc <[email protected]> * fix(sessions): cover all bulk deletion paths Worked on by: - @VACInc Co-authored-by: VACInc <[email protected]> * fix(sessions): limit planner refresh to bulk cleanup Worked on by: - @VACInc Co-authored-by: VACInc <[email protected]> --------- Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: VACInc <[email protected]>
1 parent 963f3c8 commit 9b123e2

8 files changed

Lines changed: 222 additions & 14 deletions

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

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,24 +42,29 @@ type PreparedSessionWrite<T> = {
4242
export async function runPreparedSqliteSessionWrite<T>(
4343
scope: ResolvedSqliteReadScope,
4444
prepare: () => Promise<PreparedSessionWrite<T>>,
45-
): Promise<T> {
45+
): Promise<{ deletedEntries: number; result: T }> {
4646
const prepared = await runExclusiveSqliteSessionWrite(scope, async () => {
4747
const write = await prepare();
4848
return write.deletedEntries.length || write.beforeCommit
4949
? { write }
5050
: { result: await write.commit() };
5151
});
5252
if (!prepared.write) {
53-
return prepared.result;
53+
return { deletedEntries: 0, result: prepared.result };
5454
}
5555
const write = prepared.write;
56-
return await withSqliteSessionDeletions(scope, write.deletedEntries, async (assertCurrent) => {
57-
await write.beforeCommit?.();
58-
return await runExclusiveSqliteSessionWrite(scope, async () => {
59-
assertCurrent();
60-
return await write.commit();
61-
});
62-
});
56+
const result = await withSqliteSessionDeletions(
57+
scope,
58+
write.deletedEntries,
59+
async (assertCurrent) => {
60+
await write.beforeCommit?.();
61+
return await runExclusiveSqliteSessionWrite(scope, async () => {
62+
assertCurrent();
63+
return await write.commit();
64+
});
65+
},
66+
);
67+
return { deletedEntries: write.deletedEntries.length, result };
6368
}
6469

6570
/** Prepare owner leases before entering a physical writer or changing any transcript state. */

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import {
5353
readReferencedSessionIdsAfterTargetMutation,
5454
shouldRemoveSessionEntry,
5555
} from "./session-accessor.sqlite-lifecycle-state.js";
56+
import { refreshSqliteSessionPlannerStatisticsBestEffort } from "./session-accessor.sqlite-maintenance.js";
5657
import { deleteSessionDeliveryArtifacts } from "./session-accessor.sqlite-node-artifacts.js";
5758
import { loadTranscriptEventsFromDatabase } from "./session-accessor.sqlite-read.js";
5859
import {
@@ -176,6 +177,13 @@ export async function cleanupSessionLifecycleArtifactsCore(
176177
});
177178
},
178179
);
180+
// The SQL commit survives a later archive-publication failure, so refresh
181+
// planner statistics before crossing that separate artifact boundary.
182+
const deletedEntries = Math.max(
183+
committed.removedEntries,
184+
new Set(cleanupPlan.deletePlans.map((plan) => plan.sessionId)).size,
185+
);
186+
await refreshSqliteSessionPlannerStatisticsBestEffort(resolved, deletedEntries);
179187
const archivedTranscripts = await publishSessionStateArchives(
180188
resolved,
181189
committed.archivedTranscripts,

‎src/config/sessions/session-accessor.sqlite-maintenance-writer.test.ts‎

Lines changed: 101 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
import path from "node:path";
22
import { afterEach, expect, it, vi } from "vitest";
33
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
4-
import { closeOpenClawAgentDatabasesForTest } from "../../state/openclaw-agent-db.js";
4+
import {
5+
closeOpenClawAgentDatabasesForTest,
6+
openOpenClawAgentDatabase,
7+
} from "../../state/openclaw-agent-db.js";
58
import {
69
applySessionEntryLifecycleMutation,
10+
cleanupSessionLifecycleArtifactsCore,
711
loadSessionEntry,
812
replaceSessionEntrySync,
913
replaceTranscriptEventsSync,
1014
} from "./session-accessor.js";
15+
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
1116

1217
const archiveMaterializationHook = vi.hoisted(() => ({
1318
beforeMaterialize: undefined as (() => void) | undefined,
@@ -33,6 +38,26 @@ afterEach(() => {
3338
closeOpenClawAgentDatabasesForTest();
3439
});
3540

41+
function createPlannerStore(entryCount: number) {
42+
const tempDir = tempDirs.make("openclaw-session-maintenance-planner-");
43+
const storePath = path.join(tempDir, "agents", "main", "sessions", "sessions.json");
44+
for (let index = 0; index < entryCount; index += 1) {
45+
replaceSessionEntrySync(
46+
{ sessionKey: `agent:main:planner-${index}`, storePath },
47+
{ sessionId: `planner-${index}`, updatedAt: index + 1 },
48+
);
49+
}
50+
const databasePath = resolveSqliteTargetFromSessionStorePath(storePath, {
51+
agentId: "main",
52+
}).path;
53+
if (!databasePath) {
54+
throw new Error("expected planner maintenance database path");
55+
}
56+
const database = openOpenClawAgentDatabase({ agentId: "main", path: databasePath });
57+
database.db.exec("ANALYZE; PRAGMA analysis_limit = 37;");
58+
return { database, storePath };
59+
}
60+
3661
it("releases the store writer before maintenance archive sizing completes", async () => {
3762
const tempDir = tempDirs.make("openclaw-session-maintenance-writer-");
3863
const storePath = path.join(tempDir, "agents", "main", "sessions", "sessions.json");
@@ -90,3 +115,78 @@ it("releases the store writer before maintenance archive sizing completes", asyn
90115
});
91116
expect(writerCompletedBeforeMaterialization).toBe(true);
92117
});
118+
119+
it.each([
120+
{
121+
expected: { afterCount: 1, capped: 65 },
122+
name: "maintenance pruning",
123+
mutate: async (storePath: string) =>
124+
await applySessionEntryLifecycleMutation({
125+
storePath,
126+
maintenanceOverride: {
127+
maxEntries: 1,
128+
mode: "enforce",
129+
pruneAfterMs: Number.MAX_SAFE_INTEGER,
130+
},
131+
}),
132+
},
133+
{
134+
expected: { afterCount: 1, removedEntries: 65 },
135+
name: "explicit lifecycle cleanup",
136+
mutate: async (storePath: string) =>
137+
await applySessionEntryLifecycleMutation({
138+
storePath,
139+
removals: Array.from({ length: 65 }, (_, index) => ({
140+
sessionKey: `agent:main:planner-${index + 1}`,
141+
})),
142+
skipMaintenance: true,
143+
}),
144+
},
145+
{
146+
expected: { archivedTranscriptArtifacts: 0, removedEntries: 65 },
147+
name: "lifecycle artifact cleanup",
148+
mutate: async (storePath: string) =>
149+
await cleanupSessionLifecycleArtifactsCore({
150+
storePath,
151+
sessionKeySegmentPrefix: "planner-",
152+
transcriptContentMarker: "planner-marker",
153+
orphanTranscriptMinAgeMs: 1,
154+
nowMs: 66,
155+
}),
156+
},
157+
])("refreshes planner statistics after bulk $name", async ({ expected, mutate }) => {
158+
const { database, storePath } = createPlannerStore(66);
159+
expect(
160+
database.db
161+
.prepare("SELECT stat FROM sqlite_stat1 WHERE idx = ?")
162+
.get("idx_agent_session_nodes_updated_at"),
163+
).toEqual({ stat: expect.stringMatching(/^66\b/u) });
164+
165+
await expect(mutate(storePath)).resolves.toMatchObject(expected);
166+
167+
expect(
168+
database.db
169+
.prepare("SELECT stat FROM sqlite_stat1 WHERE idx = ?")
170+
.get("idx_agent_session_nodes_updated_at"),
171+
).toEqual({ stat: expect.stringMatching(/^1\b/u) });
172+
expect(database.db.prepare("PRAGMA analysis_limit").get()).toEqual({ analysis_limit: 37 });
173+
});
174+
175+
it("does not refresh planner statistics after one routine session deletion", async () => {
176+
const { database, storePath } = createPlannerStore(66);
177+
178+
await expect(
179+
applySessionEntryLifecycleMutation({
180+
storePath,
181+
removals: [{ sessionKey: "agent:main:planner-65" }],
182+
skipMaintenance: true,
183+
}),
184+
).resolves.toMatchObject({ afterCount: 65, removedEntries: 1 });
185+
186+
expect(
187+
database.db
188+
.prepare("SELECT stat FROM sqlite_stat1 WHERE idx = ?")
189+
.get("idx_agent_session_nodes_updated_at"),
190+
).toEqual({ stat: expect.stringMatching(/^66\b/u) });
191+
expect(database.db.prepare("PRAGMA analysis_limit").get()).toEqual({ analysis_limit: 37 });
192+
});

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

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
22
import { sql } from "kysely";
33
import { executeSqliteQuerySync } from "../../infra/kysely-sync.js";
4+
import { runWithSqliteBusyTimeout } from "../../infra/sqlite-busy-timeout.js";
45
import { getChildLogger } from "../../logging/logger.js";
56
import { withOpenClawAgentDatabaseReadOnly } from "../../state/openclaw-agent-db-readonly.js";
6-
import type { OpenClawAgentDatabase } from "../../state/openclaw-agent-db.js";
7+
import {
8+
openOpenClawAgentDatabase,
9+
resolveOpenClawAgentSqlitePath,
10+
type OpenClawAgentDatabase,
11+
} from "../../state/openclaw-agent-db.js";
712
import { publishSessionStateArchives } from "./session-accessor.sqlite-archive-store.js";
813
import {
914
materializeSessionStateDeletePlans,
@@ -65,6 +70,59 @@ import type { SessionEntry } from "./types.js";
6570
const MAX_SESSION_MAINTENANCE_BATCH_ENTRIES = 64;
6671
const MAX_SESSION_MAINTENANCE_BATCH_ARCHIVE_BYTES = 64 * 1024 * 1024;
6772
const SESSION_TRANSCRIPT_BYTE_QUERY_BATCH = MAX_SESSION_MAINTENANCE_BATCH_ENTRIES;
73+
// One full maintenance batch is the bulk-deletion boundary. Smaller routine
74+
// cleanups must not pay the measured synchronous full-database analysis cost.
75+
const SESSION_PLANNER_ANALYSIS_MIN_DELETED_ENTRIES = MAX_SESSION_MAINTENANCE_BATCH_ENTRIES;
76+
const SESSION_PLANNER_ANALYSIS_LIMIT = 1_000;
77+
const plannerMaintenanceByStore = new Map<string, Promise<void>>();
78+
79+
/** Coalesce bounded planner-statistics refreshes behind the per-store writer lane. */
80+
export async function refreshSqliteSessionPlannerStatisticsBestEffort(
81+
scope: Pick<ResolvedSqliteReadScope, "agentId" | "env" | "path">,
82+
deletedEntries: number,
83+
): Promise<void> {
84+
if (deletedEntries < SESSION_PLANNER_ANALYSIS_MIN_DELETED_ENTRIES) {
85+
return;
86+
}
87+
const storePath = resolveOpenClawAgentSqlitePath(toDatabaseOptions(scope));
88+
const active = plannerMaintenanceByStore.get(storePath);
89+
if (active) {
90+
await active;
91+
return;
92+
}
93+
const completion = runExclusiveSqliteSessionWrite(scope, async () => {
94+
const database = openOpenClawAgentDatabase(toDatabaseOptions(scope));
95+
// Planner maintenance must not inherit the normal 5s writer wait: a competing
96+
// process skips this best-effort pass instead of blocking the Gateway event loop.
97+
runWithSqliteBusyTimeout(database.db, 0, () => {
98+
// SAFETY: SQLite returns this fixed numeric column for PRAGMA analysis_limit.
99+
const row = database.db.prepare("PRAGMA analysis_limit").get() as
100+
| { analysis_limit?: unknown }
101+
| undefined;
102+
const previousLimit = Number(row?.analysis_limit ?? 0);
103+
try {
104+
// Direct analysis is required after known deletions. SQLite 3.44 is still
105+
// supported and its optimize heuristic only reacts to table growth.
106+
database.db.exec(
107+
`PRAGMA analysis_limit = ${SESSION_PLANNER_ANALYSIS_LIMIT}; ANALYZE main;`,
108+
);
109+
} finally {
110+
database.db.exec(`PRAGMA analysis_limit = ${previousLimit};`);
111+
}
112+
});
113+
})
114+
.catch((error: unknown) => {
115+
getChildLogger({ subsystem: "session-sqlite" }).warn(
116+
"SQLite session planner-statistics refresh failed",
117+
{ agentId: scope.agentId, error, path: storePath },
118+
);
119+
})
120+
.finally(() => {
121+
plannerMaintenanceByStore.delete(storePath);
122+
});
123+
plannerMaintenanceByStore.set(storePath, completion);
124+
await completion;
125+
}
68126

69127
type SessionMaintenanceBatch = {
70128
archiveBytes: number;
@@ -508,6 +566,7 @@ export function applySessionEntryMaintenance(
508566
export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBestEffort(
509567
scope: Pick<ResolvedSqliteReadScope, "agentId" | "env" | "path">,
510568
plans: readonly SessionEntryMaintenancePlan[],
569+
options: { deletedEntriesBeforeMaintenance?: number } = {},
511570
): Promise<SessionEntryMaintenanceResult> {
512571
const archivedWorktrees = plans.flatMap((plan) => plan.archivedWorktrees ?? []);
513572
if (archivedWorktrees.length) {
@@ -536,6 +595,10 @@ export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBest
536595
capped: 0,
537596
};
538597
if (entryRemovals.length === 0 && stateDeletePlans.length === 0) {
598+
await refreshSqliteSessionPlannerStatisticsBestEffort(
599+
scope,
600+
options.deletedEntriesBeforeMaintenance ?? 0,
601+
);
539602
return { archivedTranscripts: [], ...committedCounts };
540603
}
541604
let archiveBytesBySessionId: Map<string, number>;
@@ -546,9 +609,14 @@ export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBest
546609
);
547610
} catch (error) {
548611
warn("SQLite session maintenance archive sizing failed", error, stateDeletePlans);
612+
await refreshSqliteSessionPlannerStatisticsBestEffort(
613+
scope,
614+
options.deletedEntriesBeforeMaintenance ?? 0,
615+
);
549616
return { archivedTranscripts: [], ...committedCounts };
550617
}
551618
const publishedTranscripts: SessionLifecycleArchivedTranscript[] = [];
619+
let deletedEntries = options.deletedEntriesBeforeMaintenance ?? 0;
552620
for (const batch of buildSessionMaintenanceBatches({
553621
archiveBytesBySessionId,
554622
entryRemovals,
@@ -582,6 +650,7 @@ export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBest
582650
warn("SQLite session maintenance cleanup failed", error, batch.stateDeletePlans);
583651
break;
584652
}
653+
deletedEntries += batch.workItems;
585654
emitCommittedSessionEntryRemovals(batch.entryRemovals);
586655
for (const removal of batch.entryRemovals) {
587656
if (removal.maintenanceReason === "model-run-pruned") {
@@ -598,5 +667,6 @@ export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBest
598667
warn("SQLite session maintenance archive publication failed", error, batch.stateDeletePlans);
599668
}
600669
}
670+
await refreshSqliteSessionPlannerStatisticsBestEffort(scope, deletedEntries);
601671
return { archivedTranscripts: publishedTranscripts, ...committedCounts };
602672
}

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ export async function applySessionStoreProjection<T>(params: {
132132
sessionKey: params.activeSessionKey ?? "",
133133
storePath: params.storePath,
134134
});
135-
const committed = await runPreparedSqliteSessionWrite(resolved, async () => {
135+
const preparedWrite = await runPreparedSqliteSessionWrite(resolved, async () => {
136136
const database = openOpenClawAgentDatabase(toDatabaseOptions(resolved));
137137
const before = readSessionEntryStore(database);
138138
const projected = structuredClone(before);
@@ -209,9 +209,11 @@ export async function applySessionStoreProjection<T>(params: {
209209
},
210210
};
211211
});
212+
const committed = preparedWrite.result;
212213
await finalizeSessionEntryMaintenancePlansAfterWriterReleaseBestEffort(
213214
resolved,
214215
committed.maintenancePlans,
216+
{ deletedEntriesBeforeMaintenance: preparedWrite.deletedEntries },
215217
);
216218
return committed.result;
217219
}
@@ -280,7 +282,7 @@ export async function applySessionEntryLifecycleMutation(params: {
280282
let projected: ProjectedLifecycleMutation;
281283
let materializedRemovalPlans: MaterializedSessionStateDeletePlan[] = [];
282284
let removalArchiveMaterializationFailed = false;
283-
const committed = await runPreparedSqliteSessionWrite(resolved, async () => {
285+
const preparedWrite = await runPreparedSqliteSessionWrite(resolved, async () => {
284286
projected = await projectSessionEntryLifecycleMutation(toDatabaseOptions(resolved), {
285287
...(params.allowCanonicalRepair ? { allowCanonicalRepair: true } : {}),
286288
archiveDirectory: resolveSqliteTranscriptArchiveDirectory(resolved),
@@ -315,6 +317,7 @@ export async function applySessionEntryLifecycleMutation(params: {
315317
),
316318
};
317319
});
320+
const committed = preparedWrite.result;
318321
params.onLifecycleCommitted?.();
319322

320323
function commitProjectedLifecycleMutation(
@@ -494,6 +497,7 @@ export async function applySessionEntryLifecycleMutation(params: {
494497
await finalizeSessionEntryMaintenancePlansAfterWriterReleaseBestEffort(
495498
resolved,
496499
committed.maintenancePlans,
500+
{ deletedEntriesBeforeMaintenance: preparedWrite.deletedEntries },
497501
);
498502
let publishedRemovalTranscripts: SessionLifecycleArchivedTranscript[] = [];
499503
try {
@@ -633,6 +637,7 @@ export async function purgeDeletedAgentSessionEntries(
633637
await finalizeSessionEntryMaintenancePlansAfterWriterReleaseBestEffort(
634638
resolved,
635639
committed.maintenancePlans,
640+
{ deletedEntriesBeforeMaintenance: prepared.entryRemovals.length },
636641
);
637642
const archivedTranscripts = [
638643
...(await publishSessionStateArchives(resolved, committed.archivedTranscripts)),

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ async function applySqliteSessionEntryReplacementProjection<T, TReplacement>(
7373
sessionKey: params.activeSessionKey ?? params.sessionKeys?.[0] ?? "",
7474
storePath: params.storePath,
7575
});
76-
const committed = await runPreparedSqliteSessionWrite(resolved, async () => {
76+
const preparedWrite = await runPreparedSqliteSessionWrite(resolved, async () => {
7777
const database = openOpenClawAgentDatabase(toDatabaseOptions(resolved));
7878
const selectedKeys = params.sessionKeys ? new Set(params.sessionKeys) : undefined;
7979
const selectedStatuses = params.statuses ? new Set(params.statuses) : undefined;
@@ -263,9 +263,11 @@ async function applySqliteSessionEntryReplacementProjection<T, TReplacement>(
263263
},
264264
};
265265
});
266+
const committed = preparedWrite.result;
266267
await finalizeSessionEntryMaintenancePlansAfterWriterReleaseBestEffort(
267268
resolved,
268269
committed.maintenancePlans,
270+
{ deletedEntriesBeforeMaintenance: preparedWrite.deletedEntries },
269271
);
270272
return committed.result;
271273
}

0 commit comments

Comments
 (0)