diff --git a/.changeset/claude-archive-move-off-event-loop.md b/.changeset/claude-archive-move-off-event-loop.md new file mode 100644 index 0000000000..a982674424 --- /dev/null +++ b/.changeset/claude-archive-move-off-event-loop.md @@ -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. diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index ae4e588cac..c7546b4814 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -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`) @@ -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 diff --git a/docs/plans/storage-lifecycle.md b/docs/plans/storage-lifecycle.md index f7e5e64786..333d9c36c6 100644 --- a/docs/plans/storage-lifecycle.md +++ b/docs/plans/storage-lifecycle.md @@ -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 diff --git a/packages/ui-backend-claude/src/transcript-archive.ts b/packages/ui-backend-claude/src/transcript-archive.ts index 43a0cea802..bcede42d96 100644 --- a/packages/ui-backend-claude/src/transcript-archive.ts +++ b/packages/ui-backend-claude/src/transcript-archive.ts @@ -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); } @@ -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 { + 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(); } @@ -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(); 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)); @@ -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); } @@ -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); @@ -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 { + 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; } @@ -246,8 +278,8 @@ export async function archiveIdleSessions(options: ArchiveOptions): Promise 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) { @@ -268,15 +300,18 @@ export async function archiveIdleSessions(options: ArchiveOptions): Promise 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) { diff --git a/packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts b/packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts new file mode 100644 index 0000000000..86d68c21cc --- /dev/null +++ b/packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts @@ -0,0 +1,135 @@ +// #2898: the idle-session move waits on fsync off the event loop; restore stays +// synchronous. Archive and restore are proved separately, and every window the +// move now yields in is exercised against a restore, a turn start and a sweep. +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; +import { open } from "node:fs/promises"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { SDKSessionInfo } from "@anthropic-ai/claude-agent-sdk"; +import { archiveIdleSessions, listArchivedSessions, restoreArchivedSession, transcriptPaths, type ArchiveOptions } from "../src/transcript-archive.js"; + +const ID = "11111111-1111-4111-8111-111111111111"; +const DAY = 86400000; +let root: string, brain: string, live: string, archive: string, now: number, options: ArchiveOptions; +let metadata: SDKSessionInfo[], errors: unknown[], active: Set; +let syncs: number, onSync: ((count: number) => void) | undefined, restoreSync: () => void; +beforeEach(async () => { + root = mkdtempSync(join(tmpdir(), "claude-archive-loop-")); brain = join(root, "brain"); mkdirSync(brain); + now = Date.parse("2026-07-12T12:00:00Z"); metadata = []; errors = []; active = new Set(); + options = { brainPath: brain, env: { CLAUDE_CONFIG_DIR: join(root, "config") }, now: () => now, + listSessionsFn: async () => metadata, log: (_message, error) => errors.push(error), activeSessionIds: () => active }; + ({ live, archive } = transcriptPaths(brain, options.env)); mkdirSync(live, { recursive: true }); + // Every asynchronous fsync is delayed, as on a host under write load; a + // hook can act as another caller at a chosen sync. + const probe = await open(tmpdir(), "r"), handle = Object.getPrototypeOf(probe) as { sync(): Promise }; + await probe.close(); + const sync = handle.sync; syncs = 0; onSync = undefined; + const delayed = spyOn(handle, "sync").mockImplementation(async function (this: unknown) { + syncs++; onSync?.(syncs); await Bun.sleep(5); return sync.call(this); + }); + restoreSync = () => delayed.mockRestore(); +}); +afterEach(() => { restoreSync(); rmSync(root, { recursive: true, force: true }); }); +function session(id = ID, age = 31) { + const time = now - age * DAY; + metadata.push({ sessionId: id, customTitle: "Return to Ithaca", summary: "Odysseus", firstPrompt: "Plan the voyage", createdAt: time - DAY, lastModified: time, fileSize: 1 }); + mkdirSync(join(live, id, "subagents"), { recursive: true }); + writeFileSync(join(live, `${id}.jsonl`), Buffer.from('Odysseus\n\u0000ΓΏ')); + writeFileSync(join(live, id, "subagents", "agent.jsonl"), "Athena\n"); + writeFileSync(join(live, id, "notes.bin"), new Uint8Array([0, 255, 17])); + for (const name of [`${id}.jsonl`, `${id}/subagents/agent.jsonl`, `${id}/notes.bin`, `${id}/subagents`, id]) + utimesSync(join(live, name), new Date(time), new Date(time)); +} +const savedIndex = () => JSON.parse(readFileSync(join(archive, "index.json"), "utf8")); +const liveBytes = () => [`${ID}.jsonl`, `${ID}/notes.bin`, `${ID}/subagents/agent.jsonl`].map(name => readFileSync(join(live, name))); +// Syncs before the first staged file: the two new archive directories' parents, +// the daily marker and its directory. +const MARKER_SYNCS = 4; + +test("an idle session's move waits on fsync off the event loop, with every sync kept", async () => { + session(); const bytes = liveBytes(); + const blocking = spyOn(fs, "fsyncSync"); + let ticks = 0, blocked = -1; const timer = setInterval(() => { ticks++; }, 1); + try { await archiveIdleSessions(options); } + finally { clearInterval(timer); blocked = blocking.mock.calls.length; blocking.mockRestore(); } + expect(errors).toEqual([]); + expect(blocked, "ARCHIVE_MOVE_NEVER_SYNC_FSYNC").toBe(0); + expect(ticks, "ARCHIVE_MOVE_LEAVES_EVENT_LOOP_FREE").toBeGreaterThan(0); + // The same syncs the synchronous move made: the marker (4); three staged + // files (file and directory each) with two new staged directories' parents + // (8); the manifest (2); the staged tree's three directories (3); the + // archive directory after the commit rename (1); the index (2); the three + // removed files' directories (3) and the live directory after pruning (1). + expect(syncs, "ARCHIVE_MOVE_STAYS_DURABLE").toBe(MARKER_SYNCS + 8 + 2 + 3 + 1 + 2 + 3 + 1); + expect(existsSync(join(live, `${ID}.jsonl`))).toBe(false); expect(existsSync(join(live, ID))).toBe(false); + expect(savedIndex().map((s: { id: string }) => s.id)).toEqual([ID]); + restoreArchivedSession(ID, options); + expect(liveBytes()).toEqual(bytes); +}); + +// Restore is the scoped residual: it stays synchronous so that no turn can +// start and no sweep can archive between its validation and publication. +test("restore stays synchronous: a sweep or turn start begun mid-restore sees it only once published", async () => { + session(); const bytes = liveBytes(); await archiveIdleSessions(options); + expect(existsSync(join(archive, ID))).toBe(true); + now += DAY; const syncsBefore = syncs; + const seen: string[] = []; let sweep: Promise | undefined; + const state = () => `${existsSync(join(archive, ID)) ? "archived" : "published"}:${existsSync(join(live, `${ID}.jsonl`)) ? "live" : "absent"}`; + restoreArchivedSession(ID, { ...options, checkpoint: phase => { + if (phase !== "restore") return; + // Between validation and publication: a concurrent sweep and turn start. + sweep = archiveIdleSessions({ ...options }); + queueMicrotask(() => { seen.push(`turn ${state()}`); active.add(ID); restoreArchivedSession(ID, options); }); + setTimeout(() => seen.push(`timer ${state()}`), 0); + } }); + expect(seen, "RESTORE_EXCLUDES_UNTIL_PUBLISHED").toEqual([]); + expect(syncs, "RESTORE_NEVER_AWAITS_A_SYNC").toBe(syncsBefore); + await sweep; await Bun.sleep(1); + expect(seen).toEqual(["turn published:live", "timer published:live"]); + expect(errors).toEqual([]); + expect(liveBytes()).toEqual(bytes); + expect(existsSync(join(archive, ID))).toBe(false); expect(savedIndex()).toEqual([]); +}); + +test("a turn that starts while the move copies keeps its live transcript and no archived copy is committed", async () => { + session(); const bytes = liveBytes(); + // The first staged file's sync: the copy has begun, nothing is committed. + onSync = count => { if (count === MARKER_SYNCS + 1) { active.add(ID); restoreArchivedSession(ID, options); } }; + await archiveIdleSessions(options); + expect(errors).toEqual([]); + expect(liveBytes(), "TURN_DURING_COPY_KEEPS_LIVE").toEqual(bytes); + expect(existsSync(join(archive, ID)), "TURN_DURING_COPY_COMMITS_NOTHING").toBe(false); + expect(readdirSync(archive).filter(name => name.startsWith("."))).toEqual([]); + expect(listArchivedSessions(options)).toEqual([]); +}); + +test("a turn admitted after the commit keeps its live transcript; its later write wins on the next sweep", async () => { + session(); const bytes = liveBytes(); + // Admitted while the committed move writes its index; it has not restored yet. + await archiveIdleSessions({ ...options, checkpoint: phase => { + if (phase === "archive") queueMicrotask(() => active.add(ID)); + } }); + expect(errors).toEqual([]); + expect(liveBytes(), "ADMITTED_TURN_KEEPS_LIVE").toEqual(bytes); + restoreArchivedSession(ID, options); + expect(liveBytes()).toEqual(bytes); + writeFileSync(join(live, `${ID}.jsonl`), "written by the resumed turn"); + active.clear(); now += DAY; + await archiveIdleSessions(options); + expect(errors).toEqual([]); + expect(readFileSync(join(live, `${ID}.jsonl`), "utf8")).toBe("written by the resumed turn"); +}); + +test("a history read that restores while the move writes its index wins: no deletion, no stale index", async () => { + session(); const bytes = liveBytes(); + await archiveIdleSessions({ ...options, checkpoint: phase => { + if (phase === "archive") queueMicrotask(() => restoreArchivedSession(ID, options)); + } }); + expect(errors, "RESTORED_MOVE_SKIPS_REMOVAL").toEqual([]); + expect(liveBytes()).toEqual(bytes); + expect(existsSync(join(archive, ID))).toBe(false); + expect(savedIndex(), "OVERTAKEN_INDEX_IS_REWRITTEN").toEqual([]); + expect(listArchivedSessions(options)).toEqual([]); +});