diff --git a/packages/code/src/checkpoint-catalog.test.ts b/packages/code/src/checkpoint-catalog.test.ts index 3209664d..90a8811f 100644 --- a/packages/code/src/checkpoint-catalog.test.ts +++ b/packages/code/src/checkpoint-catalog.test.ts @@ -4,6 +4,7 @@ import { constants } from 'node:fs'; import { chmod, link, + lstat, mkdir, mkdtemp, open, @@ -223,27 +224,193 @@ test( } ); -for (const phase of ['file-synced', 'renamed', 'committed']) { - test( - `reopen after SIGKILL with replacement ${phase}`, - { skip }, - async t => { - const { root, path } = await fixture(t); +test( + 'recovery uses the pinned directory and discards incomplete staging only', + { skip }, + async t => { + const { root, path, dir } = await fixture(t); + await CheckpointCatalog.initialize(root, old); + const saved = join(dir, 'saved'); + await rename(path, saved); + await mkdir(path, { mode: 0o700 }); + await writeFile(join(path, '.catalog.tmp'), 'decoy', { mode: 0o600 }); + await writeFile(join(saved, '.catalog.tmp.extra'), 'unrelated', { + mode: 0o600, + }); + const temp = join(saved, '.catalog.tmp'); + const prior = await stat(join(saved, 'catalog')); + const sync = t.mock.method(root, 'sync'); + + for (const bytes of [Buffer.alloc(0), Buffer.from('torn')]) { + await writeFile(temp, bytes, { mode: 0o600 }); + await chmod(temp, 0o000); + assert.equal( + await CheckpointCatalog.recoverInterruptedReplacement( + root, + async payload => { + assert.deepEqual(payload, old); + assert.equal((await lstat(temp)).size, bytes.length); + payload.fill(0); + return true; + } + ), + true + ); + } + assert.equal( + await CheckpointCatalog.recoverInterruptedReplacement( + root, + payload => payload.equals(old) + ), + false + ); + assert.equal(sync.mock.callCount(), 3); + assert.equal((await stat(join(saved, 'catalog'))).ino, prior.ino); + assert.deepEqual((await readdir(saved)).sort(), [ + '.catalog.tmp.extra', + 'catalog', + ]); + assert.deepEqual(await readdir(path), ['.catalog.tmp']); + } +); + +test( + 'recovery preserves staging when published bytes or semantics cannot be verified', + { skip }, + async t => { + const { root, path, file } = await fixture(t); + await CheckpointCatalog.initialize(root, old); + const temp = join(path, '.catalog.tmp'); + await writeFile(temp, 'staging', { mode: 0o600 }); + const prior = await stat(temp); + const sync = t.mock.method(root, 'sync'); + await assert.rejects( + CheckpointCatalog.recoverInterruptedReplacement(root, () => false), + /semantics/ + ); + const failure = new Error('validator failed'); + await assert.rejects( + CheckpointCatalog.recoverInterruptedReplacement(root, async () => { + throw failure; + }), + failure + ); + const validate = t.mock.fn(() => true); + await chmod(path, 0o750); + await assert.rejects( + CheckpointCatalog.recoverInterruptedReplacement(root, validate), + /Invalid checkpoint catalog directory/ + ); + await chmod(path, 0o700); + const handle = await open(file, 'r+'); + try { + await handle.write('x', (await handle.stat()).size - 1); + } finally { + await handle.close(); + } + await assert.rejects( + CheckpointCatalog.recoverInterruptedReplacement(root, validate), + /checksum/ + ); + await unlink(file); + await assert.rejects( + CheckpointCatalog.recoverInterruptedReplacement(root, validate), + { code: 'ENOENT' } + ); + assert.equal(validate.mock.callCount(), 0); + assert.equal(sync.mock.callCount(), 0); + assert.equal((await stat(temp)).ino, prior.ino); + assert.equal((await stat(temp)).size, prior.size); + } +); + +test( + 'recovery keeps anomalous staging entries, including links to the catalog', + { skip }, + async t => { + const { root, path, file } = await fixture(t); + await CheckpointCatalog.initialize(root, old); + const temp = join(path, '.catalog.tmp'); + await symlink(file, temp); + const recover = () => + CheckpointCatalog.recoverInterruptedReplacement(root, payload => + payload.equals(old) + ); + const reject = async ( + pattern = /Invalid checkpoint catalog temporary file/ + ) => { + const prior = await lstat(temp); + await assert.rejects(recover(), pattern); + assert.equal((await lstat(temp)).ino, prior.ino); + await rm(temp, { recursive: true }); + }; + await reject(); + await mkdir(temp, { mode: 0o700 }); + await reject(); + execFileSync('mkfifo', ['-m', '600', temp]); + await reject(); + await writeFile(temp, '', { mode: 0o600 }); + await chmod(temp, 0o640); + await reject(); + await writeFile(temp, '', { mode: 0o600 }); + await truncate(temp, ceiling + 1); + await reject(); + const other = join(path, 'other'); + await writeFile(other, '', { mode: 0o600 }); + await link(other, temp); + await reject(); + assert.equal((await stat(other)).nlink, 1); + await link(file, temp); + await reject(/Invalid checkpoint catalog file/); + assert.equal((await stat(file)).nlink, 1); + } +); + +test( + 'recovery reports a failed directory sync and retries it with no staging left', + { skip }, + async t => { + const { root, path } = await fixture(t); + await CheckpointCatalog.initialize(root, old); + await writeFile(join(path, '.catalog.tmp'), '', { mode: 0o600 }); + const recover = () => + CheckpointCatalog.recoverInterruptedReplacement(root, payload => + payload.equals(old) + ); + const failure = new Error('injected sync failure'); + const sync = t.mock.method(root, 'sync', async () => { + throw failure; + }); + await assert.rejects(recover(), failure); + assert.equal(sync.mock.callCount(), 1); + assert.deepEqual(await readdir(path), ['catalog']); + sync.mock.restore(); + const retry = t.mock.method(root, 'sync'); + assert.equal(await recover(), false); + assert.equal(retry.mock.callCount(), 1); + } +); + +for (const phase of ['initializing', 'file-synced', 'renamed', 'committed']) { + test(`catalog state after SIGKILL: ${phase}`, { skip }, async t => { + const { root, path } = await fixture(t); + if (phase !== 'initializing') await CheckpointCatalog.initialize(root, old); - const result = spawnSync( - process.execPath, - [ - '--input-type=module', - '-e', - ` + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` import { open } from 'node:fs/promises'; import { CheckpointCatalog } from ${JSON.stringify( new URL('./checkpoint-catalog.js', import.meta.url).href )}; const root = await open(process.argv[1], ${flags}); - const store = await CheckpointCatalog.open(root); + const initializing = process.argv[2] === 'initializing'; + const store = initializing ? null : await CheckpointCatalog.open(root); const kill = () => process.kill(process.pid, 'SIGKILL'); - if (process.argv[2] === 'file-synced') { + if (initializing || process.argv[2] === 'file-synced') { const handle = await open(process.argv[1], ${flags}); const proto = Object.getPrototypeOf(handle); const sync = proto.sync; @@ -252,33 +419,50 @@ for (const phase of ['file-synced', 'renamed', 'committed']) { } else if (process.argv[2] === 'renamed') { root.sync = async () => { kill(); }; } - await store.replace(Buffer.from('new')); + if (store) await store.replace(Buffer.from('new')); + else await CheckpointCatalog.initialize(root, Buffer.from('new')); kill(); `, - path, - phase, - ], - { encoding: 'utf8', timeout: 10000 } + path, + phase, + ], + { encoding: 'utf8', timeout: 10000 } + ); + assert.equal(result.signal, 'SIGKILL', result.stderr); + const recover = () => + CheckpointCatalog.recoverInterruptedReplacement(root, payload => + payload.equals(old) ); - assert.equal(result.signal, 'SIGKILL', result.stderr); - const reopened = await CheckpointCatalog.open(root); - if (phase === 'file-synced') { - assert.deepEqual(await reopened.read(), old); - assert.deepEqual((await readdir(path)).sort(), [ - '.catalog.tmp', - 'catalog', - ]); - await assert.rejects(reopened.replace(next), { - code: 'EEXIST', - }); - assert.deepEqual((await readdir(path)).sort(), [ - '.catalog.tmp', - 'catalog', - ]); - } else { - assert.deepEqual(await reopened.read(), next); - assert.deepEqual(await readdir(path), ['catalog']); - } + if (phase === 'initializing') { + assert.deepEqual(await readdir(path), ['.catalog.tmp']); + await assert.rejects(recover(), { code: 'ENOENT' }); + assert.deepEqual(await readdir(path), ['.catalog.tmp']); + return; + } + const reopened = await CheckpointCatalog.open(root); + if (phase === 'file-synced') { + assert.deepEqual(await reopened.read(), old); + assert.deepEqual((await readdir(path)).sort(), [ + '.catalog.tmp', + 'catalog', + ]); + await assert.rejects(reopened.replace(next), { + code: 'EEXIST', + }); + assert.deepEqual((await readdir(path)).sort(), [ + '.catalog.tmp', + 'catalog', + ]); + assert.equal(await recover(), true); + assert.deepEqual(await readdir(path), ['catalog']); + const recovered = await CheckpointCatalog.open(root); + assert.deepEqual(await recovered.read(), old); + await recovered.replace(next); + assert.deepEqual(await recovered.read(), next); + assert.deepEqual(await readdir(path), ['catalog']); + } else { + assert.deepEqual(await reopened.read(), next); + assert.deepEqual(await readdir(path), ['catalog']); } - ); + }); } diff --git a/packages/code/src/checkpoint-catalog.ts b/packages/code/src/checkpoint-catalog.ts index 72ac44c5..3a65b870 100644 --- a/packages/code/src/checkpoint-catalog.ts +++ b/packages/code/src/checkpoint-catalog.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto'; import { constants } from 'node:fs'; -import { lstat, open, rename } from 'node:fs/promises'; +import { lstat, open, rename, unlink } from 'node:fs/promises'; import type { FileHandle } from 'node:fs/promises'; const ceiling = 1024 * 1024; @@ -114,6 +114,54 @@ export class CheckpointCatalog { return store; } + /** + * Discard only an unpublished replacement, never complete initialization or + * promote staging bytes. Returns false when there was nothing to discard. + * The caller must retain the same exclusive lease and open handle through + * validation and directory sync. The trusted validator must not reenter + * catalog operations, mutate the directory, or release the handle or lease. + */ + static async recoverInterruptedReplacement( + root: FileHandle, + validate: (payload: Buffer) => boolean | Promise + ): Promise { + return new CheckpointCatalog(root).run(async directory => { + const payload = await read(`${directory}/${catalog}`); + if ((await validate(payload)) !== true) { + throw new Error('Invalid checkpoint catalog semantics'); + } + + const path = `${directory}/${temporary}`; + const info = await lstat(path).catch( + (error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') return null; + throw error; + } + ); + if (info) { + // A crash before chmod/write can leave a umask-restricted mode + // and any size from zero to the full record. Do not read it. + if ( + !info.isFile() || + info.uid !== process.geteuid?.() || + (info.mode & 0o7777 & ~0o600) !== 0 || + info.nlink !== 1 || + info.size > ceiling + ) { + throw new Error( + 'Invalid checkpoint catalog temporary file' + ); + } + // Linux unlinks by name, not inode. The lease and private + // directory exclude swaps between lstat and unlink. + await unlink(path); + } + // Also sync on a retry after an unlink whose sync failed. + await root.sync(); + return info !== null; + }); + } + read(): Promise { return this.run(directory => read(`${directory}/${catalog}`)); }