From 5c1ae216ff95887a106ebfcb18c8d7ac6d84ca0c Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Fri, 4 Dec 2026 18:24:07 -0500 Subject: [PATCH] feat(bridge): Seal checkpoint proof before releasing the lane --- service/src/bridge/checkpoint.ts | 112 +++++++++ service/src/bridge/store.ts | 209 +++++++++++----- service/src/workspace-tools/requests.test.ts | 241 +++++++++++++++++++ service/src/workspace-tools/requests.ts | 5 + 4 files changed, 512 insertions(+), 55 deletions(-) create mode 100644 service/src/bridge/checkpoint.ts diff --git a/service/src/bridge/checkpoint.ts b/service/src/bridge/checkpoint.ts new file mode 100644 index 00000000..91e669b0 --- /dev/null +++ b/service/src/bridge/checkpoint.ts @@ -0,0 +1,112 @@ +/** Private receipt data. Admission/negotiation must write this alongside the + * exact ownership metadata and epoch; no production path enrolls it yet. */ +export interface CheckpointAdmission { + version: 1; + epoch: string; + ownerScope: string; + tenantId: string; + pairingGeneration: string; +} + +export interface CheckpointCandidate { + epoch: string; + commitment: string; +} + +export function isCheckpointDigest(value: string | undefined): value is string { + return value != null && value.length === 64 && /^[a-f0-9]+$/.test(value); +} + +function decimal(value: unknown): value is string { + return typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value) && value.length <= 19; +} + +export function readCheckpointAdmission(raw: string | undefined, epoch: string | undefined): CheckpointAdmission | undefined { + if (raw == null || !decimal(epoch) || epoch === '0') return; + try { + const value = JSON.parse(raw) as Partial | null; + if (value?.version === 1 && value.epoch === epoch && + typeof value.ownerScope === 'string' && isCheckpointDigest(value.ownerScope) && + typeof value.tenantId === 'string' && value.tenantId.length > 0 && + decimal(value.pairingGeneration)) return value as CheckpointAdmission; + } catch { /* Malformed optional metadata never blocks ordinary work. */ } +} + +export interface CheckpointContext { + keys: string[]; + args: string[]; + epoch: string; +} + +type CheckpointVote = + | { kind: 'settlement'; candidate: CheckpointCandidate; digest: string; ackKey: string } + | { kind: 'cleanup'; candidate: CheckpointCandidate } + | { 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. */ +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 []; + const keyOffset = keys.length; + const argOffset = args.length; + const k = (i: number) => `KEYS[${keyOffset + i}]`; + const a = (i: number) => `ARGV[${argOffset + i}]`; + const receipt = k(1); + 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])); + // 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 eligible()', + ` if ${field('metadata')} ~= ${a(1)} or ${field('checkpointAdmissionV1')} ~= ${a(2)} or ${field('epoch')} ~= ${a(3)} 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`, + ` 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)}`, + ' 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)})`, + ' end', + ] : [ + ` local commitment = ${field('checkpointCommitment')}`, + ` local digest = ${field('checkpointSettlementDigest')}`, + " if type(commitment) == 'string' and type(digest) == 'string' and", + ` ${field('checkpointReceiptDigest')} == ${a(9)} and`, + ...(vote.kind === 'cleanup' ? [ + ` commitment == ${value} and ${field('localCleanup')} == false then`, + ` ${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`, + ` ${put('checkpointFinalizationVote', 'digest')}`, + ]), + ` if ${field('checkpointCleanupVote')} == digest and ${field('checkpointFinalizationVote')} == digest then`, + " local time = redis.call('TIME')", + ` ${put('checkpointCertificateV1', `cjson.encode({version = 1, epoch = ${a(3)}, commitment = commitment, settlementDigest = digest, committedAtMs = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)})`)}`, + ' end', + ' end', + ]), + ' end', + 'end', + ]; +} diff --git a/service/src/bridge/store.ts b/service/src/bridge/store.ts index 8e757d4f..9badecf5 100644 --- a/service/src/bridge/store.ts +++ b/service/src/bridge/store.ts @@ -33,6 +33,8 @@ 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 { checkpointTransition, isCheckpointDigest, readCheckpointAdmission } from './checkpoint'; import type { StoredWorkspaceRequest } from '../workspace-tools/requests'; const PREFIX = 'codeapi:bridge:v1'; @@ -148,6 +150,7 @@ export interface DurableWorkspaceOutcome { result?: WorkspaceToolResult; error?: DurableWorkspaceError; settlement?: CodeBridgeWorkspaceSettlement; + checkpointSettlementDigest?: string; } type AssignmentOwnership = Pick< @@ -602,6 +605,8 @@ export class RedisBridgeStore { public readonly laneGitEnabled = false, /** Schedule `detached` commands apart from their worktree. On by default; needs more than one slot. */ private readonly detachedCommandsEnabled = true, + /** Internal proof transitions only; not wired to deployment configuration or negotiation. */ + private readonly checkpointProofEnabled = false, ) { if ( !Number.isSafeInteger(maxWorkspaceLeaseSlots) || @@ -1114,16 +1119,17 @@ export class RedisBridgeStore { } const assignment = record.assignment; if (assignment == null) throw new Error('Durable admitted request has no assignment'); + let raw: string | null; let settlement: CodeBridgeWorkspaceSettlement; try { - const raw = await boundedCommand(this.redis.get(settlementKey(record.id)), this.redisCommandTimeoutMs, 'Durable settlement lookup'); + raw = await boundedCommand(this.redis.get(settlementKey(record.id)), this.redisCommandTimeoutMs, 'Durable settlement lookup'); if (raw == null && record.cancelRequested !== true && Date.now() < Date.parse(assignment.expiresAt)) return; - if (raw != null) settlement = JSON.parse(raw) as CodeBridgeWorkspaceSettlement; - else { + if (raw == null) { const controller = new AbortController(); if (record.cancelRequested === true) controller.abort(); - settlement = await this.waitForSettlement(assignment, Date.parse(assignment.expiresAt), controller.signal) as unknown as CodeBridgeWorkspaceSettlement; + raw = await this.waitForSettlementBytes(assignment, Date.parse(assignment.expiresAt), controller.signal); } + settlement = JSON.parse(raw) as CodeBridgeWorkspaceSettlement; } catch (error) { if (!(error instanceof BridgeStoreError) || error.code !== 'ASSIGNMENT_EXPIRED') throw error; if (record.cancelRequested === true && !isWorkspaceMutation(record.request)) return { state: 'cancelled' }; @@ -1133,7 +1139,12 @@ export class RedisBridgeStore { if (!isWorkspaceToolResult(record.request, settlement.result, record.registration.capabilities.workspaceTools)) { return { state: 'failed', error: { code: 'RESULT_INVALID', message: 'Code environment returned an invalid workspace result. Do not replay this operation.' } }; } - return { state: 'completed', result: settlement.result, settlement }; + return { + state: 'completed', result: settlement.result, settlement, + ...(this.checkpointProofEnabled && assignment.worktreeOwnerScope != null && + assignment.workspaceLeaseSlot !== undefined && record.request.operation === 'create_worktree' + ? { checkpointSettlementDigest: tokenHash(raw) } : {}), + }; } const commandFailure = readBridgeCommandFailure(settlement.commandFailure); return { @@ -1148,7 +1159,9 @@ export class RedisBridgeStore { async finishDurableWorkspaceTool(record: StoredWorkspaceRequest): Promise { if (record.assignment != null) { - if (record.settlement != null) await this.commitPendingWorkspace(record.assignment, record.settlement, record.key); + if (record.settlement != null) { + await this.commitPendingWorkspace(record.assignment, record.settlement, record.key, record); + } await this.cleanupDispatch(record.workerId, record.id, record.assignment); } else { await this.cleanupUnassignedSlot(record.workerId, record.registration.incarnationId, record.id); @@ -2033,6 +2046,7 @@ export class RedisBridgeStore { signal?: AbortSignal, identityId?: string, quarantineWorkspace = false, + checkpointCandidate?: CheckpointCandidate, ): Promise { settlement = withValidCommandFailure(settlement); if (quarantineWorkspace) { @@ -2181,6 +2195,18 @@ export class RedisBridgeStore { if (validatedWorkspaceTool) { settlementKeys.push(workspaceFenceReceiptKey(assignmentId)); } + const settlementArgs = [ + serializedSettlement, String(ttlSeconds), assignmentId, settlement.status, + identityId ?? '', hasWorkspace ? '1' : '0', settlement.incarnationId, + assignment.workspaceLeaseSlot === undefined ? '0' : '1', validatedWorkspaceTool ? '1' : '0', + String(settlementKeys.length - Number(validatedWorkspaceTool)), + ]; + const checkpoint = this.checkpointProofEnabled && settlement.status === 'fulfilled' && + checkpointCandidate != null && assignment.worktreeOwnerScope != null + ? checkpointTransition(settlementKeys, settlementArgs, + await this.readCheckpointContext(assignment, signal), + { kind: 'settlement', candidate: checkpointCandidate, digest: tokenHash(serializedSettlement), ackKey: settlementKeys[3] }) + : []; const script = [ "local existing = redis.call('GET', KEYS[2])", 'if existing then', @@ -2190,7 +2216,7 @@ export class RedisBridgeStore { "if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end", 'if ARGV[6] == "1" and redis.call(\'GET\', KEYS[6]) ~= ARGV[3] then return -2 end', 'if ARGV[4] ~= "rejected" and redis.call(\'EXISTS\', KEYS[5]) == 0 then return -3 end', - 'local last = #KEYS - tonumber(ARGV[9])', + 'local last = tonumber(ARGV[10])', 'local stableIdentityKey = KEYS[last - 1]', 'if ARGV[5] ~= "" then', " if redis.call('GET', stableIdentityKey) ~= ARGV[5] then return -4 end", @@ -2198,12 +2224,13 @@ export class RedisBridgeStore { 'end', "if redis.call('GET', KEYS[last]) ~= ARGV[7] then return -4 end", 'redis.call(\'SET\', KEYS[2], ARGV[1], \"EX\", ARGV[2])', + ...checkpoint, "if redis.call('GET', KEYS[3]) == ARGV[3] then redis.call('DEL', KEYS[3], KEYS[4]) end", 'if ARGV[6] == "1" and ARGV[4] == "rejected" and ARGV[8] ~= "1" then', " redis.call('DEL', KEYS[6])", 'end', - "if ARGV[9] == '1' and redis.call('EXISTS', KEYS[#KEYS]) == 1 then", - " redis.call('HSET', KEYS[#KEYS], 'validatedWorkspaceTool', '1')", + "if ARGV[9] == '1' and redis.call('EXISTS', KEYS[last + 1]) == 1 then", + " redis.call('HSET', KEYS[last + 1], 'validatedWorkspaceTool', '1')", 'end', 'return 1', ].join('\n'); @@ -2213,15 +2240,7 @@ export class RedisBridgeStore { script, settlementKeys.length, ...settlementKeys, - serializedSettlement, - String(ttlSeconds), - assignmentId, - settlement.status, - identityId ?? '', - hasWorkspace ? '1' : '0', - settlement.incarnationId, - assignment.workspaceLeaseSlot === undefined ? '0' : '1', - validatedWorkspaceTool ? '1' : '0', + ...settlementArgs, ), signal, 'Bridge settlement commit', @@ -2385,6 +2404,7 @@ export class RedisBridgeStore { intent: AnyCodeBridgeSettlement, signal?: AbortSignal, identityId?: string, + checkpointCandidate?: CheckpointCandidate, ): Promise { await this.quarantineSettledWorkspace( workerId, @@ -2393,9 +2413,54 @@ export class RedisBridgeStore { signal, identityId, false, + checkpointCandidate, ); } + private checkpointContext( + receipt: AssignmentOwnership, + raw: Partial>, + ): CheckpointContext | undefined { + if (receipt.durableRequestKey == null || receipt.workerIdentityId == null || + receipt.workspaceLeaseSlot === undefined || receipt.workspaceFence == null) return; + const parent = workspaceFenceParent(receipt.workspaceFence); + const admission = readCheckpointAdmission(raw.checkpointAdmissionV1, raw.epoch); + if (parent == null || admission == null || raw.metadata == null || raw.checkpointAdmissionV1 == null) return; + const { workerId, incarnationId, assignmentId } = receipt; + const fence = workspaceQuarantineKey(workerId, receipt.workspaceFence); + return { + keys: [workspaceFenceReceiptKey(assignmentId), `${fence}:epoch`, fence, + workspaceQuarantineKey(workerId, parent), workerIncarnationKey(workerId), + workerStableIdentityKey(workerId), `${PREFIX}:pairing-generation:${workerId}`, + incarnationFenceKey(workerId, incarnationId), quarantineKey(workerId, incarnationId), workerKey(workerId)], + epoch: admission.epoch, + args: [raw.metadata, raw.checkpointAdmissionV1, admission.epoch, assignmentId, incarnationId, + receipt.workerIdentityId, admission.pairingGeneration, admission.tenantId, + tokenHash(JSON.stringify([raw.metadata, raw.checkpointAdmissionV1]))], + }; + } + + private async readCheckpointContext(assignment: StoredAssignment, signal?: AbortSignal, tenantId?: string) { + 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); + if (receipt == null || admission == null || admission.ownerScope !== assignment.worktreeOwnerScope || + (tenantId != null && admission.tenantId !== 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); + } catch { /* An unavailable receipt must not decide ordinary settlement or cleanup. */ } + } + private async quarantineSettledWorkspace( workerId: string, assignmentId: string, @@ -2403,6 +2468,7 @@ export class RedisBridgeStore { signal?: AbortSignal, identityId?: string, quarantine = true, + checkpointCandidate?: CheckpointCandidate, ): Promise { // Keep a small, expiring ownership receipt separate from assignment cleanup. // A local guard can fail to clear after the result has already committed. @@ -2434,6 +2500,39 @@ export class RedisBridgeStore { ); } const fence = workspaceQuarantineKey(workerId, receipt.workspaceFence); + const keys = [ + receiptKey, + workerIncarnationKey(workerId), + workerStableIdentityKey(workerId), + `${fence}:epoch`, + fence, + settlementKey(assignmentId), + leaseClaimKey( + workerId, + receipt.incarnationId, + receipt.workspaceLeaseSlot, + ), + leaseAckKey( + workerId, + receipt.incarnationId, + receipt.workspaceLeaseSlot, + ), + ]; + const args = [ + raw.metadata, + receipt.incarnationId, + identityId ?? '', + raw.epoch, + assignmentId, + JSON.stringify(settlement), + assignmentOutcomeTtlSeconds(receipt), + quarantine ? '1' : '0', + this.detachedFenceTtlSeconds(receipt), + ]; + const checkpoint = this.checkpointProofEnabled && !quarantine && checkpointCandidate != null + ? checkpointTransition(keys, args, this.checkpointContext(receipt, raw), + { kind: 'cleanup', candidate: checkpointCandidate }) + : []; const accepted = Number( await this.leaseCommand( this.redis.eval( @@ -2457,6 +2556,7 @@ export class RedisBridgeStore { 'else', " local fence = redis.call('GET', KEYS[5])", " if fence and string.sub(fence, 1, 12) == 'quarantined:' then return 0 end", + ...checkpoint, " redis.call('HSET', KEYS[1], 'localCleanup', '1')", " if fence == ARGV[5] and redis.call('HGET', KEYS[1], 'validatedWorkspaceTool') == '1' and redis.call('EXISTS', KEYS[6]) == 1 then", " redis.call('HSET', KEYS[1], 'resultCommitted', '1')", @@ -2467,32 +2567,9 @@ export class RedisBridgeStore { "if redis.call('GET', KEYS[8]) == ARGV[5] then redis.call('DEL', KEYS[8]) end", 'return 1', ].join('\n'), - 8, - receiptKey, - workerIncarnationKey(workerId), - workerStableIdentityKey(workerId), - `${fence}:epoch`, - fence, - settlementKey(assignmentId), - leaseClaimKey( - workerId, - receipt.incarnationId, - receipt.workspaceLeaseSlot, - ), - leaseAckKey( - workerId, - receipt.incarnationId, - receipt.workspaceLeaseSlot, - ), - raw.metadata, - receipt.incarnationId, - identityId ?? '', - raw.epoch, - assignmentId, - JSON.stringify(settlement), - assignmentOutcomeTtlSeconds(receipt), - quarantine ? '1' : '0', - this.detachedFenceTtlSeconds(receipt), + keys.length, + ...keys, + ...args, ), signal, 'Workspace quarantine fence commit', @@ -2608,6 +2685,14 @@ export class RedisBridgeStore { deadlineAtMs: number, signal: AbortSignal, ): Promise { + return JSON.parse(await this.waitForSettlementBytes(assignment, deadlineAtMs, signal)) as CodeBridgeSettlement; + } + + private async waitForSettlementBytes( + assignment: StoredAssignment, + deadlineAtMs: number, + signal: AbortSignal, + ): Promise { let pollError: unknown; try { while (!signal.aborted && Date.now() < deadlineAtMs) { @@ -2620,7 +2705,7 @@ export class RedisBridgeStore { 'Bridge settlement poll', signal, ); - if (raw != null) return JSON.parse(raw) as CodeBridgeSettlement; + if (raw != null) return raw; await delay(POLL_INTERVAL_MS, signal); } } catch (error) { @@ -2663,7 +2748,7 @@ export class RedisBridgeStore { ), 'Bridge cancelled workspace settlement poll', ); - if (raw != null) return JSON.parse(raw) as CodeBridgeSettlement; + if (raw != null) return raw; await delay( Math.min( cancellationPollMs, @@ -2711,7 +2796,7 @@ export class RedisBridgeStore { 'Bridge settlement close', ); if (finalSettlement != null) { - return JSON.parse(String(finalSettlement)) as CodeBridgeSettlement; + return String(finalSettlement); } if (pollError != null && !signal.aborted && Date.now() < deadlineAtMs) { throw pollError; @@ -2988,13 +3073,32 @@ export class RedisBridgeStore { assignment: StoredAssignment, settlement: AnyCodeBridgeSettlement, durableKey?: string, + record?: StoredWorkspaceRequest, ): Promise { if (assignment.workspaceLeaseSlot !== undefined) { + const keys = [ + workspaceQuarantineKey(assignment.workerId, assignment.workspaceFence!), + workspaceFenceReceiptKey(assignment.assignmentId), + ]; + const args = [assignment.assignmentId, settlement.status]; + const checkpoint = this.checkpointProofEnabled && record?.state === 'completed' && + settlement.status === 'fulfilled' && durableKey === assignment.durableRequestKey && + durableKey != null && record.rawOutcome != null && record.rawAssignment != null && + isCheckpointDigest(record.checkpointSettlementDigest) && + 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), { + kind: 'finalization', key: durableKey, digest: record.checkpointSettlementDigest, + outcome: record.rawOutcome, assignment: record.rawAssignment, + }) + : []; const committed = Number( await boundedCommand( this.redis.eval( [ "if redis.call('EXISTS', KEYS[2]) == 0 then return 0 end", + ...checkpoint, "redis.call('HSET', KEYS[2], 'resultCommitted', '1')", // A worker rejects only work that left the root unchanged, so its fence need not // wait for a cleanup acknowledgement that a stopping worker may never deliver. @@ -3002,14 +3106,9 @@ export class RedisBridgeStore { "if (ARGV[2] == 'rejected' or redis.call('HGET', KEYS[2], 'localCleanup') == '1') and redis.call('GET', KEYS[1]) == ARGV[1] then redis.call('DEL', KEYS[1]) end", 'return 1', ].join('\n'), - 2, - workspaceQuarantineKey( - assignment.workerId, - assignment.workspaceFence!, - ), - workspaceFenceReceiptKey(assignment.assignmentId), - assignment.assignmentId, - settlement.status, + keys.length, + ...keys, + ...args, ), this.redisCommandTimeoutMs, 'Bridge native workspace result commit', diff --git a/service/src/workspace-tools/requests.test.ts b/service/src/workspace-tools/requests.test.ts index c40f5f46..69a3730f 100644 --- a/service/src/workspace-tools/requests.test.ts +++ b/service/src/workspace-tools/requests.test.ts @@ -1183,3 +1183,244 @@ for (const slots of [1, 2]) { expect((await replica.get(owner, requestId))?.state).toBe('completed'); }); } + +// Admission and wire negotiation are intentionally absent in this slice. Only +// these real-Redis tests seed a receipt extension or pass candidate metadata. +const checkpointTest = testRedisUrl ? test : test.skip; +const identityId = 'paired-worker-identity'; +const pairingKey = `codeapi:bridge:v1:pairing-generation:${workerId}`; +const slotsKey = `codeapi:bridge:v1:worker:${workerId}:workspace-slots`; +const principal = { ...owner, principalSource: 'librechat_jwt' }; +const creation = { protocolVersion: 1, operation: 'create_worktree', ...lane, commit: 'a'.repeat(40) } as const; + +async function checkpointFixture(admit = true, acknowledge = true) { + const proof = new RedisBridgeStore(redis, 600, 1000, 3, false, true, true); + await redis.set(pairingKey, '4'); + await redis.set(`codeapi:bridge:v1:stable-identity:${workerId}`, identityId); + const generation = await proof.register({ protocolVersion: 1, workerId, incarnationId, identityId, + binding: { tenantId: owner.tenantId, principal: { type: 'tenant', id: owner.tenantId } }, + capabilities: { + sandboxProfile: 'native-srt', statefulWorkspace: false, runtimes: ['bash'], + workspaceLeaseSlots: 2, requiresReadyConfirmation: true, + workspaceTools: { protocolVersion: 1, worktreeOwnerScope: true, operations: ['create_worktree'], + workspaces: [{ id: lane.workspaceId, workspaceScopes: ['git_linked_worktree'], operations: ['create_worktree'] }] }, + }, + }, { identityId, pairingGeneration: 4 }); + await proof.confirmReady(workerId, incarnationId, generation); + const requests = new RedisWorkspaceRequests(redis, proof); + await requests.submit({ owner: principal, requestId, workerId, requireTenantBinding: true, + request: creation, queueWaitMs: 300_000, executionTimeoutMs: 30_000 }); + await tick(requests); + const [key] = await redis.zrange(activeKey, 0, -1); + const assignment = (await proof.lease(workerId, incarnationId, 0, undefined, identityId, 0))!; + if (acknowledge) { + await proof.acknowledgeLease(workerId, incarnationId, assignment.assignmentId, assignment.generation, + assignment.leaseToken); + } + const id = assignment.assignmentId; + const receipt = `codeapi:bridge:v1:assignment:${id}:workspace-fence-owner`; + const settlementKey = `codeapi:bridge:v1:assignment:${id}:settlement`; + const epoch = (await redis.hget(receipt, 'epoch'))!; + const candidate = { epoch, commitment: 'b'.repeat(64) }; + if (admit) await redis.hset(receipt, 'checkpointAdmissionV1', JSON.stringify({ + version: 1, epoch, ownerScope: assignment.worktreeOwnerScope, tenantId: owner.tenantId, pairingGeneration: '4', + })); + const result = { protocolVersion: 1 as const, generation: assignment.generation, incarnationId, + leaseToken: assignment.leaseToken, status: 'fulfilled' as const, result: creation }; + const cleanup = (store = proof, ticket = candidate) => store.confirmWorkspaceCleanup(workerId, id, + rejection(assignment, 'local cleanup confirmed'), undefined, identityId, ticket); + const settle = (store = proof, ticket = candidate, body = result) => + store.settle(workerId, id, body, undefined, identityId, false, ticket); + return { proof, requests, key, id, receipt, settlementKey, candidate, cleanup, settle, result }; +} + +for (const order of ['cleanup-first', 'finalization-first'] as const) { + checkpointTest(`checkpoint joins ${order} before native fence release, including lost replies`, async () => { + const f = await checkpointFixture(); + const certificate = () => redis.hget(f.receipt, 'checkpointCertificateV1'); + const evalOriginal = redis.eval.bind(redis); + let phase = 'settlement'; + let observed = 0; + const lost = spyOn(redis, 'eval').mockImplementation((async (...args: Parameters) => { + const reply = await evalOriginal(...args); + const script = String(args[0]); + if (phase === 'settlement' && script.includes('checkpointCommitment')) throw new Error('lost settle reply'); + if (phase === 'seal' && script.includes('committedAtMs')) { + phase = 'retry'; + ++observed; + expect(await certificate()).not.toBeNull(); + expect(await redis.get(laneFence)).toBeNull(); + expect(await redis.hget(slotsKey, 'a:0')).toBe(f.id); + throw new Error('lost seal reply'); + } + return reply; + }) as Redis['eval']); + try { + await expect(f.settle()).rejects.toThrow('lost settle reply'); + phase = 'first vote'; + // Same result, different commitment: retry must not create a new winner. + await f.settle(f.proof, { ...f.candidate, commitment: 'c'.repeat(64) }); + const raw = (await redis.get(f.settlementKey))!; + const digest = createHash('sha256').update(raw).digest('hex'); + expect(JSON.parse(raw)).toEqual(f.result); + expect(await redis.hget(f.receipt, 'checkpointCommitment')).toBe(f.candidate.commitment); + expect(await redis.hget(f.receipt, 'checkpointSettlementDigest')).toBe(digest); + if (order === 'cleanup-first') await f.cleanup(); + else await tick(f.requests); + expect(await certificate()).toBeNull(); + expect(await redis.get(laneFence)).toBe(f.id); + expect(await redis.hget(slotsKey, 'a:0')).toBe(f.id); + phase = 'seal'; + if (order === 'cleanup-first') await expect(tick(f.requests)).rejects.toThrow('lost seal reply'); + else await expect(f.cleanup()).rejects.toThrow('lost seal reply'); + expect(observed).toBe(1); + const sealed = (await certificate())!; + expect(JSON.parse(sealed)).toEqual({ version: 1, ...f.candidate, settlementDigest: digest, + committedAtMs: expect.any(Number) }); + // Replacement API retries finalization/cleanup without running another lease. + await f.cleanup(); + await tick(new RedisWorkspaceRequests(redis, f.proof)); + expect(await certificate()).toBe(sealed); + expect(await redis.hlen(slotsKey)).toBe(0); + expect(await redis.zcard(activeKey)).toBe(0); + expect(await redis.pttl(f.receipt)).toBeGreaterThan(0); + expect(await f.requests.get(principal, requestId)).toMatchObject({ state: 'completed', result: creation }); + expect(await f.requests.get(principal, requestId)).not.toHaveProperty('checkpointSettlementDigest'); + expect(await f.proof.lease(workerId, incarnationId, 0, undefined, identityId, 0)).toBeUndefined(); + } finally { lost.mockRestore(); } + }); +} + +for (const legacy of ['admission', 'settlement', 'terminal outcome', 'finalizer', 'cleanup'] as const) { + checkpointTest(`older ${legacy} cannot be upgraded into a checkpoint by retries`, async () => { + const f = await checkpointFixture(legacy !== 'admission'); + const older = new RedisWorkspaceRequests(redis, bridge); + await f.settle(legacy === 'settlement' ? bridge : f.proof); + if (legacy === 'terminal outcome') { + const pause = spyOn(bridge, 'finishDurableWorkspaceTool').mockRejectedValue(new Error('stopped before commit')); + try { await expect(tick(older)).rejects.toThrow('stopped before commit'); } finally { pause.mockRestore(); } + } + if (legacy === 'finalizer') { + const pause = spyOn(f.proof, 'finishDurableWorkspaceTool').mockRejectedValue(new Error('stopped before commit')); + try { await expect(tick(f.requests)).rejects.toThrow('stopped before commit'); } finally { pause.mockRestore(); } + await tick(older); + } + await f.cleanup(legacy === 'cleanup' ? bridge : f.proof); + await f.settle(); + await f.cleanup(); + await tick(f.requests); + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).toBeNull(); + expect(await redis.get(laneFence)).toBeNull(); + expect(await redis.hlen(slotsKey)).toBe(0); + expect(await f.requests.get(principal, requestId)).toMatchObject({ state: 'completed', result: creation }); + }); +} + +for (const failure of ['digest', 'epoch', 'reset', 'pairing', 'parent fence', 'wrong type', 'unacknowledged', 'invalid result'] as const) { + checkpointTest(`checkpoint fails closed on ${failure} without changing ordinary reconciliation`, async () => { + const f = await checkpointFixture(true, failure !== 'unacknowledged'); + const stale = { ...f.candidate, epoch: '9007199254740993' }; + await f.settle(f.proof, failure === 'epoch' ? stale : f.candidate, failure === 'invalid result' + ? { ...f.result, result: { ...creation, commit: 'c'.repeat(40) } } : f.result); + if (failure === 'digest') { + // Equivalent parsed JSON is not equivalent accepted bytes. + const raw = (await redis.get(f.settlementKey))!; + await redis.set(f.settlementKey, ` ${raw}`, 'KEEPTTL'); + } + if (failure === 'pairing') await redis.incr(pairingKey); + if (failure === 'parent fence') await redis.set(fenceKey('native-workspace:primary'), 'held'); + if (failure === 'wrong type') { + await redis.del(pairingKey); + await redis.hset(pairingKey, 'wrong', 'type'); + } + if (failure === 'reset') { + // Simulate the epoch increment at the reset/successor boundary without + // touching the base control path's reservation or current fence. + await redis.incr(`${laneFence}:epoch`); + await expect(f.cleanup()).rejects.toMatchObject({ code: 'ASSIGNMENT_FENCED' }); + } else await f.cleanup(); + await tick(f.requests); + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).toBeNull(); + const state = failure === 'invalid result' ? 'failed' : 'completed'; + expect(await f.requests.get(principal, requestId)).toMatchObject({ state }); + const kept = failure === 'reset' || failure === 'invalid result'; + expect(await redis.get(laneFence)).toBe(kept ? f.id : null); + expect(await redis.hget(slotsKey, 'a:0')).toBe(kept ? f.id : null); + }); +} + +checkpointTest('a checkpoint replacement claimant seals a completed outcome and late cleanup cannot touch a successor', async () => { + const f = await checkpointFixture(); + await f.settle(); + let resume!: () => void; + let entered!: () => void; + const paused = new Promise(resolve => { resume = resolve; }); + const reached = new Promise(resolve => { entered = resolve; }); + const finish = f.proof.finishDurableWorkspaceTool.bind(f.proof); + const stopped = spyOn(f.proof, 'finishDurableWorkspaceTool').mockImplementation(async record => { + entered(); + await paused; + await finish(record); + }); + const first = tick(f.requests); + try { + await Promise.race([reached, first.then(() => { throw new Error('finalizer did not pause'); })]); + expect(await f.requests.get(principal, requestId)).toMatchObject({ state: 'completed' }); + await f.cleanup(); + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).toBeNull(); + expect(await redis.hget(slotsKey, 'a:0')).toBe(f.id); + await redis.pexpire(`${f.key}:claim`, 0); + const replacement = new RedisBridgeStore(redis, 600, 1000, 3, false, true, true); + const requests = new RedisWorkspaceRequests(redis, replacement); + await tick(requests); + const certificate = await redis.hget(f.receipt, 'checkpointCertificateV1'); + expect(certificate).not.toBeNull(); + expect(await redis.hlen(slotsKey)).toBe(0); + await requests.submit({ owner: principal, requestId: 'request-00000000002', workerId, requireTenantBinding: true, + request: creation, queueWaitMs: 300_000, executionTimeoutMs: 30_000 }); + await tick(requests); + const successor = (await replacement.lease(workerId, incarnationId, 0, undefined, identityId, 0))!; + await expect(f.cleanup()).rejects.toMatchObject({ code: 'ASSIGNMENT_FENCED' }); + resume(); + await first; + expect(await redis.get(laneFence)).toBe(successor.assignmentId); + expect(await redis.hget(slotsKey, 'a:0')).toBe(successor.assignmentId); + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).toBe(certificate); + } finally { + resume(); + await first.catch(() => undefined); + stopped.mockRestore(); + } +}); + +checkpointTest('the checkpoint cancellation wait path hashes the actual settlement winner', async () => { + const f = await checkpointFixture(); + await f.requests.cancel(principal, requestId); + const get = redis.get.bind(redis); + let intercepted = false; + const race = spyOn(redis, 'get').mockImplementation((async (...args: Parameters) => { + if (args[0] === f.settlementKey && !intercepted) { + intercepted = true; + await f.settle(); + return null; + } + return get(...args); + }) as Redis['get']); + try { await tick(f.requests); } finally { race.mockRestore(); } + expect(intercepted).toBe(true); + await f.cleanup(); + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).not.toBeNull(); + expect(await f.requests.get(principal, requestId)).toMatchObject({ state: 'completed', cancelRequested: true }); +}); + +checkpointTest('confirmed stop cannot turn a checkpoint settlement into a cleanup vote', async () => { + const f = await checkpointFixture(); + await f.settle(); + await f.proof.recoverStoppedWorker(workerId, incarnationId); + await expect(f.cleanup()).rejects.toMatchObject({ code: 'ASSIGNMENT_FENCED' }); + await tick(f.requests); + expect(await redis.hget(f.receipt, 'checkpointCertificateV1')).toBeNull(); + expect(await redis.get(laneFence)).toBe(`quarantined:${f.id}`); + expect(await redis.hlen(slotsKey)).toBe(0); + expect(await f.requests.get(principal, requestId)).toMatchObject({ state: 'completed', result: creation }); +}); diff --git a/service/src/workspace-tools/requests.ts b/service/src/workspace-tools/requests.ts index 571e9985..1d49ee21 100644 --- a/service/src/workspace-tools/requests.ts +++ b/service/src/workspace-tools/requests.ts @@ -36,6 +36,9 @@ export interface StoredWorkspaceRequest { executionTimeoutMs: number; assignment?: DurableWorkspaceAssignment; settlement?: CodeBridgeWorkspaceSettlement; + checkpointSettlementDigest?: string; + rawOutcome?: string; + rawAssignment?: string; admittedAtMs?: number; finishedAtMs?: number; state: 'queued' | 'admitted' | 'completed' | 'failed' | 'cancelled'; @@ -194,6 +197,8 @@ export class RedisWorkspaceRequests { ...JSON.parse(fields.record) as StoredWorkspaceRequest, ...(fields.outcome == null ? {} : JSON.parse(fields.outcome)), state: fields.state as StoredWorkspaceRequest['state'], + rawOutcome: fields.outcome, + rawAssignment: fields.assignment, assignment: fields.assignment == null ? undefined : JSON.parse(fields.assignment), admittedAtMs: fields.admittedAtMs == null ? undefined : Number(fields.admittedAtMs), cancelRequested: fields.cancelRequested === '1',