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
103 changes: 103 additions & 0 deletions packages/code/src/checkpoint-publication.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>;
/** 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<string, unknown>;
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',
);
}
115 changes: 87 additions & 28 deletions packages/code/src/checkpoint-retention-codec.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -8,17 +15,17 @@ 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');
}

function record(
value: unknown,
keys: readonly string[]
keys: readonly string[],
): Record<string, unknown> {
if (typeof value !== 'object' || value === null || Array.isArray(value))
invalid();
Expand All @@ -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' ||
Expand All @@ -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,
Expand All @@ -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<string, Lane>();
const charged = new Set<string>();
let total = 0;
const digests = new Set<string>();
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<string, unknown>,
expected?: string
value: unknown,
expected: string,
pending: true,
): NonNullable<Lane['pending']>;
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();
Expand All @@ -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)) {
Expand All @@ -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;
Expand Down Expand Up @@ -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;
}
Loading
Loading