From 01940261ce968e238c21decb0cf52751f769cc8f Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Sat, 5 Dec 2026 07:51:12 -0500 Subject: [PATCH] feat(worker): Reconcile interrupted restore journals --- packages/code/src/restore-journal.test.ts | 223 ++++++++++++++++++++++ packages/code/src/restore-journal.ts | 126 ++++++++++++ 2 files changed, 349 insertions(+) create mode 100644 packages/code/src/restore-journal.test.ts create mode 100644 packages/code/src/restore-journal.ts diff --git a/packages/code/src/restore-journal.test.ts b/packages/code/src/restore-journal.test.ts new file mode 100644 index 00000000..f744fbc8 --- /dev/null +++ b/packages/code/src/restore-journal.test.ts @@ -0,0 +1,223 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { constants } from 'node:fs'; +import { + copyFile, + mkdir, + mkdtemp, + open, + readFile, + readdir, + rm, + symlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import type { TestContext } from 'node:test'; + +import { CheckpointCatalog } from './checkpoint-catalog.js'; +import { reconcileRestoreJournal } from './restore-journal.js'; + +const skip = process.platform !== 'linux'; +const key = 'a'.repeat(64); +const target = 'b'.repeat(64); +const flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; +const reserved = Buffer.from(JSON.stringify({ key, phase: 'reserved' })); +const restored = Buffer.from( + JSON.stringify({ key, phase: 'restored', target }), +); +const noCreate = async (): Promise => assert.fail('creation replayed'); + +async function fixture(t: TestContext) { + const path = await mkdtemp(join(tmpdir(), 'restore-journal-')); + t.after(() => rm(path, { recursive: true, force: true })); + const dir = join(path, 'journal'); + await mkdir(dir, { mode: 0o700 }); + const root = await open(dir, flags); + t.after(() => root.close()); + return { path, dir, root, temp: join(dir, '.catalog.tmp') }; +} + +for (const point of ['reserved', 'materializing', 'committed']) { + test( + `reconciles a worker killed at ${point} without recreating`, + { skip }, + async t => { + const { path, dir, root } = await fixture(t); + const lane = join(path, 'target'); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { open, writeFile } from 'node:fs/promises'; + import { reconcileRestoreJournal } from ${JSON.stringify(new URL('./restore-journal.js', import.meta.url).href)}; + const [dir, lane, key, target, point] = process.argv.slice(1); + const root = await open(dir, ${flags}); + const kill = () => process.kill(process.pid, 'SIGKILL'); + await reconcileRestoreJournal(root, key, async () => { + if (point === 'reserved') kill(); + await writeFile(lane, point === 'materializing' ? 'partial' : 'complete', { flag: 'wx', flush: true }); + if (point === 'materializing') kill(); + return target; + }); + if (point === 'committed') kill(); + `, + dir, + lane, + key, + target, + point, + ], + { encoding: 'utf8', timeout: 10_000 }, + ); + assert.ifError(result.error); + assert.equal(result.signal, 'SIGKILL', result.stderr); + const expected = + point === 'committed' + ? { phase: 'restored', target } + : { phase: 'rejected' }; + assert.deepEqual( + await reconcileRestoreJournal(root, key), + expected, + ); + assert.deepEqual( + await reconcileRestoreJournal(root, key, noCreate), + expected, + ); + await assert.rejects( + reconcileRestoreJournal(root, 'c'.repeat(64), noCreate), + /conflicting/, + ); + if (point === 'reserved') { + await assert.rejects(readFile(lane), { code: 'ENOENT' }); + } else { + assert.equal( + await readFile(lane, 'utf8'), + point === 'committed' ? 'complete' : 'partial', + ); + } + assert.deepEqual(await readdir(dir), ['catalog']); + }, + ); +} + +test( + 'a complete but unpublished success cannot settle a reservation', + { skip }, + async t => { + const { path, root, temp, dir } = await fixture(t); + await CheckpointCatalog.initialize(root, reserved); + const staging = join(path, 'staging'); + await mkdir(staging, { mode: 0o700 }); + const handle = await open(staging, flags); + try { + await CheckpointCatalog.initialize(handle, restored); + } finally { + await handle.close(); + } + await copyFile(join(staging, 'catalog'), temp); + assert.deepEqual(await reconcileRestoreJournal(root, key, noCreate), { + phase: 'rejected', + }); + const reopened = await open(dir, flags); + try { + assert.deepEqual(await reconcileRestoreJournal(reopened, key), { + phase: 'rejected', + }); + } finally { + await reopened.close(); + } + assert.deepEqual(await readdir(dir), ['catalog']); + }, +); + +test( + 'status does not initialize and interrupted initialization remains ambiguous', + { skip }, + async t => { + const { root, dir, temp } = await fixture(t); + assert.deepEqual(await reconcileRestoreJournal(root, key), { + phase: 'absent', + }); + assert.deepEqual(await readdir(dir), []); + await writeFile(temp, reserved, { mode: 0o600 }); + await assert.rejects(reconcileRestoreJournal(root, key), /conflicting/); + await assert.rejects( + reconcileRestoreJournal(root, key, noCreate), + /conflicting/, + ); + assert.deepEqual(await readFile(temp), reserved); + assert.deepEqual(await readdir(dir), ['.catalog.tmp']); + }, +); + +test( + 'conflicting or invalid publication cannot authorize temp removal', + { skip }, + async t => { + const { root, temp } = await fixture(t); + const store = await CheckpointCatalog.initialize(root, reserved); + await writeFile(temp, 'staging', { mode: 0o600 }); + await assert.rejects( + reconcileRestoreJournal(root, target, noCreate), + /conflicting/, + ); + assert.equal(await readFile(temp, 'utf8'), 'staging'); + await rm(temp); + await store.replace( + Buffer.from( + `{"key":"${key}","phase":"restored","phase":"reserved"}`, + ), + ); + await writeFile(temp, 'staging', { mode: 0o600 }); + await assert.rejects( + reconcileRestoreJournal(root, key, noCreate), + /conflicting/, + ); + assert.equal(await readFile(temp, 'utf8'), 'staging'); + }, +); + +test('unexpected replacement types block reconciliation', { skip }, async t => { + const { root, temp, dir } = await fixture(t); + await CheckpointCatalog.initialize(root, reserved); + await symlink('catalog', temp); + await assert.rejects( + reconcileRestoreJournal(root, key, noCreate), + /temporary file/, + ); + assert.deepEqual( + await readFile(join(dir, 'catalog')), + await readFile(temp), + ); +}); + +test( + 'failed terminal directory sync reports no success until reopen confirms it', + { skip }, + async t => { + const { root, dir } = await fixture(t); + await assert.rejects( + reconcileRestoreJournal(root, key, async () => { + t.mock.method(root, 'sync', async () => { + throw new Error('terminal sync failed'); + }); + return target; + }), + /terminal sync failed/, + ); + const reopened = await open(dir, flags); + try { + assert.deepEqual( + await reconcileRestoreJournal(reopened, key, noCreate), + { phase: 'restored', target }, + ); + } finally { + await reopened.close(); + } + }, +); diff --git a/packages/code/src/restore-journal.ts b/packages/code/src/restore-journal.ts new file mode 100644 index 00000000..62eb4af3 --- /dev/null +++ b/packages/code/src/restore-journal.ts @@ -0,0 +1,126 @@ +import { lstat } from 'node:fs/promises'; +import type { FileHandle } from 'node:fs/promises'; + +import { CheckpointCatalog } from './checkpoint-catalog.js'; + +export type RestoreJournalState = + | { phase: 'absent' } + | { phase: 'rejected' } + | { phase: 'restored'; target: string }; + +type Entry = + | { key: string; phase: 'reserved' | 'rejected' } + | { key: string; phase: 'restored'; target: string }; + +const digest = /^[a-f0-9]{64}$/; + +function unavailable(): never { + throw new Error('Restore journal unavailable or conflicting'); +} + +async function exists(path: string): Promise { + try { + await lstat(path); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; + throw error; + } +} + +function parse(bytes: Buffer, key: string): Entry { + // The longest v1 record (restored with two SHA-256 digests) is 169 bytes. + if (bytes.length > 169) unavailable(); + const record: Partial | null = JSON.parse(bytes.toString('utf8')); + if (!record || record.key !== key) unavailable(); + let entry: Entry; + if ( + record.phase === 'restored' && + typeof record.target === 'string' && + digest.test(record.target) + ) { + entry = { key, phase: record.phase, target: record.target }; + } else if (record.phase === 'reserved' || record.phase === 'rejected') { + entry = { key, phase: record.phase }; + } else { + return unavailable(); + } + // Accept only the exact staged v1 serialization (no unknown or duplicate keys). + if (!bytes.equals(encode(entry))) unavailable(); + return entry; +} + +function encode(entry: Entry): Buffer { + return Buffer.from(JSON.stringify(entry)); +} + +/** + * Internal journal for one source incarnation. The caller holds the same + * exclusive, non-reentrant reservation across this entire call (including + * status-driven writes) and supplies a pinned private directory under + * CheckpointCatalog's filesystem contract. It must not replace or reinitialize + * the directory or release either lane's fence. The key binds the authorized + * intent, including the exact source incarnation and deterministic target. + * + * Without `create`, reconcile an existing attempt but never start one. With + * `create`, invoke it only after publishing a new reservation. The callback + * must reject any existing target or registration (absence of a journal does + * not prove either is absent) and return a fingerprint only after fully + * verifying and durably syncing the exact target. A returned `restored` is a + * record of that commit, not proof of the current target or authority to + * attach it. `rejected` is terminal and does not authorize cleanup or unfencing. + */ +export async function reconcileRestoreJournal( + root: FileHandle, + key: string, + create?: () => Promise, +): Promise { + const uid = process.geteuid?.(); + if ( + process.platform !== 'linux' || + uid === undefined || + typeof key !== 'string' || + !digest.test(key) + ) + unavailable(); + const info = await root.stat(); + if ( + !info.isDirectory() || + info.uid !== uid || + (info.mode & 0o7777) !== 0o700 + ) + unavailable(); + + const path = `/proc/self/fd/${root.fd}`; + if (!(await exists(`${path}/catalog`))) { + // A temp without a publication is ambiguous. Never read or adopt it, + // discard it, or treat it as an empty journal. + if (await exists(`${path}/.catalog.tmp`)) unavailable(); + if (!create) return { phase: 'absent' }; + const store = await CheckpointCatalog.initialize( + root, + encode({ key, phase: 'reserved' }), + ); + const target = await create(); + if (typeof target !== 'string' || !digest.test(target)) unavailable(); + await store.replace(encode({ key, phase: 'restored', target })); + return { phase: 'restored', target }; + } + + // Only a validated publication can authorize removal of an unpublished + // replacement. Even a complete staged success says nothing about settlement. + const published: { entry?: Entry } = {}; + await CheckpointCatalog.recoverInterruptedReplacement(root, bytes => { + published.entry = parse(bytes, key); + return true; + }); + const entry = published.entry; + if (!entry) return unavailable(); + if (entry.phase === 'restored') + return { phase: 'restored', target: entry.target }; + if (entry.phase === 'reserved') { + const store = await CheckpointCatalog.open(root); + await store.replace(encode({ key, phase: 'rejected' })); + } + return { phase: 'rejected' }; +}