Skip to content

Commit 3018a1d

Browse files
committed
fix(sessions): release writer lane during archive work
1 parent 5960e4a commit 3018a1d

5 files changed

Lines changed: 172 additions & 46 deletions

‎src/config/sessions/session-accessor.sqlite-cleanup-race.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target
1919
import type { SessionEntry } from "./types.js";
2020

2121
const archiveMaterializationHook = vi.hoisted(() => ({
22+
beforeMaterialize: undefined as (() => Promise<void>) | undefined,
2223
afterMaterialize: undefined as (() => void) | undefined,
2324
}));
2425

@@ -31,6 +32,7 @@ vi.mock("./session-accessor.sqlite-archive.js", async (importOriginal) => {
3132
materializeSqliteSessionStateDeletePlans: async (
3233
...args: Parameters<typeof actual.materializeSqliteSessionStateDeletePlans>
3334
) => {
35+
await archiveMaterializationHook.beforeMaterialize?.();
3436
const result = await actual.materializeSqliteSessionStateDeletePlans(...args);
3537
archiveMaterializationHook.afterMaterialize?.();
3638
return result;
@@ -50,6 +52,7 @@ describe("SQLite lifecycle cleanup races", () => {
5052
});
5153

5254
afterEach(() => {
55+
archiveMaterializationHook.beforeMaterialize = undefined;
5356
archiveMaterializationHook.afterMaterialize = undefined;
5457
closeOpenClawAgentDatabasesForTest();
5558
});
@@ -406,6 +409,65 @@ describe("SQLite lifecycle cleanup races", () => {
406409
]);
407410
});
408411

412+
it("releases the store writer while a transcript archive is materialized", async () => {
413+
const deletedKey = "agent:main:cleanup-race-deleted";
414+
const deletedSessionId = "cleanup-race-deleted-session";
415+
const writerKey = "agent:main:cleanup-race-writer";
416+
await replaceSessionEntry(
417+
{ sessionKey: deletedKey, storePath },
418+
{ sessionId: deletedSessionId, updatedAt: Date.now() },
419+
);
420+
await replaceSqliteTranscriptEvents(
421+
{ sessionKey: deletedKey, sessionId: deletedSessionId, storePath },
422+
[
423+
{
424+
type: "session",
425+
id: deletedSessionId,
426+
content: "archive while another writer progresses",
427+
},
428+
],
429+
);
430+
await replaceSessionEntry(
431+
{ sessionKey: writerKey, storePath },
432+
{ sessionId: "cleanup-race-writer-session", updatedAt: Date.now() },
433+
);
434+
435+
let markMaterializationStarted: () => void = () => undefined;
436+
const materializationStarted = new Promise<void>((resolve) => {
437+
markMaterializationStarted = resolve;
438+
});
439+
let releaseMaterialization: () => void = () => undefined;
440+
const materializationGate = new Promise<void>((resolve) => {
441+
releaseMaterialization = resolve;
442+
});
443+
archiveMaterializationHook.beforeMaterialize = async () => {
444+
markMaterializationStarted();
445+
await materializationGate;
446+
};
447+
448+
const deletion = deleteSessionEntryLifecycle({
449+
archiveTranscript: true,
450+
storePath,
451+
target: { canonicalKey: deletedKey, storeKeys: [deletedKey] },
452+
});
453+
await materializationStarted;
454+
const writer = replaceSessionEntry(
455+
{ sessionKey: writerKey, storePath },
456+
{ sessionId: "cleanup-race-writer-session", label: "progressed", updatedAt: Date.now() },
457+
);
458+
const progressedDuringMaterialization = await Promise.race([
459+
writer.then(() => true),
460+
new Promise<false>((resolve) => {
461+
setTimeout(() => resolve(false), 500);
462+
}),
463+
]);
464+
releaseMaterialization();
465+
466+
await expect(deletion).resolves.toMatchObject({ deleted: true });
467+
await expect(writer).resolves.toMatchObject({ label: "progressed" });
468+
expect(progressedDuringMaterialization).toBe(true);
469+
});
470+
409471
it("retains unplanned historical windows behind a placeholder node", async () => {
410472
const sessionKey = "agent:main:unplanned-history";
411473
const currentEntry: SessionEntry = {

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

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import { emitCommittedSessionIdentityDiff } from "./session-accessor.sqlite-iden
4646
import type { SqliteSessionEntryMaintenancePlan } from "./session-accessor.sqlite-lifecycle-types.js";
4747
import {
4848
applySqliteSessionEntryMaintenance,
49-
finalizeSqliteSessionEntryMaintenancePlansBestEffort,
49+
finalizeSqliteSessionEntryMaintenancePlansAfterWriterReleaseBestEffort,
5050
} from "./session-accessor.sqlite-maintenance.js";
5151
import {
5252
createFallbackSessionEntry,
@@ -535,13 +535,13 @@ async function patchSqliteSessionEntrySnapshot<TSnapshot>(
535535
params: SqliteSessionEntrySnapshotPatchParams<TSnapshot>,
536536
): Promise<SessionEntry | null> {
537537
const { options, resolved, sessionKey } = params;
538-
return await runExclusiveSqliteSessionWrite(resolved, async () => {
538+
const committed = await runExclusiveSqliteSessionWrite(resolved, async () => {
539539
const database = openOpenClawAgentDatabase(toDatabaseOptions(resolved));
540540
const prepared = params.readSnapshot(database);
541541
const existing = params.existingEntry(prepared);
542542
const writeBase = existing ?? options.fallbackEntry;
543543
if (!writeBase) {
544-
return null;
544+
return { maintenancePlans: [], result: null };
545545
}
546546
const patch = await params.update(cloneSessionEntry(writeBase), {
547547
existingEntry: existing ? cloneSessionEntry(existing) : undefined,
@@ -601,14 +601,20 @@ async function patchSqliteSessionEntrySnapshot<TSnapshot>(
601601
result = cloneSessionEntry(next);
602602
}, toDatabaseOptions(resolved));
603603
emitCommittedSessionIdentityDiff(previousIdentity, currentIdentity);
604-
await finalizeSqliteSessionEntryMaintenancePlansBestEffort(resolved, maintenancePlans);
605-
kickSessionHistoryDiskBudgetMaintenance({
606-
...(resolved.agentId ? { agentId: resolved.agentId } : {}),
607-
storePath: params.storePath,
608-
...(options.maintenanceConfig ? { maintenanceConfig: options.maintenanceConfig } : {}),
609-
});
610-
return result;
604+
return { maintenancePlans, result };
605+
});
606+
// Worker materialization runs after the initial write releases the lane;
607+
// final deletion reacquires it and revalidates every planned row.
608+
await finalizeSqliteSessionEntryMaintenancePlansAfterWriterReleaseBestEffort(
609+
resolved,
610+
committed.maintenancePlans,
611+
);
612+
kickSessionHistoryDiskBudgetMaintenance({
613+
...(resolved.agentId ? { agentId: resolved.agentId } : {}),
614+
storePath: params.storePath,
615+
...(options.maintenanceConfig ? { maintenanceConfig: options.maintenanceConfig } : {}),
611616
});
617+
return committed.result;
612618
}
613619

614620
/** Forks one parent SQLite transcript into a new child transcript. */

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

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -299,16 +299,12 @@ async function deleteSqliteSessionEntryLifecycleLocked(
299299
allowLockedEntryRemoval: boolean,
300300
expectedPluginOwnerId?: string,
301301
): Promise<DeleteSessionEntryLifecycleResult> {
302-
return await runExclusiveSqliteSessionWrite(resolved, async () => {
303-
let result: DeleteSessionEntryLifecycleResult = {
304-
archivedTranscripts: [],
305-
deleted: false,
306-
};
302+
const prepared = await runExclusiveSqliteSessionWrite(resolved, async () => {
307303
const database = openOpenClawAgentDatabase(toDatabaseOptions(resolved));
308304
const targetSnapshot = readSqliteLifecycleTargetSnapshot(database, params.target);
309305
const current = targetSnapshot.primary;
310306
if (!current) {
311-
return result;
307+
return null;
312308
}
313309
if (current.entry.modelSelectionLocked === true && !allowLockedEntryRemoval) {
314310
throw new Error(MODEL_SELECTION_LOCK_REMOVAL_MESSAGE);
@@ -432,11 +428,24 @@ async function deleteSqliteSessionEntryLifecycleLocked(
432428
emitArchivedSqliteTranscriptUpdates(archivedGeneration);
433429
historicalArchivedTranscripts.push(...archivedGeneration);
434430
}
435-
const materializedPlans = await materializeSqliteSessionStateDeletePlans(entryPlans);
431+
return { current, entryPlans, historicalArchivedTranscripts, targetSnapshot };
432+
});
433+
if (!prepared) {
434+
return { archivedTranscripts: [], deleted: false };
435+
}
436+
437+
// Archive materialization is the expensive phase. It must run between short
438+
// writer-lane sections so unrelated writes to this store can keep progressing.
439+
const materializedPlans = await materializeSqliteSessionStateDeletePlans(prepared.entryPlans);
440+
const result = await runExclusiveSqliteSessionWrite(resolved, async () => {
441+
let committed: DeleteSessionEntryLifecycleResult = {
442+
archivedTranscripts: [],
443+
deleted: false,
444+
};
436445
runOpenClawAgentWriteTransaction((transactionDb) => {
437446
const transactionSnapshot = readSqliteLifecycleTargetSnapshot(transactionDb, params.target);
438447
assertSqliteLifecycleTargetSnapshotUnchanged(
439-
targetSnapshot,
448+
prepared.targetSnapshot,
440449
transactionSnapshot,
441450
"delete session entry",
442451
);
@@ -460,28 +469,33 @@ async function deleteSqliteSessionEntryLifecycleLocked(
460469
...params.target.storeKeys,
461470
...transactionSnapshot.rows.map((row) => row.sessionKey),
462471
]);
463-
result = {
472+
committed = {
464473
archivedTranscripts,
465474
deleted: true,
466-
deletedEntry: cloneSessionEntry(current.entry),
467-
...(current.entry.sessionId ? { deletedSessionId: current.entry.sessionId } : {}),
475+
deletedEntry: cloneSessionEntry(prepared.current.entry),
476+
...(prepared.current.entry.sessionId
477+
? { deletedSessionId: prepared.current.entry.sessionId }
478+
: {}),
468479
};
469480
}, toDatabaseOptions(resolved));
470-
if (result.deleted) {
471-
emitSessionIdentityMutation({
472-
kind: "delete",
473-
previous: {
474-
...(current.entry.sessionId ? { sessionId: current.entry.sessionId } : {}),
475-
sessionKeys: targetSnapshot.rows.map((row) => row.sessionKey),
476-
},
477-
});
478-
}
479-
emitArchivedSqliteTranscriptUpdates(result.archivedTranscripts);
480-
// Historical generations were emitted per commit above; merge them into
481-
// the result after the final emit so callers still see every archive.
482-
result.archivedTranscripts.push(...historicalArchivedTranscripts);
483-
return result;
481+
return committed;
484482
});
483+
if (result.deleted) {
484+
emitSessionIdentityMutation({
485+
kind: "delete",
486+
previous: {
487+
...(prepared.current.entry.sessionId
488+
? { sessionId: prepared.current.entry.sessionId }
489+
: {}),
490+
sessionKeys: prepared.targetSnapshot.rows.map((row) => row.sessionKey),
491+
},
492+
});
493+
}
494+
emitArchivedSqliteTranscriptUpdates(result.archivedTranscripts);
495+
// Historical generations were emitted per commit above; merge them into
496+
// the result after the final emit so callers still see every archive.
497+
result.archivedTranscripts.push(...prepared.historicalArchivedTranscripts);
498+
return result;
485499
}
486500

487501
/** Deletes one persisted session entry using SQLite session rows. */

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

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import type { SqliteSessionEntryMaintenancePlan } from "./session-accessor.sqlit
2626
import {
2727
cloneSessionEntry,
2828
getSessionKysely,
29+
runExclusiveSqliteSessionWrite,
2930
toDatabaseOptions,
3031
type ResolvedSqliteReadScope,
3132
} from "./session-accessor.sqlite-scope.js";
@@ -239,6 +240,30 @@ export function applySqliteSessionEntryMaintenance(
239240
export async function finalizeSqliteSessionEntryMaintenancePlansBestEffort(
240241
scope: Pick<ResolvedSqliteReadScope, "agentId" | "env" | "path">,
241242
plans: readonly SqliteSessionEntryMaintenancePlan[],
243+
): Promise<SessionLifecycleArchivedTranscript[]> {
244+
return await finalizeSqliteSessionEntryMaintenancePlansWithCommit(scope, plans, async (commit) =>
245+
commit(),
246+
);
247+
}
248+
249+
/** Finalizes maintenance after its caller releases the per-store writer lane. */
250+
export async function finalizeSqliteSessionEntryMaintenancePlansAfterWriterReleaseBestEffort(
251+
scope: Pick<ResolvedSqliteReadScope, "agentId" | "env" | "path">,
252+
plans: readonly SqliteSessionEntryMaintenancePlan[],
253+
): Promise<SessionLifecycleArchivedTranscript[]> {
254+
return await finalizeSqliteSessionEntryMaintenancePlansWithCommit(
255+
scope,
256+
plans,
257+
async (commit) => await runExclusiveSqliteSessionWrite(scope, async () => commit()),
258+
);
259+
}
260+
261+
async function finalizeSqliteSessionEntryMaintenancePlansWithCommit(
262+
scope: Pick<ResolvedSqliteReadScope, "agentId" | "env" | "path">,
263+
plans: readonly SqliteSessionEntryMaintenancePlan[],
264+
commit: (
265+
fn: () => SessionLifecycleArchivedTranscript[],
266+
) => Promise<SessionLifecycleArchivedTranscript[]>,
242267
): Promise<SessionLifecycleArchivedTranscript[]> {
243268
const entryRemovals = plans.flatMap((plan) => plan.entryRemovals);
244269
const stateDeletePlans = plans.flatMap((plan) => plan.stateDeletePlans);
@@ -247,17 +272,20 @@ export async function finalizeSqliteSessionEntryMaintenancePlansBestEffort(
247272
}
248273
try {
249274
const materializedPlans = await materializeSqliteSessionStateDeletePlans(stateDeletePlans);
250-
let archivedTranscripts: SessionLifecycleArchivedTranscript[] = [];
251-
runOpenClawAgentWriteTransaction((database) => {
252-
assertPlannedSqliteLifecycleArtifactEntriesUnchanged(database, entryRemovals);
253-
archivedTranscripts = deleteMaterializedSqliteSessionStatePlans(
254-
database,
255-
materializedPlans,
256-
undefined,
257-
new Set(entryRemovals.map((removal) => removal.sessionKey)),
258-
);
259-
deletePlannedSqliteLifecycleArtifactEntries(database, entryRemovals);
260-
}, toDatabaseOptions(scope));
275+
const archivedTranscripts = await commit(() => {
276+
let committed: SessionLifecycleArchivedTranscript[] = [];
277+
runOpenClawAgentWriteTransaction((database) => {
278+
assertPlannedSqliteLifecycleArtifactEntriesUnchanged(database, entryRemovals);
279+
committed = deleteMaterializedSqliteSessionStatePlans(
280+
database,
281+
materializedPlans,
282+
undefined,
283+
new Set(entryRemovals.map((removal) => removal.sessionKey)),
284+
);
285+
deletePlannedSqliteLifecycleArtifactEntries(database, entryRemovals);
286+
}, toDatabaseOptions(scope));
287+
return committed;
288+
});
261289
emitCommittedSessionEntryRemovals(entryRemovals);
262290
return archivedTranscripts;
263291
} catch (error) {

‎test/scripts/sqlite-sessions-transcripts-flip-proof.built-cli.e2e.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ describe("SQLite sessions/transcripts flip built CLI proof", () => {
4242
inst.state.applyEnv();
4343
const sessionId = "sqlite-large-archive-responsive";
4444
const sessionKey = "agent:main:dashboard:sqlite-large-archive-responsive";
45+
const writerSessionKey = "agent:main:dashboard:sqlite-large-archive-writer";
4546
const warmupSessionId = "sqlite-archive-worker-warmup";
4647
const warmupSessionKey = "agent:main:dashboard:sqlite-archive-worker-warmup";
4748
const storePath = path.join(inst.stateDir, "agents", "main", "sessions", "sessions.json");
@@ -53,6 +54,10 @@ describe("SQLite sessions/transcripts flip built CLI proof", () => {
5354

5455
try {
5556
await replaceSessionEntry({ sessionKey, storePath }, { sessionId, updatedAt: Date.now() });
57+
await replaceSessionEntry(
58+
{ sessionKey: writerSessionKey, storePath },
59+
{ sessionId: "sqlite-large-archive-writer", updatedAt: Date.now() },
60+
);
5661
await replaceSqliteTranscriptEvents({ sessionKey, sessionId, storePath }, events);
5762
await replaceSessionEntry(
5863
{ sessionKey: warmupSessionKey, storePath },
@@ -128,6 +133,17 @@ describe("SQLite sessions/transcripts flip built CLI proof", () => {
128133
deleteSettled = true;
129134
});
130135
void deletion.catch(() => undefined);
136+
const writerStartedAt = performance.now();
137+
const writerResult = await probeClient.request<{ key?: string; ok?: boolean }>(
138+
"sessions.patch",
139+
{ key: writerSessionKey, label: "writer-progressed-during-archive" },
140+
{ timeoutMs: 2_000 },
141+
);
142+
const writerLatencyMs = performance.now() - writerStartedAt;
143+
expect(writerResult).toMatchObject({ ok: true, key: writerSessionKey });
144+
expect(writerLatencyMs).toBeLessThan(500);
145+
expect(deleteSettled).toBe(false);
146+
expect(archivePublishedAt).toBeUndefined();
131147
const prePublicationProbeLatencies: number[] = [];
132148
const shouldProbeBeforePublication = () => !deleteSettled && archivePublishedAt === undefined;
133149
try {

0 commit comments

Comments
 (0)