From 63f57b8ed40172fe885aa33acd5bd139451d1252 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Sat, 5 Dec 2026 08:56:55 -0500 Subject: [PATCH] feat(worker): Compose retained checkpoint holds with restore admission --- packages/code/src/restore-journal.test.ts | 45 +- packages/code/src/restore-journal.ts | 80 ++-- packages/code/src/restore-overlay.ts | 12 +- packages/code/src/worker-restore-admission.ts | 189 ++++++++ packages/code/src/worktree-restore.test.ts | 425 +++++++++++++++--- packages/code/src/worktree-restore.ts | 175 +++++--- 6 files changed, 771 insertions(+), 155 deletions(-) create mode 100644 packages/code/src/worker-restore-admission.ts diff --git a/packages/code/src/restore-journal.test.ts b/packages/code/src/restore-journal.test.ts index f744fbc8..4fc0ae8a 100644 --- a/packages/code/src/restore-journal.test.ts +++ b/packages/code/src/restore-journal.test.ts @@ -18,7 +18,7 @@ import { test } from 'node:test'; import type { TestContext } from 'node:test'; import { CheckpointCatalog } from './checkpoint-catalog.js'; -import { reconcileRestoreJournal } from './restore-journal.js'; +import { admitRestoreJournal, reconcileRestoreJournal } from './restore-journal.js'; const skip = process.platform !== 'linux'; const key = 'a'.repeat(64); @@ -54,7 +54,7 @@ for (const point of ['reserved', 'materializing', 'committed']) { '-e', ` import { open, writeFile } from 'node:fs/promises'; - import { reconcileRestoreJournal } from ${JSON.stringify(new URL('./restore-journal.js', import.meta.url).href)}; + import { admitRestoreJournal, 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'); @@ -221,3 +221,44 @@ test( } }, ); + +test( + 'process death after admission allows only the same unstarted attempt', + { skip }, + async t => { + const { root, dir } = await fixture(t); + const result = spawnSync(process.execPath, [ + '--input-type=module', + '-e', + ` + import { open } from 'node:fs/promises'; + import { admitRestoreJournal } from ${JSON.stringify(new URL('./restore-journal.js', import.meta.url).href)}; + const root = await open(process.argv[1], ${flags}); + await admitRestoreJournal(root, process.argv[2], async () => {}); + process.kill(process.pid, 'SIGKILL'); + `, + dir, + key + ]); + assert.equal(result.signal, 'SIGKILL', result.stderr.toString()); + assert.equal(await admitRestoreJournal(root, key), 'admitted'); + assert.deepEqual(await reconcileRestoreJournal(root, key), { + phase: 'absent' + }); + await assert.rejects( + admitRestoreJournal(root, target, noCreate), + /conflicting/ + ); + assert.deepEqual( + await reconcileRestoreJournal(root, key, async () => target), + { + phase: 'restored', + target + } + ); + assert.deepEqual(await reconcileRestoreJournal(root, key, noCreate), { + phase: 'restored', + target + }); + } +); diff --git a/packages/code/src/restore-journal.ts b/packages/code/src/restore-journal.ts index 62eb4af3..2747bb66 100644 --- a/packages/code/src/restore-journal.ts +++ b/packages/code/src/restore-journal.ts @@ -9,7 +9,7 @@ export type RestoreJournalState = | { phase: 'restored'; target: string }; type Entry = - | { key: string; phase: 'reserved' | 'rejected' } + | { key: string; phase: 'admitted' | 'reserved' | 'rejected' } | { key: string; phase: 'restored'; target: string }; const digest = /^[a-f0-9]{64}$/; @@ -40,7 +40,11 @@ function parse(bytes: Buffer, key: string): Entry { digest.test(record.target) ) { entry = { key, phase: record.phase, target: record.target }; - } else if (record.phase === 'reserved' || record.phase === 'rejected') { + } else if ( + record.phase === 'admitted' || + record.phase === 'reserved' || + record.phase === 'rejected' + ) { entry = { key, phase: record.phase }; } else { return unavailable(); @@ -73,8 +77,52 @@ function encode(entry: Entry): Buffer { export async function reconcileRestoreJournal( root: FileHandle, key: string, - create?: () => Promise, + create?: () => Promise ): Promise { + const entry = await readEntry(root, key); + if (!entry || entry.phase === 'admitted') { + if (!create) return { phase: 'absent' }; + const reserved = encode({ key, phase: 'reserved' }); + const store = entry + ? await CheckpointCatalog.open(root) + : await CheckpointCatalog.initialize(root, reserved); + if (entry) await store.replace(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 }; + } + + 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' }; +} + +/** Claim one exact intent before fencing a destination, without arming materialization. */ +export async function admitRestoreJournal( + root: FileHandle, + key: string, + beforeClaim?: () => Promise +): Promise<'absent' | 'admitted' | 'attempted'> { + const entry = await readEntry(root, key); + if (entry) return entry.phase === 'admitted' ? 'admitted' : 'attempted'; + if (!beforeClaim) return 'absent'; + await beforeClaim(); + await CheckpointCatalog.initialize( + root, + encode({ key, phase: 'admitted' }) + ); + return 'admitted'; +} + +async function readEntry( + root: FileHandle, + key: string +): Promise { const uid = process.geteuid?.(); if ( process.platform !== 'linux' || @@ -93,34 +141,14 @@ export async function reconcileRestoreJournal( 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. + // A temp without a publication is ambiguous, not 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 }; + return; } - - // 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' }; + return published.entry ?? unavailable(); } diff --git a/packages/code/src/restore-overlay.ts b/packages/code/src/restore-overlay.ts index 6fdcc4ed..9f83722d 100644 --- a/packages/code/src/restore-overlay.ts +++ b/packages/code/src/restore-overlay.ts @@ -234,12 +234,11 @@ function validateTree(files: ReadonlyMap): void { } } -export async function planRestore( +export async function assertRestoreConfig( git: CheckpointGit, configPath: string, - data: WorktreeCheckpoint, signal: AbortSignal -): Promise { +): Promise { // Read the repository config as data, with includes disabled. Refuse modes which can // redirect Git away from the admitted checkout or change index representation. const config = decode.decode( @@ -264,6 +263,13 @@ export async function planRestore( ) invalid(); } +} + +export async function planRestore( + git: CheckpointGit, + data: WorktreeCheckpoint, + signal: AbortSignal +): Promise { await assertRestorePin(git, data.head, signal); const raw = decode.decode( await git(['ls-tree', '-r', '-l', '-z', '--full-tree', data.head], { diff --git a/packages/code/src/worker-restore-admission.ts b/packages/code/src/worker-restore-admission.ts new file mode 100644 index 00000000..86a36ad6 --- /dev/null +++ b/packages/code/src/worker-restore-admission.ts @@ -0,0 +1,189 @@ +import { createHash } from 'node:crypto'; + +import type { FileHandle } from 'node:fs/promises'; +import type { PublicationAttempt } from './checkpoint-publication.js'; +import type { RestoreRequest } from './checkpoint-restore.js'; +import type { + RestoreDestination, + WorktreeRestoreBackend, + WorktreeRestoreIntent, +} from './worktree-restore.js'; + +import { publicationPrefix } from './checkpoint-publication.js'; +import { withCheckpointDirectory } from './checkpoint-directory.js'; +import { readHeldCheckpoint } from './checkpoint-retention-store.js'; +import { restoreBinding } from './checkpoint-restore.js'; +import { restoreGit } from './restore-overlay.js'; +import { WorktreeRestore } from './worktree-restore.js'; + +type VerifyIsolation = Parameters[1]; +type Options = Omit< + ConstructorParameters[0], + 'backend' | 'publicationKey' +>; + +interface RestoreReservation { + /** Confirm current paired support and authorization of this exact publication and operation. */ + isCurrent(request: RestoreRequest): boolean; + /** Already provisioned directories from durable worker enrollment. */ + journal: string; + retention: string; + /** Compare each descriptor to its enrolled identity and pin the actual grants. */ + verifyIsolation: VerifyIsolation; +} + +interface RestoreAdmission { + /** + * Worker-owned, never a route handler or peer input. Atomically claim the registered + * checkout (including sibling Git writers), source and reserved target against every + * dispatch, lifecycle, retirement, mount/grant and reset path. Prove prior writers + * and their subprocesses have stopped; do not infer it from lost leases or process exit. + * Supply the same isolated journal for this enrolled source after restart; never adopt + * a replacement or recreate a missing one. Hold all claims until task settles. + */ + withExclusive( + intent: WorktreeRestoreIntent, + destination: RestoreDestination, + mode: 'start' | 'status', + signal: AbortSignal, + task: (reservation: RestoreReservation) => Promise, + ): Promise; +} + +function unavailable(): never { + throw new Error('Managed worktree restore admission unavailable'); +} + +/** Worker-local composition only. No bridge route, hold release or live attach. */ +export class WorkerRestoreAdmission { + constructor( + private readonly options: Options, + private readonly admission: RestoreAdmission, + ) {} + + async recover( + intent: WorktreeRestoreIntent, + publication: PublicationAttempt, + mode: 'start' | 'status', + stop?: AbortSignal, + ) { + return this.worker(publication).recover(intent, mode, stop); + } + + /** Verify bytes, index, HEAD and target identity under the status fence; not an attach grant. */ + async verifyTarget( + intent: WorktreeRestoreIntent, + publication: PublicationAttempt, + stop?: AbortSignal, + ) { + return this.worker(publication).verifyTarget(intent, stop); + } + + private worker(input: PublicationAttempt) { + const publication = structuredClone(input); + const { workerId } = this.options; + const admission = this.admission; + const backend: WorktreeRestoreBackend = { + async withReservation(intent, destination, mode, signal, task) { + if ( + publication.workerId !== workerId || + publication.lease.ownerScope !== intent.source.ownerScope || + publication.ref.lane !== intent.sourceId || + publication.ref.sequence !== intent.selector.sequence + ) + unavailable(); + const request: RestoreRequest = { + publication, + digest: intent.selector.digest, + restoreId: createHash('sha256') + .update( + JSON.stringify([ + 'librechat/restore-id/v1', + workerId, + intent.operation, + ]), + ) + .digest('hex'), + destinationReservation: destination.key, + }; + restoreBinding(request); + return admission.withExclusive( + structuredClone(intent), + { ...destination }, + mode, + signal, + async reservation => { + const isCurrent = () => + !signal.aborted && + reservation.isCurrent(structuredClone(request)) === + true; + const assertCurrent = () => { + if (!isCurrent()) unavailable(); + }; + assertCurrent(); + if (reservation.journal === reservation.retention) + unavailable(); + return withCheckpointDirectory( + reservation.journal, + directory => reservation.verifyIsolation(directory), + async (_path, journal) => { + assertCurrent(); + const result = await task({ + journal, + assertCurrent, + readExact: () => + readCheckpoint( + journal, + reservation, + request, + mode, + signal, + isCurrent, + intent.source.checkout.path, + ), + }); + assertCurrent(); + return result; + }, + ); + }, + ); + }, + }; + const publicationKey = createHash('sha256') + .update(publicationPrefix(publication)) + .digest('hex'); + return new WorktreeRestore({ ...this.options, backend, publicationKey }); + } +} + +async function readCheckpoint( + journal: FileHandle, + reservation: RestoreReservation, + request: RestoreRequest, + mode: 'start' | 'status', + signal: AbortSignal, + isCurrent: () => boolean, + checkout: string, +) { + if (!isCurrent()) unavailable(); + const { dev, ino } = await journal.stat({ bigint: true }); + return withCheckpointDirectory( + reservation.retention, + directory => { + if (directory.dev === dev && directory.ino === ino) unavailable(); + return reservation.verifyIsolation(directory); + }, + (_path, root) => + readHeldCheckpoint( + root, + request, + mode, + { + git: restoreGit(checkout), + isCurrent, + }, + signal, + ), + ); +} diff --git a/packages/code/src/worktree-restore.test.ts b/packages/code/src/worktree-restore.test.ts index da9fb851..e221dddb 100644 --- a/packages/code/src/worktree-restore.test.ts +++ b/packages/code/src/worktree-restore.test.ts @@ -11,27 +11,45 @@ import { rm, stat, symlink, - writeFile, + writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; +import { homedir, tmpdir } from 'node:os'; import { join } from 'node:path'; import { test } from 'node:test'; +import { withCheckpointDirectory } from './checkpoint-directory.js'; +import { encodeRestoreCheckpoint } from './checkpoint-restore.js'; +import { + applyRetentionStore, + initializeRetentionStore, + publishRetentionCheckpoint, + readRetentionStore, + stageRetentionPublication, + withUnheldCheckpointHead +} from './checkpoint-retention-store.js'; +import { workspaceMutationGuard } from './workspace-guards.js'; +import { WorkerRestoreAdmission } from './worker-restore-admission.js'; import { CheckpointCatalog } from './checkpoint-catalog.js'; import { awaitRestoreGitExit } from './restore-overlay.js'; import { workspaceIsolationKey } from './protocol.js'; import { captureWorkspaceRootIdentity } from './root-identity.js'; import { defaultWorkspaceQuarantinePath, - saveWorkspaceMutationQuarantine, + saveWorkspaceMutationQuarantine } from './storage.js'; import { WorktreeLifecycle } from './worktree-lifecycle.js'; import { WorktreeRestore } from './worktree-restore.js'; +import type { + ProofQuery, + PublicationAttempt +} from './checkpoint-publication.js'; +import type { RestoreDestination } from './worktree-restore.js'; import type { TestContext } from 'node:test'; +import type { FileHandle } from 'node:fs/promises'; import type { WorktreeRestoreBackend, - WorktreeRestoreIntent, + WorktreeRestoreIntent } from './worktree-restore.js'; import type { WorkspaceCreateWorktreeRequest } from './protocol.js'; import type { WorktreeCheckpoint } from './worktree-checkpoint.js'; @@ -40,10 +58,12 @@ test('keeps the Git reservation pending after the error callback until close', a const child = new EventEmitter(); const error = new Error('cancelled'); let released = false; - const result = awaitRestoreGitExit((complete) => { + const result = awaitRestoreGitExit(complete => { complete(error); return child; - }).finally(() => { released = true; }); + }).finally(() => { + released = true; + }); const rejection = assert.rejects(result, error); await new Promise(resolve => setImmediate(resolve)); assert.equal(released, false); @@ -60,13 +80,13 @@ function git(cwd: string, ...args: string[]): string { PATH: '/usr/bin:/bin', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', - LC_ALL: 'C', - }, + LC_ALL: 'C' + } }); } -async function fixture(t: TestContext) { - const home = await mkdtemp(join(tmpdir(), 'librechat-worktree-restore-')); +async function fixture(t: TestContext, base = tmpdir()) { + const home = await mkdtemp(join(base, 'librechat-worktree-restore-')); t.after(() => rm(home, { recursive: true, force: true })); const checkout = join(home, 'project'); const journal = join(home, 'journal'); @@ -102,20 +122,20 @@ async function fixture(t: TestContext) { const settings = { codeApiUrl: 'https://worker.invalid', workerId: 'worker', - homeDirectory: home, + homeDirectory: home }; const guard = (workspaceRoot: string) => defaultWorkspaceQuarantinePath({ ...settings, workspaceRoot }); const quarantine = { ownerId: 'old-incarnation:old-assignment', - quarantinedAt: new Date().toISOString(), + quarantinedAt: new Date().toISOString() }; const marker = { version: 1 as const, workerId: settings.workerId, workspaceId: workspaceIsolationKey('project', undefined, sourceName), ...quarantine, - reason: 'interrupted', + reason: 'interrupted' }; await saveWorkspaceMutationQuarantine(guard(lane), marker); const intent: WorktreeRestoreIntent = { @@ -128,10 +148,10 @@ async function fixture(t: TestContext) { checkout: await captureWorkspaceRootIdentity(checkout), common: await captureWorkspaceRootIdentity(join(checkout, '.git')), lane: await captureWorkspaceRootIdentity(lane), - registration: await captureWorkspaceRootIdentity(registration), + registration: await captureWorkspaceRootIdentity(registration) }, selector: { sequence: 7, digest: 'a'.repeat(64) }, - quarantine, + quarantine }; const data: WorktreeCheckpoint = { head, @@ -139,75 +159,88 @@ async function fixture(t: TestContext) { { path: 'base.txt', mode: '100644', - bytes: Buffer.from('staged\n'), + bytes: Buffer.from('staged\n') }, - { path: 'remove.txt', mode: null }, + { path: 'remove.txt', mode: null } ], working: [ { path: 'base.txt', mode: '100644', - bytes: Buffer.from('working\n'), + bytes: Buffer.from('working\n') }, { path: 'bin/run', mode: '100755', - bytes: Buffer.from('literal bytes\n'), - }, - ], + bytes: Buffer.from('literal bytes\n') + } + ] }; // Concurrency fixture only; not a durable cross-route fence. let reserved = false; let destination = ''; let dropReply = false; + const payload = { + async readExact(): Promise< + | { + selector: WorktreeRestoreIntent['selector']; + checkpoint: WorktreeCheckpoint; + } + | undefined + > { + return { selector: intent.selector, checkpoint: data }; + } + }; const backend: WorktreeRestoreBackend = { async withReservation(_intent, name, _mode, _signal, task) { if (reserved) throw new Error('busy'); reserved = true; - destination = name; + destination = name.name; const handle = await open(journal, 'r'); try { - const result = await task(handle); + const result = await task({ + journal: handle, + assertCurrent: () => {}, + readExact: () => payload.readExact() + }); if (dropReply) throw new Error('reply lost'); return result; } finally { await handle.close(); reserved = false; } - }, - async readExact() { - return { selector: intent.selector, checkpoint: data }; - }, + } }; const lifecycle = new WorktreeLifecycle(); + const settingsFor = (lifecycle: WorktreeLifecycle) => ({ + ...settings, + projects: new Map([ + [ + 'project', + { + root: checkout, + identity: intent.source.checkout, + writable: true, + lifecycleEligible: true, + command: { workspaceRoot: checkout }, + repositoryInstructions: false + } + ] + ]), + checkoutQuarantines: new Map([['project', guard(checkout)]]), + lifecycle + }); const restore = (override = lifecycle) => - new WorktreeRestore({ - ...settings, - projects: new Map([ - [ - 'project', - { - root: checkout, - identity: intent.source.checkout, - writable: true, - lifecycleEligible: true, - command: { workspaceRoot: checkout }, - repositoryInstructions: false, - }, - ], - ]), - checkoutQuarantines: new Map([['project', guard(checkout)]]), - lifecycle: override, - backend, - }); + new WorktreeRestore({ ...settingsFor(override), backend }); return { + settingsFor, home, checkout, journal, lane, registration, intent, - backend, + payload, restore, data, guard, @@ -215,7 +248,7 @@ async function fixture(t: TestContext) { name: () => destination, dropReply: (drop: boolean) => { dropReply = drop; - }, + } }; } @@ -232,7 +265,7 @@ test( join(f.lane, 'base.txt'), join(f.registration, 'index'), join(f.registration, 'HEAD'), - f.guard(f.lane), + f.guard(f.lane) ].map(path => readFile(path)) ); const before = await original(); @@ -249,7 +282,7 @@ test( { mode: 0o755 } ); assert.deepEqual(await f.restore().recover(f.intent, 'status'), { - state: 'not_started', + state: 'not_started' }); f.dropReply(true); await assert.rejects( @@ -257,9 +290,9 @@ test( /reply lost/ ); f.dropReply(false); - const read = f.backend.readExact; + const read = f.payload.readExact; let reads = 0; - f.backend.readExact = async () => { + f.payload.readExact = async () => { reads++; return undefined; }; @@ -269,7 +302,7 @@ test( assert.equal(reads, 0); await assert.rejects(f.restore().verifyTarget(f.intent)); assert.equal(reads, 1); - f.backend.readExact = read; + f.payload.readExact = read; const target = await f.restore().verifyTarget(f.intent); const root = target.lane.path; assert.notEqual(root, f.lane); @@ -288,7 +321,7 @@ test( ); assert.equal((await stat(join(root, 'bin/run'))).mode & 0o777, 0o755); await assert.rejects(stat(join(root, 'remove.txt')), { - code: 'ENOENT', + code: 'ENOENT' }); await assert.rejects(stat(marker), { code: 'ENOENT' }); assert.deepEqual(await f.restore().recover(f.intent, 'status'), result); @@ -321,24 +354,25 @@ test( ); test( - 'requires exact publication and original guard and rejects a checkout-wide quarantine', + 'requires the original guard and rejects a checkout-wide quarantine', options, async t => { const f = await fixture(t); - for (const change of [ - { selector: { ...f.intent.selector, sequence: 8 } }, - { selector: { ...f.intent.selector, digest: 'f'.repeat(64) } }, - { quarantine: { ...f.intent.quarantine, ownerId: 'other' } }, - ]) - await assert.rejects( - f.restore().recover({ ...f.intent, ...change }, 'start') - ); + await assert.rejects( + f.restore().recover( + { + ...f.intent, + quarantine: { ...f.intent.quarantine, ownerId: 'other' } + }, + 'start' + ) + ); await rm(f.guard(f.lane)); await assert.rejects(f.restore().recover(f.intent, 'start')); await saveWorkspaceMutationQuarantine(f.guard(f.lane), f.marker); await saveWorkspaceMutationQuarantine(f.guard(f.checkout), { ...f.marker, - workspaceId: 'project', + workspaceId: 'project' }); await assert.rejects(f.restore().recover(f.intent, 'start')); assert.deepEqual(await readdir(f.journal), []); @@ -391,7 +425,7 @@ test( ); await rm(target, { recursive: true }); await rm(join(f.checkout, '.git', 'worktrees', f.name()), { - recursive: true, + recursive: true }); assert.deepEqual( await f.restore(lifecycle).recover(f.intent, 'start'), @@ -411,7 +445,7 @@ test( f.data.working.push({ path: '../original', mode: '100644', - bytes: Buffer.from('bad'), + bytes: Buffer.from('bad') }); await assert.rejects(f.restore().recover(f.intent, 'start')); f.data.working.pop(); @@ -425,7 +459,9 @@ test( git(f.checkout, 'config', '--unset', 'include.path'); const handle = await open(f.journal, 'r'); try { - await CheckpointCatalog.initialize(handle, Buffer.from('{}')); + await ( + await CheckpointCatalog.open(handle) + ).replace(Buffer.from('{}')); } finally { await handle.close(); } @@ -447,11 +483,11 @@ test( const release = new Promise(done => { resolve = done; }); - const read = f.backend.readExact; - f.backend.readExact = async (...args) => { + const read = f.payload.readExact; + f.payload.readExact = async () => { enter(); await release; - return read(...args); + return read(); }; const first = f.restore().recover(f.intent, 'start'); await entered; @@ -473,3 +509,252 @@ test( assert.equal((await readdir(join(f.checkout, '.worktrees'))).length, 2); } ); + +for (const interrupted of [false, true]) { + test( + `composes durable hold, fences and journal across ${interrupted ? 'interrupted checkout' : 'lost settlement'}`, + options, + async t => { + const f = await fixture( + t, + process.env.CHECKPOINT_TEST_ROOT ?? homedir() + ); + const retention = join(f.home, 'retention'); + await mkdir(retention, { mode: 0o700 }); + // Fixture has no sandbox grants. Production must verify the actual grant set. + const isolate = async () => () => {}; + const store = (task: (root: FileHandle) => Promise) => + withCheckpointDirectory(retention, isolate, (_path, root) => + task(root) + ); + const publication: PublicationAttempt = { + workerId: f.marker.workerId, + ref: { lane: f.intent.sourceId, sequence: 1 }, + epoch: '7', + lease: { + ownerScope: f.intent.source.ownerScope, + assignmentId: 'durable-000000000000000000000001', + incarnationId: 'c'.repeat(24), + generation: 1, + slot: 0 + } + }; + const proof = { + isCurrent: () => true, + async readPairedProof({ + workerId: _worker, + ...query + }: ProofQuery) { + return { ...query, state: 'proven', committedAtMs: 1 }; + } + }; + await store(initializeRetentionStore); + await store(root => + applyRetentionStore(root, { + kind: 'enroll', + lane: publication.ref.lane + }) + ); + const payload = encodeRestoreCheckpoint(f.data); + const stage = (attempt: PublicationAttempt) => + store(root => + stageRetentionPublication( + root, + attempt, + payload, + Date.now() + 60_000 + ) + ); + const first = await stage(publication); + assert.ok(first.commitment); + const digest = first.commitment; + assert.equal( + await store(root => + publishRetentionCheckpoint( + root, + publication, + digest, + null, + proof + ) + ), + 'applied' + ); + const intent = { ...f.intent, selector: { sequence: 1, digest } }; + const before = await readFile(f.guard(f.lane)); + let selected: RestoreDestination | undefined; + let busy = false; + let supported = false; + let calls = 0; + let dropReply = false; + const guard = (name: string) => + workspaceMutationGuard( + f.guard(join(f.checkout, '.worktrees', name)), + f.marker.workerId, + workspaceIsolationKey(intent.workspaceId, undefined, name), + 'fresh-incarnation' + ); + class Lifecycle extends WorktreeLifecycle { + override create( + ...args: Parameters + ) { + calls++; + const [request, source, checkout, ...rest] = args; + return super.create( + request, + source, + async () => { + await assert.rejects( + guard(request.worktree).assertAvailable() + ); + if (interrupted) + throw new Error('interrupted checkout'); + return checkout(); + }, + ...rest + ); + } + } + const reopen = () => + new WorkerRestoreAdmission(f.settingsFor(new Lifecycle()), { + async withExclusive( + _intent, + destination, + _mode, + _signal, + task + ) { + // Fixture only: the production join across all worker writers is a separate gate. + if (busy) throw new Error('busy'); + busy = true; + selected = destination; + try { + const result = await task({ + isCurrent: request => + supported && + request.destinationReservation === + destination.key, + journal: f.journal, + retention, + verifyIsolation: isolate + }); + if (dropReply) throw new Error('reply lost'); + return result; + } finally { + busy = false; + } + } + }); + await assert.rejects( + reopen().recover(intent, publication, 'start'), + /unavailable/ + ); + supported = true; + for (const change of [ + { workerId: 'different' }, + { ref: { ...publication.ref, lane: 'f'.repeat(64) } }, + { ref: { ...publication.ref, sequence: 2 } }, + { lease: { ...publication.lease, ownerScope: 'f'.repeat(64) } } + ]) + await assert.rejects( + reopen().recover( + intent, + { ...publication, ...change }, + 'start' + ) + ); + assert.deepEqual( + await reopen().recover(intent, publication, 'status'), + { state: 'not_started' } + ); + assert.deepEqual(await readdir(f.journal), []); + assert.ok(selected); + await guard(selected.name).assertAvailable(); + + dropReply = !interrupted; + await assert.rejects( + reopen().recover(intent, publication, 'start'), + interrupted ? /interrupted/ : /reply lost/ + ); + dropReply = false; + assert.equal(calls, 1); + assert.ok(selected); + const { name, key } = selected; + const state = await store(readRetentionStore); + assert.equal( + state.lanes.get(intent.sourceId)?.restore + ?.destinationReservation, + key + ); + assert.equal( + state.lanes.get(intent.sourceId)?.restore?.head, + f.data.head + ); + const next = { + ...publication, + ref: { ...publication.ref, sequence: 2 } + }; + const second = await stage(next); + assert.ok(second.commitment); + const newer = second.commitment; + assert.equal( + await store(root => + publishRetentionCheckpoint( + root, + next, + newer, + publication.ref, + proof + ) + ), + 'conflict' + ); + assert.equal( + await store(root => + withUnheldCheckpointHead(root, f.data.head, async () => + assert.fail('HEAD unpinned') + ) + ), + false + ); + const terminal = { state: interrupted ? 'rejected' : 'settled' }; + await assert.rejects(reopen().recover(intent, { ...publication, epoch: '8' }, 'status')); + await assert.rejects(reopen().recover({ ...intent, operation: 'other' }, publication, 'start')); + assert.deepEqual( + await reopen().recover(intent, publication, 'status'), + terminal + ); + assert.deepEqual( + await reopen().recover(intent, publication, 'start'), + terminal + ); + assert.equal(calls, 1); + assert.equal( + (await readdir(join(f.checkout, '.worktrees'))).length, + 2 + ); + await assert.rejects(guard(name).assertAvailable()); + await assert.rejects(guard(intent.sourceName).assertAvailable()); + assert.deepEqual(await readFile(f.guard(f.lane)), before); + if (interrupted) { + await assert.rejects( + reopen().verifyTarget(intent, publication) + ); + } else { + const target = await reopen().verifyTarget(intent, publication); + assert.equal(target.worktree, name); + await writeFile(join(target.lane.path, 'base.txt'), 'drift'); + await assert.rejects( + reopen().verifyTarget(intent, publication) + ); + await rm(f.guard(target.lane.path)); + await assert.rejects( + reopen().recover(intent, publication, 'status') + ); + await assert.rejects( + reopen().recover(intent, publication, 'start') + ); + } + } + ); +} diff --git a/packages/code/src/worktree-restore.ts b/packages/code/src/worktree-restore.ts index 916e973f..2182b3c7 100644 --- a/packages/code/src/worktree-restore.ts +++ b/packages/code/src/worktree-restore.ts @@ -6,14 +6,15 @@ import { dirname, join } from 'node:path'; import { identityIsMountPoint, readLinuxMountInfo } from './identity-mount.js'; import { LINKED_WORKTREE_DIRECTORY, - verifyLinkedWorktree, + verifyLinkedWorktree } from './linked-worktrees.js'; import { BRIDGE_PROTOCOL_VERSION, isValidLinkedWorktreeName, - workspaceIsolationKey, + workspaceIsolationKey } from './protocol.js'; import { + assertRestoreConfig, assertRestorePin, materializeRestore, planRestore, @@ -21,16 +22,19 @@ import { restoreGit, sameRestoreData, verifyRestoreFiles, - verifyRestoreIndex, + verifyRestoreIndex } from './restore-overlay.js'; +import { admitRestoreJournal } from './restore-journal.js'; import { settleRestore, verifySettledRestore } from './restore-settlement.js'; import { captureWorkspaceRootIdentity, - matchesWorkspaceRoot, + matchesWorkspaceRoot } from './root-identity.js'; import { defaultWorkspaceQuarantinePath, loadWorkspaceMutationQuarantines, + loadWorkspaceMutationQuarantine, + saveWorkspaceMutationQuarantine } from './storage.js'; import { captureWorktreeCheckpoint } from './worktree-checkpoint.js'; @@ -40,7 +44,7 @@ import type { RestoreSettlement } from './restore-settlement.js'; import type { WorkspaceRootIdentity } from './root-identity.js'; import type { CheckpointOwner, - WorktreeCheckpoint, + WorktreeCheckpoint } from './worktree-checkpoint.js'; import type { WorktreeLifecycle } from './worktree-lifecycle.js'; @@ -58,11 +62,17 @@ export interface WorktreeRestoreIntent { quarantine: Readonly<{ ownerId: string; quarantinedAt: string }>; } +export interface RestoreDestination { + name: string; + key: string; +} + export interface WorktreeRestoreBackend { /** * Reserve the exact registration, source and deterministic destination against dispatch, mounts, * writers, lifecycle, retirement and alias access. Checkout-wide operations must be excluded. - * Keep the destination denied to ordinary routes (including across restart) until explicit attach. + * Ordinary routes must honor the durable lane quarantine written by restore before + * materialization. No administrative clear or other route may bypass it during admission. * Yield an exclusively leased, pinned, durable and isolated per-source directory for the journal * only, under the same contract as CheckpointCatalog. Never alias/reinitialize a retired journal. * Failure to obtain or prove any reservation must reject before invoking task. Status must @@ -71,23 +81,23 @@ export interface WorktreeRestoreBackend { */ withReservation( intent: WorktreeRestoreIntent, - destination: string, + destination: RestoreDestination, mode: 'start' | 'status', signal: AbortSignal, - task: (journal: FileHandle) => Promise + task: (lease: RestoreLease) => Promise ): Promise; - /** Require the exact verified, retained selector and scope. Hold its pin and bytes until reservation release. */ - readExact( - source: CheckpointOwner, - selector: RestoreSelector, - signal: AbortSignal - ): Promise< +} + +interface RestoreLease { + journal: FileHandle; + assertCurrent(): void; + readExact(): Promise< | { selector: RestoreSelector; checkpoint: WorktreeCheckpoint } | undefined >; } -interface RestoreTarget { +export interface RestoreTarget { worktree: string; lane: WorkspaceRootIdentity; registration: WorkspaceRootIdentity; @@ -152,6 +162,8 @@ export class WorktreeRestore { checkoutQuarantines: ReadonlyMap; lifecycle: WorktreeLifecycle; backend: WorktreeRestoreBackend; + /** Hash of the exact proof-bound publication envelope for managed admission. */ + publicationKey?: string; } ) {} @@ -200,7 +212,7 @@ export class WorktreeRestore { sourceId, source, selector, - quarantine, + quarantine } = intent; if ( process.platform !== 'linux' || @@ -251,6 +263,7 @@ export class WorktreeRestore { selector.digest, quarantine.ownerId, quarantine.quarantinedAt, + ...(this.options.publicationKey ? [this.options.publicationKey] : []) ]); const destination = `restore-${key}`; if (sourceName.toLowerCase() === destination) unavailable(); @@ -259,16 +272,35 @@ export class WorktreeRestore { const guardOptions = { codeApiUrl: this.options.codeApiUrl, workerId: this.options.workerId, - homeDirectory: this.options.homeDirectory, + homeDirectory: this.options.homeDirectory }; const sourceGuard = defaultWorkspaceQuarantinePath({ ...guardOptions, - workspaceRoot: source.lane.path, + workspaceRoot: source.lane.path }); const targetGuard = defaultWorkspaceQuarantinePath({ ...guardOptions, - workspaceRoot: root, + workspaceRoot: root }); + const targetOwner = `worker-restore:${key}`; + const targetWorkspace = workspaceIsolationKey( + workspaceId, + undefined, + destination + ); + const assertTargetFence = async () => { + const records = await loadWorkspaceMutationQuarantines(targetGuard); + if (!records.length) return false; + const own = await loadWorkspaceMutationQuarantine(targetGuard); + if ( + records.length !== 1 || + own?.workerId !== this.options.workerId || + own.workspaceId !== targetWorkspace || + own.ownerId !== targetOwner + ) + unavailable(); + return true; + }; const assertSource = async () => { const lane = await verifyLinkedWorktree( project.root, @@ -290,8 +322,8 @@ export class WorktreeRestore { )) ) unavailable(); - const [checkout, original, target] = await Promise.all( - [checkoutGuard, sourceGuard, targetGuard].map(path => + const [checkout, original] = await Promise.all( + [checkoutGuard, sourceGuard].map(path => loadWorkspaceMutationQuarantines(path) ) ); @@ -299,7 +331,6 @@ export class WorktreeRestore { // or mismatched markers are not evidence that this is the interrupted operation. if ( checkout.length || - target.length || original.length !== 1 || original[0].workerId !== this.options.workerId || original[0].workspaceId !== @@ -313,25 +344,67 @@ export class WorktreeRestore { const signal = stop ? AbortSignal.any([stop, timeout]) : timeout; return this.options.backend.withReservation( structuredClone(intent), - destination, + { name: destination, key }, mode, signal, - async handle => { + async ({ journal, readExact, assertCurrent }) => { + assertCurrent(); signal.throwIfAborted(); await assertSource(); const assertAbsent = async () => { if ((await exists(root)) || (await exists(metadata))) unavailable(); }; + const fenced = await assertTargetFence(); + const admission = await admitRestoreJournal( + journal, + key, + mode === 'start' + ? async () => { + if (fenced) unavailable(); + await assertAbsent(); + assertCurrent(); + signal.throwIfAborted(); + } + : undefined + ); + if (!fenced && admission !== 'absent') { + if (admission !== 'admitted' || mode !== 'start') + unavailable(); + await assertAbsent(); + signal.throwIfAborted(); + await saveWorkspaceMutationQuarantine(targetGuard, { + version: 1, + workerId: this.options.workerId, + workspaceId: targetWorkspace, + ownerId: targetOwner, + quarantinedAt: new Date().toISOString(), + reason: 'Provisional worktree restore' + }); + } else if (fenced && admission === 'absent') { + unavailable(); + } + if (mode === 'start') { + // Reestablish durability even if a prior writer died before fsync. + await sync( + targetGuard, + constants.O_RDONLY | + constants.O_NOFOLLOW | + constants.O_NONBLOCK + ); + await sync(dirname(targetGuard)); + } + const requireFence = async () => { + if (!(await assertTargetFence())) unavailable(); + }; const target = async (): Promise => { const lane = await verifyLinkedWorktree( project.root, destination, source.checkout ); - const registration = await captureWorkspaceRootIdentity( - metadata - ); + const registration = + await captureWorkspaceRootIdentity(metadata); if ( lane.root !== root || lane.commonGitDir !== source.common.path || @@ -345,25 +418,13 @@ export class WorktreeRestore { return { worktree: destination, lane: lane.identity, - registration, + registration }; }; const fingerprint = (value: RestoreTarget) => hash([identity(value.lane), identity(value.registration)]); const prepareVerification = async () => { signal.throwIfAborted(); - const payload = await this.options.backend.readExact( - source, - selector, - signal - ); - if ( - !payload || - payload.selector.sequence !== selector.sequence || - payload.selector.digest !== selector.digest - ) - unavailable(); - const data = restoreData(payload.checkpoint); const git = restoreGit(root); const checkoutGit = restoreGit(project.root); const mounts = await readLinuxMountInfo(); @@ -405,12 +466,17 @@ export class WorktreeRestore { )) ) unavailable(); - const plan = await planRestore( - checkoutGit, - config, - data, - signal - ); + await requireFence(); + await assertRestoreConfig(checkoutGit, config, signal); + const payload = await readExact(); + if ( + !payload || + payload.selector.sequence !== selector.sequence || + payload.selector.digest !== selector.digest + ) + unavailable(); + const data = restoreData(payload.checkpoint); + const plan = await planRestore(checkoutGit, data, signal); const verify = async (value: RestoreTarget) => { const index = await lstat(join(metadata, 'index')); if ( @@ -435,7 +501,7 @@ export class WorktreeRestore { const owner = { ...source, lane: value.lane, - registration: value.registration, + registration: value.registration }; if ( !(await matchesWorkspaceRoot( @@ -481,6 +547,8 @@ export class WorktreeRestore { if (!captured || !sameRestoreData(data, captured)) unavailable(); await assertSource(); + await requireFence(); + assertCurrent(); signal.throwIfAborted(); }; return { checkoutGit, data, git, objectRoot, plan, verify }; @@ -491,6 +559,8 @@ export class WorktreeRestore { await assertSource(); signal.throwIfAborted(); return async () => { + await requireFence(); + assertCurrent(); const created: { value?: RestoreTarget } = {}; await this.options.lifecycle.create( { @@ -498,7 +568,7 @@ export class WorktreeRestore { operation: 'create_worktree', workspaceId, worktree: destination, - commit: data.head, + commit: data.head }, source.checkout, async () => { @@ -527,10 +597,7 @@ export class WorktreeRestore { unavailable(); for (const [directory, files] of [ [root, ['.git']], - [ - metadata, - ['HEAD', 'commondir', 'gitdir', 'index'], - ], + [metadata, ['HEAD', 'commondir', 'gitdir', 'index']] ] as const) { for (const file of files) await sync( @@ -550,7 +617,7 @@ export class WorktreeRestore { }; }; return task({ - journal: handle, + journal, key, assertAbsent, prepare, @@ -560,7 +627,7 @@ export class WorktreeRestore { if (fingerprint(current) !== expected) unavailable(); await verify(current); return current; - }, + } }); } );