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
4 changes: 2 additions & 2 deletions service/src/bridge/checkpoint-proof.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,10 @@ async function fixture({ seedCommitment = true } = {}) {
await store.acknowledgeLease(id, incarnationId, assignmentId, assignment.generation, assignment.leaseToken);
const lease = { protocolVersion: 1, incarnationId, generation: assignment.generation, leaseToken: assignment.leaseToken } as const;
const settlement = { ...lease, status: 'fulfilled', result: creation } as const;
if (seedCommitment) await store.settle(id, assignmentId, settlement, undefined, auth.identityId, false, ticket);
if (seedCommitment) await store.settle(id, assignmentId, settlement, undefined, auth.identityId, false, ticket, auth);
const seal = async () => {
await store.confirmWorkspaceCleanup(id, assignmentId, { ...lease, status: 'rejected', error: 'local cleanup' },
undefined, auth.identityId, ticket);
undefined, auth.identityId, ticket, auth);
const active = 'codeapi:workspace-requests:v1:active';
for (const key of await client.zrange(active, 0, -1)) await client.zadd(active, 0, key);
await requests.reconcile();
Expand Down
70 changes: 52 additions & 18 deletions service/src/bridge/checkpoint.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BridgeSettlement } from '../../../packages/code/src/protocol';
import { credentialDigestKey, workerIdentityKey } from './pairing';

/** Private receipt data. Admission/negotiation must write this alongside the
* exact ownership metadata and epoch; no production path enrolls it yet. */
Expand All @@ -16,7 +17,7 @@ export interface CheckpointCandidate {
}

export function isCheckpointDigest(value: string | undefined): value is string {
return value != null && value.length === 64 && /^[a-f0-9]+$/.test(value);
return typeof value === 'string' && value.length === 64 && /^[a-f0-9]+$/.test(value);
}

/** Internal HTTP sidecar, not part of the shared BridgeSettlement protocol. */
Expand Down Expand Up @@ -74,6 +75,12 @@ export interface CheckpointContext {
keys: string[];
args: string[];
epoch: string;
authority?: {
workerId: string;
activeCredentialId: string;
// Only worker-originated votes have a signing credential.
credentialId?: string;
};
}

type CheckpointVote =
Expand All @@ -82,13 +89,16 @@ type CheckpointVote =
| { kind: 'finalization'; digest: string; key: string; outcome: string; assignment: string };

