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
5 changes: 3 additions & 2 deletions packages/code/src/checkpoint-directory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ async function supportedFixture(t: TestContext): Promise<string | undefined> {

async function assertReusable(path: string): Promise<void> {
assert.equal(
await withCheckpointDirectory(path, admit, async fd => {
const pinned = await stat(fd, { bigint: true });
await withCheckpointDirectory(path, admit, async (fd, handle) => {
assert.equal(fd, `/proc/self/fd/${handle.fd}`);
const pinned = await handle.stat({ bigint: true });
const current = await stat(path, { bigint: true });
assert.equal(pinned.dev, current.dev);
assert.equal(pinned.ino, current.ino);
Expand Down
10 changes: 5 additions & 5 deletions packages/code/src/checkpoint-directory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,14 @@ async function revalidate(
* trusted Linux procfs and mount administration. Ownership, inode checks and
* flock are not isolation from the worker UID, privileged actors or aliases;
* the mandatory verifier supplies admission and pins the grant set.
* The operation gets a borrowed descriptor path, valid only until it settles;
* use it only in this process, and do not expose it to untrusted code, retain it,
* or duplicate its descriptor.
* The operation gets a borrowed descriptor path and handle, valid only until
* it settles. Await all operations on them and never expose, close, retain or
* duplicate the handle; this reservation owns it and its lock.
*/
export async function withCheckpointDirectory<T>(
path: string,
verifyIsolation: VerifyIsolation,
operation: (descriptorPath: string) => Promise<T>
operation: (descriptorPath: string, handle: FileHandle) => Promise<T>
): Promise<T> {
if (process.platform !== 'linux' || process.geteuid === undefined) {
throw new Error('Checkpoint directory reservation requires Linux');
Expand Down Expand Up @@ -224,7 +224,7 @@ export async function withCheckpointDirectory<T>(
);
try {
await revalidate(handle, directory, parts, uid);
return await operation(descriptor(handle));
return await operation(descriptor(handle), handle);
} finally {
await release();
}
Expand Down
244 changes: 244 additions & 0 deletions packages/code/src/checkpoint-retention-codec.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import {
decodeRetention,
encodeRetention,
} from './checkpoint-retention-codec.js';
import { emptyRetention, transitionRetention } from './checkpoint-retention.js';

type Command = Parameters<typeof transitionRetention>[1];

const lane = 'a'.repeat(64);
const other = 'b'.repeat(64);
const max = Number.MAX_SAFE_INTEGER;

const ref = (sequence: number, id = lane) => ({ lane: id, sequence });
const reserve = (expectedSequence: number, id = lane): Command => ({
kind: 'reserve',
lane: id,
expectedSequence,
bytes: 4,
now: 0,
expiresAt: 10,
});

function fixture() {
let state = emptyRetention();
const commands: Command[] = [
{ kind: 'enroll', lane },
{ kind: 'enroll', lane: other },
reserve(0),
{ kind: 'promote', ref: ref(1), expectedVerified: null, now: 1 },
reserve(1),
{ kind: 'discard', ref: ref(2) },
reserve(2),
reserve(0, other),
{ kind: 'discard', ref: ref(1, other) },
{ kind: 'reclaimed', ref: ref(1, other) },
];
for (const command of commands) {
const result = transitionRetention(state, command);
assert.equal(result.status, 'applied');
state = result.state;
}
return state;
}

function wire() {
return {
version: 1,
lanes: Array.from(fixture().lanes, ([key, entry]) => ({ key, entry })),
garbage: [{ ref: ref(2), bytes: 4 }],
artifacts: 3,
bytes: 12,
};
}

function pack(value: ReturnType<typeof wire>): Buffer {
return Buffer.from(
JSON.stringify({
...value,
lanes: value.lanes.map(({ key, entry }) => [key, entry]),
})
);
}

test('round-trips the versioned root set, including cleared lane counters and current pointers', () => {
for (const state of [emptyRetention(), fixture()]) {
const bytes = encodeRetention(state);
const decoded = decodeRetention(bytes);
assert.deepEqual(decoded, state);
assert.deepEqual(encodeRetention(decoded), bytes);
}
assert.deepEqual(pack(wire()), encodeRetention(fixture()));
assert.equal(
transitionRetention(decodeRetention(pack(wire())), reserve(0, other))
.status,
'conflict'
);
});

test('round-trips a full catalog at the lane, charge, byte and sequence ceilings', () => {
const bytes = 512 * 1024 * 1024;
const lanes = new Map(
Array.from({ length: 256 }, (_, index) => {
const id = index.toString(16).padStart(64, '0');
return [
id,
{
sequence: max,
pending: {
ref: ref(max, id),
bytes: bytes / 256,
expiresAt: max,
},
verified: null,
},
] as const;
})
);
const state = { lanes, garbage: [], bytes, artifacts: 256 };
assert.deepEqual(decodeRetention(encodeRetention(state)), state);
});

test('rejects malformed, ambiguous and unknown wire data', () => {
const good = pack(wire()).toString();
for (const bad of [
Buffer.alloc(0),
Buffer.alloc(128 * 1024 + 1, 32),
Buffer.from([0xff]),
Buffer.from('null'),
Buffer.from('[]'),
Buffer.from('{}'),
Buffer.from(good.slice(0, -1)),
Buffer.from(good.replace('"version":1', '"version":2')),
Buffer.from(good.replace('"version":1', '"version":1,"version":1')),
Buffer.from(good.replace('"sequence":3', '"sequence":3,"sequence":3')),
Buffer.from(good.replace('"sequence":3', '"sequence":"3"')),
Buffer.from(good.replace('"ref":', '"extra":true,"ref":')),
Buffer.from(good.replace('"verified":null', '"unknown":null')),
Buffer.from(good.replace('"artifacts":3,', '')),
Buffer.from(good.replace('"bytes":12', '"bytes":12,"unknown":0')),
])
assert.throws(
() => decodeRetention(bad),
/Invalid checkpoint retention payload/
);
});

const cases: Record<string, (value: ReturnType<typeof wire>) => void> = {
'duplicate lanes': v => v.lanes.push(v.lanes[0]),
'too many lanes': v => {
v.lanes = Array(257).fill(v.lanes[0]);
},
'invalid lane identity': v => {
v.lanes[0].key = 'x'.repeat(64);
},
'future garbage': v => {
v.garbage[0].ref.sequence = 4;
},
'unowned garbage': v => {
v.garbage[0].ref.lane = 'c'.repeat(64);
},
'duplicate garbage': v => {
v.garbage.push(v.garbage[0]);
v.artifacts++;
v.bytes += 4;
},
'too much garbage': v => {
v.garbage = Array(257).fill(v.garbage[0]);
},
'garbage aliasing verified': v => {
v.garbage[0].ref.sequence = 1;
},
'garbage aliasing pending': v => {
v.garbage[0].ref.sequence = 3;
},
'zero charge': v => {
v.garbage[0].bytes = 0;
},
'fractional charge': v => {
v.garbage[0].bytes = 4.5;
},
'oversized charge': v => {
v.garbage[0].bytes = 512 * 1024 * 1024 + 1;
},
'zero ref sequence': v => {
v.garbage[0].ref.sequence = 0;
},
'unsafe sequence counter': v => {
v.lanes[0].entry = { ...v.lanes[0].entry, sequence: max + 1 };
},
'negative sequence counter': v => {
v.lanes[1].entry = { ...v.lanes[1].entry, sequence: -1 };
},
'stale pending pointer': v => {
v.lanes[0].entry = { ...v.lanes[0].entry, sequence: 4 };
},
'wrong-lane pending pointer': v => {
v.lanes[0].entry = {
...v.lanes[0].entry,
pending: { ref: ref(3, other), bytes: 4, expiresAt: 10 },
};
},
'impossible pending expiry': v => {
v.lanes[0].entry = {
...v.lanes[0].entry,
pending: { ref: ref(3), bytes: 4, expiresAt: 0 },
};
},
'future verified pointer': v => {
v.lanes[0].entry = {
...v.lanes[0].entry,
verified: { ref: ref(4), bytes: 4 },
};
},
'wrong-lane verified pointer': v => {
v.lanes[0].entry = {
...v.lanes[0].entry,
verified: { ref: ref(1, other), bytes: 4 },
};
},
'verified aliases pending': v => {
v.lanes[0].entry = {
...v.lanes[0].entry,
verified: { ref: ref(3), bytes: 4 },
};
},
'undercharged bytes': v => {
v.bytes--;
},
'overcharged bytes': v => {
v.bytes++;
},
'over-budget bytes': v => {
v.bytes = 512 * 1024 * 1024 + 1;
},
'undercounted artifacts': v => {
v.artifacts--;
},
'overcounted artifacts': v => {
v.artifacts++;
},
'over-budget artifact count': v => {
v.artifacts = 257;
},
};

for (const [name, corrupt] of Object.entries(cases)) {
test(`rejects ${name}`, () => {
const value = wire();
corrupt(value);
assert.throws(
() => decodeRetention(pack(value)),
/Invalid checkpoint retention payload/
);
});
}

test('refuses to serialize inconsistent state', () => {
assert.throws(
() => encodeRetention({ ...fixture(), bytes: 0 }),
/Invalid checkpoint retention payload/
);
});
Loading
Loading