Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/claude-archive-move-off-event-loop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-backend-claude": patch
---

Moving an idle Claude session into the transcript archive no longer blocks the hosted server's event loop (#2898). The move, removal of the live copy, conflict set-aside and index update now wait for their file and directory fsyncs asynchronously. Order, verification and durability are unchanged. Before deleting live bytes, the sweep checks again, in the same step that deletes, that no turn has started on the session and that no restore or retirement has moved its archived copy in the meantime. Otherwise it leaves both copies for the next sweep's recovery. Restoring an archived session stays synchronous on purpose, so no turn or sweep can run between its validation and its publication.
6 changes: 3 additions & 3 deletions docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Host-copy cleanup, the endpoint and UI are not built.
**Built (#3229):** first-party native removal behind the optional
`historyRemoval` backend capability
([package contract](../integration-contract/package-api.md#native-history-removal-additive-3229)).
Claude (`removeClaudeSession`, `packages/ui-backend-claude/src/transcript-archive.ts:296-322`)
Claude (`removeClaudeSession`, `packages/ui-backend-claude/src/transcript-archive.ts:331-357`)
and Pi (`removePiSession`, `packages/ui-backend-pi/src/session-storage.ts:101-117`)
name their owned artifacts; the shared fence
(`createSessionRetirement`, `packages/ui-sdk/src/server/native-history-removal.ts:117-224`)
Expand Down Expand Up @@ -131,11 +131,11 @@ must be tested through their installed runtime, not inferred from directory name
archive manifests/index/staged or conflict copies can contain readable text.
History reads can restore archived files before reading the SDK transcript
(`createHistory`, `packages/ui-backend-claude/src/history.ts:45-103`;
`restoreArchivedSession`, `packages/ui-backend-claude/src/transcript-archive.ts:157-185`).
`restoreArchivedSession`, `packages/ui-backend-claude/src/transcript-archive.ts:179-207`).
The live/archive roots are resolved by the backend
(`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`).
Archive movement and crash recovery must join the same lifecycle fence
(`archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:229-286`).
(`archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:261-321`).
Delete all owned branches/subagents/copies, not just the displayed branch.
Unknown/unattributable archive remnants mean removal is incomplete.
- **Native Pi history.** SessionManager JSONL trees retain inactive branches and
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/storage-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Source foundations for the matrix:
Server refresh refuses incomplete enumeration and confirms missing histories
before releasing links (`function openScratchPins`, `packages/ui-server/src/cron/scratch-pins.ts:72-195`).
- Claude publishes and verifies cold copies before deleting the live source
(`export async function archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:229-286`).
(`export async function archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:261-321`).
- Journal collection requires no refs/reservations and only expires ended
turns (`function collectObjects`, `packages/ui-server/src/brain/turn-journal.ts:300-320`).
Retention is applied at admission
Expand Down
93 changes: 64 additions & 29 deletions packages/ui-backend-claude/src/transcript-archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,6 @@ function retiredOnDisk(archive: string, id: string): boolean {
catch (error) { return (error as NodeJS.ErrnoException).code !== "ENOENT"; }
}

function syncTree(path: string) {
for (const name of readdirSync(path)) {
const child = join(path, name);
if (lstatSync(child).isDirectory()) syncTree(child);
}
syncDirectory(path);
}
function syncDirectory(path: string) {
const fd = openSync(path, "r");
try { fsyncSync(fd); } finally { closeSync(fd); }
Expand All @@ -76,10 +69,18 @@ function atomic(path: string, bytes: Uint8Array | string) {
} finally { rmSync(temp, { force: true }); }
}
/**
* The same durable steps as `durableDirectory` and `atomic`, waiting on the
* file system off the event loop: every turn's cleanup writes the daily scan
* marker, and a loaded host's fsync must not stall the server (#2416).
* The same durable steps as `durableDirectory` and `atomic`, plus a staged
* tree's directory syncs, waiting on the file system off the event loop: every turn's cleanup writes
* the daily scan marker, and a loaded host's fsync must not stall the server
* (#2416). The idle-session move uses them too (#2898); restore does not.
*/
async function syncTreeAsync(path: string): Promise<void> {
for (const name of readdirSync(path)) {
const child = join(path, name);
if (lstatSync(child).isDirectory()) await syncTreeAsync(child);
}
await syncDirectoryAsync(path);
}
async function syncDirectoryAsync(path: string) {
const handle = await open(path, "r");
try { await handle.sync(); } finally { await handle.close(); }
Expand Down Expand Up @@ -121,9 +122,19 @@ function manifests(root: string, log?: ArchiveOptions["log"]): Manifest[] {
}
return result;
}
/** Counts synchronous index writes, so a sweep's asynchronous one that a restore or removal overtook is redone. */
const indexWrites = new Map<string, number>();
function index(root: string, entries: ArchivedSession[]) {
indexWrites.set(root, (indexWrites.get(root) ?? 0) + 1);
atomic(join(root, "index.json"), JSON.stringify(entries));
}
async function reindexAsync(root: string, log: ArchiveOptions["log"]) {
for (;;) {
const seen = indexWrites.get(root) ?? 0;
await atomicAsync(join(root, "index.json"), JSON.stringify(manifests(root, log).map(m => m.session)));
if ((indexWrites.get(root) ?? 0) === seen) return;
}
}
function archivedBytes(root: string, id: string, file: Manifest["files"][number]): Uint8Array {
const path = join(root, id, `${file.path}.gz`);
directory(dirname(path));
Expand All @@ -135,8 +146,17 @@ function archivedBytes(root: string, id: string, file: Manifest["files"][number]
/** A live transcript that differs from its archived copy is the newer one: keep
* it in place, set the archived copy aside under a conflict name, reindex. */
function setAside(archive: string, id: string, options: ArchiveOptions) {
renameSync(join(archive, id), join(archive, `.conflict-${id}-${options.now?.() ?? Date.now()}`)); syncDirectory(archive);
renameSync(join(archive, id), asideName(archive, id, options)); syncDirectory(archive);
index(archive, manifests(archive, options.log).map(m => m.session));
setAsideLogged(id, options);
}
async function setAsideAsync(archive: string, id: string, options: ArchiveOptions) {
renameSync(join(archive, id), asideName(archive, id, options)); await syncDirectoryAsync(archive);
await reindexAsync(archive, options.log);
setAsideLogged(id, options);
}
const asideName = (archive: string, id: string, options: ArchiveOptions) => join(archive, `.conflict-${id}-${options.now?.() ?? Date.now()}`);
function setAsideLogged(id: string, options: ArchiveOptions) {
(options.log ?? ((message, reason) => console.warn(message, reason)))(
`Transcript ${id} changed after it was archived; kept the live copy and set the archived one aside`, undefined);
}
Expand All @@ -153,7 +173,9 @@ export function listArchivedSessions(options: ArchiveOptions): ArchivedSession[]
}

/** Restore before history reads or worker snapshots. Synchronous: no turn can
* start or archive between validation and publication in this backend process. */
* start or archive between validation and publication in this backend process.
* It stays so on purpose (#2898): the sweep's move awaits its fsyncs, and a
* restore run in one of those windows is what its removal step rechecks for. */
export function restoreArchivedSession(id: string, options: ArchiveOptions): void {
validateSessionId(id);
const { live, archive } = transcriptPaths(options.brainPath, options.env);
Expand Down Expand Up @@ -204,22 +226,32 @@ function pruneEmpty(path: string) {
}
if (readdirSync(path).length === 0) rmdirSync(path);
}
/** False, deleting nothing, when the live source changed after the archive copy was taken. */
function removeSource(live: string, archive: string, record: Manifest): boolean {
/**
* False, deleting nothing, when the live source changed after the archive copy
* was taken; "skipped", deleting nothing, when while the sweep awaited a turn
* took the session, or a restore, retirement or set-aside moved its archived
* copy. That recheck, validation and deletion run as one synchronous step, so
* nothing interleaves with them (#2898); both copies then stay for recovery.
* The removed files' directories are synced after that step instead of after
* each file: a crash in between leaves a subset, which recovery accepts.
*/
async function removeSource(live: string, archive: string, record: Manifest, options: ArchiveOptions): Promise<boolean | "skipped"> {
const id = record.session.id;
if (options.activeSessionIds?.().has(id) || retiredOnDisk(archive, id) ||
!existsSync(join(archive, id)) || existsSync(join(archive, id, "restoring"))) return "skipped";
// Validate the entire remaining source before deleting anything. A crash
// during deletion leaves a subset, which the same check accepts on restart.
const known = new Map(record.files.map(f => [f.path, f.hash]));
const remaining = sessionFiles(live, record.session.id);
const remaining = sessionFiles(live, id);
for (const file of remaining) {
if (digest(regular(join(live, file), Infinity)) !== known.get(file)) return false;
}
// Verify the durable copy even on recovery, before removing live bytes.
for (const file of record.files) archivedBytes(archive, record.session.id, file);
for (const file of remaining) {
rmSync(join(live, file)); syncDirectory(dirname(join(live, file)));
}
pruneEmpty(join(live, record.session.id));
if (existsSync(live)) syncDirectory(live);
for (const file of record.files) archivedBytes(archive, id, file);
for (const file of remaining) rmSync(join(live, file));
for (const parent of new Set(remaining.map(file => dirname(join(live, file))))) await syncDirectoryAsync(parent);
pruneEmpty(join(live, id));
if (existsSync(live)) await syncDirectoryAsync(live);
return true;
}

Expand All @@ -246,8 +278,8 @@ export async function archiveIdleSessions(options: ArchiveOptions): Promise<void
if (existsSync(join(archive, record.session.id, "restoring"))) {
restoreArchivedSession(record.session.id, options);
} else {
index(archive, manifests(archive, options.log).map(m => m.session));
if (!removeSource(live, archive, record)) setAside(archive, record.session.id, options);
await reindexAsync(archive, options.log);
if (await removeSource(live, archive, record, options) === false) await setAsideAsync(archive, record.session.id, options);
}
}
for (const session of sessions) {
Expand All @@ -268,15 +300,18 @@ export async function archiveIdleSessions(options: ArchiveOptions): Promise<void
for (const name of names) {
const bytes = regular(join(live, name), Infinity);
record.files.push({ path: name, hash: digest(bytes) });
atomic(join(staging, `${name}.gz`), Bun.gzipSync(new Uint8Array(bytes)));
await atomicAsync(join(staging, `${name}.gz`), Bun.gzipSync(new Uint8Array(bytes)));
}
atomic(join(staging, "manifest.json"), JSON.stringify(record));
syncTree(staging);
renameSync(staging, join(archive, id)); syncDirectory(archive);
await atomicAsync(join(staging, "manifest.json"), JSON.stringify(record));
await syncTreeAsync(staging);
// The copy awaited: commit only if no turn, restore or retirement
// took the session meanwhile. The staged copy is dropped below.
if (options.activeSessionIds?.().has(id) || existsSync(join(archive, id)) || retiredOnDisk(archive, id)) continue;
renameSync(staging, join(archive, id)); await syncDirectoryAsync(archive);
options.checkpoint?.("archive");
index(archive, manifests(archive, options.log).map(m => m.session));
await reindexAsync(archive, options.log);
options.checkpoint?.("index");
if (!removeSource(live, archive, record)) setAside(archive, id, options);
if (await removeSource(live, archive, record, options) === false) await setAsideAsync(archive, id, options);
} finally { rmSync(staging, { recursive: true, force: true }); }
}
} catch (error) {
Expand Down
Loading
Loading