/** Append an advisory transition to an existing Redis CAS. The caller still
* owns all normal commit, cleanup and release decisions. Keys/args match the
* layout constructed by RedisBridgeStore.checkpointContext. */
* owns all normal commit, cleanup and release decisions. The shared receipt
* context occupies keys 1..10 and args 1..9; authority and vote data follow. */
export function checkpointTransition(
keys: string[], args: (string | number)[], context: CheckpointContext | undefined, vote: CheckpointVote,
): string[] {
if (context == null || (vote.kind !== 'finalization' &&
(vote.candidate.epoch !== context.epoch || !isCheckpointDigest(vote.candidate.commitment)))) return [];
if (context?.authority == null || (vote.kind !== 'finalization' &&
(vote.candidate.epoch !== context.epoch ||
!isCheckpointDigest(vote.candidate.commitment)))) return [];
const { workerId, activeCredentialId, credentialId } = context.authority;
if (vote.kind !== 'finalization' && credentialId == null) return [];
const keyOffset = keys.length;
const argOffset = args.length;
const k = (i: number) => `KEYS[${keyOffset + i}]`;
Expand All @@ -97,31 +107,55 @@ export function checkpointTransition(
const field = (name: string) => `redis.pcall('HGET', ${receipt}, '${name}')`;
const get = (i: number) => `redis.pcall('GET', ${k(i)})`;
const put = (name: string, value: string) => `redis.call('HSET', ${receipt}, '${name}', ${value})`;
const value = a(10);
if (vote.kind === 'finalization') keys.push(...context.keys, vote.key);
else if (vote.kind === 'settlement') keys.push(...context.keys, vote.ackKey);
else keys.push(...context.keys);
args.push(...context.args, ...(vote.kind === 'finalization' ? [vote.digest, vote.outcome, vote.assignment]
: vote.kind === 'settlement' ? [vote.candidate.commitment, vote.digest] : [vote.candidate.commitment]));
const activeId = a(10);
const worker = a(11);
const value = a(12);
keys.push(...context.keys, workerIdentityKey(workerId), credentialDigestKey(activeCredentialId));
args.push(...context.args, activeCredentialId, workerId);
if (vote.kind === 'finalization') {
keys.push(vote.key);
args.push(vote.digest, vote.outcome, vote.assignment);
} else {
// Even during rotation grace, the signing and active credentials can differ.
keys.push(credentialDigestKey(credentialId ?? activeCredentialId));
args.push(vote.candidate.commitment);
if (vote.kind === 'settlement') {
keys.push(vote.ackKey);
args.push(vote.digest);
}
}
// The optional reads use pcall and fail closed on wrong types. No proof
// writes can create a receipt, and HSET leaves its original expiry intact.
return [
'do',
' local function credentialMatches(raw)',
" if type(raw) ~= 'string' or #raw > 8192 then return false end",
' local ok, credential = pcall(cjson.decode, raw)',
" return ok and type(credential) == 'table' and type(credential.binding) == 'table'",
` and credential.workerId == ${worker} and credential.identityId == ${a(6)} and credential.binding.tenantId == ${a(8)}`,
' end',
' local function eligible()',
` if ${field('metadata')} ~= ${a(1)} or ${field('checkpointAdmissionV1')} ~= ${a(2)} or ${field('epoch')} ~= ${a(3)} then return false end`,
` if ${field('metadata')} ~= ${a(1)} or ${field('checkpointAdmissionV1')} ~= ${a(2)} or ${field('epoch')} ~= ${a(3)} or redis.call('PTTL', ${receipt}) <= 0 then return false end`,
` if ${get(2)} ~= ${a(3)} or ${get(3)} ~= ${a(4)} or redis.call('EXISTS', ${k(4)}) ~= 0 then return false end`,
` if ${get(5)} ~= ${a(5)} or ${get(6)} ~= ${a(6)} then return false end`,
` if (${get(7)} or '0') ~= ${a(7)} or redis.call('EXISTS', ${k(8)}, ${k(9)}) ~= 0 then return false end`,
` if ${get(11)} ~= ${activeId} or not credentialMatches(${get(12)}) then return false end`,
...(vote.kind === 'settlement' ? [] : [
` if ${field('checkpointActiveCredentialId')} ~= ${activeId} then return false end`,
]),
...(vote.kind === 'finalization' || credentialId === activeCredentialId ? [] : [
` if not credentialMatches(${get(13)}) then return false end`,
]),
` local raw = ${get(10)}`,
" if type(raw) ~= 'string' then return false end",
' local ok, registration = pcall(cjson.decode, raw)',
" return ok and type(registration) == 'table' and type(registration.binding) == 'table'",
` and registration.incarnationId == ${a(5)} and registration.identityId == ${a(6)} and registration.binding.tenantId == ${a(8)}`,
` and registration.workerId == ${worker} and registration.incarnationId == ${a(5)} and registration.identityId == ${a(6)} and registration.binding.tenantId == ${a(8)}`,
' end',
` if eligible() and ${field('checkpointCertificateV1')} == false then`,
...(vote.kind === 'settlement' ? [
` if ${get(11)} == ${a(4)} and ${field('checkpointCommitment')} == false and ${field('localCleanup')} == false then`,
` redis.call('HSET', ${receipt}, 'checkpointCommitment', ${value}, 'checkpointSettlementDigest', ${a(11)}, 'checkpointReceiptDigest', ${a(9)})`,
` if ${get(14)} == ${a(4)} and ${field('checkpointCommitment')} == false and ${field('localCleanup')} == false then`,
` redis.call('HSET', ${receipt}, 'checkpointCommitment', ${value}, 'checkpointSettlementDigest', ${a(13)}, 'checkpointReceiptDigest', ${a(9)}, 'checkpointActiveCredentialId', ${activeId})`,
' end',
] : [
` local commitment = ${field('checkpointCommitment')}`,
Expand All @@ -133,9 +167,9 @@ export function checkpointTransition(
` ${put('checkpointCleanupVote', 'digest')}`,
] : [
` digest == ${value} and ${field('resultCommitted')} == false and`,
` redis.pcall('HGET', ${k(11)}, 'state') == 'completed' and`,
` redis.pcall('HGET', ${k(11)}, 'outcome') == ${a(11)} and`,
` redis.pcall('HGET', ${k(11)}, 'assignment') == ${a(12)} then`,
` redis.pcall('HGET', ${k(13)}, 'state') == 'completed' and`,
` redis.pcall('HGET', ${k(13)}, 'outcome') == ${a(13)} and`,
` redis.pcall('HGET', ${k(13)}, 'assignment') == ${a(14)} then`,
` ${put('checkpointFinalizationVote', 'digest')}`,
]),
` if ${field('checkpointCleanupVote')} == digest and ${field('checkpointFinalizationVote')} == digest then`,
Expand Down
76 changes: 58 additions & 18 deletions service/src/bridge/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { hasLaneGit, laneGitPolicy } from './lane-git';
import { BridgeAdmissionQueue, durableAdmissionFence, durableQueuedClaimFence } from './admission';
import type { DurableWorkspaceGuard } from './admission';
import { BridgeWorkspaceSlots } from './slots';
import type { CheckpointCandidate, CheckpointContext } from './checkpoint';
import type { CheckpointAdmission, CheckpointCandidate, CheckpointContext } from './checkpoint';
import type { CheckpointProof, CheckpointProofDurability, CheckpointProofRequest } from './checkpoint-proof';
import { readCheckpointProof } from './checkpoint-proof';
import { checkpointTransition, isCheckpointDigest, readCheckpointAdmission } from './checkpoint';
Expand All @@ -55,6 +55,8 @@ export type CodeBridgeSettlement = BridgeSettlement<
}
>;
export type CodeBridgeWorkspaceSettlement = BridgeSettlement<WorkspaceToolResult>;
type PairedAuthorization = Awaited<ReturnType<RedisBridgePairingStore['authorize']>>;

type AnyCodeBridgeSettlement =
| CodeBridgeSettlement
| CodeBridgeWorkspaceSettlement;
Expand Down Expand Up @@ -2051,6 +2053,7 @@ export class RedisBridgeStore {
identityId?: string,
quarantineWorkspace = false,
checkpointCandidate?: CheckpointCandidate,
authorization?: PairedAuthorization,
): Promise<void> {
settlement = withValidCommandFailure(settlement);
if (quarantineWorkspace) {
Expand Down Expand Up @@ -2206,9 +2209,10 @@ export class RedisBridgeStore {
String(settlementKeys.length - Number(validatedWorkspaceTool)),
];
const checkpoint = this.checkpointProofEnabled && settlement.status === 'fulfilled' &&
checkpointCandidate != null && assignment.worktreeOwnerScope != null
checkpointCandidate != null && isCheckpointDigest(checkpointCandidate.commitment) &&
authorization != null && assignment.worktreeOwnerScope != null
? checkpointTransition(settlementKeys, settlementArgs,
await this.readCheckpointContext(assignment, signal),
await this.readCheckpointContext(assignment, { authorization, signal }),
{ kind: 'settlement', candidate: checkpointCandidate, digest: tokenHash(serializedSettlement), ackKey: settlementKeys[3] })
: [];
const script = [
Expand Down Expand Up @@ -2409,6 +2413,7 @@ export class RedisBridgeStore {
signal?: AbortSignal,
identityId?: string,
checkpointCandidate?: CheckpointCandidate,
authorization?: PairedAuthorization,
): Promise<void> {
await this.quarantineSettledWorkspace(
workerId,
Expand All @@ -2418,6 +2423,7 @@ export class RedisBridgeStore {
identityId,
false,
checkpointCandidate,
authorization,
);
}

Expand All @@ -2429,7 +2435,7 @@ export class RedisBridgeStore {
workerId: string,
assignmentId: string,
request: CheckpointProofRequest,
authorization: Awaited<ReturnType<RedisBridgePairingStore['authorize']>>,
authorization: PairedAuthorization,
): Promise<CheckpointProof> {
const durability = this.checkpointProofDurability;
if (!this.checkpointProofEnabled || durability == null || authorization.workerId !== workerId ||
Expand Down Expand Up @@ -2474,24 +2480,51 @@ export class RedisBridgeStore {
};
}

private async readCheckpointContext(assignment: StoredAssignment, signal?: AbortSignal, tenantId?: string) {
private checkpointVoteAuthority(
receipt: AssignmentOwnership,
admission: CheckpointAdmission,
authorization: PairedAuthorization,
): CheckpointContext['authority'] {
if (authorization.workerId !== receipt.workerId || authorization.identityId == null ||
authorization.identityId !== receipt.workerIdentityId || authorization.binding?.tenantId !== admission.tenantId ||
!Number.isSafeInteger(authorization.pairingGeneration) ||
String(authorization.pairingGeneration) !== admission.pairingGeneration ||
!isCheckpointDigest(authorization.activeCredentialId) || !isCheckpointDigest(authorization.credentialId)) return;
return { workerId: receipt.workerId, activeCredentialId: authorization.activeCredentialId,
credentialId: authorization.credentialId };
}

private async readCheckpointContext(
assignment: StoredAssignment,
source: { authorization: PairedAuthorization; signal?: AbortSignal } | { tenantId: string },
): Promise<CheckpointContext | undefined> {
if (assignment.executionKind !== 'workspace_tool' || assignment.durableRequestKey == null ||
assignment.workspaceLeaseSlot === undefined || assignment.worktreeOwnerScope == null ||
!isWorkspaceToolRequest(assignment.request) || assignment.request.operation !== 'create_worktree') return;
try {
const raw = await this.leaseCommand(this.redis.hgetall(workspaceFenceReceiptKey(assignment.assignmentId)),
signal, 'Checkpoint receipt read');
if (raw.metadata == null) return;
const receipt = JSON.parse(raw.metadata) as AssignmentOwnership | null;
const admission = readCheckpointAdmission(raw.checkpointAdmissionV1, raw.epoch);
const [metadata, checkpointAdmissionV1, epoch, activeCredentialId] = await this.leaseCommand(
this.redis.hmget(workspaceFenceReceiptKey(assignment.assignmentId),
'metadata', 'checkpointAdmissionV1', 'epoch', 'checkpointActiveCredentialId'),
'authorization' in source ? source.signal : undefined, 'Checkpoint receipt read');
if (metadata == null || checkpointAdmissionV1 == null || epoch == null) return;
const receipt = JSON.parse(metadata) as AssignmentOwnership | null;
const admission = readCheckpointAdmission(checkpointAdmissionV1, epoch);
if (receipt == null || admission == null || admission.ownerScope !== assignment.worktreeOwnerScope ||
(tenantId != null && admission.tenantId !== tenantId) ||
('tenantId' in source && admission.tenantId !== source.tenantId) ||
receipt.assignmentId !== assignment.assignmentId || receipt.workerId !== assignment.workerId ||
receipt.incarnationId !== assignment.incarnationId || receipt.generation !== assignment.generation ||
receipt.workspaceLeaseSlot !== assignment.workspaceLeaseSlot || receipt.workspaceFence !== assignment.workspaceFence ||
receipt.workerIdentityId !== assignment.workerIdentityId || receipt.leaseTokenHash !== assignment.leaseTokenHash ||
receipt.durableRequestKey !== assignment.durableRequestKey) return;
return this.checkpointContext(receipt, raw);
receipt.durableRequestKey !== assignment.durableRequestKey || receipt.expiresAt !== assignment.expiresAt) return;
const context = this.checkpointContext(receipt, { metadata, checkpointAdmissionV1, epoch });
if (context == null) return;
// The reconciler has no signed request. It can only extend the authority
// accepted by settlement, not acquire a new one after rotation/re-pairing.
const authority = 'authorization' in source
? this.checkpointVoteAuthority(receipt, admission, source.authorization)
: activeCredentialId != null && isCheckpointDigest(activeCredentialId)
? { workerId: receipt.workerId, activeCredentialId } : undefined;
if (authority != null) return { ...context, authority };
} catch { /* An unavailable receipt must not decide ordinary settlement or cleanup. */ }
}

Expand All @@ -2503,6 +2536,7 @@ export class RedisBridgeStore {
identityId?: string,
quarantine = true,
checkpointCandidate?: CheckpointCandidate,
authorization?: PairedAuthorization,
): Promise<void> {
// Keep a small, expiring ownership receipt separate from assignment cleanup.
// A local guard can fail to clear after the result has already committed.
Expand Down Expand Up @@ -2563,10 +2597,16 @@ export class RedisBridgeStore {
quarantine ? '1' : '0',
this.detachedFenceTtlSeconds(receipt),
];
const checkpoint = this.checkpointProofEnabled && !quarantine && checkpointCandidate != null
? checkpointTransition(keys, args, this.checkpointContext(receipt, raw),
{ kind: 'cleanup', candidate: checkpointCandidate })
: [];
let checkpoint: string[] = [];
if (this.checkpointProofEnabled && !quarantine && checkpointCandidate != null && authorization != null) {
const admission = readCheckpointAdmission(raw.checkpointAdmissionV1, raw.epoch);
if (admission != null) {
const authority = this.checkpointVoteAuthority(receipt, admission, authorization);
const context = authority == null ? undefined : this.checkpointContext(receipt, raw);
if (context != null) checkpoint = checkpointTransition(keys, args, { ...context, authority },
{ kind: 'cleanup', candidate: checkpointCandidate });
}
}
const accepted = Number(
await this.leaseCommand(
this.redis.eval(
Expand Down Expand Up @@ -3122,7 +3162,7 @@ export class RedisBridgeStore {
record.id === assignment.assignmentId && record.workerId === assignment.workerId &&
record.request.operation === 'create_worktree' && assignment.worktreeOwnerScope != null &&
isWorkspaceToolResult(record.request, settlement.result, record.registration.capabilities.workspaceTools)
? checkpointTransition(keys, args, await this.readCheckpointContext(assignment, undefined, record.tenantId), {
? checkpointTransition(keys, args, await this.readCheckpointContext(assignment, { tenantId: record.tenantId }), {
kind: 'finalization', key: durableKey, digest: record.checkpointSettlementDigest,
outcome: record.rawOutcome, assignment: record.rawAssignment,
})
Expand Down
Loading
Loading