Deliver the reviewed in-memory lifecycle permit model
of shared·codex-capacity-policy··Not checked
Version 104 · Files at version 105
2 files, 942 lines added, 0 removed.
--- /dev/null
+++ b/worker/project/lifecycle-permit-contract.ts
@@ -0,0 +1,504 @@
2+ * A deterministic model of the lifecycle permit contract for #560. 4+ * This is not a live issuer, durable authority, or authentication mechanism. 5+ * It models the serialized decisions a future server-owned authority must 6+ * preserve across restart. The caller supplies already authenticated facts. 9+export type LifecycleTransitionKind = "delete" | "restore" | "migration" | "revoke-actor"; 11+export interface LifecycleFence { 12+ readonly tenant: string; 13+ readonly project: string; 14+ readonly incarnation: number; 15+ readonly actor: string; 16+ readonly operationId: string; 17+ readonly requestDigest: string; 18+ readonly inputDigest: string; 19+ readonly rootDigest: string; 20+ readonly generation: number; 21+ readonly logHead: number; 22+ readonly sharedHead: number; 23+ readonly actorHead: number; 24+ readonly queueSequence: number; 25+ readonly authorizationRevision: number; 26+ readonly policyRevision: number; 27+ readonly build: string; 30+export interface LifecyclePermit { 32+ readonly fence: LifecycleFence; 33+ readonly authorityRevision: number; 34+ readonly status: "active" | "installed"; 37+export interface VerifiedReplayResult { 38+ readonly permitId: string; 39+ readonly operationId: string; 40+ readonly requestDigest: string; 41+ readonly inputDigest: string; 42+ readonly actor: string; 43+ readonly incarnation: number; 44+ readonly authorizationRevision: number; 45+ readonly policyRevision: number; 46+ readonly build: string; 47+ readonly outputDigest: string; 48+ readonly nextRootDigest: string; 49+ readonly nextGeneration: number; 50+ readonly nextLogHead: number; 51+ readonly nextSharedHead: number; 52+ readonly nextActorHead: number; 53+ readonly nextQueueSequence: number; 56+export interface InstallReceipt { 57+ readonly permitId: string; 58+ readonly operationId: string; 59+ readonly tenant: string; 60+ readonly project: string; 61+ readonly incarnation: number; 62+ readonly requestDigest: string; 63+ readonly outputDigest: string; 64+ readonly previousRootDigest: string; 65+ readonly nextRootDigest: string; 66+ readonly previousGeneration: number; 67+ readonly nextGeneration: number; 68+ readonly previousLogHead: number; 69+ readonly nextLogHead: number; 70+ readonly previousSharedHead: number; 71+ readonly nextSharedHead: number; 72+ readonly previousActorHead: number; 73+ readonly nextActorHead: number; 74+ readonly previousQueueSequence: number; 75+ readonly nextQueueSequence: number; 78+export interface LifecycleTransition { 80+ readonly kind: LifecycleTransitionKind; 81+ readonly actor?: string; 82+ readonly status: "draining" | "complete"; 85+interface ProjectAuthority { 86+ phase: "active" | "draining" | "deleted" | "blocked"; 88+ authorizationRevision: number; 89+ policyRevision: number; 91+ authorityRevision: number; 92+ permit: LifecyclePermit | null; 93+ transition: LifecycleTransition | null; 94+ transitions: Record<string, LifecycleTransition>; 95+ permits: Record<string, LifecyclePermit>; 96+ replayResults: Record<string, VerifiedReplayResult>; 97+ installReceipts: Record<string, InstallReceipt>; 100+export interface LifecycleAuthoritySnapshot { 101+ readonly authorityId: string; 102+ readonly revision: number; 103+ readonly blocked: boolean; 104+ readonly projects: Readonly<Record<string, ProjectAuthority>>; 105+ readonly tombstones: Readonly<Record<string, number>>; 108+function key(tenant: string, project: string): string { 109+ return `${tenant}\u0000${project}`; 112+function copy<T>(value: T): T { 113+ return structuredClone(value); 116+function same(a: unknown, b: unknown): boolean { 117+ return JSON.stringify(a) === JSON.stringify(b); 120+/** Modeled serialized authority. It deliberately has no timeout or expiry API. */ 121+export class LifecycleAuthorityModel { 123+ authorityId: string; 126+ projects: Record<string, ProjectAuthority>; 127+ tombstones: Record<string, number>; 130+ constructor(authorityId = "modeled-authority") { 131+ this.state = { authorityId, revision: 0, blocked: false, projects: {}, tombstones: {} }; 134+ static restart(snapshot: LifecycleAuthoritySnapshot, externalFloor: number): LifecycleAuthorityModel { 135+ const model = new LifecycleAuthorityModel(snapshot.authorityId); 136+ model.state = copy(snapshot); 137+ // A real authority must advance this floor atomically with each safety 138+ // mutation. This model only checks the supplied floor; it does not prove 139+ // that an independent durable floor exists or cannot be rewound. 140+ if (model.state.revision < externalFloor) { 141+ model.state.blocked = true; 142+ for (const project of Object.values(model.state.projects)) project.phase = "blocked"; 147+ snapshot(): LifecycleAuthoritySnapshot { 148+ return copy(this.state); 154+ actors: readonly string[], 155+ authorizationRevision = 1, 158+ if (this.state.blocked) throw new Error("authority rollback blocks project creation"); 159+ const projectKey = key(tenant, project); 160+ if (this.state.projects[projectKey] || this.state.tombstones[projectKey]) 161+ throw new Error("existing project identities require a serialized restore transition"); 162+ const incarnation = (this.state.tombstones[projectKey] ?? 0) + 1; 163+ this.state.revision++; 164+ this.state.tombstones[projectKey] = incarnation; 165+ this.state.projects[projectKey] = { 168+ authorizationRevision, 170+ actors: [...new Set(actors)].sort(), 171+ authorityRevision: this.state.revision, 177+ installReceipts: {}, 182+ grant(fence: LifecycleFence): LifecyclePermit { 183+ if (this.state.blocked) throw new Error("authority rollback blocks permits"); 184+ const project = this.project(fence.tenant, fence.project); 185+ const previous = project.permits[fence.operationId]; 187+ if (!same(previous.fence, fence)) throw new Error("operation identifier reused with a different fence"); 188+ return copy(previous); 190+ if (project.phase !== "active" || project.transition?.status === "draining") 191+ throw new Error("lifecycle transition blocks new permits"); 192+ if (!project.actors.includes(fence.actor)) throw new Error("actor is not authorized"); 194+ fence.incarnation !== project.incarnation || 195+ fence.authorizationRevision !== project.authorizationRevision || 196+ fence.policyRevision !== project.policyRevision 198+ throw new Error("stale lifecycle fence"); 199+ if (project.permit) throw new Error("another permit holds the project"); 200+ // Persisting a hold is itself a safety mutation. Advance the modeled 201+ // high-water revision before issuing a permit so a pre-grant snapshot 202+ // cannot be accepted after this grant. 203+ this.state.revision++; 204+ project.authorityRevision = this.state.revision; 205+ const permit: LifecyclePermit = { 206+ id: `${project.authorityRevision}:${fence.operationId}`, 208+ authorityRevision: project.authorityRevision, 211+ project.permit = permit; 212+ project.permits[fence.operationId] = permit; 213+ return copy(permit); 216+ registerReplayResult(permit: LifecyclePermit, result: VerifiedReplayResult): void { 217+ if (this.state.blocked) throw new Error("authority rollback blocks replay results"); 218+ const project = this.project(permit.fence.tenant, permit.fence.project); 219+ const authoritativePermit = project.permit; 220+ if (!authoritativePermit || authoritativePermit.id !== permit.id || authoritativePermit.status !== "active") 221+ throw new Error("replay result has no active permit"); 222+ if (!same(authoritativePermit, permit)) throw new Error("permit does not match the authoritative challenge"); 223+ const operationId = permit.fence.operationId; 224+ const existing = project.replayResults[operationId]; 226+ if (!same(existing, result)) throw new Error("conflicting replay result for permit"); 230+ result.permitId !== permit.id || 231+ result.operationId !== operationId || 232+ result.requestDigest !== permit.fence.requestDigest || 233+ result.inputDigest !== permit.fence.inputDigest || 234+ result.actor !== permit.fence.actor || 235+ result.incarnation !== permit.fence.incarnation || 236+ result.authorizationRevision !== permit.fence.authorizationRevision || 237+ result.policyRevision !== permit.fence.policyRevision || 238+ result.build !== permit.fence.build 240+ throw new Error("replay result does not match the permit challenge"); 241+ project.replayResults[operationId] = copy(result); 242+ this.state.revision++; 243+ project.authorityRevision = this.state.revision; 249+ transitionId: string, 250+ kind: LifecycleTransitionKind, 252+ ): LifecycleTransition { 253+ if (this.state.blocked) throw new Error("authority rollback blocks lifecycle changes"); 254+ const project = this.project(tenant, projectId); 255+ if (project.phase === "blocked") throw new Error("authority rollback blocks lifecycle changes"); 256+ const previous = project.transitions[transitionId]; 258+ if (previous.kind !== kind || previous.actor !== actor) throw new Error("conflicting lifecycle transition"); 259+ return copy(previous); 261+ if (project.transition?.status === "draining") throw new Error("conflicting lifecycle transition"); 262+ if (project.phase === "deleted" && kind !== "restore") throw new Error("deleted project requires restore"); 263+ if (project.phase !== "deleted" && kind === "restore") throw new Error("restore requires a deleted project"); 264+ if (kind === "revoke-actor" && (!actor || !project.actors.includes(actor))) 265+ throw new Error("actor revocation target is not active"); 266+ project.transition = { id: transitionId, kind, actor, status: "draining" }; 267+ project.transitions[transitionId] = project.transition; 268+ project.phase = "draining"; 269+ // Draining must also advance the floor: a snapshot from before this 270+ // transition must not be restarted as though no transition existed. 271+ this.state.revision++; 272+ project.authorityRevision = this.state.revision; 273+ if (!project.permit) this.finishTransition(project, tenant, projectId); 274+ return copy(project.transitions[transitionId]); 277+ resolveInstall(receipt: InstallReceipt): void { 278+ if (this.state.blocked) throw new Error("authority rollback blocks receipt resolution"); 279+ const project = this.projectById(receipt.project, receipt); 280+ const resolved = project.installReceipts[receipt.operationId]; 282+ if (!same(resolved, receipt)) throw new Error("conflicting install receipt"); 285+ const permit = project.permits[receipt.operationId]; 286+ if (!permit || permit.id !== receipt.permitId) throw new Error("receipt has no matching permit"); 287+ if (!project.permit || project.permit.id !== receipt.permitId) throw new Error("permit is not the active hold"); 288+ const result = project.replayResults[receipt.operationId]; 289+ if (!result) throw new Error("install outcome has no registered replay result"); 291+ receipt.tenant !== permit.fence.tenant || 292+ receipt.project !== permit.fence.project || 293+ receipt.incarnation !== permit.fence.incarnation || 294+ receipt.requestDigest !== permit.fence.requestDigest || 295+ receipt.outputDigest !== result.outputDigest || 296+ receipt.nextRootDigest !== result.nextRootDigest || 297+ receipt.nextGeneration !== result.nextGeneration || 298+ receipt.nextLogHead !== result.nextLogHead || 299+ receipt.nextSharedHead !== result.nextSharedHead || 300+ receipt.nextActorHead !== result.nextActorHead || 301+ receipt.nextQueueSequence !== result.nextQueueSequence || 302+ receipt.previousRootDigest !== permit.fence.rootDigest || 303+ receipt.previousGeneration !== permit.fence.generation || 304+ receipt.previousLogHead !== permit.fence.logHead || 305+ receipt.previousSharedHead !== permit.fence.sharedHead || 306+ receipt.previousActorHead !== permit.fence.actorHead || 307+ receipt.previousQueueSequence !== permit.fence.queueSequence 309+ throw new Error("install receipt does not match the held snapshot"); 310+ project.installReceipts[receipt.operationId] = copy(receipt); 311+ project.permits[receipt.operationId] = { ...permit, status: "installed" }; 312+ project.permit = null; 313+ this.state.revision++; 314+ project.authorityRevision = this.state.revision; 315+ if (project.transition) this.finishTransition(project, receipt.tenant, receipt.project); 318+ private finishTransition(project: ProjectAuthority, tenant: string, projectId: string): void { 319+ const transition = project.transition; 320+ if (!transition || transition.status !== "draining" || project.permit) return; 321+ if (transition.kind === "delete") { 322+ project.phase = "deleted"; 323+ project.incarnation++; 324+ this.state.tombstones[key(tenant, projectId)] = project.incarnation; 325+ } else if (transition.kind === "restore" || transition.kind === "migration") { 326+ project.incarnation++; 327+ project.phase = "active"; 328+ this.state.tombstones[key(tenant, projectId)] = project.incarnation; 330+ project.actors = project.actors.filter((entry) => entry !== transition.actor); 331+ project.authorizationRevision++; 332+ project.phase = "active"; 334+ this.state.revision++; 335+ project.authorityRevision = this.state.revision; 336+ project.transition = { ...transition, status: "complete" }; 337+ project.transitions[transition.id] = project.transition; 340+ private project(tenant: string, projectId: string): ProjectAuthority { 341+ const project = this.state.projects[key(tenant, projectId)]; 342+ if (!project) throw new Error("unknown project"); 346+ private projectById(projectId: string, receipt: InstallReceipt): ProjectAuthority { 347+ const project = this.state.projects[key(receipt.tenant, projectId)]; 348+ if (!project) throw new Error("unknown project"); 353+interface LocalProjectState { 354+ readonly tenant: string; 355+ readonly project: string; 356+ readonly incarnation: number; 362+ queueSequence: number; 365+export interface LocalInstallSnapshot { 366+ readonly projects: Readonly<Record<string, LocalProjectState>>; 367+ readonly receipts: Readonly<Record<string, InstallReceipt>>; 371+ * Models the project-local transaction only. A real implementation must use 372+ * one durable SQLite transaction for state and receipt. 374+export class LocalInstallStoreModel { 375+ private projects: Record<string, LocalProjectState> = {}; 376+ private receipts: Record<string, InstallReceipt> = {}; 378+ static restart(snapshot: LocalInstallSnapshot): LocalInstallStoreModel { 379+ const store = new LocalInstallStoreModel(); 380+ store.projects = copy(snapshot.projects); 381+ store.receipts = copy(snapshot.receipts); 385+ snapshot(): LocalInstallSnapshot { 386+ return copy({ projects: this.projects, receipts: this.receipts }); 392+ incarnation: number, 400+ this.projects[key(tenant, project)] = { 413+ install(permit: LifecyclePermit, result: VerifiedReplayResult): InstallReceipt { 414+ const fence = permit.fence; 415+ const receiptKey = `${fence.tenant}\u0000${fence.project}\u0000${fence.operationId}`; 416+ const existing = this.receipts[receiptKey]; 419+ existing.permitId !== permit.id || 420+ existing.outputDigest !== result.outputDigest || 421+ existing.nextRootDigest !== result.nextRootDigest || 422+ existing.nextGeneration !== result.nextGeneration || 423+ existing.nextLogHead !== result.nextLogHead || 424+ existing.nextSharedHead !== result.nextSharedHead || 425+ existing.nextActorHead !== result.nextActorHead || 426+ existing.nextQueueSequence !== result.nextQueueSequence 428+ throw new Error("operation already has a conflicting install receipt"); 429+ return copy(existing); 431+ if (permit.status !== "active") throw new Error("permit is not active"); 433+ result.permitId !== permit.id || 434+ result.operationId !== fence.operationId || 435+ result.requestDigest !== fence.requestDigest || 436+ result.inputDigest !== fence.inputDigest || 437+ result.actor !== fence.actor || 438+ result.incarnation !== fence.incarnation || 439+ result.authorizationRevision !== fence.authorizationRevision || 440+ result.policyRevision !== fence.policyRevision || 441+ result.build !== fence.build 443+ throw new Error("replay result does not match its permit"); 444+ const project = this.projects[key(fence.tenant, fence.project)]; 445+ if (!project) throw new Error("local project is missing"); 447+ project.incarnation !== fence.incarnation || 448+ project.rootDigest !== fence.rootDigest || 449+ project.generation !== fence.generation || 450+ project.logHead !== fence.logHead || 451+ project.sharedHead !== fence.sharedHead || 452+ project.actorHead !== fence.actorHead || 453+ project.queueSequence !== fence.queueSequence 455+ throw new Error("local project changed after snapshot authorization"); 457+ result.nextGeneration <= project.generation || 458+ result.nextLogHead < project.logHead || 459+ result.nextSharedHead < project.sharedHead || 460+ result.nextActorHead < project.actorHead || 461+ result.nextQueueSequence < project.queueSequence 463+ throw new Error("replay result moves a head backwards"); 465+ const receipt: InstallReceipt = { 466+ permitId: permit.id, 467+ operationId: fence.operationId, 468+ tenant: fence.tenant, 469+ project: fence.project, 470+ incarnation: fence.incarnation, 471+ requestDigest: fence.requestDigest, 472+ outputDigest: result.outputDigest, 473+ previousRootDigest: project.rootDigest, 474+ nextRootDigest: result.nextRootDigest, 475+ previousGeneration: project.generation, 476+ nextGeneration: result.nextGeneration, 477+ previousLogHead: project.logHead, 478+ nextLogHead: result.nextLogHead, 479+ previousSharedHead: project.sharedHead, 480+ nextSharedHead: result.nextSharedHead, 481+ previousActorHead: project.actorHead, 482+ nextActorHead: result.nextActorHead, 483+ previousQueueSequence: project.queueSequence, 484+ nextQueueSequence: result.nextQueueSequence, 486+ // Construct everything first, then perform the modeled atomic state/receipt commit. 487+ this.projects[key(fence.tenant, fence.project)] = { 489+ rootDigest: receipt.nextRootDigest, 490+ generation: receipt.nextGeneration, 491+ logHead: receipt.nextLogHead, 492+ sharedHead: receipt.nextSharedHead, 493+ actorHead: receipt.nextActorHead, 494+ queueSequence: receipt.nextQueueSequence, 496+ this.receipts[receiptKey] = receipt; 497+ return copy(receipt); 500+ readReceipt(tenant: string, project: string, operationId: string): InstallReceipt | null { 501+ const receipt = this.receipts[`${tenant}\u0000${project}\u0000${operationId}`]; 502+ return receipt ? copy(receipt) : null; --- /dev/null
+++ b/worker/project/test/lifecycle-permit-contract.test.ts
@@ -0,0 +1,438 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 4+ LifecycleAuthorityModel, 7+ LocalInstallStoreModel, 8+ type VerifiedReplayResult, 9+} from "../lifecycle-permit-contract.ts"; 12+ const authority = new LifecycleAuthorityModel("authority-test"); 13+ const incarnation = authority.createProject("tenant", "project", ["alice", "bob"]); 14+ const fence: LifecycleFence = { 19+ operationId: "operation-1", 20+ requestDigest: "request-digest", 21+ inputDigest: "canonical-input-digest", 22+ rootDigest: "root-0", 28+ authorizationRevision: 1, 30+ build: "engine-build-1", 32+ const beforeGrant = authority.snapshot(); 33+ const permit = authority.grant(fence); 34+ const result: VerifiedReplayResult = { 36+ operationId: fence.operationId, 37+ requestDigest: fence.requestDigest, 38+ inputDigest: fence.inputDigest, 41+ authorizationRevision: fence.authorizationRevision, 42+ policyRevision: fence.policyRevision, 44+ outputDigest: "output-digest", 45+ nextRootDigest: "root-1", 50+ nextQueueSequence: 4, 52+ const local = new LocalInstallStoreModel(); 53+ local.seed("tenant", "project", incarnation, "root-0", 0, 10, 4, 6, 3); 54+ return { authority, beforeGrant, fence, incarnation, permit, result, local }; 57+function install(permit: LifecyclePermit, result: VerifiedReplayResult, local: LocalInstallStoreModel) { 58+ return local.install(permit, result); 61+test("every new safety mutation advances the modeled rollback floor", () => { 62+ const { authority, beforeGrant, fence, permit, result, local } = setup(); 63+ const afterGrant = authority.snapshot(); 64+ assert.equal(afterGrant.revision, beforeGrant.revision + 1); 65+ assert.equal(permit.authorityRevision, afterGrant.revision); 66+ assert.deepEqual(authority.grant(fence), permit); 67+ assert.equal(authority.snapshot().revision, afterGrant.revision); 69+ const beforeReplay = authority.snapshot(); 70+ authority.registerReplayResult(permit, result); 71+ const afterReplay = authority.snapshot().revision; 72+ assert.equal(afterReplay, beforeReplay.revision + 1); 73+ authority.registerReplayResult(permit, result); 74+ assert.equal(authority.snapshot().revision, afterReplay); 76+ const beforeTransition = authority.snapshot(); 77+ const transition = authority.requestTransition("tenant", "project", "delete-floor", "delete"); 78+ const afterTransition = authority.snapshot(); 79+ assert.equal(transition.status, "draining"); 80+ assert.equal(afterTransition.revision, beforeTransition.revision + 1); 81+ assert.equal(afterTransition.projects["tenant\u0000project"]?.authorityRevision, afterTransition.revision); 82+ assert.deepEqual(authority.requestTransition("tenant", "project", "delete-floor", "delete"), transition); 83+ assert.equal(authority.snapshot().revision, afterTransition.revision); 85+ const receipt = install(permit, result, local); 86+ const beforeInstallResolution = authority.snapshot().revision; 87+ authority.resolveInstall(receipt); 88+ const afterInstallResolution = authority.snapshot().revision; 89+ assert.equal(afterInstallResolution, beforeInstallResolution + 2); 90+ assert.equal(authority.snapshot().projects["tenant\u0000project"]?.authorityRevision, afterInstallResolution); 91+ authority.resolveInstall(receipt); 92+ assert.equal(authority.snapshot().revision, afterInstallResolution); 95+test("rollback floors reject snapshots taken before grant, replay registration, or drain", () => { 96+ const { authority, beforeGrant, fence, permit, result, local } = setup(); 97+ const grantRevision = authority.snapshot().revision; 98+ const afterGrantRestart = LifecycleAuthorityModel.restart(beforeGrant, grantRevision); 99+ assert.equal(afterGrantRestart.snapshot().blocked, true); 100+ assert.equal(afterGrantRestart.snapshot().projects["tenant\u0000project"]?.permit, null); 101+ const receipt = install(permit, result, local); 102+ const blockedBeforeGrantActions = afterGrantRestart.snapshot(); 103+ assert.throws(() => afterGrantRestart.grant({ ...fence, operationId: "after-rollback" }), /rollback blocks/); 105+ () => afterGrantRestart.requestTransition("tenant", "project", "after-rollback", "delete"), 108+ assert.throws(() => afterGrantRestart.resolveInstall(receipt), /rollback blocks/); 109+ assert.deepEqual(afterGrantRestart.snapshot(), blockedBeforeGrantActions); 111+ const beforeReplay = authority.snapshot(); 112+ authority.registerReplayResult(permit, result); 113+ const afterReplayRevision = authority.snapshot().revision; 114+ assert.equal(afterReplayRevision, beforeReplay.revision + 1); 115+ const afterReplayRollback = LifecycleAuthorityModel.restart(beforeReplay, afterReplayRevision); 116+ assert.equal(afterReplayRollback.snapshot().blocked, true); 117+ const blockedBeforeReplayRegistration = afterReplayRollback.snapshot(); 118+ assert.throws(() => afterReplayRollback.registerReplayResult(permit, result), /rollback blocks/); 119+ assert.deepEqual(afterReplayRollback.snapshot(), blockedBeforeReplayRegistration); 121+ const beforeDrain = authority.snapshot(); 122+ authority.requestTransition("tenant", "project", "delete-floor", "delete"); 123+ const drainRevision = authority.snapshot().revision; 124+ assert.equal(drainRevision, beforeDrain.revision + 1); 125+ const afterDrainRollback = LifecycleAuthorityModel.restart(beforeDrain, drainRevision); 126+ assert.equal(afterDrainRollback.snapshot().blocked, true); 127+ assert.equal(afterDrainRollback.snapshot().projects["tenant\u0000project"]?.permit?.id, permit.id); 128+ const blockedBeforeDrainActions = afterDrainRollback.snapshot(); 130+ () => afterDrainRollback.grant({ ...permit.fence, operationId: "during-stale-drain" }), 134+ () => afterDrainRollback.requestTransition("tenant", "project", "second-transition", "migration"), 137+ assert.throws(() => afterDrainRollback.resolveInstall(receipt), /rollback blocks/); 138+ assert.deepEqual(afterDrainRollback.snapshot(), blockedBeforeDrainActions); 141+test("grant-first serializes deletion behind an exact installation receipt", () => { 142+ const { authority, permit, result, local } = setup(); 143+ assert.equal(authority.requestTransition("tenant", "project", "delete-1", "delete").status, "draining"); 144+ assert.throws(() => authority.grant({ ...permit.fence, operationId: "operation-2" }), /transition blocks/); 145+ assert.equal(authority.snapshot().projects["tenant\u0000project"]?.phase, "draining"); 147+ authority.registerReplayResult(permit, result); 148+ const receipt = install(permit, result, local); 149+ authority.resolveInstall(receipt); 150+ assert.equal(authority.snapshot().projects["tenant\u0000project"]?.phase, "deleted"); 151+ assert.equal(authority.snapshot().tombstones["tenant\u0000project"], 2); 152+ assert.throws(() => authority.grant({ ...permit.fence, operationId: "operation-2" }), /transition blocks/); 155+test("transition-first blocks permits and restore rotates the retained incarnation", () => { 156+ const authority = new LifecycleAuthorityModel(); 157+ const firstIncarnation = authority.createProject("tenant", "project", ["alice"]); 158+ assert.equal(authority.requestTransition("tenant", "project", "delete-1", "delete").status, "complete"); 159+ const beforeRestore = authority.snapshot(); 160+ assert.throws(() => authority.grant({ ...setup().fence, incarnation: firstIncarnation }), /transition blocks/); 161+ assert.equal(authority.requestTransition("tenant", "project", "restore-1", "restore").status, "complete"); 162+ const restored = authority.snapshot(); 163+ assert.equal(restored.projects["tenant\u0000project"]?.incarnation, 3); 164+ assert.equal(restored.tombstones["tenant\u0000project"], 3); 165+ assert.equal(beforeRestore.tombstones["tenant\u0000project"], 2); 166+ assert.throws(() => authority.grant({ ...setup().fence, incarnation: firstIncarnation }), /stale lifecycle fence/); 169+test("restart preserves an active hold and a lost install acknowledgement resolves by exact receipt", () => { 170+ const { authority, permit, result, local } = setup(); 171+ const transition = authority.requestTransition("tenant", "project", "migration-1", "migration"); 172+ assert.equal(transition.status, "draining"); 173+ authority.registerReplayResult(permit, result); 175+ const restartedAuthority = LifecycleAuthorityModel.restart(authority.snapshot(), authority.snapshot().revision); 176+ const restartedLocal = LocalInstallStoreModel.restart(local.snapshot()); 177+ assert.throws(() => restartedAuthority.grant({ ...permit.fence, operationId: "operation-2" }), /transition blocks/); 178+ assert.equal(restartedAuthority.snapshot().projects["tenant\u0000project"]?.permit?.id, permit.id); 179+ assert.equal(restartedLocal.readReceipt("tenant", "project", permit.fence.operationId), null); 181+ const receipt = install(permit, result, restartedLocal); 182+ const afterLocalCommit = LocalInstallStoreModel.restart(restartedLocal.snapshot()); 183+ const afterAuthorityCommit = LifecycleAuthorityModel.restart( 184+ restartedAuthority.snapshot(), 185+ restartedAuthority.snapshot().revision, 187+ const recoveredReceipt = afterLocalCommit.readReceipt("tenant", "project", permit.fence.operationId); 188+ assert.deepEqual(recoveredReceipt, receipt); 189+ afterAuthorityCommit.resolveInstall(recoveredReceipt!); 190+ assert.equal(afterAuthorityCommit.snapshot().projects["tenant\u0000project"]?.phase, "active"); 191+ assert.equal(afterAuthorityCommit.snapshot().projects["tenant\u0000project"]?.incarnation, 2); 193+ afterAuthorityCommit.snapshot().projects["tenant\u0000project"]?.installReceipts["operation-1"], 198+test("no install outcome leaves the hold intact across restart; there is no timeout release", () => { 199+ const { authority, permit } = setup(); 200+ authority.requestTransition("tenant", "project", "delete-1", "delete"); 201+ const restarted = LifecycleAuthorityModel.restart(authority.snapshot(), authority.snapshot().revision); 202+ assert.equal(restarted.snapshot().projects["tenant\u0000project"]?.permit?.id, permit.id); 203+ assert.equal(restarted.snapshot().projects["tenant\u0000project"]?.transition?.status, "draining"); 204+ assert.throws(() => restarted.grant({ ...permit.fence, operationId: "retry-with-new-id" }), /transition blocks/); 207+ restarted.resolveInstall({ 208+ permitId: permit.id, 209+ operationId: permit.fence.operationId, 210+ tenant: permit.fence.tenant, 211+ project: permit.fence.project, 212+ incarnation: permit.fence.incarnation, 213+ requestDigest: permit.fence.requestDigest, 214+ outputDigest: "unknown", 215+ previousRootDigest: permit.fence.rootDigest, 216+ nextRootDigest: "unknown", 217+ previousGeneration: permit.fence.generation, 219+ previousLogHead: permit.fence.logHead, 220+ nextLogHead: permit.fence.logHead, 221+ previousSharedHead: permit.fence.sharedHead, 222+ nextSharedHead: permit.fence.sharedHead, 223+ previousActorHead: permit.fence.actorHead, 224+ nextActorHead: permit.fence.actorHead, 225+ previousQueueSequence: permit.fence.queueSequence, 226+ nextQueueSequence: permit.fence.queueSequence, 228+ /no registered replay result/, 230+ assert.equal(restarted.snapshot().projects["tenant\u0000project"]?.permit?.id, permit.id); 233+test("local install commits heads and exact receipt together and retries idempotently", () => { 234+ const { permit, result, local } = setup(); 235+ const receipt = install(permit, result, local); 236+ assert.deepEqual(install(permit, result, local), receipt); 237+ const state = local.snapshot().projects["tenant\u0000project"]; 238+ assert.equal(state?.rootDigest, "root-1"); 239+ assert.equal(state?.generation, 1); 240+ assert.equal(state?.logHead, 12); 241+ assert.equal(state?.sharedHead, 5); 242+ assert.equal(state?.actorHead, 7); 243+ assert.equal(state?.queueSequence, 4); 244+ assert.deepEqual(local.readReceipt("tenant", "project", "operation-1"), receipt); 245+ assert.throws(() => install(permit, { ...result, outputDigest: "conflict" }, local), /conflicting install receipt/); 248+test("a stale local snapshot or mismatched challenge changes neither state nor receipt", () => { 249+ const { permit, result, local } = setup(); 250+ local.seed("tenant", "project", permit.fence.incarnation, "changed-root", 0, 10, 4, 6, 3); 251+ const before = local.snapshot(); 252+ assert.throws(() => install(permit, result, local), /changed after snapshot/); 253+ assert.deepEqual(local.snapshot(), before); 255+ const fresh = new LocalInstallStoreModel(); 256+ fresh.seed("tenant", "project", permit.fence.incarnation, permit.fence.rootDigest, 0, 10, 4, 6, 3); 257+ assert.throws(() => install(permit, { ...result, build: "unreviewed-build" }, fresh), /does not match its permit/); 258+ assert.equal(fresh.readReceipt("tenant", "project", "operation-1"), null); 261+test("a same-ID permit clone cannot redefine the challenge used for replay registration", () => { 262+ const { authority, permit, result } = setup(); 263+ const before = authority.snapshot(); 264+ const alteredPermit: LifecyclePermit = { 269+ authorizationRevision: 2, 271+ build: "different-build", 274+ const alteredResult = { 277+ authorizationRevision: 2, 279+ build: "different-build", 283+ () => authority.registerReplayResult(alteredPermit, alteredResult), 284+ /does not match the authoritative challenge/, 286+ assert.deepEqual(authority.snapshot(), before); 289+test("completed lifecycle transitions are not replayed by later installs after restart", () => { 290+ const initial = setup(); 291+ let authority = initial.authority; 292+ let local = initial.local; 293+ let actor = "alice"; 294+ let operationNumber = 0; 295+ let rootDigest = initial.fence.rootDigest; 296+ let generation = initial.fence.generation; 297+ let logHead = initial.fence.logHead; 298+ let sharedHead = initial.fence.sharedHead; 299+ let actorHead = initial.fence.actorHead; 300+ let queueSequence = initial.fence.queueSequence; 302+ const perform = (transition?: { kind: "delete" | "migration" | "revoke-actor"; actor?: string }) => { 303+ const project = authority.snapshot().projects["tenant\u0000project"]!; 304+ const operationId = `operation-${++operationNumber}`; 305+ const fence: LifecycleFence = { 309+ incarnation: project.incarnation, 310+ authorizationRevision: project.authorizationRevision, 311+ policyRevision: project.policyRevision, 319+ const permit = authority.grant(fence); 321+ authority.requestTransition( 324+ `transition-${operationNumber}`, 328+ const result: VerifiedReplayResult = { 329+ permitId: permit.id, 331+ requestDigest: fence.requestDigest, 332+ inputDigest: fence.inputDigest, 334+ incarnation: fence.incarnation, 335+ authorizationRevision: fence.authorizationRevision, 336+ policyRevision: fence.policyRevision, 338+ outputDigest: `output-${operationNumber}`, 339+ nextRootDigest: `root-${operationNumber}`, 340+ nextGeneration: generation + 1, 341+ nextLogHead: logHead + 2, 342+ nextSharedHead: sharedHead + 1, 343+ nextActorHead: actorHead + 1, 344+ nextQueueSequence: queueSequence, 346+ authority.registerReplayResult(permit, result); 347+ const receipt = local.install(permit, result); 348+ authority.resolveInstall(receipt); 349+ rootDigest = result.nextRootDigest; 350+ generation = result.nextGeneration; 351+ logHead = result.nextLogHead; 352+ sharedHead = result.nextSharedHead; 353+ actorHead = result.nextActorHead; 354+ queueSequence = result.nextQueueSequence; 355+ return authority.snapshot().projects["tenant\u0000project"]!; 358+ const restart = () => { 359+ const snapshot = authority.snapshot(); 360+ authority = LifecycleAuthorityModel.restart(snapshot, snapshot.revision); 361+ local = LocalInstallStoreModel.restart(local.snapshot()); 363+ const rebindLocalIncarnation = (incarnation: number) => { 364+ const snapshot = local.snapshot(); 365+ const projectKey = "tenant\u0000project"; 366+ const projectState = snapshot.projects[projectKey]!; 367+ local = LocalInstallStoreModel.restart({ 369+ projects: { ...snapshot.projects, [projectKey]: { ...projectState, incarnation } }, 373+ let project = perform({ kind: "migration" }); 374+ assert.equal(project.incarnation, 2); 375+ assert.equal(project.authorityRevision, authority.snapshot().revision); 377+ rebindLocalIncarnation(project.incarnation); 378+ project = perform(); 379+ assert.equal(project.incarnation, 2); 381+ project = perform({ kind: "revoke-actor", actor: "alice" }); 382+ assert.equal(project.authorizationRevision, 2); 383+ assert.equal(project.actors.includes("alice"), false); 386+ project = perform(); 387+ assert.equal(project.incarnation, 2); 388+ assert.equal(project.authorizationRevision, 2); 390+ project = perform({ kind: "delete" }); 391+ assert.equal(project.phase, "deleted"); 392+ assert.equal(project.incarnation, 3); 394+ authority.requestTransition("tenant", "project", "restore-final", "restore"); 395+ project = authority.snapshot().projects["tenant\u0000project"]!; 396+ assert.equal(project.phase, "active"); 397+ assert.equal(project.incarnation, 4); 399+ local = new LocalInstallStoreModel(); 403+ project.incarnation, 411+ project = perform(); 412+ assert.equal(project.incarnation, 4); 413+ assert.equal(project.authorizationRevision, 2); 416+test("actor revocation drains an active permit and invalidates the old authorization revision", () => { 417+ const { authority, permit, result, local } = setup(); 419+ authority.requestTransition("tenant", "project", "revoke-alice", "revoke-actor", "alice").status, 422+ authority.registerReplayResult(permit, result); 423+ const receipt = install(permit, result, local); 424+ authority.resolveInstall(receipt); 425+ const state = authority.snapshot().projects["tenant\u0000project"]; 426+ assert.equal(state?.authorizationRevision, 2); 427+ assert.equal(state?.actors.includes("alice"), false); 428+ assert.throws(() => authority.grant({ ...permit.fence, operationId: "operation-2" }), /actor is not authorized/); 431+test("authority rollback behind the independent high-water floor fails closed", () => { 432+ const { authority, permit } = setup(); 433+ const behind = LifecycleAuthorityModel.restart(authority.snapshot(), authority.snapshot().revision + 1); 434+ assert.throws(() => behind.grant({ ...permit.fence, operationId: "operation-2" }), /rollback blocks/); 435+ assert.throws(() => behind.requestTransition("tenant", "project", "delete-1", "delete"), /rollback blocks/); 436+ assert.throws(() => behind.createProject("tenant", "other", ["alice"]), /rollback blocks/); 437+ assert.equal(behind.snapshot().projects["tenant\u0000project"]?.phase, "blocked");