Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions packages/code/src/restore-journal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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
});
}
);
80 changes: 54 additions & 26 deletions packages/code/src/restore-journal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}$/;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -73,8 +77,52 @@ function encode(entry: Entry): Buffer {
export async function reconcileRestoreJournal(
root: FileHandle,
key: string,
create?: () => Promise<string>,
create?: () => Promise<string>
): Promise<RestoreJournalState> {
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<void>
): 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<Entry | undefined> {
const uid = process.geteuid?.();
if (
process.platform !== 'linux' ||
Expand All @@ -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();
}
12 changes: 9 additions & 3 deletions packages/code/src/restore-overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,11 @@ function validateTree(files: ReadonlyMap<string, File>): void {
}
}

export async function planRestore(
export async function assertRestoreConfig(
git: CheckpointGit,
configPath: string,
data: WorktreeCheckpoint,
signal: AbortSignal
): Promise<Plan> {
): Promise<void> {
// 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(
Expand All @@ -264,6 +263,13 @@ export async function planRestore(
)
invalid();
}
}

export async function planRestore(
git: CheckpointGit,
data: WorktreeCheckpoint,
signal: AbortSignal
): Promise<Plan> {
await assertRestorePin(git, data.head, signal);
const raw = decode.decode(
await git(['ls-tree', '-r', '-l', '-z', '--full-tree', data.head], {
Expand Down
189 changes: 189 additions & 0 deletions packages/code/src/worker-restore-admission.ts
Original file line number Diff line number Diff line change
@@ -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<typeof withCheckpointDirectory>[1];
type Options = Omit<
ConstructorParameters<typeof WorktreeRestore>[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<T>(
intent: WorktreeRestoreIntent,
destination: RestoreDestination,
mode: 'start' | 'status',
signal: AbortSignal,
task: (reservation: RestoreReservation) => Promise<T>,
): Promise<T>;
}

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,
),
);
}
Loading
Loading