Skip to content

Commit 141a16f

Browse files
fix(sessions): release writer lane during transcript archival (#119460)
1 parent 4b7a989 commit 141a16f

4 files changed

Lines changed: 405 additions & 139 deletions

File tree

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

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,213 @@ describe("SQLite lifecycle cleanup races", () => {
468468
expect(progressedDuringMaterialization).toBe(true);
469469
});
470470

471+
it("releases the store writer while a historical generation is archived", async () => {
472+
const deletedKey = "agent:main:historical-race-deleted";
473+
const currentSessionId = "historical-race-current";
474+
const historicalSessionId = "historical-race-unplanned";
475+
const writerKey = "agent:main:historical-race-writer";
476+
await replaceSessionEntry(
477+
{ sessionKey: deletedKey, storePath },
478+
{ sessionId: currentSessionId, updatedAt: Date.now() },
479+
);
480+
await replaceSqliteTranscriptEvents(
481+
{ sessionKey: deletedKey, sessionId: currentSessionId, storePath },
482+
[{ type: "session", id: currentSessionId, content: "current transcript" }],
483+
);
484+
await replaceSqliteTranscriptEvents(
485+
{ sessionKey: deletedKey, sessionId: historicalSessionId, storePath },
486+
[{ type: "session", id: historicalSessionId, content: "historical transcript" }],
487+
);
488+
await replaceSessionEntry(
489+
{ sessionKey: writerKey, storePath },
490+
{ sessionId: "historical-race-writer-session", updatedAt: Date.now() },
491+
);
492+
493+
let markMaterializationStarted: () => void = () => undefined;
494+
const materializationStarted = new Promise<void>((resolve) => {
495+
markMaterializationStarted = resolve;
496+
});
497+
let releaseMaterialization: () => void = () => undefined;
498+
const materializationGate = new Promise<void>((resolve) => {
499+
releaseMaterialization = resolve;
500+
});
501+
archiveMaterializationHook.beforeMaterialize = async () => {
502+
markMaterializationStarted();
503+
await materializationGate;
504+
};
505+
506+
const deletion = deleteSessionEntryLifecycle({
507+
archiveTranscript: true,
508+
storePath,
509+
target: { canonicalKey: deletedKey, storeKeys: [deletedKey] },
510+
});
511+
await materializationStarted;
512+
const writer = replaceSessionEntry(
513+
{ sessionKey: writerKey, storePath },
514+
{
515+
sessionId: "historical-race-writer-session",
516+
label: "progressed",
517+
updatedAt: Date.now(),
518+
},
519+
);
520+
const progressedDuringMaterialization = await Promise.race([
521+
writer.then(() => true),
522+
new Promise<false>((resolve) => {
523+
setTimeout(() => resolve(false), 500);
524+
}),
525+
]);
526+
releaseMaterialization();
527+
528+
await expect(deletion).resolves.toMatchObject({ deleted: true });
529+
await expect(writer).resolves.toMatchObject({ label: "progressed" });
530+
expect(progressedDuringMaterialization).toBe(true);
531+
});
532+
533+
it("releases the store writer while lifecycle cleanup archives a transcript", async () => {
534+
const now = Date.now();
535+
const deletedKey = "agent:main:cleanup-race-archived";
536+
const deletedSessionId = "cleanup-race-archived-session";
537+
const writerKey = "agent:main:cleanup-race-cleanup-writer";
538+
await replaceSessionEntry(
539+
{ sessionKey: deletedKey, storePath },
540+
{ sessionId: deletedSessionId, updatedAt: now - 600_000 },
541+
);
542+
await replaceSqliteTranscriptEvents(
543+
{ sessionKey: deletedKey, sessionId: deletedSessionId, storePath },
544+
[
545+
{
546+
runId: "cleanup-race-marker-archived",
547+
timestamp: new Date(now - 600_000).toISOString(),
548+
type: "metadata",
549+
},
550+
],
551+
);
552+
await replaceSessionEntry(
553+
{ sessionKey: writerKey, storePath },
554+
{ sessionId: "cleanup-race-cleanup-writer-session", updatedAt: now },
555+
);
556+
557+
let markMaterializationStarted: () => void = () => undefined;
558+
const materializationStarted = new Promise<void>((resolve) => {
559+
markMaterializationStarted = resolve;
560+
});
561+
let releaseMaterialization: () => void = () => undefined;
562+
const materializationGate = new Promise<void>((resolve) => {
563+
releaseMaterialization = resolve;
564+
});
565+
archiveMaterializationHook.beforeMaterialize = async () => {
566+
markMaterializationStarted();
567+
await materializationGate;
568+
};
569+
570+
const cleanup = cleanupSessionLifecycleArtifacts({
571+
storePath,
572+
sessionKeySegmentPrefix: "cleanup-race-",
573+
transcriptContentMarker: "cleanup-race-marker",
574+
orphanTranscriptMinAgeMs: 300_000,
575+
nowMs: now,
576+
});
577+
await materializationStarted;
578+
const writer = replaceSessionEntry(
579+
{ sessionKey: writerKey, storePath },
580+
{
581+
sessionId: "cleanup-race-cleanup-writer-session",
582+
label: "progressed",
583+
updatedAt: now + 1,
584+
},
585+
);
586+
const progressedDuringMaterialization = await Promise.race([
587+
writer.then(() => true),
588+
new Promise<false>((resolve) => {
589+
setTimeout(() => resolve(false), 500);
590+
}),
591+
]);
592+
releaseMaterialization();
593+
594+
await expect(cleanup).resolves.toEqual({
595+
removedEntries: 1,
596+
archivedTranscriptArtifacts: 1,
597+
});
598+
await expect(writer).resolves.toMatchObject({ label: "progressed" });
599+
expect(progressedDuringMaterialization).toBe(true);
600+
});
601+
602+
it("releases the store writer while a lifecycle mutation archives a transcript", async () => {
603+
const removedKey = "agent:main:lifecycle-race-archived";
604+
const removedEntry: SessionEntry = {
605+
sessionId: "lifecycle-race-archived-session",
606+
updatedAt: Date.now(),
607+
};
608+
const writerKey = "agent:main:lifecycle-race-writer";
609+
await replaceSessionEntry({ sessionKey: removedKey, storePath }, removedEntry);
610+
const persistedRemovedEntry = loadSessionEntry({ sessionKey: removedKey, storePath });
611+
if (!persistedRemovedEntry) {
612+
throw new Error("expected persisted lifecycle removal entry");
613+
}
614+
await replaceSqliteTranscriptEvents(
615+
{ sessionKey: removedKey, sessionId: removedEntry.sessionId, storePath },
616+
[
617+
{
618+
type: "session",
619+
id: removedEntry.sessionId,
620+
content: "lifecycle mutation archive",
621+
},
622+
],
623+
);
624+
await replaceSessionEntry(
625+
{ sessionKey: writerKey, storePath },
626+
{ sessionId: "lifecycle-race-writer-session", updatedAt: Date.now() },
627+
);
628+
629+
let markMaterializationStarted: () => void = () => undefined;
630+
const materializationStarted = new Promise<void>((resolve) => {
631+
markMaterializationStarted = resolve;
632+
});
633+
let releaseMaterialization: () => void = () => undefined;
634+
const materializationGate = new Promise<void>((resolve) => {
635+
releaseMaterialization = resolve;
636+
});
637+
archiveMaterializationHook.beforeMaterialize = async () => {
638+
markMaterializationStarted();
639+
await materializationGate;
640+
};
641+
642+
const mutation = applySessionEntryLifecycleMutation({
643+
storePath,
644+
removals: [
645+
{
646+
sessionKey: removedKey,
647+
expectedEntry: persistedRemovedEntry,
648+
archiveRemovedTranscript: true,
649+
},
650+
],
651+
skipMaintenance: true,
652+
});
653+
await materializationStarted;
654+
const writer = replaceSessionEntry(
655+
{ sessionKey: writerKey, storePath },
656+
{
657+
sessionId: "lifecycle-race-writer-session",
658+
label: "progressed",
659+
updatedAt: Date.now(),
660+
},
661+
);
662+
const progressedDuringMaterialization = await Promise.race([
663+
writer.then(() => true),
664+
new Promise<false>((resolve) => {
665+
setTimeout(() => resolve(false), 500);
666+
}),
667+
]);
668+
releaseMaterialization();
669+
670+
await expect(mutation).resolves.toMatchObject({
671+
removedEntries: 1,
672+
removedSessionKeys: [removedKey],
673+
});
674+
await expect(writer).resolves.toMatchObject({ label: "progressed" });
675+
expect(progressedDuringMaterialization).toBe(true);
676+
});
677+
471678
it("retains unplanned historical windows behind a placeholder node", async () => {
472679
const sessionKey = "agent:main:unplanned-history";
473680
const currentEntry: SessionEntry = {

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

Lines changed: 50 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,9 @@ export async function cleanupSqliteSessionLifecycleArtifacts(
124124
if (!withOpenClawAgentDatabaseReadOnly(() => true, databaseOptions).found) {
125125
return { removedEntries: 0, archivedTranscriptArtifacts: 0 };
126126
}
127-
return await runExclusiveSqliteSessionWrite(resolved, async () => {
127+
const cleanupPlan = await runExclusiveSqliteSessionWrite(resolved, async () => {
128128
const database = openOpenClawAgentDatabase(databaseOptions);
129-
const cleanupPlan = planSqliteSessionLifecycleArtifactCleanup(database, {
129+
return planSqliteSessionLifecycleArtifactCleanup(database, {
130130
...(params.agentId !== undefined ? { agentId: resolved.agentId } : {}),
131131
archiveRemovedEntryTranscripts: params.archiveRemovedEntryTranscripts !== false,
132132
archiveDirectory: resolveSqliteTranscriptArchiveDirectory(resolved),
@@ -136,9 +136,9 @@ export async function cleanupSqliteSessionLifecycleArtifacts(
136136
orphanTranscriptMinAgeMs: params.orphanTranscriptMinAgeMs,
137137
nowMs: params.nowMs ?? Date.now(),
138138
});
139-
const materializedPlans = await materializeSqliteSessionStateDeletePlans(
140-
cleanupPlan.deletePlans,
141-
);
139+
});
140+
const materializedPlans = await materializeSqliteSessionStateDeletePlans(cleanupPlan.deletePlans);
141+
return await runExclusiveSqliteSessionWrite(resolved, async () => {
142142
let removedEntries = 0;
143143
let archivedTranscripts: SessionLifecycleArchivedTranscript[] = [];
144144
runOpenClawAgentWriteTransaction((transactionDb) => {
@@ -371,16 +371,28 @@ async function deleteSqliteSessionEntryLifecycleLocked(
371371
);
372372
}
373373
}
374-
const historicalArchivedTranscripts: SessionLifecycleArchivedTranscript[] = [];
375-
for (const sessionId of historicalGenerationIds) {
374+
return { archiveDirectory, current, entryPlans, historicalGenerationIds, targetSnapshot };
375+
});
376+
if (!prepared) {
377+
return { archivedTranscripts: [], deleted: false };
378+
}
379+
380+
const historicalArchivedTranscripts: SessionLifecycleArchivedTranscript[] = [];
381+
for (const sessionId of prepared.historicalGenerationIds) {
382+
const plan = await runExclusiveSqliteSessionWrite(resolved, async () => {
383+
const database = openOpenClawAgentDatabase(toDatabaseOptions(resolved));
384+
assertSqliteLifecycleTargetSnapshotUnchanged(
385+
prepared.targetSnapshot,
386+
readSqliteLifecycleTargetSnapshot(database, params.target),
387+
"delete session entry",
388+
);
389+
const referencedAfterDelete = readReferencedSqliteSessionIdsAfterTargetMutation(
390+
database,
391+
params.target,
392+
);
376393
if (referencedAfterDelete.has(sessionId)) {
377-
// Another live entry or route still owns this generation; deleting
378-
// this entry must not destroy shared history.
379-
continue;
394+
return null;
380395
}
381-
// Recomputed per generation so a run admitted after preflight cannot
382-
// lose the generation it just adopted; such a race aborts the deletion,
383-
// and since the live entry is still present a retry finishes the rest.
384396
const admissionProtected = collectAdmissionProtectedSessionIds({
385397
database,
386398
storePath: params.storePath,
@@ -390,25 +402,27 @@ async function deleteSqliteSessionEntryLifecycleLocked(
390402
`cannot delete session history while work is in flight for ${sessionId}; retry after the run completes`,
391403
);
392404
}
393-
const plan = planSqliteSessionStateDeleteIfUnreferenced({
394-
archiveDirectory,
405+
return planSqliteSessionStateDeleteIfUnreferenced({
406+
archiveDirectory: prepared.archiveDirectory,
395407
archiveTranscript: params.archiveTranscript,
396408
database,
397409
reason: "deleted",
398410
referencedSessionIds: referencedAfterDelete,
399411
sessionId,
400412
});
401-
if (!plan) {
402-
continue;
403-
}
404-
const materializedGeneration = await materializeSqliteSessionStateDeletePlans([plan]);
405-
const archivedGeneration: SessionLifecycleArchivedTranscript[] = [];
413+
});
414+
if (!plan) {
415+
continue;
416+
}
417+
const materializedGeneration = await materializeSqliteSessionStateDeletePlans([plan]);
418+
const archivedGeneration = await runExclusiveSqliteSessionWrite(resolved, async () => {
419+
let committed: SessionLifecycleArchivedTranscript[] = [];
406420
runOpenClawAgentWriteTransaction((transactionDb) => {
407-
// Authoritative fence: admissions are process-local sync state and this
408-
// callback runs synchronously, so a run admitted after the pre-checks
409-
// cannot interleave past this point. An outer lifecycle-mutation hold
410-
// (as eviction uses) would invert lock order against the exclusive
411-
// SQLite write this function already holds.
421+
assertSqliteLifecycleTargetSnapshotUnchanged(
422+
prepared.targetSnapshot,
423+
readSqliteLifecycleTargetSnapshot(transactionDb, params.target),
424+
"delete session entry",
425+
);
412426
const fenceAtDelete = collectAdmissionProtectedSessionIds({
413427
database: transactionDb,
414428
storePath: params.storePath,
@@ -418,20 +432,18 @@ async function deleteSqliteSessionEntryLifecycleLocked(
418432
`cannot delete session history while work is in flight for ${sessionId}; retry after the run completes`,
419433
);
420434
}
421-
archivedGeneration.push(
422-
...deleteMaterializedSqliteSessionStatePlans(transactionDb, materializedGeneration),
435+
committed = deleteMaterializedSqliteSessionStatePlans(
436+
transactionDb,
437+
materializedGeneration,
423438
);
424439
}, toDatabaseOptions(resolved));
425-
// Publish each committed generation immediately: a later archive or
426-
// transaction failure aborts the deletion, and observers must still see
427-
// the removals that already happened (retry completes the remainder).
428-
emitArchivedSqliteTranscriptUpdates(archivedGeneration);
429-
historicalArchivedTranscripts.push(...archivedGeneration);
430-
}
431-
return { current, entryPlans, historicalArchivedTranscripts, targetSnapshot };
432-
});
433-
if (!prepared) {
434-
return { archivedTranscripts: [], deleted: false };
440+
return committed;
441+
});
442+
// Publish each committed generation immediately: a later archive or
443+
// transaction failure aborts the deletion, and observers must still see
444+
// the removals that already happened (retry completes the remainder).
445+
emitArchivedSqliteTranscriptUpdates(archivedGeneration);
446+
historicalArchivedTranscripts.push(...archivedGeneration);
435447
}
436448

437449
// Archive materialization is the expensive phase. It must run between short
@@ -494,7 +506,7 @@ async function deleteSqliteSessionEntryLifecycleLocked(
494506
emitArchivedSqliteTranscriptUpdates(result.archivedTranscripts);
495507
// Historical generations were emitted per commit above; merge them into
496508
// the result after the final emit so callers still see every archive.
497-
result.archivedTranscripts.push(...prepared.historicalArchivedTranscripts);
509+
result.archivedTranscripts.push(...historicalArchivedTranscripts);
498510
return result;
499511
}
500512

0 commit comments

Comments
 (0)