From 3d70ea558e638d849ed16ffb0238ca087c7f258d Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Sat, 5 Dec 2026 08:31:00 -0500 Subject: [PATCH] feat(worker): Bind retained checkpoints to paired publication proof --- packages/code/src/checkpoint-publication.ts | 103 +++++ .../code/src/checkpoint-retention-codec.ts | 115 ++++-- .../src/checkpoint-retention-store.test.ts | 391 ++++++++++++++++-- .../code/src/checkpoint-retention-store.ts | 177 +++++++- packages/code/src/checkpoint-retention.ts | 33 +- packages/code/src/checkpoint-stage.ts | 28 +- 6 files changed, 759 insertions(+), 88 deletions(-) create mode 100644 packages/code/src/checkpoint-publication.ts diff --git a/packages/code/src/checkpoint-publication.ts b/packages/code/src/checkpoint-publication.ts new file mode 100644 index 00000000..a4652108 --- /dev/null +++ b/packages/code/src/checkpoint-publication.ts @@ -0,0 +1,103 @@ +import { isValidBridgeWorkerId } from './protocol.js'; +import { isLane } from './checkpoint-retention.js'; +import { validManagedWorktreeCreationLease } from './worktree-baseline.js'; + +import type { ManagedWorktreeCreationLease } from './worktree-baseline.js'; +import type { Ref } from './checkpoint-retention.js'; + +export type PublicationAttempt = Readonly<{ + workerId: string; + ref: Ref; + lease: ManagedWorktreeCreationLease; + epoch: string; +}>; + +export type ProofQuery = Readonly<{ + version: 1; + workerId: string; + assignmentId: string; + originalIncarnationId: string; + generation: number; + slot: number; + epoch: string; + commitment: string; +}>; + +/** Supplied only by the worker, never by an executor or a request body. */ +export interface PublicationAuthority { + /** Read the fresh certificate over the current paired, authenticated bridge connection. */ + readPairedProof(query: ProofQuery, signal: AbortSignal): Promise; + /** Check current enrollment, exact source incarnation, pairing and local commit fence. */ + isCurrent(attempt: PublicationAttempt): boolean; +} + +export function proofQuery( + attempt: PublicationAttempt, + commitment: string, +): ProofQuery { + const { workerId, lease, epoch } = attempt; + return Object.freeze({ + version: 1, + workerId, + assignmentId: lease.assignmentId, + originalIncarnationId: lease.incarnationId, + generation: lease.generation, + slot: lease.slot, + epoch, + commitment, + }); +} + +/** The bridge's proven response excludes workerId; authenticated routing binds it. */ +export function exactPairedProof(value: unknown, query: ProofQuery): boolean { + if ( + value === null || + typeof value !== 'object' || + Array.isArray(value) || + Object.keys(value).length !== 9 + ) + return false; + const { workerId: _worker, ...expected } = query; + const proof = value as Record; + return ( + Object.hasOwn(proof, 'state') && + proof.state === 'proven' && + Object.hasOwn(proof, 'committedAtMs') && + typeof proof.committedAtMs === 'number' && + Number.isSafeInteger(proof.committedAtMs) && + proof.committedAtMs > 0 && + Object.entries(expected).every( + ([key, field]) => Object.hasOwn(proof, key) && proof[key] === field, + ) + ); +} + +/** Exact prefix included in the commitment, not an independently trusted sidecar. */ +export function publicationPrefix(attempt: PublicationAttempt): Buffer { + const { workerId, ref, lease, epoch } = attempt; + if ( + typeof workerId !== 'string' || + !isValidBridgeWorkerId(workerId) || + !isLane(ref.lane) || + !Number.isSafeInteger(ref.sequence) || + ref.sequence < 1 || + !validManagedWorktreeCreationLease(lease) || + typeof epoch !== 'string' || + !/^[1-9][0-9]{0,18}$/.test(epoch) + ) + throw new Error('Invalid checkpoint publication attempt'); + return Buffer.from( + JSON.stringify([ + 'librechat/checkpoint-publication/v1', + workerId, + lease.ownerScope, + ref.lane, + ref.sequence, + lease.assignmentId, + lease.incarnationId, + lease.generation, + lease.slot, + epoch, + ]) + '\n', + ); +} diff --git a/packages/code/src/checkpoint-retention-codec.ts b/packages/code/src/checkpoint-retention-codec.ts index 6ec3c236..cb79b682 100644 --- a/packages/code/src/checkpoint-retention-codec.ts +++ b/packages/code/src/checkpoint-retention-codec.ts @@ -1,5 +1,12 @@ -import type { Artifact, Lane, State } from './checkpoint-retention.js'; +import type { + Artifact, + Lane, + Publication, + State, +} from './checkpoint-retention.js'; +import { isValidBridgeWorkerId } from './protocol.js'; +import { maxStagePayloadBytes, stageNonceBytes } from './checkpoint-stage.js'; import { isLane, maxArtifacts, @@ -8,9 +15,9 @@ import { } from './checkpoint-retention.js'; // At most 256 lane records and 256 charged artifacts with fixed-width IDs -// and safe integers. Leave slack above the largest v1 encoding, below the catalog cap. -const limit = 128 * 1024; -const version = 1; +// and bounded publication bindings, below the catalog cap. +const v1Limit = 128 * 1024; +const limit = 256 * 1024; function invalid(): never { throw new Error('Invalid checkpoint retention payload'); @@ -18,7 +25,7 @@ function invalid(): never { function record( value: unknown, - keys: readonly string[] + keys: readonly string[], ): Record { if (typeof value !== 'object' || value === null || Array.isArray(value)) invalid(); @@ -38,7 +45,7 @@ function list(value: unknown, max: number): readonly unknown[] { function integer( value: unknown, min: number, - max = Number.MAX_SAFE_INTEGER + max = Number.MAX_SAFE_INTEGER, ): number { if ( typeof value !== 'number' || @@ -52,9 +59,15 @@ function integer( } function wire(state: State) { + const lanes = [...state.lanes]; + const bound = + lanes.some( + ([, lane]) => + lane.verified?.publication || lane.pending?.publication, + ) || state.garbage.some(artifact => artifact.publication); return { - version, - lanes: [...state.lanes], + version: bound ? 2 : 1, + lanes, garbage: state.garbage, artifacts: state.artifacts, bytes: state.bytes, @@ -69,16 +82,54 @@ function validate(value: unknown): State { 'artifacts', 'bytes', ]); - if (root.version !== version) invalid(); + if (root.version !== 1 && root.version !== 2) invalid(); const artifacts = integer(root.artifacts, 0, maxArtifacts); const bytes = integer(root.bytes, 0, maxBytes); const lanes = new Map(); const charged = new Set(); let total = 0; + const digests = new Set(); + function publication(value: unknown, size: number): Publication { + const { workerId, ownerScope, digest, payloadBytes } = record(value, [ + 'workerId', + 'ownerScope', + 'digest', + 'payloadBytes', + ]); + if ( + typeof workerId !== 'string' || + !isValidBridgeWorkerId(workerId) || + !isLane(ownerScope) || + !isLane(digest) || + digests.has(digest) || + size > maxStagePayloadBytes + stageNonceBytes + ) + invalid(); + const length = integer(payloadBytes, 1, maxStagePayloadBytes); + if (length + stageNonceBytes !== size) invalid(); + digests.add(digest); + return { workerId, ownerScope, digest, payloadBytes: length }; + } + function charge( - entry: Record, - expected?: string + value: unknown, + expected: string, + pending: true, + ): NonNullable; + function charge(value: unknown, expected?: string): Artifact; + function charge( + value: unknown, + expected?: string, + pending = false, ): Artifact { + const bound = + root.version === 2 && + typeof value === 'object' && + value !== null && + Object.hasOwn(value, 'publication'); + const keys = pending ? ['ref', 'bytes', 'expiresAt'] : ['ref', 'bytes']; + if (bound) keys.push('publication'); + const entry = record(value, keys); const { lane, sequence } = record(entry.ref, ['lane', 'sequence']); if (!isLane(lane) || (expected !== undefined && lane !== expected)) invalid(); @@ -93,7 +144,14 @@ function validate(value: unknown): State { invalid(); charged.add(key); total += size; - return { ref: { lane, sequence: seq }, bytes: size }; + const artifact = { + ref: { lane, sequence: seq }, + bytes: size, + ...(pending ? { expiresAt: integer(entry.expiresAt, 1) } : {}), + }; + return bound + ? { ...artifact, publication: publication(entry.publication, size) } + : artifact; } for (const pair of list(root.lanes, maxLanes)) { @@ -102,27 +160,25 @@ function validate(value: unknown): State { const entry = record(item, ['sequence', 'pending', 'verified']); const sequence = integer(entry.sequence, 0); const verified = - entry.verified === null - ? null - : charge(record(entry.verified, ['ref', 'bytes']), lane); - const candidate = - entry.pending === null - ? null - : record(entry.pending, ['ref', 'bytes', 'expiresAt']); - const pending = candidate && { - ...charge(candidate, lane), - expiresAt: integer(candidate.expiresAt, 1), - }; + entry.verified === null ? null : charge(entry.verified, lane); + const pending = + entry.pending === null ? null : charge(entry.pending, lane, true); if ( (pending && pending.ref.sequence !== sequence) || - (verified && verified.ref.sequence > sequence) + (verified && verified.ref.sequence > sequence) || + (pending?.publication && + verified?.publication && + (pending.publication.workerId !== + verified.publication.workerId || + pending.publication.ownerScope !== + verified.publication.ownerScope)) ) invalid(); lanes.set(lane, { sequence, pending, verified }); } const garbage = list(root.garbage, maxArtifacts).map(item => { - const entry = charge(record(item, ['ref', 'bytes'])); + const entry = charge(item); const lane = lanes.get(entry.ref.lane); if (!lane || entry.ref.sequence > lane.sequence) invalid(); return entry; @@ -151,8 +207,11 @@ export function decodeRetention(payload: Buffer): State { invalid(); } const state = validate(value); - // Byte equality enforces the v1 wire spelling and rejects duplicate fields - // and malformed UTF-8 that JSON.parse could otherwise normalize. - if (!serialize(state).equals(payload)) invalid(); + // Byte equality rejects duplicate fields, invalid UTF-8 and noncanonical versions. + if ( + (payload.length > v1Limit && wire(state).version === 1) || + !serialize(state).equals(payload) + ) + invalid(); return state; } diff --git a/packages/code/src/checkpoint-retention-store.test.ts b/packages/code/src/checkpoint-retention-store.test.ts index 0d3ab884..eeccf67b 100644 --- a/packages/code/src/checkpoint-retention-store.test.ts +++ b/packages/code/src/checkpoint-retention-store.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; import { constants } from 'node:fs'; import { mkdtemp, @@ -19,7 +20,16 @@ import { applyRetentionStore, initializeRetentionStore, readRetentionStore, + publishRetentionCheckpoint, + stageRetentionPublication, } from './checkpoint-retention-store.js'; +import { publicationPrefix } from './checkpoint-publication.js'; +import { CheckpointStage } from './checkpoint-stage.js'; +import type { + ProofQuery, + PublicationAttempt, + PublicationAuthority, +} from './checkpoint-publication.js'; import { emptyRetention } from './checkpoint-retention.js'; import { CheckpointCatalog } from './checkpoint-catalog.js'; import { tryLockDescriptor } from './process-lock.js'; @@ -36,25 +46,52 @@ const reserve = (expectedSequence: number) => bytes: 4, now: 0, expiresAt: 10, - } as const); -const promote = (sequence: number) => - ({ - kind: 'promote', - ref: ref(sequence), - expectedVerified: sequence === 1 ? null : ref(sequence - 1), - now: 1, - } as const); + }) as const; +const attempt = (sequence: number): PublicationAttempt => ({ + workerId: 'worker', + ref: ref(sequence), + lease: { + ownerScope: 'b'.repeat(64), + assignmentId: `durable-${String(sequence).padStart(24, '0')}`, + incarnationId: 'c'.repeat(24), + generation: sequence, + slot: 0, + }, + epoch: String(sequence), +}); +const proof = ({ workerId: _worker, ...query }: ProofQuery) => ({ + ...query, + state: 'proven', + committedAtMs: 1, +}); +const authority: PublicationAuthority = { + readPairedProof: async query => proof(query), + isCurrent: () => true, +}; +const payload = Buffer.from('pinned HEAD and captured bytes'); + +async function stage(root: FileHandle, sequence: number) { + const result = await stageRetentionPublication( + root, + attempt(sequence), + payload, + Date.now() + 60_000, + ); + assert.equal(result.status, 'applied'); + assert.ok(result.commitment); + return result.commitment; +} async function fixture(t: TestContext) { const dir = await mkdtemp(join(tmpdir(), 'checkpoint-retention-')); t.after(() => rm(dir, { recursive: true, force: true })); // Use real flock without a production grant verifier or mount admission. async function lease( - operation: (root: FileHandle) => Promise + operation: (root: FileHandle) => Promise, ): Promise { const root = await open( dir, - constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW + constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW, ); try { assert.equal(await tryLockDescriptor(root.fd), true); @@ -75,29 +112,81 @@ test( lease(root => applyRetentionStore(root, command)); await lease(initializeRetentionStore); assert.deepEqual(await lease(readRetentionStore), emptyRetention()); - for (const command of [enroll, reserve(0), promote(1), reserve(1)]) { - assert.equal(await apply(command), 'applied'); - } + assert.equal(await apply(enroll), 'applied'); + const first = await lease(root => stage(root, 1)); + const secondAttempt = attempt(2); + assert.equal( + await lease(root => + publishRetentionCheckpoint( + root, + attempt(1), + first, + null, + authority, + ), + ), + 'applied', + ); + const second = await lease(root => stage(root, 2)); const before = await lease(readRetentionStore); const inode = (await stat(file)).ino; assert.equal(await apply(reserve(2)), 'conflict'); assert.equal((await stat(file)).ino, inode); - assert.equal(await apply(promote(2)), 'applied'); + assert.equal( + await lease(root => + publishRetentionCheckpoint( + root, + secondAttempt, + second, + ref(1), + authority, + ), + ), + 'applied', + ); assert.notEqual((await stat(file)).ino, inode); const after = await lease(readRetentionStore); + const binding = (sequence: number, digest: string) => { + const payloadBytes = + publicationPrefix(attempt(sequence)).length + payload.length; + return { + ref: ref(sequence), + bytes: payloadBytes + 32, + publication: { + workerId: 'worker', + ownerScope: attempt(sequence).lease.ownerScope, + digest, + payloadBytes, + }, + }; + }; assert.deepEqual(after.lanes.get(lane), { sequence: 2, pending: null, - verified: { ref: ref(2), bytes: 4 }, + verified: binding(2, second), }); - assert.deepEqual(after.garbage, [{ ref: ref(1), bytes: 4 }]); + assert.deepEqual(after.garbage, [binding(1, first)]); assert.equal(after.bytes, before.bytes); assert.equal(after.artifacts, before.artifacts); const committed = (await stat(file)).ino; - assert.equal(await apply(promote(2)), 'already-current'); + assert.equal( + await lease(root => + publishRetentionCheckpoint( + root, + secondAttempt, + second, + ref(1), + authority, + ), + ), + 'conflict', + ); assert.equal((await stat(file)).ino, committed); - assert.deepEqual(await readdir(dir), ['catalog']); - } + assert.deepEqual( + await lease(root => new CheckpointStage(root).read(second)), + Buffer.concat([publicationPrefix(secondAttempt), payload]), + ); + }, ); test( @@ -107,31 +196,31 @@ test( const { dir, file, lease } = await fixture(t); await assert.rejects( lease(root => applyRetentionStore(root, enroll)), - { code: 'ENOENT' } + { code: 'ENOENT' }, ); assert.deepEqual(await readdir(dir), []); await lease(async root => { await CheckpointCatalog.initialize( root, Buffer.from( - '{"version":1,"lanes":[],"garbage":[],"artifacts":1,"bytes":1}' - ) + '{"version":1,"lanes":[],"garbage":[],"artifacts":1,"bytes":1}', + ), ); }); const bytes = await readFile(file); await assert.rejects( lease(readRetentionStore), - /Invalid checkpoint retention payload/ + /Invalid checkpoint retention payload/, ); await assert.rejects( lease(root => applyRetentionStore(root, enroll)), - /Invalid checkpoint retention payload/ + /Invalid checkpoint retention payload/, ); await assert.rejects(lease(initializeRetentionStore), /already exists/); assert.deepEqual(await readFile(file), bytes); await unlink(file); assert.deepEqual(await readdir(dir), []); - } + }, ); test( @@ -144,30 +233,30 @@ test( const first = applyRetentionStore(root, enroll); await assert.rejects( applyRetentionStore(root, enroll), - /unavailable/ + /unavailable/, ); assert.equal(await first, 'applied'); assert.equal( await applyRetentionStore(root, reserve(0)), - 'applied' + 'applied', ); assert.equal( await applyRetentionStore(root, { kind: 'discard', ref: ref(1), }), - 'applied' + 'applied', ); const before = await readFile(file); await assert.rejects( // @ts-expect-error The dark store must not acknowledge reclamation. applyRetentionStore(root, { kind: 'reclaimed', ref: ref(1) }), - /Invalid checkpoint retention store command/ + /Invalid checkpoint retention store command/, ); assert.deepEqual(await readFile(file), before); assert.equal((await readRetentionStore(root)).bytes, 4); }); - } + }, ); test( @@ -186,12 +275,250 @@ test( }); await assert.rejects( applyRetentionStore(root, enroll), - /injected directory sync failure/ + /injected directory sync failure/, ); await assert.rejects(readRetentionStore(root), /unavailable/); assert.equal(calls, 2); }); const state = await lease(readRetentionStore); assert.equal(state.lanes.get(lane)?.sequence, 0); - } + }, +); + +test( + 'rejects mismatched proof, stage and source scope without publishing', + options, + async t => { + const { lease, file, dir } = await fixture(t); + await lease(initializeRetentionStore); + await lease(root => applyRetentionStore(root, enroll)); + const digest = await lease(root => stage(root, 1)); + const requested = attempt(1); + const crosswired = await lease(root => + new CheckpointStage(root).stage( + Buffer.concat([ + publicationPrefix(requested), + Buffer.alloc(payload.length, 1), + ]), + ), + ); + const publish = ( + overrides: Partial = {}, + input = requested, + commitment = digest, + ) => + lease(root => + publishRetentionCheckpoint(root, input, commitment, null, { + ...authority, + ...overrides, + }), + ); + const before = await readFile(file); + for (const wrong of [ + { ...requested, workerId: 'other' }, + { + ...requested, + lease: { ...requested.lease, ownerScope: 'd'.repeat(64) }, + }, + { ...requested, ref: { lane: 'd'.repeat(64), sequence: 1 } }, + { ...requested, ref: ref(2) }, + { + ...requested, + lease: { ...requested.lease, incarnationId: 'd'.repeat(24) }, + }, + ]) { + assert.notEqual( + await publish( + { + readPairedProof: async () => + assert.fail('unexpected proof read'), + }, + wrong, + ), + 'applied', + ); + } + assert.equal( + await publish( + { + readPairedProof: async () => + assert.fail('unexpected proof read'), + }, + requested, + crosswired, + ), + 'conflict', + ); + for (const mismatch of [ + { version: 2 }, + { assignmentId: 'other' }, + { originalIncarnationId: 'other' }, + { epoch: '2' }, + { slot: 1 }, + { generation: 2 }, + { commitment: crosswired }, + { committedAtMs: 0 }, + { extra: true }, + ]) { + assert.equal( + await publish({ + readPairedProof: async query => ({ + ...proof(query), + ...mismatch, + }), + }), + 'unavailable', + ); + } + for (const response of [ + { state: 'pending' }, + { state: 'unavailable' }, + { version: 1, epoch: '1' }, + ]) { + assert.equal( + await publish({ readPairedProof: async () => response }), + 'unavailable', + ); + } + let current = true; + assert.equal( + await publish({ + readPairedProof: async query => { + current = false; + return proof(query); + }, + isCurrent: () => current, + }), + 'unavailable', + ); + await assert.rejects( + lease(root => + applyRetentionStore(root, { + // @ts-expect-error Raw promotion must not cross the catalog adapter. + kind: 'promote', + ref: ref(1), + expectedVerified: null, + now: 1, + }), + ), + /Invalid checkpoint retention store command/, + ); + assert.deepEqual(await readFile(file), before); + await unlink(join(dir, digest)); + await assert.rejects( + publish({ + readPairedProof: async () => + assert.fail('unexpected proof read'), + }), + { code: 'ENOENT' }, + ); + assert.deepEqual(await readFile(file), before); + }, +); + +for (const point of ['before-publish', 'after-publish']) { + test( + `retains exactly the staged HEAD and bytes after SIGKILL ${point}`, + options, + async t => { + const { dir, lease } = await fixture(t); + await lease(initializeRetentionStore); + await lease(root => applyRetentionStore(root, enroll)); + const input = attempt(1); + const captured = Buffer.from( + JSON.stringify({ + head: 'a'.repeat(40), + staged: 'index', + working: 'worktree', + }), + ); + const child = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import assert from 'node:assert/strict'; + import { open } from 'node:fs/promises'; + import { stageRetentionPublication, publishRetentionCheckpoint } from ${JSON.stringify(new URL('./checkpoint-retention-store.js', import.meta.url).href)}; + import { tryLockDescriptor } from ${JSON.stringify(new URL('./process-lock.js', import.meta.url).href)}; + const [dir, input, captured, point] = process.argv.slice(1); + const root = await open(dir); + assert.equal(await tryLockDescriptor(root.fd), true); + const attempt = JSON.parse(input); + const { status, commitment } = await stageRetentionPublication(root, attempt, Buffer.from(captured), Date.now() + 60_000); + assert.equal(status, 'applied'); + if (point === 'after-publish') { + assert.equal(await publishRetentionCheckpoint(root, attempt, commitment, null, { + isCurrent: () => true, + readPairedProof: async ({ workerId, ...query }) => ({ ...query, state: 'proven', committedAtMs: 1 }), + }), 'applied'); + } + process.kill(process.pid, 'SIGKILL'); + `, + dir, + JSON.stringify(input), + captured.toString(), + point, + ], + { encoding: 'utf8', timeout: 10_000 }, + ); + assert.ifError(child.error); + assert.equal(child.signal, 'SIGKILL', child.stderr); + const lane = (await lease(readRetentionStore)).lanes.get( + input.ref.lane, + ); + const verified = point === 'after-publish'; + assert.equal(Boolean(lane?.verified), verified); + assert.equal(Boolean(lane?.pending), !verified); + const binding = (verified ? lane?.verified : lane?.pending) + ?.publication; + assert.ok(binding); + const bytes = await lease(root => + new CheckpointStage(root).read( + binding.digest, + binding.payloadBytes, + ), + ); + assert.deepEqual( + bytes, + Buffer.concat([publicationPrefix(input), captured]), + ); + }, + ); +} + +test( + 'an ambiguous publication sync cannot report success or reuse the lease', + options, + async t => { + const { lease } = await fixture(t); + await lease(initializeRetentionStore); + await lease(root => applyRetentionStore(root, enroll)); + const digest = await lease(root => stage(root, 1)); + await lease(async root => { + const sync = root.sync.bind(root); + let calls = 0; + t.mock.method(root, 'sync', async () => { + if (++calls === 2) + throw new Error('injected publication sync failure'); + await sync(); + }); + await assert.rejects( + publishRetentionCheckpoint( + root, + attempt(1), + digest, + null, + authority, + ), + /injected publication sync failure/, + ); + await assert.rejects(readRetentionStore(root), /unavailable/); + }); + const verified = (await lease(readRetentionStore)).lanes.get( + lane, + )?.verified; + assert.equal(verified?.publication?.digest, digest); + }, ); diff --git a/packages/code/src/checkpoint-retention-store.ts b/packages/code/src/checkpoint-retention-store.ts index fea99c48..a4f2ed69 100644 --- a/packages/code/src/checkpoint-retention-store.ts +++ b/packages/code/src/checkpoint-retention-store.ts @@ -1,15 +1,34 @@ import type { FileHandle } from 'node:fs/promises'; +import type { + PublicationAttempt, + PublicationAuthority, +} from './checkpoint-publication.js'; +import type { Ref } from './checkpoint-retention.js'; import { decodeRetention, encodeRetention, } from './checkpoint-retention-codec.js'; -import { emptyRetention, transitionRetention } from './checkpoint-retention.js'; +import { + emptyRetention, + isLane, + transitionRetention, +} from './checkpoint-retention.js'; import { CheckpointCatalog } from './checkpoint-catalog.js'; +import { + CheckpointStage, + maxStagePayloadBytes, + stageNonceBytes, +} from './checkpoint-stage.js'; +import { + exactPairedProof, + proofQuery, + publicationPrefix, +} from './checkpoint-publication.js'; type Command = Exclude< Parameters[1], - { kind: 'reclaimed' } + { kind: 'reclaimed' | 'promote' } >; type Status = ReturnType['status']; @@ -22,7 +41,7 @@ const active = new WeakSet(); */ async function use( root: FileHandle, - operation: () => Promise + operation: () => Promise, ): Promise { if (active.has(root)) throw new Error('Checkpoint retention store unavailable'); @@ -39,7 +58,7 @@ export function initializeRetentionStore(root: FileHandle): Promise { return use(root, async () => { await CheckpointCatalog.initialize( root, - encodeRetention(emptyRetention()) + encodeRetention(emptyRetention()), ); }); } @@ -53,19 +72,17 @@ export function readRetentionStore(root: FileHandle) { } /** - * Dark bookkeeping only. Live authority, durable bytes and fresh proof must - * be joined under the commit fence before wiring promotion into the runtime. - * The input is a trusted internal command; no operation releases charges. + * Trusted internal bookkeeping only. No raw promotion or charge release. + * Callers with captured bytes use stageRetentionPublication instead of reserve. */ export async function applyRetentionStore( root: FileHandle, - command: Command + command: Command, ): Promise { const requested = structuredClone(command); switch (requested.kind) { case 'enroll': case 'reserve': - case 'promote': case 'discard': break; default: @@ -75,10 +92,150 @@ export async function applyRetentionStore( const catalog = await CheckpointCatalog.open(root); const result = transitionRetention( decodeRetention(await catalog.read()), - requested + requested, ); if (result.status === 'applied') await catalog.replace(encodeRetention(result.state)); return result.status; }); } + +function matchesScope( + attempt: PublicationAttempt, + current: { workerId: string; ownerScope: string } | undefined, +): boolean { + return ( + !current || + (current.workerId === attempt.workerId && + current.ownerScope === attempt.lease.ownerScope) + ); +} + +/** + * Called under capture admission with the same exclusive private store lease + * used for promotion. Charge the exact envelope before writing; an abandoned + * or ambiguous stage stays charged. Never expose this path to an executor. + */ +export async function stageRetentionPublication( + root: FileHandle, + attempt: PublicationAttempt, + payload: Buffer, + expiresAt: number, +): Promise<{ status: Status; commitment?: string }> { + const requested = structuredClone(attempt); + const prefix = publicationPrefix(requested); + if ( + !payload.length || + payload.length > maxStagePayloadBytes - prefix.length + ) + return { status: 'invalid' }; + const bytes = Buffer.concat([prefix, payload]); + return use(root, async () => { + const catalog = await CheckpointCatalog.open(root); + const state = decodeRetention(await catalog.read()); + const { lane, sequence } = requested.ref; + if ( + !matchesScope( + requested, + state.lanes.get(lane)?.verified?.publication, + ) + ) + return { status: 'conflict' }; + const result = transitionRetention(state, { + kind: 'reserve', + lane, + expectedSequence: sequence - 1, + bytes: bytes.length + stageNonceBytes, + expiresAt, + now: Date.now(), + }); + if (result.status !== 'applied') return { status: result.status }; + await catalog.replace(encodeRetention(result.state)); + const commitment = await new CheckpointStage(root).stage(bytes); + const entry = result.state.lanes.get(lane); + if (!entry?.pending) throw new Error('Checkpoint reservation missing'); + const lanes = new Map(result.state.lanes); + lanes.set(lane, { + ...entry, + pending: { + ...entry.pending, + publication: { + workerId: requested.workerId, + ownerScope: requested.lease.ownerScope, + digest: commitment, + payloadBytes: bytes.length, + }, + }, + }); + await catalog.replace(encodeRetention({ ...result.state, lanes })); + return { status: 'applied', commitment }; + }); +} + +/** + * The caller holds both the source's local commit fence and the private store + * lease through completion. The bridge read is bounded and must honor abort; + * don't race it and release the lease while an authority check is in flight. + * There is no raw promote, inference from tickets, or lookup of another digest. + */ +export async function publishRetentionCheckpoint( + root: FileHandle, + attempt: PublicationAttempt, + commitment: string, + expectedVerified: Ref | null, + authority: PublicationAuthority, +): Promise { + const requested = structuredClone(attempt); + const expected = structuredClone(expectedVerified); + const prefix = publicationPrefix(requested); + if (!isLane(commitment)) return 'invalid'; + return use(root, async () => { + const catalog = await CheckpointCatalog.open(root); + const state = decodeRetention(await catalog.read()); + const { lane, sequence } = requested.ref; + const current = state.lanes.get(lane); + if (!current) return 'missing'; + if (!matchesScope(requested, current.verified?.publication)) + return 'conflict'; + const pending = current.pending; + const binding = pending?.publication; + if ( + pending?.ref.sequence !== sequence || + !binding || + binding.digest !== commitment || + !matchesScope(requested, binding) || + (expected === null + ? current.verified !== null + : expected.lane !== lane || + expected.sequence !== current.verified?.ref.sequence) + ) + return 'conflict'; + if (pending.expiresAt <= Date.now()) return 'expired'; + if (!authority.isCurrent(requested)) return 'unavailable'; + const length = binding.payloadBytes; + if (length <= prefix.length || length > maxStagePayloadBytes) + return 'conflict'; + const bytes = await new CheckpointStage(root).read(commitment, length); + if (!bytes.subarray(0, prefix.length).equals(prefix)) return 'conflict'; + const remaining = pending.expiresAt - Date.now(); + if (remaining <= 0) return 'expired'; + const query = proofQuery(requested, commitment); + const signal = AbortSignal.timeout(Math.min(5_000, remaining)); + const proof = await authority.readPairedProof(query, signal); + if ( + signal.aborted || + !exactPairedProof(proof, query) || + !authority.isCurrent(requested) + ) + return 'unavailable'; + const result = transitionRetention(state, { + kind: 'promote', + ref: requested.ref, + expectedVerified: expected, + now: Date.now(), + }); + if (result.status === 'applied') + 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 86eaf2e6..05e9f7d1 100644 --- a/packages/code/src/checkpoint-retention.ts +++ b/packages/code/src/checkpoint-retention.ts @@ -3,8 +3,18 @@ export const maxArtifacts = 256; export const maxBytes = 512 * 1024 * 1024; const incarnation = /^[0-9a-f]{64}$/; -type Ref = Readonly<{ lane: string; sequence: number }>; -export type Artifact = Readonly<{ ref: Ref; bytes: number }>; +export type Ref = Readonly<{ lane: string; sequence: number }>; +export type Publication = Readonly<{ + workerId: string; + ownerScope: string; + digest: string; + payloadBytes: number; +}>; +export type Artifact = Readonly<{ + ref: Ref; + bytes: number; + publication?: Publication; +}>; type Pending = Artifact & Readonly<{ expiresAt: number }>; export type Lane = Readonly<{ sequence: number; @@ -27,7 +37,12 @@ type Command = expiresAt: number; now: number; } - | { kind: 'promote'; ref: Ref; expectedVerified: Ref | null; now: number } + | { + kind: 'promote'; + ref: Ref; + expectedVerified: Ref | null; + now: number; + } | { kind: 'discard'; ref: Ref } | { kind: 'reclaimed'; ref: Ref }; type Status = @@ -85,7 +100,7 @@ function time(value: number): boolean { */ export function transitionRetention( state: State, - command: Command + command: Command, ): { status: Status; state: State } { const reject = (status: Exclude) => ({ status, state }); const lane = 'lane' in command ? command.lane : command.ref.lane; @@ -109,7 +124,7 @@ export function transitionRetention( if (command.kind === 'reclaimed') { const index = state.garbage.findIndex(entry => - same(entry.ref, command.ref) + same(entry.ref, command.ref), ); if (index < 0) return reject('conflict'); return { @@ -145,7 +160,7 @@ export function transitionRetention( const pending = { ref: { lane, sequence }, bytes, expiresAt }; return update( { ...current, sequence, pending }, - { artifacts: state.artifacts + 1, bytes: state.bytes + bytes } + { artifacts: state.artifacts + 1, bytes: state.bytes + bytes }, ); } @@ -156,11 +171,11 @@ export function transitionRetention( return reject('already-current'); const pending = current.pending; if (!pending || !same(pending.ref, command.ref)) return reject('conflict'); - const candidate = { ref: pending.ref, bytes: pending.bytes }; + const { expiresAt: _expiresAt, ...candidate } = pending; if (command.kind === 'discard') { return update( { ...current, pending: null }, - { garbage: [...state.garbage, candidate] } + { garbage: [...state.garbage, candidate] }, ); } if (!time(command.now)) return reject('invalid'); @@ -171,6 +186,6 @@ export function transitionRetention( { ...current, pending: null, verified: candidate }, current.verified ? { garbage: [...state.garbage, current.verified] } - : undefined + : undefined, ); } diff --git a/packages/code/src/checkpoint-stage.ts b/packages/code/src/checkpoint-stage.ts index 064175dc..5bd0f822 100644 --- a/packages/code/src/checkpoint-stage.ts +++ b/packages/code/src/checkpoint-stage.ts @@ -3,7 +3,8 @@ import { constants } from 'node:fs'; import { link, open, opendir, unlink } from 'node:fs/promises'; import type { FileHandle } from 'node:fs/promises'; -const maxBytes = 16 * 1024 * 1024; +export const maxStagePayloadBytes = 16 * 1024 * 1024; +export const stageNonceBytes = 32; const maxEntries = 32; const key = /^[a-f0-9]{64}$/; const domain = 'librechat/checkpoint-stage/v1\0'; @@ -41,12 +42,19 @@ export class CheckpointStage { /** Bytes encode the caller's immutable manifest and payload together. */ async stage(payload: Buffer): Promise { - if (this.busy || !payload.length || payload.length > maxBytes) + if ( + this.busy || + !payload.length || + payload.length > maxStagePayloadBytes + ) unavailable(); this.busy = true; try { // Snapshot caller bytes before yielding; the private nonce prevents a digest oracle. - const bytes = Buffer.concat([randomBytes(32), payload]); + const bytes = Buffer.concat([ + randomBytes(stageNonceBytes), + payload, + ]); const digest = commitment(bytes); const directory = await this.directory(); const entries = await opendir(directory); @@ -78,12 +86,12 @@ export class CheckpointStage { } /** Only returns intact staged bytes; a caller must separately consume fresh bridge proof. */ - async read(digest: string): Promise { + async read(digest: string, expectedPayloadBytes?: number): Promise { if (!key.test(digest)) unavailable(); const directory = await this.directory(); const file = await open( `${directory}/${digest}`, - constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, ); try { const info = await file.stat(); @@ -92,8 +100,10 @@ export class CheckpointStage { info.uid !== process.getuid?.() || (info.mode & 0o7777) !== 0o600 || info.nlink !== 1 || - info.size <= 32 || - info.size > maxBytes + 32 + (expectedPayloadBytes !== undefined && + info.size !== expectedPayloadBytes + stageNonceBytes) || + info.size <= stageNonceBytes || + info.size > maxStagePayloadBytes + stageNonceBytes ) unavailable(); const bytes = Buffer.alloc(info.size + 1); @@ -103,7 +113,7 @@ export class CheckpointStage { bytes, offset, bytes.length - offset, - offset + offset, ); if (!bytesRead) break; offset += bytesRead; @@ -111,7 +121,7 @@ export class CheckpointStage { const content = bytes.subarray(0, offset); if (offset !== info.size || commitment(content) !== digest) unavailable(); - return content.subarray(32); + return content.subarray(stageNonceBytes); } finally { await file.close(); }