From bbb233952b7066bd3098a61af2a4427499074114 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Sat, 5 Dec 2026 08:42:34 -0500 Subject: [PATCH] feat(worker): Hold exact retained checkpoints across restore crashes --- packages/code/src/checkpoint-restore.test.ts | 528 ++++++++++++++++++ packages/code/src/checkpoint-restore.ts | 128 +++++ .../code/src/checkpoint-retention-codec.ts | 78 ++- .../code/src/checkpoint-retention-store.ts | 251 ++++++++- packages/code/src/checkpoint-retention.ts | 20 + packages/code/src/checkpoint-stage.ts | 25 +- 6 files changed, 1022 insertions(+), 8 deletions(-) create mode 100644 packages/code/src/checkpoint-restore.test.ts create mode 100644 packages/code/src/checkpoint-restore.ts diff --git a/packages/code/src/checkpoint-restore.test.ts b/packages/code/src/checkpoint-restore.test.ts new file mode 100644 index 00000000..f1e83de2 --- /dev/null +++ b/packages/code/src/checkpoint-restore.test.ts @@ -0,0 +1,528 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { + link, + mkdir, + mkdtemp, + open, + readFile, + rm, + unlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; + +import type { FileHandle } from 'node:fs/promises'; +import type { TestContext } from 'node:test'; +import type { RestoreAuthority, RestoreRequest } from './checkpoint-restore.js'; + +import { tryLockDescriptor } from './process-lock.js'; +import { reconcileRestoreJournal } from './restore-journal.js'; +import { encodeRestoreCheckpoint } from './checkpoint-restore.js'; +import { restoreGit } from './restore-overlay.js'; +import { CheckpointCatalog } from './checkpoint-catalog.js'; +import { decodeRetention } from './checkpoint-retention-codec.js'; +import { + applyRetentionStore, + initializeRetentionStore, + publishRetentionCheckpoint, + readHeldCheckpoint, + readRetentionStore, + reclaimRetentionCheckpoint, + releaseCheckpointHold, + stageRetentionPublication, + withUnheldCheckpointHead, +} from './checkpoint-retention-store.js'; + +const options = { skip: process.platform !== 'linux', timeout: 15_000 }; +const hex = (digit: string) => digit.repeat(64); +const lane = hex('a'); +const signal = new AbortController().signal; +const publication = (sequence: number) => ({ + workerId: 'worker', + ref: { lane, sequence }, + lease: { + ownerScope: hex('b'), + assignmentId: `durable-${'a'.repeat(24)}`, + incarnationId: 'c'.repeat(24), + generation: 1, + slot: 0, + }, + epoch: '1', +}); + +async function fixture(t: TestContext) { + const dir = await mkdtemp(join(tmpdir(), 'checkpoint-restore-')); + t.after(() => rm(dir, { force: true, recursive: true })); + const store = join(dir, 'store'); + const checkout = join(dir, 'checkout'); + const journal = join(dir, 'journal'); + for (const path of [store, checkout, journal]) + await mkdir(path, { mode: 0o700 }); + function git(...args: string[]) { + return execFileSync('git', ['-C', checkout, ...args], { + encoding: 'utf8', + }).trim(); + } + git('init', '-q'); + git( + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + 'commit', + '--allow-empty', + '-qm', + 'checkpoint', + ); + const head = git('rev-parse', 'HEAD'); + const pin = `refs/librechat/checkpoints/${head}`; + git('update-ref', pin, head); + const checkpoint = { + head, + staged: [ + { + path: 'staged.txt', + mode: '100644' as const, + bytes: Buffer.from([0, 255]), + }, + ], + working: [{ path: 'staged.txt', mode: null }], + }; + async function lease( + operation: (root: FileHandle) => Promise, + path = store, + ) { + const root = await open(path); + try { + assert.equal(await tryLockDescriptor(root.fd), true); + return await operation(root); + } finally { + await root.close(); + } + } + async function stage( + sequence: number, + bytes = encodeRestoreCheckpoint(checkpoint), + ) { + const result = await lease(root => + stageRetentionPublication( + root, + publication(sequence), + bytes, + Date.now() + 60_000, + ), + ); + assert.equal(result.status, 'applied'); + assert.ok(result.commitment); + return result.commitment; + } + function publish(sequence: number, digest: string) { + const attempt = publication(sequence); + return lease(root => + publishRetentionCheckpoint( + root, + attempt, + digest, + sequence === 1 ? null : publication(sequence - 1).ref, + { + isCurrent: () => true, + readPairedProof: async ({ + workerId: _worker, + ...query + }) => ({ ...query, state: 'proven', committedAtMs: 1 }), + }, + ), + ); + } + await lease(initializeRetentionStore); + assert.equal( + await lease(root => + applyRetentionStore(root, { kind: 'enroll', lane }), + ), + 'applied', + ); + const digest = await stage(1); + assert.equal(await publish(1, digest), 'applied'); + const request = { + publication: publication(1), + digest, + restoreId: hex('d'), + destinationReservation: hex('e'), + }; + const authority: RestoreAuthority = { + isCurrent: () => true, + git: restoreGit(checkout), + }; + const read = ( + input = request, + mode: 'start' | 'status' = 'start', + auth = authority, + ) => lease(root => readHeldCheckpoint(root, input, mode, auth, signal)); + return { + authority, + checkout, + checkpoint, + git, + head, + journal, + lease, + pin, + publish, + read, + request, + stage, + store, + }; +} + +for (const point of ['held', 'reserved', 'settled']) { + test( + `SIGKILL after ${point} preserves exact bytes and HEAD until durable release`, + options, + async t => { + const f = await fixture(t); + const second = await f.stage(2); + assert.equal(await f.read(f.request, 'status'), undefined); + const command = ` + import assert from 'node:assert/strict'; + import { open } from 'node:fs/promises'; + import { readHeldCheckpoint } from ${JSON.stringify( + new URL('./checkpoint-retention-store.js', import.meta.url) + .href, + )}; + import { restoreGit } from ${JSON.stringify( + new URL('./restore-overlay.js', import.meta.url).href, + )}; + import { reconcileRestoreJournal } from ${JSON.stringify( + new URL('./restore-journal.js', import.meta.url).href, + )}; + import { tryLockDescriptor } from ${JSON.stringify( + new URL('./process-lock.js', import.meta.url).href, + )}; + const [store, checkout, journal, raw, point] = process.argv.slice(1); + const request = JSON.parse(raw); + const signal = new AbortController().signal; + const root = await open(store); + assert.equal(await tryLockDescriptor(root.fd), true); + assert.ok(await readHeldCheckpoint(root, request, 'start', { isCurrent: () => true, git: restoreGit(checkout) }, signal)); + await root.close(); + const kill = () => process.kill(process.pid, 'SIGKILL'); + if (point !== 'held') { + const target = await open(journal); + assert.equal(await tryLockDescriptor(target.fd), true); + await reconcileRestoreJournal(target, request.destinationReservation, async () => { + if (point === 'reserved') kill(); + return 'f'.repeat(64); + }); + } + kill(); + `; + const child = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + command, + f.store, + f.checkout, + f.journal, + JSON.stringify(f.request), + point, + ], + { encoding: 'utf8', timeout: 8000 }, + ); + assert.ifError(child.error); + assert.equal(child.signal, 'SIGKILL', child.stderr); + const before = await f.lease(readRetentionStore); + assert.equal(await f.publish(2, second), 'conflict'); + assert.equal( + await f.lease(root => + reclaimRetentionCheckpoint( + root, + f.request.publication.ref, + f.request.digest, + ), + ), + 'conflict', + ); + assert.equal( + await f.lease(root => + withUnheldCheckpointHead(root, f.head, async () => + assert.fail('HEAD reclaimed'), + ), + ), + false, + ); + assert.deepEqual(await f.lease(readRetentionStore), before); + assert.deepEqual(await f.read(f.request, 'status'), { + selector: { sequence: 1, digest: f.request.digest }, + checkpoint: f.checkpoint, + }); + const key = f.request.destinationReservation; + const journal = await f.lease( + root => reconcileRestoreJournal(root, key), + f.journal, + ); + assert.equal( + journal.phase, + point === 'held' + ? 'absent' + : point === 'reserved' + ? 'rejected' + : 'restored', + ); + const release = (canReleaseRestored: () => Promise) => + f.lease( + journal => + f.lease(root => + releaseCheckpointHold( + root, + f.request, + journal, + { ...f.authority, canReleaseRestored }, + signal, + ), + ), + f.journal, + ); + // An absent journal or a restored receipt without verification cannot unpin. + const released = await release(async () => false); + assert.equal(released, journal.phase === 'rejected'); + if (!released) return; + assert.equal( + await release(async () => assert.fail('terminal proof reread')), + true, + ); + assert.equal(await f.read(), undefined); + assert.equal(await f.publish(2, second), 'applied'); + const reclaim = () => + f.lease(root => + reclaimRetentionCheckpoint( + root, + f.request.publication.ref, + f.request.digest, + ), + ); + assert.equal(await reclaim(), 'applied'); + assert.equal(await reclaim(), 'conflict'); + await assert.rejects(readFile(join(f.store, f.request.digest)), { + code: 'ENOENT', + }); + assert.equal( + (await f.lease(readRetentionStore)).artifacts, + before.artifacts - 1, + ); + }, + ); +} + +test( + 'exact reader denies pending, foreign, released and cross-wired bindings', + options, + async t => { + const f = await fixture(t); + const { request } = f; + const pending = await f.stage(2); + assert.equal( + await f.read({ + ...request, + publication: publication(2), + digest: pending, + }), + undefined, + ); + assert.equal(await f.read({ ...request, digest: pending }), undefined); + const wrongIncarnation = { + ...request, + publication: { + ...request.publication, + lease: { + ...request.publication.lease, + incarnationId: 'd'.repeat(24), + }, + }, + }; + assert.equal(await f.read(wrongIncarnation), undefined); + assert.equal( + (await f.lease(readRetentionStore)).lanes.get(lane)?.restore, + undefined, + ); + assert.ok(await f.read()); + const wrong: RestoreRequest[] = [ + wrongIncarnation, + { ...request, restoreId: hex('1') }, + { ...request, destinationReservation: hex('2') }, + { + ...request, + publication: { ...request.publication, workerId: 'other' }, + }, + { + ...request, + publication: { + ...request.publication, + lease: { + ...request.publication.lease, + ownerScope: hex('3'), + }, + }, + }, + ]; + for (const input of wrong) assert.equal(await f.read(input), undefined); + assert.equal( + await f.read(request, 'status', { + ...f.authority, + isCurrent: () => false, + }), + undefined, + ); + const aborted = AbortSignal.abort(); + assert.equal( + await f.lease(root => + readHeldCheckpoint( + root, + request, + 'status', + f.authority, + aborted, + ), + ), + undefined, + ); + assert.equal( + await f.lease( + journal => + f.lease(root => + releaseCheckpointHold( + root, + wrong[1], + journal, + { + ...f.authority, + canReleaseRestored: async () => + assert.fail('foreign terminal query'), + }, + signal, + ), + ), + f.journal, + ), + false, + ); + }, +); + +test( + 'missing Git pin, corrupt bytes, and ambiguous replacement never return payload', + options, + async t => { + const f = await fixture(t); + f.git('update-ref', '-d', f.pin); + await assert.rejects(f.read()); + f.git('update-ref', f.pin, f.head); + const file = join(f.store, f.request.digest); + const alias = join(f.store, 'alias'); + const bytes = await readFile(file); + await link(file, alias); + await assert.rejects(f.read()); + await unlink(alias); + await writeFile(file, bytes.subarray(0, -1)); + await assert.rejects(f.read()); + await writeFile(file, bytes); + assert.equal( + (await f.lease(readRetentionStore)).lanes.get(lane)?.restore, + undefined, + ); + + await writeFile(join(f.store, '.catalog.tmp'), '', { mode: 0o600 }); + await assert.rejects(f.read(), { code: 'EEXIST' }); + assert.equal(await f.read(f.request, 'status'), undefined); + assert.equal( + await f.lease(root => + CheckpointCatalog.recoverInterruptedReplacement(root, bytes => + Boolean(decodeRetention(bytes)), + ), + ), + true, + ); + assert.ok(await f.read()); + }, +); + +test( + 'a synced-on-reopen hold survives a failed directory sync without disclosure', + options, + async t => { + const f = await fixture(t); + await f.lease(async root => { + const sync = root.sync.bind(root); + let calls = 0; + root.sync = async () => { + if (++calls === 2) + throw new Error('injected hold sync failure'); + await sync(); + }; + await assert.rejects( + readHeldCheckpoint( + root, + f.request, + 'start', + f.authority, + signal, + ), + /hold sync failure/, + ); + await assert.rejects(readRetentionStore(root), /store unavailable/); + }); + assert.equal( + (await f.lease(readRetentionStore)).lanes.get(lane)?.restore?.phase, + 'held', + ); + assert.ok(await f.read(f.request, 'status')); + }, +); + +test( + 'reclamation is fenced while a live consumer holds the artifact', + options, + async t => { + const f = await fixture(t); + const second = await f.stage(2); + const held = await f.read(); + assert.ok(held); + const child = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import assert from 'node:assert/strict'; + import { open } from 'node:fs/promises'; + import { tryLockDescriptor } from ${JSON.stringify( + new URL('./process-lock.js', import.meta.url).href, + )}; + import { reclaimRetentionCheckpoint, withUnheldCheckpointHead } from ${JSON.stringify( + new URL('./checkpoint-retention-store.js', import.meta.url).href, + )}; + const [store, raw, head] = process.argv.slice(1); + const request = JSON.parse(raw); + const root = await open(store); + assert.equal(await tryLockDescriptor(root.fd), true); + assert.equal(await reclaimRetentionCheckpoint(root, request.publication.ref, request.digest), 'conflict'); + assert.equal(await withUnheldCheckpointHead(root, head, async () => assert.fail('reclaimed live HEAD')), false); + await root.close(); + `, + f.store, + JSON.stringify(f.request), + f.head, + ], + { encoding: 'utf8', timeout: 8000 }, + ); + assert.ifError(child.error); + assert.equal(child.status, 0, child.stderr); + assert.equal(await f.publish(2, second), 'conflict'); + assert.deepEqual(held.checkpoint, f.checkpoint); + }, +); diff --git a/packages/code/src/checkpoint-restore.ts b/packages/code/src/checkpoint-restore.ts new file mode 100644 index 00000000..97669f0f --- /dev/null +++ b/packages/code/src/checkpoint-restore.ts @@ -0,0 +1,128 @@ +import { createHash } from 'node:crypto'; + +import type { PublicationAttempt } from './checkpoint-publication.js'; +import type { + CheckpointGit, + WorktreeCheckpoint, +} from './worktree-checkpoint.js'; + +import { publicationPrefix } from './checkpoint-publication.js'; +import { isCheckpointHead, isLane } from './checkpoint-retention.js'; +import { maxStagePayloadBytes } from './checkpoint-stage.js'; +import { restoreData } from './restore-overlay.js'; + +export type RestoreRequest = Readonly<{ + publication: PublicationAttempt; + digest: string; + restoreId: string; + /** Exact journal key of the independently fenced deterministic destination. */ + destinationReservation: string; +}>; + +/** Trusted worker code only. None of these checks can be supplied by a peer. */ +export interface RestoreAuthority { + /** Check paired support, current worker/owner/source and the exact durable destination fence. */ + isCurrent(request: RestoreRequest): boolean; + /** Confined Git reader for the admitted source's shared Git directory, not a peer-supplied path. */ + git: CheckpointGit; +} + +export interface RestoreReleaseAuthority + extends Pick { + /** + * Verify the exact target has a durable decision ending its need for these + * bytes. Read durable evidence only; do not reenter the holding store lease. + * The journal fingerprint alone is not a verification or attach decision. + */ + canReleaseRestored( + request: RestoreRequest, + target: string, + signal: AbortSignal, + ): Promise; +} + +export function restoreBinding(request: RestoreRequest) { + const { digest, restoreId, destinationReservation } = request; + if (![digest, restoreId, destinationReservation].every(isLane)) + throw new Error('Invalid retained restore request'); + const prefix = publicationPrefix(request.publication); + const key = createHash('sha256') + .update('librechat/checkpoint-restore/v1\0') + .update(prefix) + .update(digest) + .update(restoreId) + .update(destinationReservation) + .digest('hex'); + return { prefix, key }; +} + +/** Wire format staged inside the existing proof-bound publication envelope. */ +export function encodeRestoreCheckpoint( + checkpoint: WorktreeCheckpoint, +): Buffer { + const data = restoreData(checkpoint); + const layer = (changes: WorktreeCheckpoint['staged']) => + changes.map(change => + change.mode === null + ? [change.path, null] + : [change.path, change.mode, change.bytes.toString('base64')], + ); + return Buffer.from( + JSON.stringify([ + 'librechat/worktree-checkpoint/v1', + data.head, + layer(data.staged), + layer(data.working), + ]), + ); +} + +export function decodeRestoreCheckpoint(bytes: Buffer): WorktreeCheckpoint { + const invalid = (): never => { + throw new Error('Invalid retained restore payload'); + }; + if (!bytes.length || bytes.length > maxStagePayloadBytes) invalid(); + let value: unknown; + try { + value = JSON.parse( + new TextDecoder('utf-8', { fatal: true }).decode(bytes), + ); + } catch { + return invalid(); + } + if ( + !Array.isArray(value) || + value.length !== 4 || + value[0] !== 'librechat/worktree-checkpoint/v1' || + !isCheckpointHead(value[1]) + ) + return invalid(); + let budget = 8 * 1024 * 1024; + const layer = (items: unknown): WorktreeCheckpoint['staged'] => { + if (!Array.isArray(items) || items.length > 4096) return invalid(); + return items.map(item => { + if (!Array.isArray(item) || typeof item[0] !== 'string') + return invalid(); + const [path, mode, encoded] = item; + if (item.length === 2 && mode === null) return { path, mode }; + if ( + item.length !== 3 || + (mode !== '100644' && mode !== '100755') || + typeof encoded !== 'string' || + encoded.length > + Math.ceil(Math.min(budget, 2 * 1024 * 1024) / 3) * 4 + ) + return invalid(); + const bytes = Buffer.from(encoded, 'base64'); + budget -= bytes.length; + if (budget < 0 || bytes.toString('base64') !== encoded) + return invalid(); + return { path, mode, bytes }; + }); + }; + return restoreData({ + head: value[1], + staged: layer(value[2]), + working: layer(value[3]), + }); +} diff --git a/packages/code/src/checkpoint-retention-codec.ts b/packages/code/src/checkpoint-retention-codec.ts index cb79b682..95a2158f 100644 --- a/packages/code/src/checkpoint-retention-codec.ts +++ b/packages/code/src/checkpoint-retention-codec.ts @@ -2,12 +2,14 @@ import type { Artifact, Lane, Publication, + RestoreHold, State, } from './checkpoint-retention.js'; import { isValidBridgeWorkerId } from './protocol.js'; import { maxStagePayloadBytes, stageNonceBytes } from './checkpoint-stage.js'; import { + isCheckpointHead, isLane, maxArtifacts, maxBytes, @@ -15,7 +17,7 @@ import { } from './checkpoint-retention.js'; // At most 256 lane records and 256 charged artifacts with fixed-width IDs -// and bounded publication bindings, below the catalog cap. +// and bounded publication bindings plus at most one hold per lane. const v1Limit = 128 * 1024; const limit = 256 * 1024; @@ -66,7 +68,7 @@ function wire(state: State) { lane.verified?.publication || lane.pending?.publication, ) || state.garbage.some(artifact => artifact.publication); return { - version: bound ? 2 : 1, + version: lanes.some(([, lane]) => lane.restore) ? 3 : bound ? 2 : 1, lanes, garbage: state.garbage, artifacts: state.artifacts, @@ -82,7 +84,8 @@ function validate(value: unknown): State { 'artifacts', 'bytes', ]); - if (root.version !== 1 && root.version !== 2) invalid(); + if (root.version !== 1 && root.version !== 2 && root.version !== 3) + invalid(); const artifacts = integer(root.artifacts, 0, maxArtifacts); const bytes = integer(root.bytes, 0, maxBytes); const lanes = new Map(); @@ -123,7 +126,7 @@ function validate(value: unknown): State { pending = false, ): Artifact { const bound = - root.version === 2 && + root.version !== 1 && typeof value === 'object' && value !== null && Object.hasOwn(value, 'publication'); @@ -154,10 +157,19 @@ function validate(value: unknown): State { : artifact; } + const restores = new Set(); + const destinations = new Set(); for (const pair of list(root.lanes, maxLanes)) { const [lane, item] = list(pair, 2); if (!isLane(lane) || lanes.has(lane)) invalid(); - const entry = record(item, ['sequence', 'pending', 'verified']); + const keys = ['sequence', 'pending', 'verified']; + const held = + root.version === 3 && + item !== null && + typeof item === 'object' && + Object.hasOwn(item, 'restore'); + if (held) keys.push('restore'); + const entry = record(item, keys); const sequence = integer(entry.sequence, 0); const verified = entry.verified === null ? null : charge(entry.verified, lane); @@ -174,7 +186,61 @@ function validate(value: unknown): State { verified.publication.ownerScope)) ) invalid(); - lanes.set(lane, { sequence, pending, verified }); + let restore: RestoreHold | undefined; + if (held) { + const { + key, + restoreId, + destinationReservation, + sequence: selected, + digest, + head, + phase, + } = record(entry.restore, [ + 'key', + 'restoreId', + 'destinationReservation', + 'sequence', + 'digest', + 'head', + 'phase', + ]); + if ( + !isLane(key) || + !isLane(restoreId) || + !isLane(destinationReservation) || + !isLane(digest) || + !isCheckpointHead(head) || + (phase !== 'held' && phase !== 'released') || + restores.has(restoreId) || + destinations.has(destinationReservation) + ) + invalid(); + const seq = integer(selected, 1, sequence); + if ( + phase === 'held' && + (verified?.ref.sequence !== seq || + verified.publication?.digest !== digest) + ) + invalid(); + restores.add(restoreId); + destinations.add(destinationReservation); + restore = { + key, + restoreId, + destinationReservation, + sequence: seq, + digest, + head, + phase, + }; + } + lanes.set(lane, { + sequence, + pending, + verified, + ...(restore ? { restore } : {}), + }); } const garbage = list(root.garbage, maxArtifacts).map(item => { diff --git a/packages/code/src/checkpoint-retention-store.ts b/packages/code/src/checkpoint-retention-store.ts index a4f2ed69..b518a79a 100644 --- a/packages/code/src/checkpoint-retention-store.ts +++ b/packages/code/src/checkpoint-retention-store.ts @@ -3,7 +3,19 @@ import type { PublicationAttempt, PublicationAuthority, } from './checkpoint-publication.js'; -import type { Ref } from './checkpoint-retention.js'; +import type { Ref, RestoreHold, State } from './checkpoint-retention.js'; +import type { + RestoreAuthority, + RestoreReleaseAuthority, + RestoreRequest, +} from './checkpoint-restore.js'; + +import { reconcileRestoreJournal } from './restore-journal.js'; +import { assertRestorePin } from './restore-overlay.js'; +import { + decodeRestoreCheckpoint, + restoreBinding, +} from './checkpoint-restore.js'; import { decodeRetention, @@ -11,6 +23,7 @@ import { } from './checkpoint-retention-codec.js'; import { emptyRetention, + isCheckpointHead, isLane, transitionRetention, } from './checkpoint-retention.js'; @@ -195,6 +208,7 @@ export async function publishRetentionCheckpoint( const { lane, sequence } = requested.ref; const current = state.lanes.get(lane); if (!current) return 'missing'; + if (current.restore?.phase === 'held') return 'conflict'; if (!matchesScope(requested, current.verified?.publication)) return 'conflict'; const pending = current.pending; @@ -239,3 +253,238 @@ export async function publishRetentionCheckpoint( return result.status; }); } + +function replaceHold(state: State, lane: string, restore: RestoreHold): Buffer { + const entry = state.lanes.get(lane); + if (!entry) throw new Error('Retained restore source is missing'); + const lanes = new Map(state.lanes); + lanes.set(lane, { ...entry, restore }); + return encodeRetention({ ...state, lanes }); +} + +/** + * Exact restore read under the private store lease AND an independently admitted + * exclusive destination reservation. Status may only resume an existing hold. + * No journal or destination is created here. The caller keeps its destination + * fence through consumption; the durable retention hold outlives either lease. + * The producer must already have durably installed the worker-owned Git ref. + * All removers of those refs must take the same lease and check holds below. + * Unsupported, revoked or mismatched reservations must never reach materialization. + */ +export async function readHeldCheckpoint( + root: FileHandle, + request: RestoreRequest, + mode: 'start' | 'status', + authority: RestoreAuthority, + signal: AbortSignal, +) { + if (mode !== 'start' && mode !== 'status') return; + const requested = structuredClone(request); + const { publication, digest, restoreId, destinationReservation } = + requested; + const { key, prefix } = restoreBinding(requested); + const { lane, sequence } = publication.ref; + return use(root, async () => { + if ( + signal.aborted || + authority.isCurrent(structuredClone(requested)) !== true + ) + return; + const catalog = await CheckpointCatalog.open(root); + const state = decodeRetention(await catalog.read()); + const current = state.lanes.get(lane); + const artifact = current?.verified; + const binding = artifact?.publication; + if ( + artifact?.ref.sequence !== sequence || + !binding || + binding.digest !== digest || + !matchesScope(publication, binding) + ) + return; + const prior = current?.restore; + if (prior) { + if ( + prior.phase !== 'held' || + prior.key !== key || + prior.restoreId !== restoreId || + prior.destinationReservation !== destinationReservation + ) + return; + } else { + if (mode !== 'start') return; + for (const entry of state.lanes.values()) { + if ( + entry.restore?.restoreId === restoreId || + entry.restore?.destinationReservation === + destinationReservation + ) + return; + } + } + const bytes = await new CheckpointStage(root).read( + digest, + binding.payloadBytes, + ); + if ( + bytes.length <= prefix.length || + !bytes.subarray(0, prefix.length).equals(prefix) + ) + return; + const checkpoint = decodeRestoreCheckpoint( + bytes.subarray(prefix.length), + ); + if (prior && prior.head !== checkpoint.head) return; + await assertRestorePin(authority.git, checkpoint.head, signal); + // A matching ref alone doesn't establish that its commit is present. + const type = await authority.git(['cat-file', '-t', checkpoint.head], { + maxBytes: 32, + signal, + }); + if (!type.equals(Buffer.from('commit\n'))) return; + if ( + signal.aborted || + authority.isCurrent(structuredClone(requested)) !== true + ) + return; + if (!prior) { + await catalog.replace( + replaceHold(state, lane, { + key, + restoreId, + destinationReservation, + sequence, + digest, + head: checkpoint.head, + phase: 'held', + }), + ); + if ( + signal.aborted || + authority.isCurrent(structuredClone(requested)) !== true + ) + return; + } + return { selector: { sequence, digest }, checkpoint }; + }); +} + +/** + * Compare-release under the same exclusive destination fence as the reader. + * Borrow its already isolated journal; acquire the destination fence before + * the store lease. Only an exact durable journal outcome can permit release. + * As with restore status, reconciling an interrupted reservation requires + * proving the old materializer is stopped before borrowing this journal. + * Never infer terminality from lease loss, process death or elapsed time. The + * tombstone prevents the source's one-shot restore journal from being reopened + * as a different attempt; it does not keep the artifact rooted. + */ +export async function releaseCheckpointHold( + root: FileHandle, + request: RestoreRequest, + journal: FileHandle, + authority: RestoreReleaseAuthority, + signal: AbortSignal, +): Promise { + const requested = structuredClone(request); + const { key } = restoreBinding(requested); + const { lane } = requested.publication.ref; + return use(root, async () => { + if ( + signal.aborted || + authority.isCurrent(structuredClone(requested)) !== true + ) + return false; + const catalog = await CheckpointCatalog.open(root); + const state = decodeRetention(await catalog.read()); + const prior = state.lanes.get(lane)?.restore; + if ( + !prior || + prior.key !== key || + prior.restoreId !== requested.restoreId || + prior.destinationReservation !== requested.destinationReservation + ) + return false; + if (prior.phase === 'released') return true; + if (root === journal) return false; + const terminal = await reconcileRestoreJournal( + journal, + prior.destinationReservation, + ); + if (terminal.phase === 'absent') return false; + if ( + terminal.phase === 'restored' && + (signal.aborted || + authority.isCurrent(structuredClone(requested)) !== true || + (await authority.canReleaseRestored( + structuredClone(requested), + terminal.target, + signal, + )) !== true) + ) + return false; + if ( + signal.aborted || + authority.isCurrent(structuredClone(requested)) !== true + ) + return false; + await catalog.replace( + replaceHold(state, lane, { ...prior, phase: 'released' }), + ); + return true; + }); +} + +/** + * Required fence for worker-owned checkpoint HEAD ref removal. Callers hold the + * same exclusive private store lease and must separately exclude all other + * Git retention roots and concurrent writers. A common Git directory must not + * share checkpoint refs with an unfenced reclamation path or another catalog. + * Keep the lease until deletion (and any Git subprocess) has fully settled. + * This never runs Git GC, removes a source lane, or releases a catalog charge. + */ +export function withUnheldCheckpointHead( + root: FileHandle, + head: string, + reclaim: () => Promise, +): Promise { + return use(root, async () => { + if (!isCheckpointHead(head)) return false; + const catalog = await CheckpointCatalog.open(root); + const state = decodeRetention(await catalog.read()); + for (const lane of state.lanes.values()) { + if (lane.restore?.phase === 'held' && lane.restore.head === head) + return false; + } + await reclaim(); + return true; + }); +} + +/** Reclaim one known proof-bound garbage entry, never a pending or verified root. */ +export function reclaimRetentionCheckpoint( + root: FileHandle, + ref: Ref, + digest: string, +): Promise { + const requested = structuredClone(ref); + return use(root, async () => { + const catalog = await CheckpointCatalog.open(root); + const state = decodeRetention(await catalog.read()); + const entry = state.garbage.find( + ({ ref }) => + ref.lane === requested.lane && + ref.sequence === requested.sequence, + ); + const binding = entry?.publication; + if (!binding || binding.digest !== digest) return 'conflict'; + const result = transitionRetention(state, { + kind: 'reclaimed', + ref: requested, + }); + if (result.status !== 'applied') return result.status; + await new CheckpointStage(root).reclaim(digest, binding.payloadBytes); + await catalog.replace(encodeRetention(result.state)); + return result.status; + }); +} diff --git a/packages/code/src/checkpoint-retention.ts b/packages/code/src/checkpoint-retention.ts index 05e9f7d1..98e2a174 100644 --- a/packages/code/src/checkpoint-retention.ts +++ b/packages/code/src/checkpoint-retention.ts @@ -16,10 +16,20 @@ export type Artifact = Readonly<{ publication?: Publication; }>; type Pending = Artifact & Readonly<{ expiresAt: number }>; +export type RestoreHold = Readonly<{ + key: string; + restoreId: string; + destinationReservation: string; + sequence: number; + digest: string; + head: string; + phase: 'held' | 'released'; +}>; export type Lane = Readonly<{ sequence: number; pending: Pending | null; verified: Artifact | null; + restore?: RestoreHold; }>; export type State = Readonly<{ lanes: ReadonlyMap; @@ -71,6 +81,14 @@ export function isLane(value: unknown): value is string { ); } +export function isCheckpointHead(value: unknown): value is string { + return ( + typeof value === 'string' && + (value.length === 40 || value.length === 64) && + /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value) + ); +} + function time(value: number): boolean { return Number.isSafeInteger(value) && value >= 0; } @@ -178,6 +196,8 @@ export function transitionRetention( { garbage: [...state.garbage, candidate] }, ); } + // Rotation would remove the exact verified root needed for restart. + if (current.restore?.phase === 'held') return reject('conflict'); if (!time(command.now)) return reject('invalid'); if (pending.expiresAt <= command.now) return reject('expired'); if (!same(current.verified?.ref ?? null, command.expectedVerified)) diff --git a/packages/code/src/checkpoint-stage.ts b/packages/code/src/checkpoint-stage.ts index 5bd0f822..0185f9d2 100644 --- a/packages/code/src/checkpoint-stage.ts +++ b/packages/code/src/checkpoint-stage.ts @@ -1,6 +1,6 @@ import { createHash, randomBytes } from 'node:crypto'; import { constants } from 'node:fs'; -import { link, open, opendir, unlink } from 'node:fs/promises'; +import { link, lstat, open, opendir, unlink } from 'node:fs/promises'; import type { FileHandle } from 'node:fs/promises'; export const maxStagePayloadBytes = 16 * 1024 * 1024; @@ -85,6 +85,29 @@ export class CheckpointStage { } } + /** Only after catalog GC proves this exact artifact unreachable under the store lease. */ + async reclaim(digest: string, payloadBytes: number): Promise { + if (!key.test(digest)) unavailable(); + const path = `${await this.directory()}/${digest}`; + const info = await lstat(path).catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') return undefined; + throw error; + }); + if (info) { + if ( + !info.isFile() || + info.uid !== process.getuid?.() || + (info.mode & 0o7777) !== 0o600 || + info.nlink !== 1 || + info.size !== payloadBytes + stageNonceBytes + ) + unavailable(); + await unlink(path); + } + // A retry after unlink but before metadata commit must sync absence too. + await this.root.sync(); + } + /** Only returns intact staged bytes; a caller must separately consume fresh bridge proof. */ async read(digest: string, expectedPayloadBytes?: number): Promise { if (!key.test(digest)) unavailable();