From 2f5b6baaad55b744dc2e5b77b60b9cca57f9f6dc Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Fri, 4 Dec 2026 22:13:11 -0500 Subject: [PATCH] feat(worker): Model bounded rolling checkpoint retention --- .../code/src/checkpoint-retention.test.ts | 195 ++++++++++++++++++ packages/code/src/checkpoint-retention.ts | 169 +++++++++++++++ 2 files changed, 364 insertions(+) create mode 100644 packages/code/src/checkpoint-retention.test.ts create mode 100644 packages/code/src/checkpoint-retention.ts diff --git a/packages/code/src/checkpoint-retention.test.ts b/packages/code/src/checkpoint-retention.test.ts new file mode 100644 index 00000000..c01c6254 --- /dev/null +++ b/packages/code/src/checkpoint-retention.test.ts @@ -0,0 +1,195 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { emptyRetention, transitionRetention } from './checkpoint-retention.js'; + +type Command = Parameters[1]; +type Status = ReturnType['status']; + +const lane = 'a'.repeat(64); +const other = 'b'.repeat(64); +const bytes = 16 * 1024 * 1024; + +function fixture() { + let state = emptyRetention(); + return { + read: () => state, + apply(command: Command, status: Status = 'applied') { + const result = transitionRetention(state, command); + assert.equal(result.status, status); + if (status !== 'applied') assert.strictEqual(result.state, state); + state = result.state; + }, + }; +} + +function reserve(expectedSequence: number, charge = bytes, id = lane): Command { + return { + kind: 'reserve', + lane: id, + expectedSequence, + bytes: charge, + now: 10, + expiresAt: 20, + }; +} + +function ref(sequence: number, id = lane) { + return { lane: id, sequence }; +} + +function promote( + sequence: number, + expectedVerified: ReturnType | null, + now = 11 +): Command { + return { kind: 'promote', ref: ref(sequence), expectedVerified, now }; +} + +test('requires explicit enrollment and never resets an enrolled incarnation', () => { + const { apply, read } = fixture(); + apply(reserve(0), 'missing'); + apply(promote(1, null), 'missing'); + apply({ kind: 'enroll', lane: 'worktree-name' }, 'invalid'); + apply({ kind: 'enroll', lane }); + const before = read(); + apply(reserve(0)); + assert.deepEqual(before.lanes.get(lane), { + sequence: 0, + pending: null, + verified: null, + }); + assert.equal(before.bytes, 0); + apply({ kind: 'enroll', lane }, 'conflict'); + apply(reserve(1), 'conflict'); + apply({ kind: 'discard', ref: ref(1) }); + apply({ kind: 'reclaimed', ref: ref(1) }); + apply(reserve(0), 'conflict'); + apply(reserve(1)); + assert.deepEqual(read().lanes.get(lane)?.pending?.ref, ref(2)); +}); + +test('promotes only the exact pending attempt and expected pointer, including absence', () => { + const { apply, read } = fixture(); + apply({ kind: 'enroll', lane }); + apply({ kind: 'enroll', lane: other }); + apply(reserve(0)); + apply(reserve(0, bytes, other)); + apply(promote(1, ref(1, other)), 'conflict'); + apply(promote(1, null)); + apply(reserve(1)); + apply(promote(2, null), 'conflict'); + apply(promote(2, ref(1, other)), 'conflict'); + apply(promote(2, ref(2)), 'conflict'); + apply({ kind: 'discard', ref: ref(2, other) }, 'conflict'); + const before = read(); + apply(promote(2, ref(1))); + assert.deepEqual(before.lanes.get(lane)?.verified?.ref, ref(1)); + assert.deepEqual(before.lanes.get(lane)?.pending?.ref, ref(2)); + assert.deepEqual(before.garbage, []); + assert.deepEqual(read().lanes.get(lane)?.verified?.ref, ref(2)); + assert.equal(read().lanes.get(lane)?.pending, null); + assert.deepEqual(read().lanes.get(other)?.pending?.ref, ref(1, other)); + assert.deepEqual(read().garbage, [{ ref: ref(1), bytes }]); + assert.equal(read().bytes, before.bytes); + assert.equal(read().artifacts, before.artifacts); +}); + +test('expiration, failed attempts, and stale or lost retries preserve the latest verified pointer', () => { + const { apply, read } = fixture(); + apply({ kind: 'enroll', lane }); + apply(reserve(0)); + apply(promote(1, null)); + apply(promote(1, null, 21), 'already-current'); + apply(reserve(1)); + apply(promote(2, ref(1), Number.NaN), 'invalid'); + apply(promote(2, ref(1), 20), 'expired'); + apply({ kind: 'reclaimed', ref: ref(2) }, 'conflict'); + apply({ kind: 'discard', ref: ref(2) }); + assert.deepEqual(read().lanes.get(lane)?.verified?.ref, ref(1)); + assert.equal(read().bytes, 2 * bytes); + apply(reserve(1), 'conflict'); + apply(reserve(2)); + apply(promote(2, ref(1)), 'conflict'); + apply({ kind: 'discard', ref: ref(2) }, 'conflict'); + apply(promote(3, ref(1))); + apply(promote(1, null), 'conflict'); + apply(promote(3, ref(1)), 'already-current'); + apply({ kind: 'reclaimed', ref: ref(3) }, 'conflict'); + apply({ kind: 'discard', ref: ref(3) }, 'conflict'); + assert.deepEqual(read().lanes.get(lane)?.verified?.ref, ref(3)); +}); + +test('5,000 synthetic promotions plateau at two charged entries with simulated cleanup', () => { + const { apply, read } = fixture(); + apply({ kind: 'enroll', lane }); + for (let seq = 1; seq <= 5_000; seq++) { + const prior = seq === 1 ? null : ref(seq - 1); + apply(reserve(seq - 1)); + apply(promote(seq, prior)); + assert.equal(read().lanes.size, 1); + assert.equal(read().artifacts, prior ? 2 : 1); + assert.equal(read().bytes, (prior ? 2 : 1) * bytes); + assert.equal(read().garbage.length, prior ? 1 : 0); + assert.deepEqual(read().lanes.get(lane)?.verified?.ref, ref(seq)); + if (prior) { + apply({ kind: 'reclaimed', ref: prior }); + apply({ kind: 'reclaimed', ref: prior }, 'conflict'); + } + assert.equal(read().artifacts, 1); + assert.equal(read().bytes, bytes); + assert.equal(read().garbage.length, 0); + } +}); + +test('byte and entry exhaustion keep the last verified entry and charge garbage until acknowledged', () => { + for (const [size, limit] of [ + [bytes, 32], + [1, 256], + ]) { + const { apply, read } = fixture(); + apply({ kind: 'enroll', lane }); + for (let seq = 1; seq <= limit; seq++) { + apply(reserve(seq - 1, size)); + apply(promote(seq, seq === 1 ? null : ref(seq - 1))); + } + apply(reserve(limit, size), 'full'); + assert.deepEqual(read().lanes.get(lane)?.verified?.ref, ref(limit)); + assert.equal(read().garbage.length, limit - 1); + assert.equal(read().bytes, limit * size); + assert.equal(read().artifacts, limit); + apply({ kind: 'reclaimed', ref: ref(1) }); + apply(reserve(limit, size)); + assert.deepEqual(read().lanes.get(lane)?.verified?.ref, ref(limit)); + } +}); + +test('caps lane metadata and fails closed on sequence exhaustion', () => { + const { apply, read } = fixture(); + for (let i = 0; i < 256; i++) { + apply({ kind: 'enroll', lane: i.toString(16).padStart(64, '0') }); + } + apply({ kind: 'enroll', lane }, 'full'); + assert.equal(read().lanes.size, 256); + + const last = Number.MAX_SAFE_INTEGER; + const verified = { ref: ref(last - 1), bytes }; + const seed = { + ...emptyRetention(), + lanes: new Map([ + [lane, { sequence: last - 1, pending: null, verified }], + ]), + artifacts: 1, + bytes, + }; + const reserved = transitionRetention(seed, reserve(last - 1)); + assert.equal(reserved.status, 'applied'); + const promoted = transitionRetention( + reserved.state, + promote(last, ref(last - 1)) + ); + assert.equal(promoted.status, 'applied'); + const exhausted = transitionRetention(promoted.state, reserve(last)); + assert.equal(exhausted.status, 'full'); + assert.strictEqual(exhausted.state, promoted.state); + assert.deepEqual(exhausted.state.lanes.get(lane)?.verified?.ref, ref(last)); +}); diff --git a/packages/code/src/checkpoint-retention.ts b/packages/code/src/checkpoint-retention.ts new file mode 100644 index 00000000..2a09bcca --- /dev/null +++ b/packages/code/src/checkpoint-retention.ts @@ -0,0 +1,169 @@ +const maxLanes = 256; +const maxArtifacts = 256; +const maxBytes = 512 * 1024 * 1024; +const incarnation = /^[0-9a-f]{64}$/; + +type Ref = Readonly<{ lane: string; sequence: number }>; +type Artifact = Readonly<{ ref: Ref; bytes: number }>; +type Pending = Artifact & Readonly<{ expiresAt: number }>; +type Lane = Readonly<{ + sequence: number; + pending: Pending | null; + verified: Artifact | null; +}>; +type State = Readonly<{ + lanes: ReadonlyMap; + garbage: readonly Artifact[]; + artifacts: number; + bytes: number; +}>; +type Command = + | { kind: 'enroll'; lane: string } + | { + kind: 'reserve'; + lane: string; + expectedSequence: number; + bytes: number; + expiresAt: number; + now: number; + } + | { kind: 'promote'; ref: Ref; expectedVerified: Ref | null; now: number } + | { kind: 'discard'; ref: Ref } + | { kind: 'reclaimed'; ref: Ref }; +type Status = + | 'applied' + | 'invalid' + | 'missing' + | 'conflict' + | 'full' + | 'expired' + | 'already-current'; + +export function emptyRetention(): State { + return { lanes: new Map(), garbage: [], artifacts: 0, bytes: 0 }; +} + +function same(left: Ref | null, right: Ref | null): boolean { + if (left === null || right === null) return left === right; + return left.lane === right.lane && left.sequence === right.sequence; +} + +function time(value: number): boolean { + return Number.isSafeInteger(value) && value >= 0; +} + +/** + * Internal bookkeeping for a trusted worker adapter, not an admission, proof, + * or persistence API. Lane keys are opaque, nonreused identities for the exact + * admitted incarnation and authority scope, not worktree names or paths. A ref + * is unique within one store lifetime; this slice never drops lane high-water marks. + * Use only emptyRetention or a validated authoritative state, never request data. + * `now` and `expiresAt` must use the same trusted timebase; unverifiable time means + * no promotion. Verified expiry, retirement, and owner quotas are outside this slice. + * + * The adapter must serialize read/check/transition/durable commit on authoritative + * state. Commit reservations (sequence and worst-case byte charge) before writing + * bytes; a reservation alone says nothing about whether an artifact exists. Only + * dispatch promote after verifying durable immutable bytes and fresh same-attempt + * proof and rechecking live authority, incarnation and deadline under the commit + * fence. Persist the new pointer and old garbage mark in one atomic commit before + * reporting success. An already-current result is read-only, not fresh authority. + * + * Discard only the exact failed/abandoned attempt (including expired attempts). + * Reclaim only durable garbage, after excluding readers and writers; acknowledge + * only after durable deletion or verified durable absence, then atomically release + * its charge. On an ambiguous commit, reload and validate or stop; never infer an + * empty store, reuse a ref, reconstruct authority from bytes, or delete on a guess. + */ +export function transitionRetention( + state: State, + command: Command +): { status: Status; state: State } { + const reject = (status: Exclude) => ({ status, state }); + const lane = 'lane' in command ? command.lane : command.ref.lane; + const current = state.lanes.get(lane); + const update = (entry: Lane, changes: Partial = {}) => { + const lanes = new Map(state.lanes); + lanes.set(lane, entry); + return { + status: 'applied' as const, + state: { ...state, ...changes, lanes }, + }; + }; + + if (command.kind === 'enroll') { + if (lane.length !== 64 || !incarnation.test(lane)) + return reject('invalid'); + if (current) return reject('conflict'); + if (state.lanes.size >= maxLanes) return reject('full'); + return update({ sequence: 0, pending: null, verified: null }); + } + if (!current) return reject('missing'); + + if (command.kind === 'reclaimed') { + const index = state.garbage.findIndex(entry => + same(entry.ref, command.ref) + ); + if (index < 0) return reject('conflict'); + return { + status: 'applied', + state: { + ...state, + garbage: state.garbage.filter((_, i) => i !== index), + artifacts: state.artifacts - 1, + bytes: state.bytes - state.garbage[index].bytes, + }, + }; + } + + if (command.kind === 'reserve') { + const { bytes, expiresAt, now, expectedSequence } = command; + if ( + !time(now) || + !time(expiresAt) || + !Number.isSafeInteger(bytes) || + bytes <= 0 + ) + return reject('invalid'); + if (expiresAt <= now) return reject('expired'); + if (current.sequence !== expectedSequence || current.pending) + return reject('conflict'); + if ( + current.sequence === Number.MAX_SAFE_INTEGER || + state.artifacts >= maxArtifacts || + bytes > maxBytes - state.bytes + ) + return reject('full'); + const sequence = current.sequence + 1; + const pending = { ref: { lane, sequence }, bytes, expiresAt }; + return update( + { ...current, sequence, pending }, + { artifacts: state.artifacts + 1, bytes: state.bytes + bytes } + ); + } + + if ( + command.kind === 'promote' && + same(current.verified?.ref ?? null, command.ref) + ) + 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 }; + if (command.kind === 'discard') { + return update( + { ...current, pending: null }, + { garbage: [...state.garbage, candidate] } + ); + } + if (!time(command.now)) return reject('invalid'); + if (pending.expiresAt <= command.now) return reject('expired'); + if (!same(current.verified?.ref ?? null, command.expectedVerified)) + return reject('conflict'); + return update( + { ...current, pending: null, verified: candidate }, + current.verified + ? { garbage: [...state.garbage, current.verified] } + : undefined + ); +}