@effect-agent/storage-memory 0.1.0-beta.52 → 0.1.0-beta.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,7 +62,11 @@ const decodeProducerEpoch = Schema.decodeSync(ProducerEpoch);
62
62
  const equivalentPersistedJson = Schema.toEquivalence(PersistedJson);
63
63
  const equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);
64
64
  const utc = (millis) => DateTime.toUtc(DateTime.makeUnsafe(millis));
65
- const admissionKey = (threadId, principal, idempotencyKey) => `${threadId}\u001f${principal}\u001f${idempotencyKey}`;
65
+ const admissionKey = (threadId, principal, idempotencyKey) => JSON.stringify([
66
+ threadId,
67
+ principal,
68
+ idempotencyKey
69
+ ]);
66
70
  const toSnapshot = (row) => SubmissionSnapshot.make({
67
71
  submissionId: row.submissionId,
68
72
  threadId: row.threadId,
@@ -395,6 +399,10 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
395
399
  const stored = current.submissions.get(request.submissionId);
396
400
  if (stored === void 0) return [failure(ledgerError("markInputApplied", `Unknown Submission ${request.submissionId}`)), current];
397
401
  if (!ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
402
+ if (stored.inputApplied !== void 0) {
403
+ if (stored.inputApplied.recordId === request.recordId && stored.inputApplied.sequence === request.sequence) return [success(void 0), current];
404
+ return [failure(ledgerError("markInputApplied", `A different canonical input marker is already recorded for Submission ${request.submissionId}`)), current];
405
+ }
398
406
  const marker = InputAppliedMarker.make({
399
407
  recordId: request.recordId,
400
408
  sequence: request.sequence
@@ -1 +1 @@
1
- {"version":3,"file":"MemorySubmissionLedger.mjs","names":[],"sources":["../src/MemorySubmissionLedger.ts"],"sourcesContent":["import {\n type ToolCallId,\n AttemptId,\n ReceiptId,\n SubmissionId,\n type AgentId,\n type ThreadId,\n type SettlementId,\n} from \"@effect-agent/core/Identifiers\";\nimport {\n PersistedJson,\n ProducerEpoch,\n type DefinitionDigests,\n type DeploymentId,\n type Digest,\n type ProducerId,\n type RecordEnvelope,\n type SettlementOutcome,\n} from \"@effect-agent/thread/Records\";\nimport {\n type ParentLinkage,\n AbortCommand,\n AdmissionAdmitted,\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionIndeterminate,\n AdmissionNotAdmitted,\n AdmissionRequest,\n SubmissionAdmissionFence,\n AdmissionResult,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n AttachChildToReservationRequest,\n BeginChildBudgetReleaseRequest,\n ChildAttachmentSnapshot,\n ChildBudgetReservationRequest,\n ChildBudgetReservationSnapshot,\n ChildReservationConflict,\n ChildSettledNotification,\n Claim,\n ClaimJoiningRequest,\n ClaimRequest,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n InputAppliedMarker,\n JoinSnapshot,\n JoinedToHost,\n JoiningClaim,\n LedgerCapabilities,\n LedgerError,\n MarkInputAppliedRequest,\n MarkJoinedRequest,\n MarkReadyRequest,\n MarkUnknownRequest,\n OwnershipLost,\n OwnershipRenewal,\n OwnershipSnapshot,\n OwnershipToken,\n QueueSequence,\n RecoverySnapshot,\n RecoverySnapshotRequest,\n ReleaseChildBudgetRequest,\n ReleaseOwnershipRequest,\n RenewOwnershipRequest,\n ReservedChildBudget,\n ReservedSettlement,\n RevertJoiningRequest,\n Settlement,\n SettlementConflict,\n SettlementFinalization,\n SettlementReservation,\n SettlementReservationSnapshot,\n settlementFailureFromRecord,\n AbortIntent,\n AbortIntentRequest,\n SubmissionLedger,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n SuspendRequest,\n SuspensionSnapshot,\n UnknownResolution,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n type ChildReservationId,\n type ChildReservationStatus,\n type ChildSettledOutcome,\n type IdempotencyKey,\n type Principal,\n type SubmissionState,\n type SuspensionOutcome,\n type SuspensionReason,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n Clock,\n Cause,\n Exit,\n Fiber,\n DateTime,\n Duration,\n Effect,\n Layer,\n Option,\n Ref,\n Schema,\n Stream,\n} from \"effect\";\n\nconst MAX_SUBMISSIONS = 65_536;\n\n/**\n * Lifecycle ordering used to advance-but-never-regress the operational state marker: a reclaimed\n * Attempt must not erase progress markers (input-applied, terminalizing) that an earlier Attempt\n * already committed.\n */\nconst STATE_RANK: Record<SubmissionState, number> = {\n admitted: 0,\n ready: 1,\n joining: 2,\n joined: 3,\n running: 4,\n \"input-applied\": 5,\n suspended: 6,\n unknown: 7,\n terminalizing: 8,\n settled: 9,\n};\n\ninterface SubmissionRow {\n readonly submissionId: SubmissionId;\n readonly threadId: ThreadId;\n readonly queueSequence: QueueSequence;\n readonly principal: Principal;\n readonly idempotencyKey: IdempotencyKey;\n readonly agentId: AgentId;\n readonly agentDigests: DefinitionDigests;\n readonly deploymentId: DeploymentId;\n readonly inputPayload: PersistedJson;\n readonly inputDigest: Digest;\n readonly receiptId: ReceiptId;\n readonly state: SubmissionState;\n readonly settledOutcome: SettlementOutcome | undefined;\n readonly createdAtMillis: number;\n readonly readyAtMillis: number | undefined;\n /** Immutable child-side lineage recorded at admission (spec §12 step 5). */\n readonly parentLinkage: ParentLinkage | undefined;\n readonly admissionGroup?: string;\n readonly admissionFence?: AdmissionRequest[\"admissionFence\"];\n}\n\ninterface StoredOwnership {\n readonly attemptId: AttemptId;\n readonly ownershipToken: OwnershipToken;\n readonly producerEpoch: ProducerEpoch;\n readonly ownerProducerId: ProducerId;\n readonly leaseExpiresAtMillis: number;\n}\n\ninterface StoredReservation {\n readonly settlementId: SettlementId;\n readonly outcome: SettlementOutcome;\n readonly record: RecordEnvelope;\n readonly recordDigest: Digest;\n readonly finalizedAtMillis: number | undefined;\n}\n\ninterface StoredSuspension {\n readonly reason: SuspensionReason;\n readonly suspendedAtMillis: number;\n}\n\ninterface StoredUnknownMark {\n readonly reason: MarkUnknownRequest[\"reason\"];\n readonly toolCallIds: ReadonlyArray<ToolCallId>;\n}\n\ninterface StoredUnknownResolution {\n readonly intent: UnknownResolutionIntent;\n}\n\ninterface StoredSubmission {\n readonly row: SubmissionRow;\n readonly ownership: StoredOwnership | undefined;\n readonly inputApplied: InputAppliedMarker | undefined;\n readonly reservation: StoredReservation | undefined;\n readonly abortIntent: AbortIntent | undefined;\n /** Host linkage recorded at `claimJoining` time; cleared by `revertJoining` (DUR-016). */\n readonly joinedHostSubmissionId: SubmissionId | undefined;\n readonly suspension: StoredSuspension | undefined;\n readonly unknownMark: StoredUnknownMark | undefined;\n readonly approvalDecisions: ReadonlyMap<ToolCallId, ApprovalDecisionIntent>;\n readonly unknownResolutions: ReadonlyMap<ToolCallId, StoredUnknownResolution>;\n}\n\n/**\n * States in which `claim` never grants the head: the lane is host-owned (`joining`/`joined`)\n * or durably suspended rather than worker-claimable. Unknown heads are checked against abort\n * intent separately: abort authorizes cleanup and settlement, never ordinary Tool replay.\n */\nconst BLOCKED_HEAD_STATES: ReadonlySet<SubmissionState> = new Set([\n \"joining\",\n \"joined\",\n \"suspended\",\n]);\n\ninterface LaneState {\n readonly nextQueueSequence: number;\n readonly producerEpoch: number;\n}\n\n/** One parent-owned child budget reservation row (spec §12 steps 2 and 6). */\ninterface StoredChildReservation {\n readonly reservationId: ChildReservationId;\n readonly parentSubmissionId: SubmissionId;\n readonly parentToolCallId: ToolCallId;\n readonly childSubmissionId: SubmissionId | undefined;\n readonly status: ChildReservationStatus;\n readonly allocation: PersistedJson;\n readonly allocationDigest: Digest;\n readonly accounting: PersistedJson | undefined;\n readonly reservedAtMillis: number;\n readonly releaseBeganAtMillis: number | undefined;\n readonly releasedAtMillis: number | undefined;\n}\n\ninterface LedgerState {\n readonly submissions: ReadonlyMap<SubmissionId, StoredSubmission>;\n readonly admissionIndex: ReadonlyMap<string, SubmissionId>;\n readonly lanes: ReadonlyMap<ThreadId, LaneState>;\n readonly childReservations: ReadonlyMap<ChildReservationId, StoredChildReservation>;\n readonly mintCounter: number;\n}\n\ntype Decision<A, E> =\n | { readonly _tag: \"failure\"; readonly error: E }\n | { readonly _tag: \"success\"; readonly value: A };\n\nconst failure = <E>(error: E): Decision<never, E> => ({ _tag: \"failure\", error });\nconst success = <A>(value: A): Decision<A, never> => ({ _tag: \"success\", value });\n\nconst ledgerError = (operation: string, message: string, cause?: unknown): LedgerError =>\n cause === undefined\n ? LedgerError.make({ operation, message })\n : LedgerError.make({ operation, message, cause });\n\nconst validate = Effect.fn(\"MemorySubmissionLedger.validate\")(\n <A, I>(\n schema: Schema.Codec<A, I>,\n operation: string,\n value: unknown,\n ): Effect.Effect<A, LedgerError> =>\n Schema.encodeUnknownEffect(schema)(value).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(schema)),\n Effect.mapError((error) => ledgerError(operation, `Invalid ${operation} request`, error)),\n ),\n);\n\nconst decodeSubmissionId = Schema.decodeSync(SubmissionId);\nconst decodeReceiptId = Schema.decodeSync(ReceiptId);\nconst decodeAttemptId = Schema.decodeSync(AttemptId);\nconst decodeOwnershipToken = Schema.decodeSync(OwnershipToken);\nconst decodeQueueSequence = Schema.decodeSync(QueueSequence);\nconst decodeProducerEpoch = Schema.decodeSync(ProducerEpoch);\nconst equivalentPersistedJson = Schema.toEquivalence(PersistedJson);\nconst equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);\n\nconst utc = (millis: number): DateTime.Utc => DateTime.toUtc(DateTime.makeUnsafe(millis));\n\nconst admissionKey = (\n threadId: ThreadId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n): string => `${threadId}\\u001f${principal}\\u001f${idempotencyKey}`;\n\nconst toSnapshot = (row: SubmissionRow): SubmissionSnapshot =>\n SubmissionSnapshot.make({\n submissionId: row.submissionId,\n threadId: row.threadId,\n queueSequence: row.queueSequence,\n principal: row.principal,\n idempotencyKey: row.idempotencyKey,\n agentId: row.agentId,\n agentDigests: row.agentDigests,\n deploymentId: row.deploymentId,\n inputPayload: row.inputPayload,\n inputDigest: row.inputDigest,\n receiptId: row.receiptId,\n state: row.state,\n createdAt: utc(row.createdAtMillis),\n ...(row.admissionGroup === undefined ? {} : { admissionGroup: row.admissionGroup }),\n ...(row.admissionFence === undefined ? {} : { admissionFence: row.admissionFence }),\n ...(row.settledOutcome === undefined ? {} : { settledOutcome: row.settledOutcome }),\n ...(row.readyAtMillis === undefined ? {} : { readyAt: utc(row.readyAtMillis) }),\n ...(row.parentLinkage === undefined ? {} : { parentLinkage: row.parentLinkage }),\n });\n\nconst toReservationSnapshot = (row: StoredChildReservation): ChildBudgetReservationSnapshot =>\n ChildBudgetReservationSnapshot.make({\n reservationId: row.reservationId,\n parentSubmissionId: row.parentSubmissionId,\n parentToolCallId: row.parentToolCallId,\n status: row.status,\n allocation: row.allocation,\n allocationDigest: row.allocationDigest,\n reservedAt: utc(row.reservedAtMillis),\n ...(row.childSubmissionId === undefined ? {} : { childSubmissionId: row.childSubmissionId }),\n ...(row.accounting === undefined ? {} : { accounting: row.accounting }),\n ...(row.releaseBeganAtMillis === undefined\n ? {}\n : { releaseBeganAt: utc(row.releaseBeganAtMillis) }),\n ...(row.releasedAtMillis === undefined ? {} : { releasedAt: utc(row.releasedAtMillis) }),\n });\n\n/** Linkage equality: both absent, or both present naming the same parent Tool Call. */\nconst sameParentLinkage = (\n left: ParentLinkage | undefined,\n right: ParentLinkage | undefined,\n): boolean =>\n left === undefined\n ? right === undefined\n : right !== undefined &&\n left.parentSubmissionId === right.parentSubmissionId &&\n left.parentToolCallId === right.parentToolCallId;\n\nconst laneEpoch = (state: LedgerState, threadId: ThreadId): number =>\n state.lanes.get(threadId)?.producerEpoch ?? 0;\n\nconst ownershipLost = (state: LedgerState, stored: StoredSubmission): OwnershipLost =>\n OwnershipLost.make({\n submissionId: stored.row.submissionId,\n actualEpoch: decodeProducerEpoch(laneEpoch(state, stored.row.threadId)),\n });\n\n/** The presented token owns the lane only while it matches the live ownership record. */\nconst ownsLane = (stored: StoredSubmission, ownershipToken: OwnershipToken): boolean =>\n stored.ownership !== undefined && stored.ownership.ownershipToken === ownershipToken;\n\nconst withSubmission = (state: LedgerState, stored: StoredSubmission): LedgerState => ({\n ...state,\n submissions: new Map(state.submissions).set(stored.row.submissionId, stored),\n});\n\nconst withChildReservation = (\n state: LedgerState,\n reservation: StoredChildReservation,\n): LedgerState => ({\n ...state,\n childReservations: new Map(state.childReservations).set(reservation.reservationId, reservation),\n});\n\nconst findHead = (state: LedgerState, threadId: ThreadId): StoredSubmission | undefined => {\n let head: StoredSubmission | undefined;\n\n for (const stored of state.submissions.values()) {\n if (stored.row.threadId !== threadId || stored.row.state === \"settled\") continue;\n if (head === undefined || stored.row.queueSequence < head.row.queueSequence) head = stored;\n }\n\n return head;\n};\n\n/**\n * Reference in-memory SubmissionLedger. It implements the full port contract — atomic idempotent\n * admission, FIFO-head claims, producer-epoch fencing, Clock-driven ownership leases, idempotent\n * settlement reservation/finalization, and durable abort intent — with every transition applied\n * as one atomic `Ref.modify`, but its state does not survive the process (`non-durable`).\n *\n * Adapter-specific semantics within the port's latitude:\n *\n * - Time comes exclusively from the Effect `Clock` service, so `TestClock` drives lease expiry\n * deterministically; no wall clock is consulted.\n * - The ownership lease is pinned to `DEFAULT_OWNERSHIP_LEASE_DURATION` (D5); durable adapters\n * own the configuration seam.\n * - A live lease blocks claims from other producers only: the same `producerId` may reclaim its\n * own live lease (restart recovery), which supersedes and fences the prior Attempt's token.\n * - Claiming advances `ready` to `running` and otherwise preserves the recorded state, so\n * progress markers from an earlier Attempt survive a reclaim.\n * - `renewOwnership` keeps the token stable (the port allows rotation); a replayed admission\n * reports the Submission's current state alongside the original identities.\n * - `claimJoining` walks the strictly-later queue: rows already `joining`/`joined` to the\n * SAME host extend the claimed prefix and are skipped, and an aborted-settled row is a\n * closed obligation that is also skipped (P7 §7(c)); any other non-`ready` row (an\n * `admitted` gap, a non-aborted settled row, foreign-host linkage) breaks the prefix\n * conservatively.\n * - `markJoined` verifies the token against the HOST's live ownership (the lane is\n * host-owned), so a later host Attempt can repair a lost marker from history (DUR-016). The\n * join marker reuses the input-applied marker: the joined input IS `input:{sid}`.\n * - `suspend` and `markUnknown` refuse when an exact settlement is already reserved\n * (`SettlementConflict` with the reserved outcome) — DUR-011's reservation wins.\n * - `resolveAdmission` derives its answer from the single strongly consistent store, so it\n * never answers `Indeterminate` on its own; the test-only `resolveAdmissionFault` option\n * injects the `Indeterminate` classification so SUB-031 callers can be conformance-tested.\n * - `recordChildSettled` and `suspend(WaitingForChild)` observe child settlement directly from\n * the child rows (single-store latitude); no separate notification marker is stored.\n */\nconst makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>\n Effect.gen(function* () {\n const state = yield* Ref.make<LedgerState>({\n submissions: new Map(),\n admissionIndex: new Map(),\n lanes: new Map(),\n childReservations: new Map(),\n mintCounter: 0,\n });\n\n const admissionFence = yield* SubmissionAdmissionFence;\n const leaseMillis = Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION);\n\n const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: \"non-durable\" }));\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"MemorySubmissionLedger.admit\")(\n (unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(AdmissionRequest, \"admit\", unvalidated);\n\n const nowMillis = yield* Clock.currentTimeMillis;\n const services = yield* Effect.context<never>();\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n (\n | Decision<AdmissionResult, AdmissionConflict | AdmissionPolicyError | LedgerError>\n | { readonly _tag: \"cause\"; readonly cause: Cause.Cause<AdmissionPolicyError> }\n ),\n LedgerState,\n ] => {\n const key = admissionKey(request.threadId, request.principal, request.idempotencyKey);\n const existingId = current.admissionIndex.get(key);\n\n if (existingId !== undefined) {\n const existing = current.submissions.get(existingId);\n\n if (existing === undefined) {\n return [\n failure(\n ledgerError(\"admit\", \"Admission index references a missing Submission\"),\n ),\n current,\n ];\n }\n // A replay must repeat the exact canonical input AND the exact parent linkage\n // (or its absence): linkage is immutable lineage (spec §12 step 5, SUB-016).\n if (\n existing.row.inputDigest !== request.inputDigest ||\n !sameParentLinkage(existing.row.parentLinkage, request.parentLinkage) ||\n existing.row.admissionGroup !== request.admissionGroup ||\n !Schema.toEquivalence(Schema.optional(Schema.Json))(\n existing.row.admissionFence,\n request.admissionFence,\n )\n ) {\n return [\n failure(\n AdmissionConflict.make({\n threadId: request.threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n existingInputDigest: existing.row.inputDigest,\n attemptedInputDigest: request.inputDigest,\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n AdmissionResult.make({\n submissionId: existing.row.submissionId,\n receiptId: existing.row.receiptId,\n queueSequence: existing.row.queueSequence,\n state: existing.row.state,\n replayed: true,\n }),\n ),\n current,\n ];\n }\n // A memory policy and the ledger mutation share one synchronous critical section.\n // An asynchronous policy cannot fence this Ref and therefore fails closed.\n const checked = Effect.runSyncExitWith(services)(admissionFence.check(request));\n\n if (Exit.isFailure(checked)) {\n return [{ _tag: \"cause\", cause: checked.cause }, current];\n }\n if (\n request.admissionGroup !== undefined &&\n [...current.submissions.values()].some(\n ({ row }) =>\n row.threadId === request.threadId &&\n row.admissionGroup === request.admissionGroup &&\n row.state !== \"settled\",\n )\n )\n return [\n failure(\n AdmissionPolicyError.make({ reason: \"occupied\", code: \"admission-group\" }),\n ),\n current,\n ];\n if (current.submissions.size >= MAX_SUBMISSIONS) {\n return [\n failure(\n ledgerError(\"admit\", `In-memory submission limit ${MAX_SUBMISSIONS} exceeded`),\n ),\n current,\n ];\n }\n\n const lane = current.lanes.get(request.threadId) ?? {\n nextQueueSequence: 1,\n producerEpoch: 0,\n };\n\n const mintCounter = current.mintCounter + 1;\n\n const row: SubmissionRow = {\n submissionId: decodeSubmissionId(`submission-memory-${mintCounter}`),\n threadId: request.threadId,\n queueSequence: decodeQueueSequence(lane.nextQueueSequence),\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n agentId: request.agentId,\n agentDigests: request.agentDigests,\n deploymentId: request.deploymentId,\n inputPayload: request.inputPayload,\n inputDigest: request.inputDigest,\n receiptId: decodeReceiptId(`receipt-memory-${mintCounter}`),\n state: \"admitted\",\n settledOutcome: undefined,\n createdAtMillis: nowMillis,\n readyAtMillis: undefined,\n parentLinkage: request.parentLinkage,\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n };\n\n const submissions = new Map(current.submissions).set(row.submissionId, {\n row,\n ownership: undefined,\n inputApplied: undefined,\n reservation: undefined,\n abortIntent: undefined,\n joinedHostSubmissionId: undefined,\n suspension: undefined,\n unknownMark: undefined,\n approvalDecisions: new Map<ToolCallId, ApprovalDecisionIntent>(),\n unknownResolutions: new Map<ToolCallId, StoredUnknownResolution>(),\n });\n\n const admissionIndex = new Map(current.admissionIndex).set(key, row.submissionId);\n\n const lanes = new Map(current.lanes).set(request.threadId, {\n nextQueueSequence: lane.nextQueueSequence + 1,\n producerEpoch: lane.producerEpoch,\n });\n\n return [\n success(\n AdmissionResult.make({\n submissionId: row.submissionId,\n receiptId: row.receiptId,\n queueSequence: row.queueSequence,\n state: row.state,\n replayed: false,\n }),\n ),\n { ...current, submissions, admissionIndex, lanes, mintCounter },\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n if (decision._tag === \"cause\") {\n for (const reason of decision.cause.reasons) {\n if (Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)) {\n yield* Fiber.interrupt(reason.defect.fiber);\n\n return yield* AdmissionPolicyError.make({\n reason: \"unavailable\",\n code: \"synchronous-memory-policy-required\",\n });\n }\n }\n\n return yield* Effect.failCause(decision.cause);\n }\n\n return decision.value;\n }),\n Effect.uninterruptible,\n );\n\n const markReady: SubmissionLedger[\"Service\"][\"markReady\"] = Effect.fn(\n \"MemorySubmissionLedger.markReady\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkReadyRequest, \"markReady\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markReady\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state !== \"admitted\") return [success(undefined), current];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"ready\", readyAtMillis: nowMillis },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const lookup: SubmissionLedger[\"Service\"][\"lookup\"] = Effect.fn(\n \"MemorySubmissionLedger.lookup\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SubmissionLookup, \"lookup\", unvalidated);\n const current = yield* Ref.get(state);\n\n const submissionId =\n request._tag === \"SubmissionLookupById\"\n ? request.submissionId\n : current.admissionIndex.get(\n admissionKey(request.threadId, request.principal, request.idempotencyKey),\n );\n\n const stored =\n submissionId === undefined ? undefined : current.submissions.get(submissionId);\n\n return stored === undefined ? Option.none() : Option.some(toSnapshot(stored.row));\n }),\n );\n\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"MemorySubmissionLedger.resolveAdmission\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SubmissionLookupByKey, \"resolveAdmission\", unvalidated);\n\n // Test-only fault seam: lets suites exercise the Indeterminate classification that a\n // single strongly consistent store never produces on its own (SUB-031, P6 honesty).\n if (options.resolveAdmissionFault !== undefined) {\n const fault = yield* options.resolveAdmissionFault;\n\n if (Option.isSome(fault)) {\n return AdmissionIndeterminate.make({ reason: fault.value });\n }\n }\n const current = yield* Ref.get(state);\n\n const submissionId = current.admissionIndex.get(\n admissionKey(request.threadId, request.principal, request.idempotencyKey),\n );\n\n const stored =\n submissionId === undefined ? undefined : current.submissions.get(submissionId);\n\n return stored === undefined\n ? AdmissionNotAdmitted.make()\n : AdmissionAdmitted.make({ submission: toSnapshot(stored.row) });\n }),\n );\n\n const claim: SubmissionLedger[\"Service\"][\"claim\"] = Effect.fn(\"MemorySubmissionLedger.claim\")(\n (unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ClaimRequest, \"claim\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<Option.Option<Claim>, LedgerError>, LedgerState] => {\n const head = findHead(current, request.threadId);\n\n if (head === undefined) return [success(Option.none()), current];\n if (\n BLOCKED_HEAD_STATES.has(head.row.state) ||\n (head.row.state === \"unknown\" && head.abortIntent === undefined)\n )\n return [success(Option.none()), current];\n if (\n head.ownership !== undefined &&\n head.ownership.leaseExpiresAtMillis > nowMillis &&\n head.ownership.ownerProducerId !== request.producerId\n ) {\n return [success(Option.none()), current];\n }\n const lane = current.lanes.get(request.threadId);\n\n if (lane === undefined) {\n return [\n failure(ledgerError(\"claim\", \"Claimable head without a Thread lane\")),\n current,\n ];\n }\n const producerEpoch = decodeProducerEpoch(lane.producerEpoch + 1);\n const mintCounter = current.mintCounter + 1;\n\n const ownership: StoredOwnership = {\n attemptId: decodeAttemptId(`attempt-memory-${mintCounter}`),\n ownershipToken: decodeOwnershipToken(`ownership-memory-${mintCounter}`),\n producerEpoch,\n ownerProducerId: request.producerId,\n leaseExpiresAtMillis: nowMillis + leaseMillis,\n };\n\n const row: SubmissionRow =\n head.row.state === \"ready\" ? { ...head.row, state: \"running\" } : head.row;\n\n const next = withSubmission(current, { ...head, row, ownership });\n\n const lanes = new Map(next.lanes).set(request.threadId, {\n nextQueueSequence: lane.nextQueueSequence,\n producerEpoch: lane.producerEpoch + 1,\n });\n\n return [\n success(\n Option.some(\n Claim.make({\n submissionId: row.submissionId,\n attemptId: ownership.attemptId,\n ownershipToken: ownership.ownershipToken,\n producerEpoch,\n leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),\n inputPayload: row.inputPayload,\n }),\n ),\n ),\n { ...next, lanes, mintCounter },\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const renewOwnership: SubmissionLedger[\"Service\"][\"renewOwnership\"] = Effect.fn(\n \"MemorySubmissionLedger.renewOwnership\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(RenewOwnershipRequest, \"renewOwnership\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [Decision<OwnershipRenewal, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"renewOwnership\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (stored.ownership === undefined || !ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n const ownership: StoredOwnership = {\n ...stored.ownership,\n leaseExpiresAtMillis: nowMillis + leaseMillis,\n };\n\n return [\n success(\n OwnershipRenewal.make({\n ownershipToken: ownership.ownershipToken,\n leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),\n }),\n ),\n withSubmission(current, { ...stored, ownership }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const releaseOwnership: SubmissionLedger[\"Service\"][\"releaseOwnership\"] = Effect.fn(\n \"MemorySubmissionLedger.releaseOwnership\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ReleaseOwnershipRequest, \"releaseOwnership\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"releaseOwnership\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n return [\n success(undefined),\n withSubmission(current, { ...stored, ownership: undefined }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const markInputApplied: SubmissionLedger[\"Service\"][\"markInputApplied\"] = Effect.fn(\n \"MemorySubmissionLedger.markInputApplied\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkInputAppliedRequest, \"markInputApplied\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"markInputApplied\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n const marker = InputAppliedMarker.make({\n recordId: request.recordId,\n sequence: request.sequence,\n });\n\n const row: SubmissionRow =\n STATE_RANK[stored.row.state] < STATE_RANK[\"input-applied\"]\n ? { ...stored.row, state: \"input-applied\" }\n : stored.row;\n\n return [\n success(undefined),\n withSubmission(current, { ...stored, row, inputApplied: marker }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const reserveSettlement: SubmissionLedger[\"Service\"][\"reserveSettlement\"] = Effect.fn(\n \"MemorySubmissionLedger.reserveSettlement\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SettlementReservation, \"reserveSettlement\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReservedSettlement, SettlementConflict | OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"reserveSettlement\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n\n // A `joined` Submission settles WITH its host (plan §2.5) and its lane is never\n // worker-claimable, so no ownership token can exist for it: the recorded host\n // linkage authorizes the reservation and the presented token is not consulted.\n const joinedSettlement =\n stored.row.state === \"joined\" && stored.joinedHostSubmissionId !== undefined;\n\n // P7 §7(c): an aborted, never-claimed, still-queued Submission likewise has no\n // live ownership to fence against — its durable abort intent authorizes exactly\n // its ABORTED settlement (`terminalizing` is the same pass's crash replay). Every\n // other reservation stays fenced by the target lane's live ownership.\n const queuedAbortSettlement =\n request.outcome === \"aborted\" &&\n stored.abortIntent !== undefined &&\n stored.ownership === undefined &&\n (stored.row.state === \"ready\" || stored.row.state === \"terminalizing\");\n\n if (\n !joinedSettlement &&\n !queuedAbortSettlement &&\n !ownsLane(stored, request.ownershipToken)\n ) {\n return [failure(ownershipLost(current, stored)), current];\n }\n const existing = stored.reservation;\n\n if (existing !== undefined) {\n if (\n existing.settlementId !== request.settlementId ||\n existing.outcome !== request.outcome ||\n existing.recordDigest !== request.recordDigest\n ) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: existing.outcome,\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n ReservedSettlement.make({\n submissionId: request.submissionId,\n settlementId: existing.settlementId,\n outcome: existing.outcome,\n record: existing.record,\n recordDigest: existing.recordDigest,\n replayed: true,\n }),\n ),\n current,\n ];\n }\n\n const reservation: StoredReservation = {\n settlementId: request.settlementId,\n outcome: request.outcome,\n record: request.record,\n recordDigest: request.recordDigest,\n finalizedAtMillis: undefined,\n };\n\n const row: SubmissionRow =\n STATE_RANK[stored.row.state] < STATE_RANK.terminalizing\n ? { ...stored.row, state: \"terminalizing\" }\n : stored.row;\n\n return [\n success(\n ReservedSettlement.make({\n submissionId: request.submissionId,\n settlementId: reservation.settlementId,\n outcome: reservation.outcome,\n record: reservation.record,\n recordDigest: reservation.recordDigest,\n replayed: false,\n }),\n ),\n withSubmission(current, { ...stored, row, reservation }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const finalizeSettlement: SubmissionLedger[\"Service\"][\"finalizeSettlement\"] = Effect.fn(\n \"MemorySubmissionLedger.finalizeSettlement\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SettlementFinalization, \"finalizeSettlement\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [Decision<Settlement, SettlementConflict | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"finalizeSettlement\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n const reservation = stored.reservation;\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"finalizeSettlement\",\n `No settlement reservation for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n const settlementFailure = settlementFailureFromRecord(reservation.record);\n\n if ((reservation.outcome === \"failed\") !== (settlementFailure !== undefined)) {\n return [\n failure(\n ledgerError(\n \"finalizeSettlement\",\n `Settlement reservation for Submission ${request.submissionId} has contradictory failure evidence`,\n ),\n ),\n current,\n ];\n }\n if (reservation.settlementId !== request.settlementId) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: reservation.outcome,\n }),\n ),\n current,\n ];\n }\n if (reservation.finalizedAtMillis !== undefined) {\n return [\n success(\n Settlement.make({\n submissionId: stored.row.submissionId,\n settlementId: reservation.settlementId,\n receiptId: stored.row.receiptId,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: utc(reservation.finalizedAtMillis),\n }),\n ),\n current,\n ];\n }\n\n const next = withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"settled\", settledOutcome: reservation.outcome },\n ownership: undefined,\n reservation: { ...reservation, finalizedAtMillis: nowMillis },\n });\n\n return [\n success(\n Settlement.make({\n submissionId: stored.row.submissionId,\n settlementId: reservation.settlementId,\n receiptId: stored.row.receiptId,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: utc(nowMillis),\n }),\n ),\n next,\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const requestAbort: SubmissionLedger[\"Service\"][\"requestAbort\"] = Effect.fn(\n \"MemorySubmissionLedger.requestAbort\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(AbortCommand, \"requestAbort\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<AbortIntent, SettlementConflict | JoinedToHost | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"requestAbort\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n // A joined Submission settles WITH its host; the abort target is the host (plan\n // §2.5). A joining Submission still records the intent: it is honored only if the\n // host has not consumed the input (revert-then-abort).\n if (stored.row.state === \"joined\") {\n if (stored.joinedHostSubmissionId === undefined) {\n return [\n failure(\n ledgerError(\n \"requestAbort\",\n `Joined Submission ${request.submissionId} is missing its host linkage`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n JoinedToHost.make({\n submissionId: request.submissionId,\n hostSubmissionId: stored.joinedHostSubmissionId,\n }),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"requestAbort\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n if (stored.abortIntent !== undefined) return [success(stored.abortIntent), current];\n\n const intent = AbortIntent.make({\n submissionId: request.submissionId,\n author: request.author,\n reason: request.reason,\n requestedAt: utc(nowMillis),\n });\n\n return [success(intent), withSubmission(current, { ...stored, abortIntent: intent })];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const claimJoining: SubmissionLedger[\"Service\"][\"claimJoining\"] = Effect.fn(\n \"MemorySubmissionLedger.claimJoining\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ClaimJoiningRequest, \"claimJoining\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReadonlyArray<JoiningClaim>, OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const host = current.submissions.get(request.hostSubmissionId);\n\n if (host === undefined) {\n return [\n failure(\n ledgerError(\"claimJoining\", `Unknown Submission ${request.hostSubmissionId}`),\n ),\n current,\n ];\n }\n if (host.row.threadId !== request.threadId) {\n return [\n failure(\n ledgerError(\n \"claimJoining\",\n `Host Submission ${request.hostSubmissionId} does not belong to Thread ${request.threadId}`,\n ),\n ),\n current,\n ];\n }\n if (!ownsLane(host, request.ownershipToken)) {\n return [failure(ownershipLost(current, host)), current];\n }\n\n const later = [...current.submissions.values()]\n .filter(\n (stored) =>\n stored.row.threadId === request.threadId &&\n stored.row.queueSequence > host.row.queueSequence,\n )\n .sort((left, right) => left.row.queueSequence - right.row.queueSequence);\n\n const claims: Array<JoiningClaim> = [];\n const submissions = new Map(current.submissions);\n\n for (const stored of later) {\n if (claims.length >= request.maxCount) break;\n // Rows already claimed by THIS host extend its contiguous prefix and are skipped;\n // the coordinator re-delivers already-joined input through the coverage rule.\n if (\n (stored.row.state === \"joining\" || stored.row.state === \"joined\") &&\n stored.joinedHostSubmissionId === request.hostSubmissionId\n ) {\n continue;\n }\n // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery\n // settles aborted never-claimed queued work immediately, and settlement order of\n // never-run work is not execution order (DUR-004 bounds execution).\n if (stored.row.state === \"settled\" && stored.row.settledOutcome === \"aborted\") {\n continue;\n }\n // Any other non-ready row — an admitted-not-ready gap in particular — breaks the\n // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).\n if (stored.row.state !== \"ready\") break;\n submissions.set(stored.row.submissionId, {\n ...stored,\n row: { ...stored.row, state: \"joining\" },\n joinedHostSubmissionId: request.hostSubmissionId,\n });\n claims.push(\n JoiningClaim.make({\n submissionId: stored.row.submissionId,\n queueSequence: stored.row.queueSequence,\n inputPayload: stored.row.inputPayload,\n }),\n );\n }\n\n return [success(claims), { ...current, submissions }];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const markJoined: SubmissionLedger[\"Service\"][\"markJoined\"] = Effect.fn(\n \"MemorySubmissionLedger.markJoined\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkJoinedRequest, \"markJoined\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markJoined\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.joinedHostSubmissionId === undefined) {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Submission ${request.submissionId} was never claimed for joining`,\n ),\n ),\n current,\n ];\n }\n const host = current.submissions.get(stored.joinedHostSubmissionId);\n\n if (host === undefined) {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Host Submission ${stored.joinedHostSubmissionId} is missing`,\n ),\n ),\n current,\n ];\n }\n // The lane is host-owned: the presented token must own the HOST's ownership period,\n // which also lets a later host Attempt repair a lost marker from history (DUR-016).\n if (!ownsLane(host, request.ownershipToken)) {\n return [failure(ownershipLost(current, host)), current];\n }\n if (stored.inputApplied !== undefined) {\n if (\n stored.inputApplied.recordId === request.recordId &&\n stored.inputApplied.sequence === request.sequence\n ) {\n return [success(undefined), current];\n }\n\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `A different join marker is already recorded for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state !== \"joining\" && stored.row.state !== \"joined\") {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Cannot mark Submission ${request.submissionId} joined from state ${stored.row.state}`,\n ),\n ),\n current,\n ];\n }\n\n const marker = InputAppliedMarker.make({\n recordId: request.recordId,\n sequence: request.sequence,\n });\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"joined\" },\n inputApplied: marker,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const revertJoining: SubmissionLedger[\"Service\"][\"revertJoining\"] = Effect.fn(\n \"MemorySubmissionLedger.revertJoining\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(RevertJoiningRequest, \"revertJoining\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"revertJoining\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n // Idempotent and recovery-only: only a still-`joining` Submission reverts; an\n // already-joined (or already-reverted) Submission is a no-op (DUR-016).\n if (stored.row.state !== \"joining\") return [success(undefined), current];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"ready\" },\n joinedHostSubmissionId: undefined,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const suspend: SubmissionLedger[\"Service\"][\"suspend\"] = Effect.fn(\n \"MemorySubmissionLedger.suspend\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SuspendRequest, \"suspend\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<SuspensionOutcome, OwnershipLost | SettlementConflict | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"suspend\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"suspend\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n // An exact terminal outcome is already reserved (DUR-011); suspension would\n // contradict it, so the reservation wins.\n if (stored.reservation !== undefined) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.reservation.outcome,\n }),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n // A covering event that raced ahead of the suspend transaction (an approval decision,\n // or a child settlement observed directly from the child's row in this single store)\n // resumes the caller immediately WITHOUT releasing the lane (plan §2.6, spec §12).\n const alreadyCovered =\n request.reason._tag === \"ApprovalPending\"\n ? request.reason.toolCallIds.every((toolCallId) =>\n stored.approvalDecisions.has(toolCallId),\n )\n : request.reason.children.every(\n (child) =>\n current.submissions.get(child.childSubmissionId)?.row.state === \"settled\",\n );\n\n if (alreadyCovered) {\n return [success(\"resume-immediately\" as const), current];\n }\n\n return [\n success(\"suspended\" as const),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"suspended\" },\n ownership: undefined,\n suspension: { reason: request.reason, suspendedAtMillis: nowMillis },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"MemorySubmissionLedger.recordApprovalDecision\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const command = yield* validate(\n ApprovalDecisionCommand,\n \"recordApprovalDecision\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ApprovalDecisionIntent, ApprovalConflict | SettlementConflict | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(command.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\n \"recordApprovalDecision\",\n `Unknown Submission ${command.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"recordApprovalDecision\",\n `Settled Submission ${command.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: command.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n const existing = stored.approvalDecisions.get(command.toolCallId);\n\n if (existing !== undefined) {\n if (existing.decision !== command.decision) {\n return [\n failure(\n ApprovalConflict.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n existingDecision: existing.decision,\n }),\n ),\n current,\n ];\n }\n\n return [success(existing), current];\n }\n\n const intent = ApprovalDecisionIntent.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n decision: command.decision,\n resolver: command.resolver,\n reason: command.reason,\n decidedAt: utc(nowMillis),\n });\n\n const approvalDecisions = new Map(stored.approvalDecisions).set(\n command.toolCallId,\n intent,\n );\n\n // Once every pending call of an ApprovalPending suspension is decided, the lane\n // wakes: suspended → input-applied (plan §2.6). A WaitingForChild suspension wakes\n // only through recordChildSettled.\n const wakes =\n stored.row.state === \"suspended\" &&\n stored.suspension !== undefined &&\n stored.suspension.reason._tag === \"ApprovalPending\" &&\n stored.suspension.reason.toolCallIds.every((toolCallId) =>\n approvalDecisions.has(toolCallId),\n );\n\n return [\n success(intent),\n withSubmission(current, {\n ...stored,\n row: wakes ? { ...stored.row, state: \"input-applied\" } : stored.row,\n suspension: wakes ? undefined : stored.suspension,\n approvalDecisions,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const markUnknown: SubmissionLedger[\"Service\"][\"markUnknown\"] = Effect.fn(\n \"MemorySubmissionLedger.markUnknown\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkUnknownRequest, \"markUnknown\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, SettlementConflict | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markUnknown\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"markUnknown\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n // A reserved exact outcome wins over a late Unknown marking (DUR-011); the recovery\n // classifier orders reservation ahead of MarkUnknown for the same reason.\n if (stored.reservation !== undefined) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.reservation.outcome,\n }),\n ),\n current,\n ];\n }\n // Idempotent merge: repeating is a no-op; additional open calls extend the marked\n // set while the first recorded reason is kept.\n const existing = stored.unknownMark;\n const known = new Set(existing?.toolCallIds ?? []);\n\n const merged = [\n ...(existing?.toolCallIds ?? []),\n ...request.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),\n ];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row:\n stored.row.state === \"unknown\" ? stored.row : { ...stored.row, state: \"unknown\" },\n unknownMark: { reason: existing?.reason ?? request.reason, toolCallIds: merged },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const recordUnknownResolution: SubmissionLedger[\"Service\"][\"recordUnknownResolution\"] =\n Effect.fn(\"MemorySubmissionLedger.recordUnknownResolution\")((unvalidated) =>\n Effect.gen(function* () {\n const command = yield* validate(\n UnknownResolutionCommand,\n \"recordUnknownResolution\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<\n UnknownResolutionIntent,\n UnknownResolutionConflict | SettlementConflict | LedgerError\n >,\n LedgerState,\n ] => {\n const stored = current.submissions.get(command.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\n \"recordUnknownResolution\",\n `Unknown Submission ${command.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"recordUnknownResolution\",\n `Settled Submission ${command.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: command.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n const existing = stored.unknownResolutions.get(command.toolCallId);\n\n if (\n existing !== undefined &&\n !equivalentUnknownResolution(existing.intent.resolution, command.resolution)\n ) {\n return [\n failure(\n UnknownResolutionConflict.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n }),\n ),\n current,\n ];\n }\n\n const intent =\n existing?.intent ??\n UnknownResolutionIntent.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n author: command.author,\n reason: command.reason,\n resolution: command.resolution,\n resolvedAt: utc(nowMillis),\n });\n\n const unknownResolutions =\n existing !== undefined\n ? stored.unknownResolutions\n : new Map(stored.unknownResolutions).set(command.toolCallId, {\n intent,\n });\n\n // The lane reopens only when EVERY marked open call has a durable resolution\n // intent: unknown → input-applied (DUR-017). Replays re-run the coverage check so\n // a recovering caller can wake the lane idempotently.\n const wakes =\n stored.row.state === \"unknown\" &&\n stored.unknownMark !== undefined &&\n stored.unknownMark.toolCallIds.every((toolCallId) =>\n unknownResolutions.has(toolCallId),\n );\n\n return [\n success(intent),\n withSubmission(current, {\n ...stored,\n row: wakes ? { ...stored.row, state: \"input-applied\" } : stored.row,\n unknownMark: wakes ? undefined : stored.unknownMark,\n unknownResolutions,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const recordChildSettled: SubmissionLedger[\"Service\"][\"recordChildSettled\"] = Effect.fn(\n \"MemorySubmissionLedger.recordChildSettled\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ChildSettledNotification,\n \"recordChildSettled\",\n unvalidated,\n );\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<ChildSettledOutcome, LedgerError>, LedgerState] => {\n const parent = current.submissions.get(request.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"recordChildSettled\",\n `Unknown Submission ${request.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n // The caller may notify after the canonical Settlement append but before ledger\n // finalization. In a single store, an exact reservation plus `terminalizing` is the\n // narrow durable prefix that makes that ordering admissible; earlier states remain\n // a caller error.\n const child = current.submissions.get(request.childSubmissionId);\n\n const announced =\n child !== undefined &&\n (child.row.state === \"settled\" ||\n (child.row.state === \"terminalizing\" && child.reservation !== undefined));\n\n if (!announced) {\n return [\n failure(\n ledgerError(\n \"recordChildSettled\",\n `Child Submission ${request.childSubmissionId} has no recorded settlement`,\n ),\n ),\n current,\n ];\n }\n if (\n parent.row.state !== \"suspended\" ||\n parent.suspension === undefined ||\n parent.suspension.reason._tag !== \"WaitingForChild\"\n ) {\n return [success(\"not-waiting\" as const), current];\n }\n const children = parent.suspension.reason.children;\n\n if (!children.some((entry) => entry.childSubmissionId === request.childSubmissionId)) {\n return [success(\"not-waiting\" as const), current];\n }\n\n // Every listed child must be either finalized or canonically announced from the\n // exact terminalizing reservation. Replays re-run this coverage check idempotently.\n const allSettled = children.every((entry) => {\n const listed = current.submissions.get(entry.childSubmissionId);\n\n return (\n listed?.row.state === \"settled\" ||\n (listed?.row.state === \"terminalizing\" && listed.reservation !== undefined)\n );\n });\n\n if (!allSettled) return [success(\"still-waiting\" as const), current];\n\n return [\n success(\"woken\" as const),\n withSubmission(current, {\n ...parent,\n row: { ...parent.row, state: \"input-applied\" },\n suspension: undefined,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const reserveChildBudget: SubmissionLedger[\"Service\"][\"reserveChildBudget\"] = Effect.fn(\n \"MemorySubmissionLedger.reserveChildBudget\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ChildBudgetReservationRequest,\n \"reserveChildBudget\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReservedChildBudget, ChildReservationConflict | OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const existing = current.childReservations.get(request.reservationId);\n\n if (existing !== undefined) {\n // Identical replays short-circuit before the fence, mirroring reserveSettlement:\n // a replay creates nothing, so a recovering caller resumes rather than duplicates.\n const identical =\n existing.parentSubmissionId === request.parentSubmissionId &&\n existing.parentToolCallId === request.parentToolCallId &&\n existing.allocationDigest === request.allocationDigest &&\n equivalentPersistedJson(existing.allocation, request.allocation);\n\n if (!identical) {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: existing.status,\n message:\n \"A reservation with this identity exists with a different parent Tool Call or allocation.\",\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n ReservedChildBudget.make({\n reservation: toReservationSnapshot(existing),\n replayed: true,\n }),\n ),\n current,\n ];\n }\n for (const reservation of current.childReservations.values()) {\n if (\n reservation.parentSubmissionId === request.parentSubmissionId &&\n reservation.parentToolCallId === request.parentToolCallId\n ) {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Parent Tool Call ${request.parentToolCallId} already owns reservation ${reservation.reservationId}.`,\n }),\n ),\n current,\n ];\n }\n }\n const parent = current.submissions.get(request.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"reserveChildBudget\",\n `Unknown Submission ${request.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale\n // parent Attempt can never create new reservation state.\n if (!ownsLane(parent, request.ownershipToken)) {\n return [failure(ownershipLost(current, parent)), current];\n }\n\n const reservation: StoredChildReservation = {\n reservationId: request.reservationId,\n parentSubmissionId: request.parentSubmissionId,\n parentToolCallId: request.parentToolCallId,\n childSubmissionId: undefined,\n status: \"reserved\",\n allocation: request.allocation,\n allocationDigest: request.allocationDigest,\n accounting: undefined,\n reservedAtMillis: nowMillis,\n releaseBeganAtMillis: undefined,\n releasedAtMillis: undefined,\n };\n\n return [\n success(\n ReservedChildBudget.make({\n reservation: toReservationSnapshot(reservation),\n replayed: false,\n }),\n ),\n withChildReservation(current, reservation),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const attachChildToReservation: SubmissionLedger[\"Service\"][\"attachChildToReservation\"] =\n Effect.fn(\"MemorySubmissionLedger.attachChildToReservation\")((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n AttachChildToReservationRequest,\n \"attachChildToReservation\",\n unvalidated,\n );\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<\n ChildBudgetReservationSnapshot,\n ChildReservationConflict | OwnershipLost | LedgerError\n >,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n if (reservation.childSubmissionId !== undefined) {\n // Idempotent replay of the recorded attachment (unfenced — it mutates nothing).\n if (reservation.childSubmissionId === request.childSubmissionId) {\n return [success(toReservationSnapshot(reservation)), current];\n }\n\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Reservation ${request.reservationId} already records child ${reservation.childSubmissionId}.`,\n }),\n ),\n current,\n ];\n }\n const parent = current.submissions.get(reservation.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown Submission ${reservation.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n if (!ownsLane(parent, request.ownershipToken)) {\n return [failure(ownershipLost(current, parent)), current];\n }\n if (reservation.status !== \"reserved\") {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Cannot attach a child to a ${reservation.status} reservation.`,\n }),\n ),\n current,\n ];\n }\n // Single-store latitude: the admitted child must exist here, so a dangling\n // attachment can never enter the recovery view.\n if (!current.submissions.has(request.childSubmissionId)) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown child Submission ${request.childSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n\n const attached: StoredChildReservation = {\n ...reservation,\n childSubmissionId: request.childSubmissionId,\n };\n\n return [\n success(toReservationSnapshot(attached)),\n withChildReservation(current, attached),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const beginChildBudgetRelease: SubmissionLedger[\"Service\"][\"beginChildBudgetRelease\"] =\n Effect.fn(\"MemorySubmissionLedger.beginChildBudgetRelease\")((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n BeginChildBudgetReleaseRequest,\n \"beginChildBudgetRelease\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"beginChildBudgetRelease\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n if (reservation.status !== \"reserved\") {\n // The accounting decision was already frozen exactly once; an identical replay is\n // a no-op and a divergent decision conflicts (spec §12 join step 6).\n if (\n reservation.accounting !== undefined &&\n equivalentPersistedJson(reservation.accounting, request.accounting)\n ) {\n return [success(toReservationSnapshot(reservation)), current];\n }\n\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message:\n \"A different accounting decision is already frozen for this reservation.\",\n }),\n ),\n current,\n ];\n }\n\n const frozen: StoredChildReservation = {\n ...reservation,\n status: \"releasePending\",\n accounting: request.accounting,\n releaseBeganAtMillis: nowMillis,\n };\n\n return [\n success(toReservationSnapshot(frozen)),\n withChildReservation(current, frozen),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const releaseChildBudget: SubmissionLedger[\"Service\"][\"releaseChildBudget\"] = Effect.fn(\n \"MemorySubmissionLedger.releaseChildBudget\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ReleaseChildBudgetRequest,\n \"releaseChildBudget\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"releaseChildBudget\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n // Applied exactly once: replaying a released reservation returns the stored row\n // unchanged (spec §12: \"never available twice\").\n if (reservation.status === \"released\") {\n return [success(toReservationSnapshot(reservation)), current];\n }\n if (reservation.status !== \"releasePending\") {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message:\n \"Cannot release a reservation whose accounting decision is not frozen.\",\n }),\n ),\n current,\n ];\n }\n\n const released: StoredChildReservation = {\n ...reservation,\n status: \"released\",\n releasedAtMillis: nowMillis,\n };\n\n return [\n success(toReservationSnapshot(released)),\n withChildReservation(current, released),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const scanNonterminal: SubmissionLedger[\"Service\"][\"scanNonterminal\"] = Stream.unwrap(\n Ref.get(state).pipe(\n Effect.map((current) => {\n const snapshots = [...current.submissions.values()]\n .filter((stored) => stored.row.state !== \"settled\")\n .sort((left, right) =>\n left.row.threadId < right.row.threadId\n ? -1\n : left.row.threadId > right.row.threadId\n ? 1\n : left.row.queueSequence - right.row.queueSequence,\n )\n .map((stored) => toSnapshot(stored.row));\n\n return Stream.fromIterable(snapshots);\n }),\n ),\n );\n\n const readAbortIntent: SubmissionLedger[\"Service\"][\"readAbortIntent\"] = Effect.fn(\n \"MemorySubmissionLedger.readAbortIntent\",\n )(function* (unvalidated) {\n const request = yield* validate(AbortIntentRequest, \"readAbortIntent\", unvalidated);\n const stored = (yield* Ref.get(state)).submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return yield* ledgerError(\"readAbortIntent\", `Unknown Submission ${request.submissionId}`);\n }\n\n return stored.abortIntent;\n });\n\n const loadRecoverySnapshot: SubmissionLedger[\"Service\"][\"loadRecoverySnapshot\"] = Effect.fn(\n \"MemorySubmissionLedger.loadRecoverySnapshot\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n RecoverySnapshotRequest,\n \"loadRecoverySnapshot\",\n unvalidated,\n );\n\n const current = yield* Ref.get(state);\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return yield* ledgerError(\n \"loadRecoverySnapshot\",\n `Unknown Submission ${request.submissionId}`,\n );\n }\n\n const joins = [...current.submissions.values()]\n .filter((candidate) => candidate.joinedHostSubmissionId === request.submissionId)\n .sort((left, right) => left.row.queueSequence - right.row.queueSequence)\n .map((candidate) =>\n JoinSnapshot.make({\n submissionId: candidate.row.submissionId,\n state: candidate.row.state,\n hostSubmissionId: request.submissionId,\n }),\n );\n\n const byToolCallId = <A extends { readonly toolCallId: ToolCallId }>(\n left: A,\n right: A,\n ): number =>\n left.toolCallId < right.toolCallId ? -1 : left.toolCallId > right.toolCallId ? 1 : 0;\n\n // Parent-side subagent view: this Submission's child budget reservations in parent Tool\n // Call order, plus each attached child's current lane state (a disposable derived view;\n // the canonical records stay the recovery truth, DUR-015).\n const childReservations = [...current.childReservations.values()]\n .filter((reservation) => reservation.parentSubmissionId === request.submissionId)\n .sort((left, right) =>\n left.parentToolCallId < right.parentToolCallId\n ? -1\n : left.parentToolCallId > right.parentToolCallId\n ? 1\n : 0,\n );\n\n const childAttachments: Array<ChildAttachmentSnapshot> = [];\n\n for (const reservation of childReservations) {\n if (reservation.childSubmissionId === undefined) continue;\n const child = current.submissions.get(reservation.childSubmissionId);\n\n if (child === undefined) continue;\n childAttachments.push(\n ChildAttachmentSnapshot.make({\n toolCallId: reservation.parentToolCallId,\n childSubmissionId: reservation.childSubmissionId,\n childState: child.row.state,\n ...(child.row.settledOutcome === undefined\n ? {}\n : { childOutcome: child.row.settledOutcome }),\n }),\n );\n }\n\n return RecoverySnapshot.make({\n submission: toSnapshot(stored.row),\n joins,\n approvalDecisions: [...stored.approvalDecisions.values()].sort(byToolCallId),\n unknownResolutions: [...stored.unknownResolutions.values()]\n .map((resolution) => resolution.intent)\n .sort(byToolCallId),\n childReservations: childReservations.map(toReservationSnapshot),\n childAttachments,\n ...(stored.row.parentLinkage === undefined\n ? {}\n : { parentLinkage: stored.row.parentLinkage }),\n ...(stored.joinedHostSubmissionId === undefined\n ? {}\n : { hostSubmissionId: stored.joinedHostSubmissionId }),\n ...(stored.suspension === undefined\n ? {}\n : {\n suspension: SuspensionSnapshot.make({\n reason: stored.suspension.reason,\n suspendedAt: utc(stored.suspension.suspendedAtMillis),\n }),\n }),\n ...(stored.ownership === undefined\n ? {}\n : {\n ownership: OwnershipSnapshot.make({\n attemptId: stored.ownership.attemptId,\n ownerProducerId: stored.ownership.ownerProducerId,\n producerEpoch: stored.ownership.producerEpoch,\n leaseExpiresAt: utc(stored.ownership.leaseExpiresAtMillis),\n }),\n }),\n ...(stored.inputApplied === undefined ? {} : { inputApplied: stored.inputApplied }),\n ...(stored.reservation === undefined\n ? {}\n : {\n reservation: SettlementReservationSnapshot.make({\n settlementId: stored.reservation.settlementId,\n outcome: stored.reservation.outcome,\n record: stored.reservation.record,\n recordDigest: stored.reservation.recordDigest,\n finalized: stored.reservation.finalizedAtMillis !== undefined,\n }),\n }),\n ...(stored.abortIntent === undefined ? {} : { abortIntent: stored.abortIntent }),\n });\n }),\n );\n\n return SubmissionLedger.of({\n capabilities,\n admit,\n markReady,\n lookup,\n resolveAdmission,\n claim,\n renewOwnership,\n releaseOwnership,\n markInputApplied,\n reserveSettlement,\n finalizeSettlement,\n requestAbort,\n claimJoining,\n markJoined,\n revertJoining,\n suspend,\n recordApprovalDecision,\n markUnknown,\n recordUnknownResolution,\n recordChildSettled,\n reserveChildBudget,\n attachChildToReservation,\n beginChildBudgetRelease,\n releaseChildBudget,\n scanNonterminal,\n loadRecoverySnapshot,\n readAbortIntent,\n });\n });\n\n/** Construction options for the in-memory reference SubmissionLedger. */\nexport interface MemorySubmissionLedgerOptions {\n /**\n * Test-only fault seam for `resolveAdmission` (SUB-031): when the effect yields a reason,\n * the resolution answers `Indeterminate` with it instead of consulting the store — modelling\n * an authoritative child owner that is temporarily unreachable. `Option.none()` restores the\n * store-derived answer. Ledger state is never mutated by the fault.\n */\n readonly resolveAdmissionFault?: Effect.Effect<Option.Option<string>>;\n}\n\n/**\n * In-memory reference SubmissionLedger Layer (durability `non-durable`). All state lives in one\n * `Ref` owned by the Layer's Scope; no daemon fibers are spawned and no wall clock is consulted.\n */\nexport const memorySubmissionLedgerLayer = (\n options: MemorySubmissionLedgerOptions = {},\n): Layer.Layer<SubmissionLedger> => Layer.effect(SubmissionLedger, makeSubmissionLedger(options));\n\nexport const MemorySubmissionLedgerLive: Layer.Layer<SubmissionLedger> =\n memorySubmissionLedgerLayer();\n"],"mappings":";;;;;;;;;;AA6GA,MAAM,kBAAkB;;;;;;AAOxB,MAAM,aAA8C;CAClD,UAAU;CACV,OAAO;CACP,SAAS;CACT,QAAQ;CACR,SAAS;CACT,iBAAiB;CACjB,WAAW;CACX,SAAS;CACT,eAAe;CACf,SAAS;AACX;;;;;;AAyEA,MAAM,sCAAoD,IAAI,IAAI;CAChE;CACA;CACA;AACF,CAAC;AAkCD,MAAM,WAAc,WAAkC;CAAE,MAAM;CAAW;AAAM;AAC/E,MAAM,WAAc,WAAkC;CAAE,MAAM;CAAW;AAAM;AAE/E,MAAM,eAAe,WAAmB,SAAiB,UACvD,UAAU,KAAA,IACN,YAAY,KAAK;CAAE;CAAW;AAAQ,CAAC,IACvC,YAAY,KAAK;CAAE;CAAW;CAAS;AAAM,CAAC;AAEpD,MAAM,WAAW,OAAO,GAAG,iCAAiC,CAAC,EAEzD,QACA,WACA,UAEA,OAAO,oBAAoB,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KACxC,OAAO,QAAQ,OAAO,oBAAoB,MAAM,CAAC,GACjD,OAAO,UAAU,UAAU,YAAY,WAAW,WAAW,UAAU,WAAW,KAAK,CAAC,CAC1F,CACJ;AAEA,MAAM,qBAAqB,OAAO,WAAW,YAAY;AACzD,MAAM,kBAAkB,OAAO,WAAW,SAAS;AACnD,MAAM,kBAAkB,OAAO,WAAW,SAAS;AACnD,MAAM,uBAAuB,OAAO,WAAW,cAAc;AAC7D,MAAM,sBAAsB,OAAO,WAAW,aAAa;AAC3D,MAAM,sBAAsB,OAAO,WAAW,aAAa;AAC3D,MAAM,0BAA0B,OAAO,cAAc,aAAa;AAClE,MAAM,8B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AQ,OAAO,YAAY;IAC3B,cAAc,OAAO,YAAY;IACjC,WAAW,OAAO,YAAY,sBAAsB,KAAA;GACtD,CAAC,EACH;GACJ,GAAI,OAAO,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,OAAO,YAAY;EAChF,CAAC;CACH,CAAC,CACH;CAEA,OAAO,iBAAiB,GAAG;EACzB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH,CAAC;;;;;AAiBH,MAAa,+BACX,UAAyC,CAAC,MACR,MAAM,OAAO,kBAAkB,qBAAqB,OAAO,CAAC;AAEhG,MAAa,6BACX,4BAA4B"}
1
+ {"version":3,"file":"MemorySubmissionLedger.mjs","names":[],"sources":["../src/MemorySubmissionLedger.ts"],"sourcesContent":["import {\n type ToolCallId,\n AttemptId,\n ReceiptId,\n SubmissionId,\n type AgentId,\n type ThreadId,\n type SettlementId,\n} from \"@effect-agent/core/Identifiers\";\nimport {\n PersistedJson,\n ProducerEpoch,\n type DefinitionDigests,\n type DeploymentId,\n type Digest,\n type ProducerId,\n type RecordEnvelope,\n type SettlementOutcome,\n} from \"@effect-agent/thread/Records\";\nimport {\n type ParentLinkage,\n AbortCommand,\n AdmissionAdmitted,\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionIndeterminate,\n AdmissionNotAdmitted,\n AdmissionRequest,\n SubmissionAdmissionFence,\n AdmissionResult,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n AttachChildToReservationRequest,\n BeginChildBudgetReleaseRequest,\n ChildAttachmentSnapshot,\n ChildBudgetReservationRequest,\n ChildBudgetReservationSnapshot,\n ChildReservationConflict,\n ChildSettledNotification,\n Claim,\n ClaimJoiningRequest,\n ClaimRequest,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n InputAppliedMarker,\n JoinSnapshot,\n JoinedToHost,\n JoiningClaim,\n LedgerCapabilities,\n LedgerError,\n MarkInputAppliedRequest,\n MarkJoinedRequest,\n MarkReadyRequest,\n MarkUnknownRequest,\n OwnershipLost,\n OwnershipRenewal,\n OwnershipSnapshot,\n OwnershipToken,\n QueueSequence,\n RecoverySnapshot,\n RecoverySnapshotRequest,\n ReleaseChildBudgetRequest,\n ReleaseOwnershipRequest,\n RenewOwnershipRequest,\n ReservedChildBudget,\n ReservedSettlement,\n RevertJoiningRequest,\n Settlement,\n SettlementConflict,\n SettlementFinalization,\n SettlementReservation,\n SettlementReservationSnapshot,\n settlementFailureFromRecord,\n AbortIntent,\n AbortIntentRequest,\n SubmissionLedger,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n SuspendRequest,\n SuspensionSnapshot,\n UnknownResolution,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n type ChildReservationId,\n type ChildReservationStatus,\n type ChildSettledOutcome,\n type IdempotencyKey,\n type Principal,\n type SubmissionState,\n type SuspensionOutcome,\n type SuspensionReason,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n Clock,\n Cause,\n Exit,\n Fiber,\n DateTime,\n Duration,\n Effect,\n Layer,\n Option,\n Ref,\n Schema,\n Stream,\n} from \"effect\";\n\nconst MAX_SUBMISSIONS = 65_536;\n\n/**\n * Lifecycle ordering used to advance-but-never-regress the operational state marker: a reclaimed\n * Attempt must not erase progress markers (input-applied, terminalizing) that an earlier Attempt\n * already committed.\n */\nconst STATE_RANK: Record<SubmissionState, number> = {\n admitted: 0,\n ready: 1,\n joining: 2,\n joined: 3,\n running: 4,\n \"input-applied\": 5,\n suspended: 6,\n unknown: 7,\n terminalizing: 8,\n settled: 9,\n};\n\ninterface SubmissionRow {\n readonly submissionId: SubmissionId;\n readonly threadId: ThreadId;\n readonly queueSequence: QueueSequence;\n readonly principal: Principal;\n readonly idempotencyKey: IdempotencyKey;\n readonly agentId: AgentId;\n readonly agentDigests: DefinitionDigests;\n readonly deploymentId: DeploymentId;\n readonly inputPayload: PersistedJson;\n readonly inputDigest: Digest;\n readonly receiptId: ReceiptId;\n readonly state: SubmissionState;\n readonly settledOutcome: SettlementOutcome | undefined;\n readonly createdAtMillis: number;\n readonly readyAtMillis: number | undefined;\n /** Immutable child-side lineage recorded at admission (spec §12 step 5). */\n readonly parentLinkage: ParentLinkage | undefined;\n readonly admissionGroup?: string;\n readonly admissionFence?: AdmissionRequest[\"admissionFence\"];\n}\n\ninterface StoredOwnership {\n readonly attemptId: AttemptId;\n readonly ownershipToken: OwnershipToken;\n readonly producerEpoch: ProducerEpoch;\n readonly ownerProducerId: ProducerId;\n readonly leaseExpiresAtMillis: number;\n}\n\ninterface StoredReservation {\n readonly settlementId: SettlementId;\n readonly outcome: SettlementOutcome;\n readonly record: RecordEnvelope;\n readonly recordDigest: Digest;\n readonly finalizedAtMillis: number | undefined;\n}\n\ninterface StoredSuspension {\n readonly reason: SuspensionReason;\n readonly suspendedAtMillis: number;\n}\n\ninterface StoredUnknownMark {\n readonly reason: MarkUnknownRequest[\"reason\"];\n readonly toolCallIds: ReadonlyArray<ToolCallId>;\n}\n\ninterface StoredUnknownResolution {\n readonly intent: UnknownResolutionIntent;\n}\n\ninterface StoredSubmission {\n readonly row: SubmissionRow;\n readonly ownership: StoredOwnership | undefined;\n readonly inputApplied: InputAppliedMarker | undefined;\n readonly reservation: StoredReservation | undefined;\n readonly abortIntent: AbortIntent | undefined;\n /** Host linkage recorded at `claimJoining` time; cleared by `revertJoining` (DUR-016). */\n readonly joinedHostSubmissionId: SubmissionId | undefined;\n readonly suspension: StoredSuspension | undefined;\n readonly unknownMark: StoredUnknownMark | undefined;\n readonly approvalDecisions: ReadonlyMap<ToolCallId, ApprovalDecisionIntent>;\n readonly unknownResolutions: ReadonlyMap<ToolCallId, StoredUnknownResolution>;\n}\n\n/**\n * States in which `claim` never grants the head: the lane is host-owned (`joining`/`joined`)\n * or durably suspended rather than worker-claimable. Unknown heads are checked against abort\n * intent separately: abort authorizes cleanup and settlement, never ordinary Tool replay.\n */\nconst BLOCKED_HEAD_STATES: ReadonlySet<SubmissionState> = new Set([\n \"joining\",\n \"joined\",\n \"suspended\",\n]);\n\ninterface LaneState {\n readonly nextQueueSequence: number;\n readonly producerEpoch: number;\n}\n\n/** One parent-owned child budget reservation row (spec §12 steps 2 and 6). */\ninterface StoredChildReservation {\n readonly reservationId: ChildReservationId;\n readonly parentSubmissionId: SubmissionId;\n readonly parentToolCallId: ToolCallId;\n readonly childSubmissionId: SubmissionId | undefined;\n readonly status: ChildReservationStatus;\n readonly allocation: PersistedJson;\n readonly allocationDigest: Digest;\n readonly accounting: PersistedJson | undefined;\n readonly reservedAtMillis: number;\n readonly releaseBeganAtMillis: number | undefined;\n readonly releasedAtMillis: number | undefined;\n}\n\ninterface LedgerState {\n readonly submissions: ReadonlyMap<SubmissionId, StoredSubmission>;\n readonly admissionIndex: ReadonlyMap<string, SubmissionId>;\n readonly lanes: ReadonlyMap<ThreadId, LaneState>;\n readonly childReservations: ReadonlyMap<ChildReservationId, StoredChildReservation>;\n readonly mintCounter: number;\n}\n\ntype Decision<A, E> =\n | { readonly _tag: \"failure\"; readonly error: E }\n | { readonly _tag: \"success\"; readonly value: A };\n\nconst failure = <E>(error: E): Decision<never, E> => ({ _tag: \"failure\", error });\nconst success = <A>(value: A): Decision<A, never> => ({ _tag: \"success\", value });\n\nconst ledgerError = (operation: string, message: string, cause?: unknown): LedgerError =>\n cause === undefined\n ? LedgerError.make({ operation, message })\n : LedgerError.make({ operation, message, cause });\n\nconst validate = Effect.fn(\"MemorySubmissionLedger.validate\")(\n <A, I>(\n schema: Schema.Codec<A, I>,\n operation: string,\n value: unknown,\n ): Effect.Effect<A, LedgerError> =>\n Schema.encodeUnknownEffect(schema)(value).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(schema)),\n Effect.mapError((error) => ledgerError(operation, `Invalid ${operation} request`, error)),\n ),\n);\n\nconst decodeSubmissionId = Schema.decodeSync(SubmissionId);\nconst decodeReceiptId = Schema.decodeSync(ReceiptId);\nconst decodeAttemptId = Schema.decodeSync(AttemptId);\nconst decodeOwnershipToken = Schema.decodeSync(OwnershipToken);\nconst decodeQueueSequence = Schema.decodeSync(QueueSequence);\nconst decodeProducerEpoch = Schema.decodeSync(ProducerEpoch);\nconst equivalentPersistedJson = Schema.toEquivalence(PersistedJson);\nconst equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);\n\nconst utc = (millis: number): DateTime.Utc => DateTime.toUtc(DateTime.makeUnsafe(millis));\n\nconst admissionKey = (\n threadId: ThreadId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n): string => JSON.stringify([threadId, principal, idempotencyKey]);\n\nconst toSnapshot = (row: SubmissionRow): SubmissionSnapshot =>\n SubmissionSnapshot.make({\n submissionId: row.submissionId,\n threadId: row.threadId,\n queueSequence: row.queueSequence,\n principal: row.principal,\n idempotencyKey: row.idempotencyKey,\n agentId: row.agentId,\n agentDigests: row.agentDigests,\n deploymentId: row.deploymentId,\n inputPayload: row.inputPayload,\n inputDigest: row.inputDigest,\n receiptId: row.receiptId,\n state: row.state,\n createdAt: utc(row.createdAtMillis),\n ...(row.admissionGroup === undefined ? {} : { admissionGroup: row.admissionGroup }),\n ...(row.admissionFence === undefined ? {} : { admissionFence: row.admissionFence }),\n ...(row.settledOutcome === undefined ? {} : { settledOutcome: row.settledOutcome }),\n ...(row.readyAtMillis === undefined ? {} : { readyAt: utc(row.readyAtMillis) }),\n ...(row.parentLinkage === undefined ? {} : { parentLinkage: row.parentLinkage }),\n });\n\nconst toReservationSnapshot = (row: StoredChildReservation): ChildBudgetReservationSnapshot =>\n ChildBudgetReservationSnapshot.make({\n reservationId: row.reservationId,\n parentSubmissionId: row.parentSubmissionId,\n parentToolCallId: row.parentToolCallId,\n status: row.status,\n allocation: row.allocation,\n allocationDigest: row.allocationDigest,\n reservedAt: utc(row.reservedAtMillis),\n ...(row.childSubmissionId === undefined ? {} : { childSubmissionId: row.childSubmissionId }),\n ...(row.accounting === undefined ? {} : { accounting: row.accounting }),\n ...(row.releaseBeganAtMillis === undefined\n ? {}\n : { releaseBeganAt: utc(row.releaseBeganAtMillis) }),\n ...(row.releasedAtMillis === undefined ? {} : { releasedAt: utc(row.releasedAtMillis) }),\n });\n\n/** Linkage equality: both absent, or both present naming the same parent Tool Call. */\nconst sameParentLinkage = (\n left: ParentLinkage | undefined,\n right: ParentLinkage | undefined,\n): boolean =>\n left === undefined\n ? right === undefined\n : right !== undefined &&\n left.parentSubmissionId === right.parentSubmissionId &&\n left.parentToolCallId === right.parentToolCallId;\n\nconst laneEpoch = (state: LedgerState, threadId: ThreadId): number =>\n state.lanes.get(threadId)?.producerEpoch ?? 0;\n\nconst ownershipLost = (state: LedgerState, stored: StoredSubmission): OwnershipLost =>\n OwnershipLost.make({\n submissionId: stored.row.submissionId,\n actualEpoch: decodeProducerEpoch(laneEpoch(state, stored.row.threadId)),\n });\n\n/** The presented token owns the lane only while it matches the live ownership record. */\nconst ownsLane = (stored: StoredSubmission, ownershipToken: OwnershipToken): boolean =>\n stored.ownership !== undefined && stored.ownership.ownershipToken === ownershipToken;\n\nconst withSubmission = (state: LedgerState, stored: StoredSubmission): LedgerState => ({\n ...state,\n submissions: new Map(state.submissions).set(stored.row.submissionId, stored),\n});\n\nconst withChildReservation = (\n state: LedgerState,\n reservation: StoredChildReservation,\n): LedgerState => ({\n ...state,\n childReservations: new Map(state.childReservations).set(reservation.reservationId, reservation),\n});\n\nconst findHead = (state: LedgerState, threadId: ThreadId): StoredSubmission | undefined => {\n let head: StoredSubmission | undefined;\n\n for (const stored of state.submissions.values()) {\n if (stored.row.threadId !== threadId || stored.row.state === \"settled\") continue;\n if (head === undefined || stored.row.queueSequence < head.row.queueSequence) head = stored;\n }\n\n return head;\n};\n\n/**\n * Reference in-memory SubmissionLedger. It implements the full port contract — atomic idempotent\n * admission, FIFO-head claims, producer-epoch fencing, Clock-driven ownership leases, idempotent\n * settlement reservation/finalization, and durable abort intent — with every transition applied\n * as one atomic `Ref.modify`, but its state does not survive the process (`non-durable`).\n *\n * Adapter-specific semantics within the port's latitude:\n *\n * - Time comes exclusively from the Effect `Clock` service, so `TestClock` drives lease expiry\n * deterministically; no wall clock is consulted.\n * - The ownership lease is pinned to `DEFAULT_OWNERSHIP_LEASE_DURATION` (D5); durable adapters\n * own the configuration seam.\n * - A live lease blocks claims from other producers only: the same `producerId` may reclaim its\n * own live lease (restart recovery), which supersedes and fences the prior Attempt's token.\n * - Claiming advances `ready` to `running` and otherwise preserves the recorded state, so\n * progress markers from an earlier Attempt survive a reclaim.\n * - `renewOwnership` keeps the token stable (the port allows rotation); a replayed admission\n * reports the Submission's current state alongside the original identities.\n * - `claimJoining` walks the strictly-later queue: rows already `joining`/`joined` to the\n * SAME host extend the claimed prefix and are skipped, and an aborted-settled row is a\n * closed obligation that is also skipped (P7 §7(c)); any other non-`ready` row (an\n * `admitted` gap, a non-aborted settled row, foreign-host linkage) breaks the prefix\n * conservatively.\n * - `markJoined` verifies the token against the HOST's live ownership (the lane is\n * host-owned), so a later host Attempt can repair a lost marker from history (DUR-016). The\n * join marker reuses the input-applied marker: the joined input IS `input:{sid}`.\n * - `suspend` and `markUnknown` refuse when an exact settlement is already reserved\n * (`SettlementConflict` with the reserved outcome) — DUR-011's reservation wins.\n * - `resolveAdmission` derives its answer from the single strongly consistent store, so it\n * never answers `Indeterminate` on its own; the test-only `resolveAdmissionFault` option\n * injects the `Indeterminate` classification so SUB-031 callers can be conformance-tested.\n * - `recordChildSettled` and `suspend(WaitingForChild)` observe child settlement directly from\n * the child rows (single-store latitude); no separate notification marker is stored.\n */\nconst makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>\n Effect.gen(function* () {\n const state = yield* Ref.make<LedgerState>({\n submissions: new Map(),\n admissionIndex: new Map(),\n lanes: new Map(),\n childReservations: new Map(),\n mintCounter: 0,\n });\n\n const admissionFence = yield* SubmissionAdmissionFence;\n const leaseMillis = Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION);\n\n const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: \"non-durable\" }));\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"MemorySubmissionLedger.admit\")(\n (unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(AdmissionRequest, \"admit\", unvalidated);\n\n const nowMillis = yield* Clock.currentTimeMillis;\n const services = yield* Effect.context<never>();\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n (\n | Decision<AdmissionResult, AdmissionConflict | AdmissionPolicyError | LedgerError>\n | { readonly _tag: \"cause\"; readonly cause: Cause.Cause<AdmissionPolicyError> }\n ),\n LedgerState,\n ] => {\n const key = admissionKey(request.threadId, request.principal, request.idempotencyKey);\n const existingId = current.admissionIndex.get(key);\n\n if (existingId !== undefined) {\n const existing = current.submissions.get(existingId);\n\n if (existing === undefined) {\n return [\n failure(\n ledgerError(\"admit\", \"Admission index references a missing Submission\"),\n ),\n current,\n ];\n }\n // A replay must repeat the exact canonical input AND the exact parent linkage\n // (or its absence): linkage is immutable lineage (spec §12 step 5, SUB-016).\n if (\n existing.row.inputDigest !== request.inputDigest ||\n !sameParentLinkage(existing.row.parentLinkage, request.parentLinkage) ||\n existing.row.admissionGroup !== request.admissionGroup ||\n !Schema.toEquivalence(Schema.optional(Schema.Json))(\n existing.row.admissionFence,\n request.admissionFence,\n )\n ) {\n return [\n failure(\n AdmissionConflict.make({\n threadId: request.threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n existingInputDigest: existing.row.inputDigest,\n attemptedInputDigest: request.inputDigest,\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n AdmissionResult.make({\n submissionId: existing.row.submissionId,\n receiptId: existing.row.receiptId,\n queueSequence: existing.row.queueSequence,\n state: existing.row.state,\n replayed: true,\n }),\n ),\n current,\n ];\n }\n // A memory policy and the ledger mutation share one synchronous critical section.\n // An asynchronous policy cannot fence this Ref and therefore fails closed.\n const checked = Effect.runSyncExitWith(services)(admissionFence.check(request));\n\n if (Exit.isFailure(checked)) {\n return [{ _tag: \"cause\", cause: checked.cause }, current];\n }\n if (\n request.admissionGroup !== undefined &&\n [...current.submissions.values()].some(\n ({ row }) =>\n row.threadId === request.threadId &&\n row.admissionGroup === request.admissionGroup &&\n row.state !== \"settled\",\n )\n )\n return [\n failure(\n AdmissionPolicyError.make({ reason: \"occupied\", code: \"admission-group\" }),\n ),\n current,\n ];\n if (current.submissions.size >= MAX_SUBMISSIONS) {\n return [\n failure(\n ledgerError(\"admit\", `In-memory submission limit ${MAX_SUBMISSIONS} exceeded`),\n ),\n current,\n ];\n }\n\n const lane = current.lanes.get(request.threadId) ?? {\n nextQueueSequence: 1,\n producerEpoch: 0,\n };\n\n const mintCounter = current.mintCounter + 1;\n\n const row: SubmissionRow = {\n submissionId: decodeSubmissionId(`submission-memory-${mintCounter}`),\n threadId: request.threadId,\n queueSequence: decodeQueueSequence(lane.nextQueueSequence),\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n agentId: request.agentId,\n agentDigests: request.agentDigests,\n deploymentId: request.deploymentId,\n inputPayload: request.inputPayload,\n inputDigest: request.inputDigest,\n receiptId: decodeReceiptId(`receipt-memory-${mintCounter}`),\n state: \"admitted\",\n settledOutcome: undefined,\n createdAtMillis: nowMillis,\n readyAtMillis: undefined,\n parentLinkage: request.parentLinkage,\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n };\n\n const submissions = new Map(current.submissions).set(row.submissionId, {\n row,\n ownership: undefined,\n inputApplied: undefined,\n reservation: undefined,\n abortIntent: undefined,\n joinedHostSubmissionId: undefined,\n suspension: undefined,\n unknownMark: undefined,\n approvalDecisions: new Map<ToolCallId, ApprovalDecisionIntent>(),\n unknownResolutions: new Map<ToolCallId, StoredUnknownResolution>(),\n });\n\n const admissionIndex = new Map(current.admissionIndex).set(key, row.submissionId);\n\n const lanes = new Map(current.lanes).set(request.threadId, {\n nextQueueSequence: lane.nextQueueSequence + 1,\n producerEpoch: lane.producerEpoch,\n });\n\n return [\n success(\n AdmissionResult.make({\n submissionId: row.submissionId,\n receiptId: row.receiptId,\n queueSequence: row.queueSequence,\n state: row.state,\n replayed: false,\n }),\n ),\n { ...current, submissions, admissionIndex, lanes, mintCounter },\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n if (decision._tag === \"cause\") {\n for (const reason of decision.cause.reasons) {\n if (Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)) {\n yield* Fiber.interrupt(reason.defect.fiber);\n\n return yield* AdmissionPolicyError.make({\n reason: \"unavailable\",\n code: \"synchronous-memory-policy-required\",\n });\n }\n }\n\n return yield* Effect.failCause(decision.cause);\n }\n\n return decision.value;\n }),\n Effect.uninterruptible,\n );\n\n const markReady: SubmissionLedger[\"Service\"][\"markReady\"] = Effect.fn(\n \"MemorySubmissionLedger.markReady\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkReadyRequest, \"markReady\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markReady\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state !== \"admitted\") return [success(undefined), current];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"ready\", readyAtMillis: nowMillis },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const lookup: SubmissionLedger[\"Service\"][\"lookup\"] = Effect.fn(\n \"MemorySubmissionLedger.lookup\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SubmissionLookup, \"lookup\", unvalidated);\n const current = yield* Ref.get(state);\n\n const submissionId =\n request._tag === \"SubmissionLookupById\"\n ? request.submissionId\n : current.admissionIndex.get(\n admissionKey(request.threadId, request.principal, request.idempotencyKey),\n );\n\n const stored =\n submissionId === undefined ? undefined : current.submissions.get(submissionId);\n\n return stored === undefined ? Option.none() : Option.some(toSnapshot(stored.row));\n }),\n );\n\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"MemorySubmissionLedger.resolveAdmission\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SubmissionLookupByKey, \"resolveAdmission\", unvalidated);\n\n // Test-only fault seam: lets suites exercise the Indeterminate classification that a\n // single strongly consistent store never produces on its own (SUB-031, P6 honesty).\n if (options.resolveAdmissionFault !== undefined) {\n const fault = yield* options.resolveAdmissionFault;\n\n if (Option.isSome(fault)) {\n return AdmissionIndeterminate.make({ reason: fault.value });\n }\n }\n const current = yield* Ref.get(state);\n\n const submissionId = current.admissionIndex.get(\n admissionKey(request.threadId, request.principal, request.idempotencyKey),\n );\n\n const stored =\n submissionId === undefined ? undefined : current.submissions.get(submissionId);\n\n return stored === undefined\n ? AdmissionNotAdmitted.make()\n : AdmissionAdmitted.make({ submission: toSnapshot(stored.row) });\n }),\n );\n\n const claim: SubmissionLedger[\"Service\"][\"claim\"] = Effect.fn(\"MemorySubmissionLedger.claim\")(\n (unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ClaimRequest, \"claim\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<Option.Option<Claim>, LedgerError>, LedgerState] => {\n const head = findHead(current, request.threadId);\n\n if (head === undefined) return [success(Option.none()), current];\n if (\n BLOCKED_HEAD_STATES.has(head.row.state) ||\n (head.row.state === \"unknown\" && head.abortIntent === undefined)\n )\n return [success(Option.none()), current];\n if (\n head.ownership !== undefined &&\n head.ownership.leaseExpiresAtMillis > nowMillis &&\n head.ownership.ownerProducerId !== request.producerId\n ) {\n return [success(Option.none()), current];\n }\n const lane = current.lanes.get(request.threadId);\n\n if (lane === undefined) {\n return [\n failure(ledgerError(\"claim\", \"Claimable head without a Thread lane\")),\n current,\n ];\n }\n const producerEpoch = decodeProducerEpoch(lane.producerEpoch + 1);\n const mintCounter = current.mintCounter + 1;\n\n const ownership: StoredOwnership = {\n attemptId: decodeAttemptId(`attempt-memory-${mintCounter}`),\n ownershipToken: decodeOwnershipToken(`ownership-memory-${mintCounter}`),\n producerEpoch,\n ownerProducerId: request.producerId,\n leaseExpiresAtMillis: nowMillis + leaseMillis,\n };\n\n const row: SubmissionRow =\n head.row.state === \"ready\" ? { ...head.row, state: \"running\" } : head.row;\n\n const next = withSubmission(current, { ...head, row, ownership });\n\n const lanes = new Map(next.lanes).set(request.threadId, {\n nextQueueSequence: lane.nextQueueSequence,\n producerEpoch: lane.producerEpoch + 1,\n });\n\n return [\n success(\n Option.some(\n Claim.make({\n submissionId: row.submissionId,\n attemptId: ownership.attemptId,\n ownershipToken: ownership.ownershipToken,\n producerEpoch,\n leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),\n inputPayload: row.inputPayload,\n }),\n ),\n ),\n { ...next, lanes, mintCounter },\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const renewOwnership: SubmissionLedger[\"Service\"][\"renewOwnership\"] = Effect.fn(\n \"MemorySubmissionLedger.renewOwnership\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(RenewOwnershipRequest, \"renewOwnership\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [Decision<OwnershipRenewal, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"renewOwnership\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (stored.ownership === undefined || !ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n const ownership: StoredOwnership = {\n ...stored.ownership,\n leaseExpiresAtMillis: nowMillis + leaseMillis,\n };\n\n return [\n success(\n OwnershipRenewal.make({\n ownershipToken: ownership.ownershipToken,\n leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),\n }),\n ),\n withSubmission(current, { ...stored, ownership }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const releaseOwnership: SubmissionLedger[\"Service\"][\"releaseOwnership\"] = Effect.fn(\n \"MemorySubmissionLedger.releaseOwnership\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ReleaseOwnershipRequest, \"releaseOwnership\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"releaseOwnership\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n return [\n success(undefined),\n withSubmission(current, { ...stored, ownership: undefined }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const markInputApplied: SubmissionLedger[\"Service\"][\"markInputApplied\"] = Effect.fn(\n \"MemorySubmissionLedger.markInputApplied\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkInputAppliedRequest, \"markInputApplied\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"markInputApplied\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n if (stored.inputApplied !== undefined) {\n if (\n stored.inputApplied.recordId === request.recordId &&\n stored.inputApplied.sequence === request.sequence\n ) {\n return [success(undefined), current];\n }\n\n return [\n failure(\n ledgerError(\n \"markInputApplied\",\n `A different canonical input marker is already recorded for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n\n const marker = InputAppliedMarker.make({\n recordId: request.recordId,\n sequence: request.sequence,\n });\n\n const row: SubmissionRow =\n STATE_RANK[stored.row.state] < STATE_RANK[\"input-applied\"]\n ? { ...stored.row, state: \"input-applied\" }\n : stored.row;\n\n return [\n success(undefined),\n withSubmission(current, { ...stored, row, inputApplied: marker }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const reserveSettlement: SubmissionLedger[\"Service\"][\"reserveSettlement\"] = Effect.fn(\n \"MemorySubmissionLedger.reserveSettlement\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SettlementReservation, \"reserveSettlement\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReservedSettlement, SettlementConflict | OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"reserveSettlement\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n\n // A `joined` Submission settles WITH its host (plan §2.5) and its lane is never\n // worker-claimable, so no ownership token can exist for it: the recorded host\n // linkage authorizes the reservation and the presented token is not consulted.\n const joinedSettlement =\n stored.row.state === \"joined\" && stored.joinedHostSubmissionId !== undefined;\n\n // P7 §7(c): an aborted, never-claimed, still-queued Submission likewise has no\n // live ownership to fence against — its durable abort intent authorizes exactly\n // its ABORTED settlement (`terminalizing` is the same pass's crash replay). Every\n // other reservation stays fenced by the target lane's live ownership.\n const queuedAbortSettlement =\n request.outcome === \"aborted\" &&\n stored.abortIntent !== undefined &&\n stored.ownership === undefined &&\n (stored.row.state === \"ready\" || stored.row.state === \"terminalizing\");\n\n if (\n !joinedSettlement &&\n !queuedAbortSettlement &&\n !ownsLane(stored, request.ownershipToken)\n ) {\n return [failure(ownershipLost(current, stored)), current];\n }\n const existing = stored.reservation;\n\n if (existing !== undefined) {\n if (\n existing.settlementId !== request.settlementId ||\n existing.outcome !== request.outcome ||\n existing.recordDigest !== request.recordDigest\n ) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: existing.outcome,\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n ReservedSettlement.make({\n submissionId: request.submissionId,\n settlementId: existing.settlementId,\n outcome: existing.outcome,\n record: existing.record,\n recordDigest: existing.recordDigest,\n replayed: true,\n }),\n ),\n current,\n ];\n }\n\n const reservation: StoredReservation = {\n settlementId: request.settlementId,\n outcome: request.outcome,\n record: request.record,\n recordDigest: request.recordDigest,\n finalizedAtMillis: undefined,\n };\n\n const row: SubmissionRow =\n STATE_RANK[stored.row.state] < STATE_RANK.terminalizing\n ? { ...stored.row, state: \"terminalizing\" }\n : stored.row;\n\n return [\n success(\n ReservedSettlement.make({\n submissionId: request.submissionId,\n settlementId: reservation.settlementId,\n outcome: reservation.outcome,\n record: reservation.record,\n recordDigest: reservation.recordDigest,\n replayed: false,\n }),\n ),\n withSubmission(current, { ...stored, row, reservation }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const finalizeSettlement: SubmissionLedger[\"Service\"][\"finalizeSettlement\"] = Effect.fn(\n \"MemorySubmissionLedger.finalizeSettlement\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SettlementFinalization, \"finalizeSettlement\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [Decision<Settlement, SettlementConflict | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"finalizeSettlement\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n const reservation = stored.reservation;\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"finalizeSettlement\",\n `No settlement reservation for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n const settlementFailure = settlementFailureFromRecord(reservation.record);\n\n if ((reservation.outcome === \"failed\") !== (settlementFailure !== undefined)) {\n return [\n failure(\n ledgerError(\n \"finalizeSettlement\",\n `Settlement reservation for Submission ${request.submissionId} has contradictory failure evidence`,\n ),\n ),\n current,\n ];\n }\n if (reservation.settlementId !== request.settlementId) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: reservation.outcome,\n }),\n ),\n current,\n ];\n }\n if (reservation.finalizedAtMillis !== undefined) {\n return [\n success(\n Settlement.make({\n submissionId: stored.row.submissionId,\n settlementId: reservation.settlementId,\n receiptId: stored.row.receiptId,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: utc(reservation.finalizedAtMillis),\n }),\n ),\n current,\n ];\n }\n\n const next = withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"settled\", settledOutcome: reservation.outcome },\n ownership: undefined,\n reservation: { ...reservation, finalizedAtMillis: nowMillis },\n });\n\n return [\n success(\n Settlement.make({\n submissionId: stored.row.submissionId,\n settlementId: reservation.settlementId,\n receiptId: stored.row.receiptId,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: utc(nowMillis),\n }),\n ),\n next,\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const requestAbort: SubmissionLedger[\"Service\"][\"requestAbort\"] = Effect.fn(\n \"MemorySubmissionLedger.requestAbort\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(AbortCommand, \"requestAbort\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<AbortIntent, SettlementConflict | JoinedToHost | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"requestAbort\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n // A joined Submission settles WITH its host; the abort target is the host (plan\n // §2.5). A joining Submission still records the intent: it is honored only if the\n // host has not consumed the input (revert-then-abort).\n if (stored.row.state === \"joined\") {\n if (stored.joinedHostSubmissionId === undefined) {\n return [\n failure(\n ledgerError(\n \"requestAbort\",\n `Joined Submission ${request.submissionId} is missing its host linkage`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n JoinedToHost.make({\n submissionId: request.submissionId,\n hostSubmissionId: stored.joinedHostSubmissionId,\n }),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"requestAbort\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n if (stored.abortIntent !== undefined) return [success(stored.abortIntent), current];\n\n const intent = AbortIntent.make({\n submissionId: request.submissionId,\n author: request.author,\n reason: request.reason,\n requestedAt: utc(nowMillis),\n });\n\n return [success(intent), withSubmission(current, { ...stored, abortIntent: intent })];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const claimJoining: SubmissionLedger[\"Service\"][\"claimJoining\"] = Effect.fn(\n \"MemorySubmissionLedger.claimJoining\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ClaimJoiningRequest, \"claimJoining\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReadonlyArray<JoiningClaim>, OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const host = current.submissions.get(request.hostSubmissionId);\n\n if (host === undefined) {\n return [\n failure(\n ledgerError(\"claimJoining\", `Unknown Submission ${request.hostSubmissionId}`),\n ),\n current,\n ];\n }\n if (host.row.threadId !== request.threadId) {\n return [\n failure(\n ledgerError(\n \"claimJoining\",\n `Host Submission ${request.hostSubmissionId} does not belong to Thread ${request.threadId}`,\n ),\n ),\n current,\n ];\n }\n if (!ownsLane(host, request.ownershipToken)) {\n return [failure(ownershipLost(current, host)), current];\n }\n\n const later = [...current.submissions.values()]\n .filter(\n (stored) =>\n stored.row.threadId === request.threadId &&\n stored.row.queueSequence > host.row.queueSequence,\n )\n .sort((left, right) => left.row.queueSequence - right.row.queueSequence);\n\n const claims: Array<JoiningClaim> = [];\n const submissions = new Map(current.submissions);\n\n for (const stored of later) {\n if (claims.length >= request.maxCount) break;\n // Rows already claimed by THIS host extend its contiguous prefix and are skipped;\n // the coordinator re-delivers already-joined input through the coverage rule.\n if (\n (stored.row.state === \"joining\" || stored.row.state === \"joined\") &&\n stored.joinedHostSubmissionId === request.hostSubmissionId\n ) {\n continue;\n }\n // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery\n // settles aborted never-claimed queued work immediately, and settlement order of\n // never-run work is not execution order (DUR-004 bounds execution).\n if (stored.row.state === \"settled\" && stored.row.settledOutcome === \"aborted\") {\n continue;\n }\n // Any other non-ready row — an admitted-not-ready gap in particular — breaks the\n // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).\n if (stored.row.state !== \"ready\") break;\n submissions.set(stored.row.submissionId, {\n ...stored,\n row: { ...stored.row, state: \"joining\" },\n joinedHostSubmissionId: request.hostSubmissionId,\n });\n claims.push(\n JoiningClaim.make({\n submissionId: stored.row.submissionId,\n queueSequence: stored.row.queueSequence,\n inputPayload: stored.row.inputPayload,\n }),\n );\n }\n\n return [success(claims), { ...current, submissions }];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const markJoined: SubmissionLedger[\"Service\"][\"markJoined\"] = Effect.fn(\n \"MemorySubmissionLedger.markJoined\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkJoinedRequest, \"markJoined\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markJoined\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.joinedHostSubmissionId === undefined) {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Submission ${request.submissionId} was never claimed for joining`,\n ),\n ),\n current,\n ];\n }\n const host = current.submissions.get(stored.joinedHostSubmissionId);\n\n if (host === undefined) {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Host Submission ${stored.joinedHostSubmissionId} is missing`,\n ),\n ),\n current,\n ];\n }\n // The lane is host-owned: the presented token must own the HOST's ownership period,\n // which also lets a later host Attempt repair a lost marker from history (DUR-016).\n if (!ownsLane(host, request.ownershipToken)) {\n return [failure(ownershipLost(current, host)), current];\n }\n if (stored.inputApplied !== undefined) {\n if (\n stored.inputApplied.recordId === request.recordId &&\n stored.inputApplied.sequence === request.sequence\n ) {\n return [success(undefined), current];\n }\n\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `A different join marker is already recorded for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state !== \"joining\" && stored.row.state !== \"joined\") {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Cannot mark Submission ${request.submissionId} joined from state ${stored.row.state}`,\n ),\n ),\n current,\n ];\n }\n\n const marker = InputAppliedMarker.make({\n recordId: request.recordId,\n sequence: request.sequence,\n });\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"joined\" },\n inputApplied: marker,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const revertJoining: SubmissionLedger[\"Service\"][\"revertJoining\"] = Effect.fn(\n \"MemorySubmissionLedger.revertJoining\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(RevertJoiningRequest, \"revertJoining\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"revertJoining\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n // Idempotent and recovery-only: only a still-`joining` Submission reverts; an\n // already-joined (or already-reverted) Submission is a no-op (DUR-016).\n if (stored.row.state !== \"joining\") return [success(undefined), current];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"ready\" },\n joinedHostSubmissionId: undefined,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const suspend: SubmissionLedger[\"Service\"][\"suspend\"] = Effect.fn(\n \"MemorySubmissionLedger.suspend\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SuspendRequest, \"suspend\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<SuspensionOutcome, OwnershipLost | SettlementConflict | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"suspend\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"suspend\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n // An exact terminal outcome is already reserved (DUR-011); suspension would\n // contradict it, so the reservation wins.\n if (stored.reservation !== undefined) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.reservation.outcome,\n }),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n // A covering event that raced ahead of the suspend transaction (an approval decision,\n // or a child settlement observed directly from the child's row in this single store)\n // resumes the caller immediately WITHOUT releasing the lane (plan §2.6, spec §12).\n const alreadyCovered =\n request.reason._tag === \"ApprovalPending\"\n ? request.reason.toolCallIds.every((toolCallId) =>\n stored.approvalDecisions.has(toolCallId),\n )\n : request.reason.children.every(\n (child) =>\n current.submissions.get(child.childSubmissionId)?.row.state === \"settled\",\n );\n\n if (alreadyCovered) {\n return [success(\"resume-immediately\" as const), current];\n }\n\n return [\n success(\"suspended\" as const),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"suspended\" },\n ownership: undefined,\n suspension: { reason: request.reason, suspendedAtMillis: nowMillis },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"MemorySubmissionLedger.recordApprovalDecision\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const command = yield* validate(\n ApprovalDecisionCommand,\n \"recordApprovalDecision\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ApprovalDecisionIntent, ApprovalConflict | SettlementConflict | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(command.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\n \"recordApprovalDecision\",\n `Unknown Submission ${command.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"recordApprovalDecision\",\n `Settled Submission ${command.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: command.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n const existing = stored.approvalDecisions.get(command.toolCallId);\n\n if (existing !== undefined) {\n if (existing.decision !== command.decision) {\n return [\n failure(\n ApprovalConflict.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n existingDecision: existing.decision,\n }),\n ),\n current,\n ];\n }\n\n return [success(existing), current];\n }\n\n const intent = ApprovalDecisionIntent.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n decision: command.decision,\n resolver: command.resolver,\n reason: command.reason,\n decidedAt: utc(nowMillis),\n });\n\n const approvalDecisions = new Map(stored.approvalDecisions).set(\n command.toolCallId,\n intent,\n );\n\n // Once every pending call of an ApprovalPending suspension is decided, the lane\n // wakes: suspended → input-applied (plan §2.6). A WaitingForChild suspension wakes\n // only through recordChildSettled.\n const wakes =\n stored.row.state === \"suspended\" &&\n stored.suspension !== undefined &&\n stored.suspension.reason._tag === \"ApprovalPending\" &&\n stored.suspension.reason.toolCallIds.every((toolCallId) =>\n approvalDecisions.has(toolCallId),\n );\n\n return [\n success(intent),\n withSubmission(current, {\n ...stored,\n row: wakes ? { ...stored.row, state: \"input-applied\" } : stored.row,\n suspension: wakes ? undefined : stored.suspension,\n approvalDecisions,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const markUnknown: SubmissionLedger[\"Service\"][\"markUnknown\"] = Effect.fn(\n \"MemorySubmissionLedger.markUnknown\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkUnknownRequest, \"markUnknown\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, SettlementConflict | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markUnknown\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"markUnknown\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n // A reserved exact outcome wins over a late Unknown marking (DUR-011); the recovery\n // classifier orders reservation ahead of MarkUnknown for the same reason.\n if (stored.reservation !== undefined) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.reservation.outcome,\n }),\n ),\n current,\n ];\n }\n // Idempotent merge: repeating is a no-op; additional open calls extend the marked\n // set while the first recorded reason is kept.\n const existing = stored.unknownMark;\n const known = new Set(existing?.toolCallIds ?? []);\n\n const merged = [\n ...(existing?.toolCallIds ?? []),\n ...request.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),\n ];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row:\n stored.row.state === \"unknown\" ? stored.row : { ...stored.row, state: \"unknown\" },\n unknownMark: { reason: existing?.reason ?? request.reason, toolCallIds: merged },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const recordUnknownResolution: SubmissionLedger[\"Service\"][\"recordUnknownResolution\"] =\n Effect.fn(\"MemorySubmissionLedger.recordUnknownResolution\")((unvalidated) =>\n Effect.gen(function* () {\n const command = yield* validate(\n UnknownResolutionCommand,\n \"recordUnknownResolution\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<\n UnknownResolutionIntent,\n UnknownResolutionConflict | SettlementConflict | LedgerError\n >,\n LedgerState,\n ] => {\n const stored = current.submissions.get(command.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\n \"recordUnknownResolution\",\n `Unknown Submission ${command.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"recordUnknownResolution\",\n `Settled Submission ${command.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: command.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n const existing = stored.unknownResolutions.get(command.toolCallId);\n\n if (\n existing !== undefined &&\n !equivalentUnknownResolution(existing.intent.resolution, command.resolution)\n ) {\n return [\n failure(\n UnknownResolutionConflict.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n }),\n ),\n current,\n ];\n }\n\n const intent =\n existing?.intent ??\n UnknownResolutionIntent.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n author: command.author,\n reason: command.reason,\n resolution: command.resolution,\n resolvedAt: utc(nowMillis),\n });\n\n const unknownResolutions =\n existing !== undefined\n ? stored.unknownResolutions\n : new Map(stored.unknownResolutions).set(command.toolCallId, {\n intent,\n });\n\n // The lane reopens only when EVERY marked open call has a durable resolution\n // intent: unknown → input-applied (DUR-017). Replays re-run the coverage check so\n // a recovering caller can wake the lane idempotently.\n const wakes =\n stored.row.state === \"unknown\" &&\n stored.unknownMark !== undefined &&\n stored.unknownMark.toolCallIds.every((toolCallId) =>\n unknownResolutions.has(toolCallId),\n );\n\n return [\n success(intent),\n withSubmission(current, {\n ...stored,\n row: wakes ? { ...stored.row, state: \"input-applied\" } : stored.row,\n unknownMark: wakes ? undefined : stored.unknownMark,\n unknownResolutions,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const recordChildSettled: SubmissionLedger[\"Service\"][\"recordChildSettled\"] = Effect.fn(\n \"MemorySubmissionLedger.recordChildSettled\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ChildSettledNotification,\n \"recordChildSettled\",\n unvalidated,\n );\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<ChildSettledOutcome, LedgerError>, LedgerState] => {\n const parent = current.submissions.get(request.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"recordChildSettled\",\n `Unknown Submission ${request.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n // The caller may notify after the canonical Settlement append but before ledger\n // finalization. In a single store, an exact reservation plus `terminalizing` is the\n // narrow durable prefix that makes that ordering admissible; earlier states remain\n // a caller error.\n const child = current.submissions.get(request.childSubmissionId);\n\n const announced =\n child !== undefined &&\n (child.row.state === \"settled\" ||\n (child.row.state === \"terminalizing\" && child.reservation !== undefined));\n\n if (!announced) {\n return [\n failure(\n ledgerError(\n \"recordChildSettled\",\n `Child Submission ${request.childSubmissionId} has no recorded settlement`,\n ),\n ),\n current,\n ];\n }\n if (\n parent.row.state !== \"suspended\" ||\n parent.suspension === undefined ||\n parent.suspension.reason._tag !== \"WaitingForChild\"\n ) {\n return [success(\"not-waiting\" as const), current];\n }\n const children = parent.suspension.reason.children;\n\n if (!children.some((entry) => entry.childSubmissionId === request.childSubmissionId)) {\n return [success(\"not-waiting\" as const), current];\n }\n\n // Every listed child must be either finalized or canonically announced from the\n // exact terminalizing reservation. Replays re-run this coverage check idempotently.\n const allSettled = children.every((entry) => {\n const listed = current.submissions.get(entry.childSubmissionId);\n\n return (\n listed?.row.state === \"settled\" ||\n (listed?.row.state === \"terminalizing\" && listed.reservation !== undefined)\n );\n });\n\n if (!allSettled) return [success(\"still-waiting\" as const), current];\n\n return [\n success(\"woken\" as const),\n withSubmission(current, {\n ...parent,\n row: { ...parent.row, state: \"input-applied\" },\n suspension: undefined,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const reserveChildBudget: SubmissionLedger[\"Service\"][\"reserveChildBudget\"] = Effect.fn(\n \"MemorySubmissionLedger.reserveChildBudget\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ChildBudgetReservationRequest,\n \"reserveChildBudget\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReservedChildBudget, ChildReservationConflict | OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const existing = current.childReservations.get(request.reservationId);\n\n if (existing !== undefined) {\n // Identical replays short-circuit before the fence, mirroring reserveSettlement:\n // a replay creates nothing, so a recovering caller resumes rather than duplicates.\n const identical =\n existing.parentSubmissionId === request.parentSubmissionId &&\n existing.parentToolCallId === request.parentToolCallId &&\n existing.allocationDigest === request.allocationDigest &&\n equivalentPersistedJson(existing.allocation, request.allocation);\n\n if (!identical) {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: existing.status,\n message:\n \"A reservation with this identity exists with a different parent Tool Call or allocation.\",\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n ReservedChildBudget.make({\n reservation: toReservationSnapshot(existing),\n replayed: true,\n }),\n ),\n current,\n ];\n }\n for (const reservation of current.childReservations.values()) {\n if (\n reservation.parentSubmissionId === request.parentSubmissionId &&\n reservation.parentToolCallId === request.parentToolCallId\n ) {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Parent Tool Call ${request.parentToolCallId} already owns reservation ${reservation.reservationId}.`,\n }),\n ),\n current,\n ];\n }\n }\n const parent = current.submissions.get(request.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"reserveChildBudget\",\n `Unknown Submission ${request.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale\n // parent Attempt can never create new reservation state.\n if (!ownsLane(parent, request.ownershipToken)) {\n return [failure(ownershipLost(current, parent)), current];\n }\n\n const reservation: StoredChildReservation = {\n reservationId: request.reservationId,\n parentSubmissionId: request.parentSubmissionId,\n parentToolCallId: request.parentToolCallId,\n childSubmissionId: undefined,\n status: \"reserved\",\n allocation: request.allocation,\n allocationDigest: request.allocationDigest,\n accounting: undefined,\n reservedAtMillis: nowMillis,\n releaseBeganAtMillis: undefined,\n releasedAtMillis: undefined,\n };\n\n return [\n success(\n ReservedChildBudget.make({\n reservation: toReservationSnapshot(reservation),\n replayed: false,\n }),\n ),\n withChildReservation(current, reservation),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const attachChildToReservation: SubmissionLedger[\"Service\"][\"attachChildToReservation\"] =\n Effect.fn(\"MemorySubmissionLedger.attachChildToReservation\")((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n AttachChildToReservationRequest,\n \"attachChildToReservation\",\n unvalidated,\n );\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<\n ChildBudgetReservationSnapshot,\n ChildReservationConflict | OwnershipLost | LedgerError\n >,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n if (reservation.childSubmissionId !== undefined) {\n // Idempotent replay of the recorded attachment (unfenced — it mutates nothing).\n if (reservation.childSubmissionId === request.childSubmissionId) {\n return [success(toReservationSnapshot(reservation)), current];\n }\n\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Reservation ${request.reservationId} already records child ${reservation.childSubmissionId}.`,\n }),\n ),\n current,\n ];\n }\n const parent = current.submissions.get(reservation.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown Submission ${reservation.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n if (!ownsLane(parent, request.ownershipToken)) {\n return [failure(ownershipLost(current, parent)), current];\n }\n if (reservation.status !== \"reserved\") {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Cannot attach a child to a ${reservation.status} reservation.`,\n }),\n ),\n current,\n ];\n }\n // Single-store latitude: the admitted child must exist here, so a dangling\n // attachment can never enter the recovery view.\n if (!current.submissions.has(request.childSubmissionId)) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown child Submission ${request.childSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n\n const attached: StoredChildReservation = {\n ...reservation,\n childSubmissionId: request.childSubmissionId,\n };\n\n return [\n success(toReservationSnapshot(attached)),\n withChildReservation(current, attached),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const beginChildBudgetRelease: SubmissionLedger[\"Service\"][\"beginChildBudgetRelease\"] =\n Effect.fn(\"MemorySubmissionLedger.beginChildBudgetRelease\")((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n BeginChildBudgetReleaseRequest,\n \"beginChildBudgetRelease\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"beginChildBudgetRelease\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n if (reservation.status !== \"reserved\") {\n // The accounting decision was already frozen exactly once; an identical replay is\n // a no-op and a divergent decision conflicts (spec §12 join step 6).\n if (\n reservation.accounting !== undefined &&\n equivalentPersistedJson(reservation.accounting, request.accounting)\n ) {\n return [success(toReservationSnapshot(reservation)), current];\n }\n\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message:\n \"A different accounting decision is already frozen for this reservation.\",\n }),\n ),\n current,\n ];\n }\n\n const frozen: StoredChildReservation = {\n ...reservation,\n status: \"releasePending\",\n accounting: request.accounting,\n releaseBeganAtMillis: nowMillis,\n };\n\n return [\n success(toReservationSnapshot(frozen)),\n withChildReservation(current, frozen),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const releaseChildBudget: SubmissionLedger[\"Service\"][\"releaseChildBudget\"] = Effect.fn(\n \"MemorySubmissionLedger.releaseChildBudget\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ReleaseChildBudgetRequest,\n \"releaseChildBudget\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"releaseChildBudget\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n // Applied exactly once: replaying a released reservation returns the stored row\n // unchanged (spec §12: \"never available twice\").\n if (reservation.status === \"released\") {\n return [success(toReservationSnapshot(reservation)), current];\n }\n if (reservation.status !== \"releasePending\") {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message:\n \"Cannot release a reservation whose accounting decision is not frozen.\",\n }),\n ),\n current,\n ];\n }\n\n const released: StoredChildReservation = {\n ...reservation,\n status: \"released\",\n releasedAtMillis: nowMillis,\n };\n\n return [\n success(toReservationSnapshot(released)),\n withChildReservation(current, released),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const scanNonterminal: SubmissionLedger[\"Service\"][\"scanNonterminal\"] = Stream.unwrap(\n Ref.get(state).pipe(\n Effect.map((current) => {\n const snapshots = [...current.submissions.values()]\n .filter((stored) => stored.row.state !== \"settled\")\n .sort((left, right) =>\n left.row.threadId < right.row.threadId\n ? -1\n : left.row.threadId > right.row.threadId\n ? 1\n : left.row.queueSequence - right.row.queueSequence,\n )\n .map((stored) => toSnapshot(stored.row));\n\n return Stream.fromIterable(snapshots);\n }),\n ),\n );\n\n const readAbortIntent: SubmissionLedger[\"Service\"][\"readAbortIntent\"] = Effect.fn(\n \"MemorySubmissionLedger.readAbortIntent\",\n )(function* (unvalidated) {\n const request = yield* validate(AbortIntentRequest, \"readAbortIntent\", unvalidated);\n const stored = (yield* Ref.get(state)).submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return yield* ledgerError(\"readAbortIntent\", `Unknown Submission ${request.submissionId}`);\n }\n\n return stored.abortIntent;\n });\n\n const loadRecoverySnapshot: SubmissionLedger[\"Service\"][\"loadRecoverySnapshot\"] = Effect.fn(\n \"MemorySubmissionLedger.loadRecoverySnapshot\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n RecoverySnapshotRequest,\n \"loadRecoverySnapshot\",\n unvalidated,\n );\n\n const current = yield* Ref.get(state);\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return yield* ledgerError(\n \"loadRecoverySnapshot\",\n `Unknown Submission ${request.submissionId}`,\n );\n }\n\n const joins = [...current.submissions.values()]\n .filter((candidate) => candidate.joinedHostSubmissionId === request.submissionId)\n .sort((left, right) => left.row.queueSequence - right.row.queueSequence)\n .map((candidate) =>\n JoinSnapshot.make({\n submissionId: candidate.row.submissionId,\n state: candidate.row.state,\n hostSubmissionId: request.submissionId,\n }),\n );\n\n const byToolCallId = <A extends { readonly toolCallId: ToolCallId }>(\n left: A,\n right: A,\n ): number =>\n left.toolCallId < right.toolCallId ? -1 : left.toolCallId > right.toolCallId ? 1 : 0;\n\n // Parent-side subagent view: this Submission's child budget reservations in parent Tool\n // Call order, plus each attached child's current lane state (a disposable derived view;\n // the canonical records stay the recovery truth, DUR-015).\n const childReservations = [...current.childReservations.values()]\n .filter((reservation) => reservation.parentSubmissionId === request.submissionId)\n .sort((left, right) =>\n left.parentToolCallId < right.parentToolCallId\n ? -1\n : left.parentToolCallId > right.parentToolCallId\n ? 1\n : 0,\n );\n\n const childAttachments: Array<ChildAttachmentSnapshot> = [];\n\n for (const reservation of childReservations) {\n if (reservation.childSubmissionId === undefined) continue;\n const child = current.submissions.get(reservation.childSubmissionId);\n\n if (child === undefined) continue;\n childAttachments.push(\n ChildAttachmentSnapshot.make({\n toolCallId: reservation.parentToolCallId,\n childSubmissionId: reservation.childSubmissionId,\n childState: child.row.state,\n ...(child.row.settledOutcome === undefined\n ? {}\n : { childOutcome: child.row.settledOutcome }),\n }),\n );\n }\n\n return RecoverySnapshot.make({\n submission: toSnapshot(stored.row),\n joins,\n approvalDecisions: [...stored.approvalDecisions.values()].sort(byToolCallId),\n unknownResolutions: [...stored.unknownResolutions.values()]\n .map((resolution) => resolution.intent)\n .sort(byToolCallId),\n childReservations: childReservations.map(toReservationSnapshot),\n childAttachments,\n ...(stored.row.parentLinkage === undefined\n ? {}\n : { parentLinkage: stored.row.parentLinkage }),\n ...(stored.joinedHostSubmissionId === undefined\n ? {}\n : { hostSubmissionId: stored.joinedHostSubmissionId }),\n ...(stored.suspension === undefined\n ? {}\n : {\n suspension: SuspensionSnapshot.make({\n reason: stored.suspension.reason,\n suspendedAt: utc(stored.suspension.suspendedAtMillis),\n }),\n }),\n ...(stored.ownership === undefined\n ? {}\n : {\n ownership: OwnershipSnapshot.make({\n attemptId: stored.ownership.attemptId,\n ownerProducerId: stored.ownership.ownerProducerId,\n producerEpoch: stored.ownership.producerEpoch,\n leaseExpiresAt: utc(stored.ownership.leaseExpiresAtMillis),\n }),\n }),\n ...(stored.inputApplied === undefined ? {} : { inputApplied: stored.inputApplied }),\n ...(stored.reservation === undefined\n ? {}\n : {\n reservation: SettlementReservationSnapshot.make({\n settlementId: stored.reservation.settlementId,\n outcome: stored.reservation.outcome,\n record: stored.reservation.record,\n recordDigest: stored.reservation.recordDigest,\n finalized: stored.reservation.finalizedAtMillis !== undefined,\n }),\n }),\n ...(stored.abortIntent === undefined ? {} : { abortIntent: stored.abortIntent }),\n });\n }),\n );\n\n return SubmissionLedger.of({\n capabilities,\n admit,\n markReady,\n lookup,\n resolveAdmission,\n claim,\n renewOwnership,\n releaseOwnership,\n markInputApplied,\n reserveSettlement,\n finalizeSettlement,\n requestAbort,\n claimJoining,\n markJoined,\n revertJoining,\n suspend,\n recordApprovalDecision,\n markUnknown,\n recordUnknownResolution,\n recordChildSettled,\n reserveChildBudget,\n attachChildToReservation,\n beginChildBudgetRelease,\n releaseChildBudget,\n scanNonterminal,\n loadRecoverySnapshot,\n readAbortIntent,\n });\n });\n\n/** Construction options for the in-memory reference SubmissionLedger. */\nexport interface MemorySubmissionLedgerOptions {\n /**\n * Test-only fault seam for `resolveAdmission` (SUB-031): when the effect yields a reason,\n * the resolution answers `Indeterminate` with it instead of consulting the store — modelling\n * an authoritative child owner that is temporarily unreachable. `Option.none()` restores the\n * store-derived answer. Ledger state is never mutated by the fault.\n */\n readonly resolveAdmissionFault?: Effect.Effect<Option.Option<string>>;\n}\n\n/**\n * In-memory reference SubmissionLedger Layer (durability `non-durable`). All state lives in one\n * `Ref` owned by the Layer's Scope; no daemon fibers are spawned and no wall clock is consulted.\n */\nexport const memorySubmissionLedgerLayer = (\n options: MemorySubmissionLedgerOptions = {},\n): Layer.Layer<SubmissionLedger> => Layer.effect(SubmissionLedger, makeSubmissionLedger(options));\n\nexport const MemorySubmissionLedgerLive: Layer.Layer<SubmissionLedger> =\n memorySubmissionLedgerLayer();\n"],"mappings":";;;;;;;;;;AA6GA,MAAM,kBAAkB;;;;;;AAOxB,MAAM,aAA8C;CAClD,UAAU;CACV,OAAO;CACP,SAAS;CACT,QAAQ;CACR,SAAS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CAAC,EACH;GACJ,GAAI,OAAO,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,OAAO,YAAY;EAChF,CAAC;CACH,CAAC,CACH;CAEA,OAAO,iBAAiB,GAAG;EACzB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH,CAAC;;;;;AAiBH,MAAa,+BACX,UAAyC,CAAC,MACR,MAAM,OAAO,kBAAkB,qBAAqB,OAAO,CAAC;AAEhG,MAAa,6BACX,4BAA4B"}
@@ -3,7 +3,7 @@ import { compareScheduleNames } from "@effect-agent/thread/ScheduleTransition";
3
3
  import { Clock, Effect, Layer, Ref, Result, Schema } from "effect";
4
4
  import { Digest } from "@effect-agent/thread/Records";
5
5
  import { AcceptedEvent, DeliveryChange, SourcePartition, SubscriptionChange, SubscriptionDelivery, SubscriptionDeliveryKey, SubscriptionError, SubscriptionFailpoint, SubscriptionKey, SubscriptionLimits, SubscriptionName, SubscriptionRecord, SubscriptionRetentionPolicy, SubscriptionScanCursors, SubscriptionStore, subscriptionDeliveryKeyString, subscriptionKeyString } from "@effect-agent/thread/Subscription";
6
- import { applySubscriptionChange, applySubscriptionDeliveryChange, subscriptionCanSelect, subscriptionDeliveryCanSelect, validateEventRetention } from "@effect-agent/thread/SubscriptionTransition";
6
+ import { applySubscriptionChange, applySubscriptionDeliveryChange, sameAcceptedEventIdentity, subscriptionCanSelect, subscriptionDeliveryCanSelect, validateEventRetention } from "@effect-agent/thread/SubscriptionTransition";
7
7
  //#region src/MemorySubscriptionStore.ts
8
8
  var MemorySubscriptionStore_exports = /* @__PURE__ */ __exportAll({ memorySubscriptionStoreLayer: () => memorySubscriptionStoreLayer });
9
9
  const error = (reason, code) => SubscriptionError.make({
@@ -34,7 +34,7 @@ const eventCandidateIndexKey = (event) => JSON.stringify([
34
34
  event.source.version,
35
35
  event.matchingKey
36
36
  ]);
37
- const sameEventIdentity = (left, right) => samePartition(left.partition, right.partition) && left.eventId === right.eventId && sameSource(left.source, right.source) && left.matchingKey === right.matchingKey && left.payloadDigest === right.payloadDigest && left.occurredAtMillis === right.occurredAtMillis;
37
+ const sameEventIdentity = sameAcceptedEventIdentity;
38
38
  const deliveryBelongsTo = (delivery, record, event) => subscriptionKeyString(delivery.key.subscription) === subscriptionKeyString(record.key) && delivery.key.eventId === event.eventId && sameSource(delivery.source, event.source);
39
39
  const removeKeys = (keys, removed) => {
40
40
  if (removed.size === 0) return keys;
@@ -1 +1 @@
1
- {"version":3,"file":"MemorySubscriptionStore.mjs","names":[],"sources":["../src/MemorySubscriptionStore.ts"],"sourcesContent":["import { Digest } from \"@effect-agent/thread/Records\";\nimport { compareScheduleNames } from \"@effect-agent/thread/ScheduleTransition\";\nimport {\n AcceptedEvent,\n DeliveryChange,\n SubscriptionChange,\n SourcePartition,\n SubscriptionDelivery,\n SubscriptionDeliveryKey,\n SubscriptionError,\n SubscriptionFailpoint,\n SubscriptionKey,\n SubscriptionLimits,\n SubscriptionRetentionPolicy,\n SubscriptionName,\n SubscriptionRecord,\n SubscriptionScanCursors,\n SubscriptionStore,\n subscriptionDeliveryKeyString,\n subscriptionKeyString,\n} from \"@effect-agent/thread/Subscription\";\nimport {\n applySubscriptionDeliveryChange,\n applySubscriptionChange,\n validateEventRetention,\n subscriptionCanSelect,\n subscriptionDeliveryCanSelect,\n} from \"@effect-agent/thread/SubscriptionTransition\";\nimport { Clock, Effect, Layer, Ref, Result, Schema } from \"effect\";\n\ninterface MemorySubscriptionState {\n readonly sequence: number;\n readonly retentionDeadline: number | null;\n readonly tombstoneCount: number;\n readonly eventKeys: ReadonlyArray<string>;\n readonly deliveryKeys: ReadonlyArray<string>;\n readonly maintenanceEvents: string;\n readonly maintenanceDeliveries: string;\n readonly recoveryCounts: ReadonlyMap<string, number>;\n readonly eventDeliveryCounts: ReadonlyMap<string, number>;\n readonly retentionHorizon: number | null;\n readonly registrations: ReadonlyMap<string, string>;\n readonly events: ReadonlyMap<string, string>;\n readonly deliveries: ReadonlyMap<string, string>;\n readonly registrationIndex: ReadonlyMap<string, RegistrationIndex>;\n readonly candidateIndex: ReadonlyMap<string, ReadonlyArray<string>>;\n readonly ownerRegistrationCounts: ReadonlyMap<string, number>;\n readonly eventIndex: ReadonlyMap<string, EventIndex>;\n readonly deliveryIndex: ReadonlyMap<string, DeliveryIndex>;\n readonly ownerDeliveryCounts: ReadonlyMap<string, number>;\n readonly scanCursors: SubscriptionScanCursors;\n}\n\ninterface RegistrationIndex {\n readonly key: SubscriptionKey;\n readonly ordinal: number;\n readonly state: SubscriptionRecord[\"state\"];\n readonly recoveryKey: string | null;\n readonly recoveryAt: number | null;\n}\ninterface EventIndex {\n readonly routingComplete: boolean;\n readonly nextAttemptAtMillis: number;\n}\ninterface DeliveryIndex {\n readonly key: SubscriptionDeliveryKey;\n readonly state: SubscriptionDelivery[\"state\"];\n readonly parked?: boolean;\n readonly observeSettlement?: boolean;\n readonly nextAttemptAtMillis: number;\n}\n\nconst error = (reason: SubscriptionError[\"reason\"], code: string) =>\n SubscriptionError.make({ reason, code });\n\nconst samePartition = (left: SourcePartition, right: SourcePartition): boolean =>\n left.tenantId === right.tenantId && left.address === right.address;\n\nconst sameSource = (left: AcceptedEvent[\"source\"], right: AcceptedEvent[\"source\"]): boolean =>\n left.name === right.name && left.version === right.version;\n\nconst encode = <A, I>(\n schema: Schema.Codec<A, I>,\n value: A,\n code: string,\n): Result.Result<string, SubscriptionError> =>\n Result.try({\n try: () => Schema.encodeSync(Schema.fromJsonString(schema))(value),\n catch: () => error(\"corrupt\", code),\n });\n\nconst decode = <A, I>(\n schema: Schema.Codec<A, I>,\n value: string,\n code: string,\n): Result.Result<A, SubscriptionError> =>\n Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(schema))(value),\n catch: () => error(\"corrupt\", code),\n });\n\nconst decodeEffect = <A, I>(schema: Schema.Codec<A, I>, value: string, code: string) =>\n Effect.fromResult(decode(schema, value, code));\n\nconst validate = <A, I>(schema: Schema.Codec<A, I>, value: unknown, code: string) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => error(\"validation\", code)));\n\nconst jsonBytes = (value: unknown): number =>\n new TextEncoder().encode(JSON.stringify(value)).byteLength;\n\nconst sameDeliveryIdentity = (left: SubscriptionDelivery, right: SubscriptionDelivery): boolean =>\n subscriptionDeliveryKeyString(left.key) === subscriptionDeliveryKeyString(right.key) &&\n left.deliveryId === right.deliveryId &&\n left.source.name === right.source.name &&\n left.source.version === right.source.version &&\n left.threadId === right.threadId &&\n left.admissionKey === right.admissionKey &&\n left.subscriptionFingerprint === right.subscriptionFingerprint &&\n left.eventDigest === right.eventDigest;\n\nconst candidateIndexKey = (record: SubscriptionRecord): string =>\n JSON.stringify([\n record.configuration.source.name,\n record.configuration.source.version,\n record.configuration.matchingKey,\n ]);\n\nconst eventCandidateIndexKey = (event: AcceptedEvent): string =>\n JSON.stringify([event.source.name, event.source.version, event.matchingKey]);\n\nconst sameEventIdentity = (left: AcceptedEvent, right: AcceptedEvent): boolean =>\n samePartition(left.partition, right.partition) &&\n left.eventId === right.eventId &&\n sameSource(left.source, right.source) &&\n left.matchingKey === right.matchingKey &&\n left.payloadDigest === right.payloadDigest &&\n left.occurredAtMillis === right.occurredAtMillis;\n\nconst deliveryBelongsTo = (\n delivery: SubscriptionDelivery,\n record: SubscriptionRecord,\n event: AcceptedEvent,\n): boolean =>\n subscriptionKeyString(delivery.key.subscription) === subscriptionKeyString(record.key) &&\n delivery.key.eventId === event.eventId &&\n sameSource(delivery.source, event.source);\n\n// Ordered in-memory indexes allow bounded maintenance pages without scanning retained values.\nconst removeKeys = (\n keys: ReadonlyArray<string>,\n removed: ReadonlySet<string>,\n): ReadonlyArray<string> => {\n if (removed.size === 0) return keys;\n const result = [...keys];\n\n for (const key of removed) {\n const index = upperBound(result, key) - 1;\n\n if (result[index] === key) result.splice(index, 1);\n }\n\n return result;\n};\n\nconst upperBound = (keys: ReadonlyArray<string>, after: string): number => {\n let low = 0;\n let high = keys.length;\n\n while (low < high) {\n const middle = Math.floor((low + high) / 2);\n const key = keys[middle];\n\n if (key !== undefined && compareScheduleNames(key, after) <= 0) low = middle + 1;\n else high = middle;\n }\n\n return low;\n};\n\nconst insertKey = (keys: ReadonlyArray<string>, key: string): ReadonlyArray<string> => {\n const at = upperBound(keys, key);\n\n if (at > 0 && keys[at - 1] === key) return keys;\n\n return [...keys.slice(0, at), key, ...keys.slice(at)];\n};\n\nconst recoveryCountsAfter = (\n current: MemorySubscriptionState,\n next: ReadonlyMap<string, RegistrationIndex>,\n keys: ReadonlyArray<string>,\n): ReadonlyMap<string, number> => {\n const counts = new Map(current.recoveryCounts);\n\n for (const key of keys) {\n const before = current.registrationIndex.get(key)?.recoveryKey;\n const after = next.get(key)?.recoveryKey;\n\n if (before === after) continue;\n if (before !== null && before !== undefined) counts.set(before, (counts.get(before) ?? 0) - 1);\n if (after !== null && after !== undefined) counts.set(after, (counts.get(after) ?? 0) + 1);\n }\n\n return counts;\n};\n\nconst makeMemorySubscriptionStore = Effect.fn(\"makeMemorySubscriptionStore\")(function* (\n ownedPartition: SourcePartition,\n) {\n const partition = yield* validate(SourcePartition, ownedPartition, \"partition\");\n\n const state = yield* Ref.make<MemorySubscriptionState>({\n sequence: 0,\n retentionDeadline: null,\n tombstoneCount: 0,\n eventKeys: [],\n deliveryKeys: [],\n maintenanceEvents: \"\",\n maintenanceDeliveries: \"\",\n recoveryCounts: new Map(),\n eventDeliveryCounts: new Map(),\n retentionHorizon: null,\n registrations: new Map(),\n events: new Map(),\n deliveries: new Map(),\n registrationIndex: new Map(),\n candidateIndex: new Map(),\n ownerRegistrationCounts: new Map(),\n eventIndex: new Map(),\n deliveryIndex: new Map(),\n ownerDeliveryCounts: new Map(),\n scanCursors: { events: \"\", deliveries: \"\", recovery: 0 },\n });\n\n const failpoint = yield* SubscriptionFailpoint;\n\n const requirePartition = <A extends { readonly partition: SourcePartition }>(\n value: A,\n code: string,\n ) =>\n samePartition(value.partition, partition)\n ? Effect.succeed(value)\n : Effect.fail(error(\"validation\", code));\n\n const requireKey = (key: SubscriptionKey, code: string) =>\n validate(SubscriptionKey, key, code).pipe(\n Effect.flatMap((decoded) => requirePartition(decoded, code)),\n );\n\n const register: SubscriptionStore[\"Service\"][\"register\"] = Effect.fn(\n \"MemorySubscriptionStore.register\",\n )(function* (input, inputLimits) {\n const record = yield* validate(SubscriptionRecord, input, \"register-record\");\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"register-limits\");\n\n yield* requirePartition(record.key, \"register-partition\");\n yield* failpoint.hit(\"subscription:register:before\");\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<SubscriptionRecord, SubscriptionError>,\n MemorySubscriptionState,\n ] => {\n const key = subscriptionKeyString(record.key);\n const existingText = current.registrations.get(key);\n\n if (existingText !== undefined) {\n const existing = decode(SubscriptionRecord, existingText, \"register-existing\");\n\n if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];\n\n return existing.success.creationFingerprint === record.creationFingerprint\n ? [Result.succeed(existing.success), current]\n : [Result.fail(error(\"conflict\", \"registration-identity\")), current];\n }\n if (jsonBytes(record.configuration.context) > limits.maxContextBytes)\n return [Result.fail(error(\"capacity\", \"context-bytes\")), current];\n if (jsonBytes(record.configuration.parameters) > limits.maxPayloadBytes)\n return [Result.fail(error(\"capacity\", \"parameters-bytes\")), current];\n if (\n record.configuration.expiresAtMillis !== null &&\n record.configuration.expiresAtMillis - record.createdAtMillis > limits.maxLifetimeMillis\n )\n return [Result.fail(error(\"capacity\", \"lifetime\")), current];\n if (current.registrations.size >= limits.maxRegistrations)\n return [Result.fail(error(\"capacity\", \"registrations\")), current];\n const ownerCount = current.ownerRegistrationCounts.get(record.key.ownerId) ?? 0;\n\n if (ownerCount >= limits.maxRegistrationsPerOwner)\n return [Result.fail(error(\"capacity\", \"owner-registrations\")), current];\n const assigned = { ...record, ordinal: current.sequence + 1 };\n const encoded = encode(SubscriptionRecord, assigned, \"register-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const registrations = new Map(current.registrations);\n\n registrations.set(key, encoded.success);\n const registrationIndex = new Map(current.registrationIndex);\n\n registrationIndex.set(key, {\n key: assigned.key,\n ordinal: assigned.ordinal,\n state: assigned.state,\n recoveryKey: assigned.recovery === null ? null : candidateIndexKey(assigned),\n recoveryAt: assigned.recovery?.nextAttemptAtMillis ?? null,\n });\n const candidateIndex = new Map(current.candidateIndex);\n const candidateKey = candidateIndexKey(assigned);\n\n candidateIndex.set(candidateKey, [...(candidateIndex.get(candidateKey) ?? []), key]);\n const ownerRegistrationCounts = new Map(current.ownerRegistrationCounts);\n\n ownerRegistrationCounts.set(assigned.key.ownerId, ownerCount + 1);\n\n return [\n Result.succeed(assigned),\n {\n ...current,\n sequence: assigned.ordinal,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [key]),\n candidateIndex,\n ownerRegistrationCounts,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(\"subscription:register:after\");\n\n return result;\n });\n\n const get: SubscriptionStore[\"Service\"][\"get\"] = Effect.fn(\"MemorySubscriptionStore.get\")(\n function* (input) {\n const key = yield* requireKey(input, \"get-key\");\n const text = (yield* Ref.get(state)).registrations.get(subscriptionKeyString(key));\n\n return text === undefined\n ? null\n : yield* decodeEffect(SubscriptionRecord, text, \"get-record\");\n },\n );\n\n const list: SubscriptionStore[\"Service\"][\"list\"] = Effect.fn(\"MemorySubscriptionStore.list\")(\n function* (ownerId, after, limit) {\n if (!Number.isSafeInteger(after) || after < 0 || !Number.isSafeInteger(limit) || limit <= 0)\n return yield* error(\"validation\", \"list-page\");\n const current = yield* Ref.get(state);\n const records: Array<SubscriptionRecord> = [];\n\n for (const [storageKey, indexed] of current.registrationIndex) {\n if (indexed.key.ownerId !== ownerId || indexed.ordinal <= after) continue;\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return yield* error(\"corrupt\", \"list-index\");\n records.push(yield* decodeEffect(SubscriptionRecord, text, \"list-record\"));\n }\n records.sort((a, b) => a.ordinal - b.ordinal);\n\n return records.slice(0, limit);\n },\n );\n\n const change: SubscriptionStore[\"Service\"][\"change\"] = Effect.fn(\n \"MemorySubscriptionStore.change\",\n )(function* (input, expectedRevision, inputChange) {\n const key = yield* requireKey(input, \"change-key\");\n const change = yield* validate(SubscriptionChange, inputChange, \"change\");\n\n yield* validate(Schema.Int.check(Schema.isGreaterThan(0)), expectedRevision, \"revision\");\n yield* failpoint.hit(\"subscription:change:before\");\n\n const updated = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<SubscriptionRecord, SubscriptionError>,\n MemorySubscriptionState,\n ] => {\n const storageKey = subscriptionKeyString(key);\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"subscription\")), current];\n const existing = decode(SubscriptionRecord, text, \"change-record\");\n\n if (Result.isFailure(existing)) return [existing, current];\n const updated = applySubscriptionChange(existing.success, expectedRevision, change);\n\n if (Result.isFailure(updated)) return [updated, current];\n const revised = { ...updated.success, ordinal: current.sequence + 1 };\n const encoded = encode(SubscriptionRecord, revised, \"change-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const registrations = new Map(current.registrations);\n\n registrations.set(storageKey, encoded.success);\n const registrationIndex = new Map(current.registrationIndex);\n\n registrationIndex.set(storageKey, {\n key,\n ordinal: revised.ordinal,\n state: revised.state,\n recoveryKey: revised.recovery === null ? null : candidateIndexKey(revised),\n recoveryAt: revised.recovery?.nextAttemptAtMillis ?? null,\n });\n const candidateIndex = new Map(current.candidateIndex);\n const oldKey = candidateIndexKey(existing.success);\n const nextKey = candidateIndexKey(revised);\n\n {\n candidateIndex.set(\n oldKey,\n (candidateIndex.get(oldKey) ?? []).filter((key) => key !== storageKey),\n );\n candidateIndex.set(\n nextKey,\n [...(candidateIndex.get(nextKey) ?? []), storageKey].sort(\n (a, b) =>\n (registrationIndex.get(a)?.ordinal ?? 0) -\n (registrationIndex.get(b)?.ordinal ?? 0),\n ),\n );\n }\n\n return [\n Result.succeed(revised),\n {\n ...current,\n sequence: revised.ordinal,\n registrations,\n registrationIndex,\n candidateIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(\"subscription:change:after\");\n\n return updated;\n });\n\n const cancel: SubscriptionStore[\"Service\"][\"cancel\"] = Effect.fn(\n \"MemorySubscriptionStore.cancel\",\n )(function* (input, expectedRevision) {\n const key = yield* requireKey(input, \"cancel-key\");\n\n yield* failpoint.hit(\"subscription:cancel:before\");\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<SubscriptionRecord, SubscriptionError>,\n MemorySubscriptionState,\n ] => {\n const storageKey = subscriptionKeyString(key);\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"subscription\")), current];\n const decoded = decode(SubscriptionRecord, text, \"cancel-record\");\n\n if (Result.isFailure(decoded)) return [decoded, current];\n if (\n expectedRevision !== undefined &&\n expectedRevision !== decoded.success.configurationRevision &&\n !(\n decoded.success.state === \"cancelled\" &&\n expectedRevision + 1 === decoded.success.configurationRevision\n )\n )\n return [\n Result.fail(\n SubscriptionError.make({\n reason: \"conflict\",\n code: \"configuration-revision\",\n currentRevision: decoded.success.configurationRevision,\n currentState: decoded.success.state,\n }),\n ),\n current,\n ];\n if (decoded.success.state === \"cancelled\")\n return [Result.succeed(decoded.success), current];\n\n const cancelled = {\n ...decoded.success,\n configurationRevision: decoded.success.configurationRevision + 1,\n state: \"cancelled\" as const,\n recovery: null,\n };\n\n const encoded = encode(SubscriptionRecord, cancelled, \"cancel-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const registrations = new Map(current.registrations);\n\n registrations.set(storageKey, encoded.success);\n const registrationIndex = new Map(current.registrationIndex);\n const indexed = registrationIndex.get(storageKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"cancel-index\")), current];\n registrationIndex.set(storageKey, {\n ...indexed,\n state: \"cancelled\",\n recoveryAt: null,\n recoveryKey: null,\n });\n\n return [\n Result.succeed(cancelled),\n {\n ...current,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(\"subscription:cancel:after\");\n\n return result;\n });\n\n const accept: SubscriptionStore[\"Service\"][\"accept\"] = Effect.fn(\n \"MemorySubscriptionStore.accept\",\n )(function* (input, inputLimits) {\n const event = yield* validate(AcceptedEvent, input, \"accept-event\");\n const currentTimeMillis = yield* Clock.currentTimeMillis;\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"accept-limits\");\n\n yield* requirePartition(event, \"accept-partition\");\n yield* failpoint.hit(\"subscription:accept:before\");\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [Result.Result<AcceptedEvent, SubscriptionError>, MemorySubscriptionState] => {\n const existingText = current.events.get(event.eventId);\n\n if (existingText !== undefined) {\n const existing = decode(AcceptedEvent, existingText, \"accept-existing\");\n\n if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];\n\n return sameEventIdentity(existing.success, event)\n ? [Result.succeed(existing.success), current]\n : [Result.fail(error(\"conflict\", \"event-identity\")), current];\n }\n if (\n current.retentionHorizon !== null &&\n current.retentionHorizon !== limits.retention?.replayHorizonMillis\n )\n return [Result.fail(error(\"conflict\", \"retention-horizon\")), current];\n const horizon = validateEventRetention(event, limits, currentTimeMillis);\n\n if (Result.isFailure(horizon)) return [Result.fail(horizon.failure), current];\n if (jsonBytes(event.payload) > limits.maxPayloadBytes)\n return [Result.fail(error(\"capacity\", \"payload-bytes\")), current];\n if (current.events.size - current.tombstoneCount >= limits.maxEvents)\n return [Result.fail(error(\"capacity\", \"events\")), current];\n\n const accepted: AcceptedEvent = {\n ...event,\n cutoff: current.sequence + 1,\n cursor: 0,\n routingComplete: false,\n routingFailure: null,\n };\n\n const encoded = encode(AcceptedEvent, accepted, \"accept-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const events = new Map(current.events);\n\n events.set(accepted.eventId, encoded.success);\n const eventIndex = new Map(current.eventIndex);\n\n eventIndex.set(accepted.eventId, {\n routingComplete: false,\n nextAttemptAtMillis: accepted.nextAttemptAtMillis,\n });\n\n return [\n Result.succeed(accepted),\n {\n ...current,\n sequence: accepted.cutoff,\n events,\n eventIndex,\n eventKeys: insertKey(current.eventKeys, accepted.eventId),\n retentionHorizon: limits.retention?.replayHorizonMillis ?? current.retentionHorizon,\n retentionDeadline:\n limits.retention === undefined\n ? current.retentionDeadline\n : accepted.acceptedAtMillis,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(\"subscription:accept:after\");\n\n return result;\n });\n\n const event: SubscriptionStore[\"Service\"][\"event\"] = Effect.fn(\"MemorySubscriptionStore.event\")(\n function* (eventId) {\n const text = (yield* Ref.get(state)).events.get(eventId);\n\n return text === undefined ? null : yield* decodeEffect(AcceptedEvent, text, \"event-record\");\n },\n );\n\n const pendingEvents: SubscriptionStore[\"Service\"][\"pendingEvents\"] = Effect.fn(\n \"MemorySubscriptionStore.pendingEvents\",\n )(function* (nowMillis, after, limit) {\n const events: Array<string> = [];\n\n for (const [eventId, indexed] of (yield* Ref.get(state)).eventIndex) {\n if (\n !indexed.routingComplete &&\n indexed.nextAttemptAtMillis <= nowMillis &&\n compareScheduleNames(eventId, after) > 0\n )\n events.push(eventId);\n }\n events.sort(compareScheduleNames);\n\n return events.slice(0, limit);\n });\n\n const candidates: SubscriptionStore[\"Service\"][\"candidates\"] = Effect.fn(\n \"MemorySubscriptionStore.candidates\",\n )(function* (input, limit) {\n const accepted = yield* validate(AcceptedEvent, input, \"candidates-event\");\n\n yield* requirePartition(accepted, \"candidates-partition\");\n const stored = yield* event(accepted.eventId);\n\n if (stored === null || !sameEventIdentity(stored, accepted))\n return yield* error(stored === null ? \"not-found\" : \"conflict\", \"event\");\n const current = yield* Ref.get(state);\n const records: Array<SubscriptionRecord> = [];\n\n for (const storageKey of current.candidateIndex.get(eventCandidateIndexKey(stored)) ?? []) {\n const indexed = current.registrationIndex.get(storageKey);\n\n if (indexed === undefined) return yield* error(\"corrupt\", \"candidate-index\");\n if (indexed.ordinal <= stored.cursor || indexed.ordinal > stored.cutoff) continue;\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return yield* error(\"corrupt\", \"candidate-record\");\n records.push(yield* decodeEffect(SubscriptionRecord, text, \"candidate-record\"));\n }\n records.sort((a, b) => a.ordinal - b.ordinal);\n\n return records.slice(0, limit);\n });\n\n const select: SubscriptionStore[\"Service\"][\"select\"] = Effect.fn(\n \"MemorySubscriptionStore.select\",\n )(function* (inputEvent, inputDeliveries, cursor, complete, nowMillis, inputLimits) {\n const suppliedEvent = yield* validate(AcceptedEvent, inputEvent, \"select-event\");\n\n const deliveries = yield* validate(\n Schema.Array(SubscriptionDelivery),\n inputDeliveries,\n \"select-deliveries\",\n );\n\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"select-limits\");\n\n yield* requirePartition(suppliedEvent, \"select-partition\");\n yield* failpoint.hit(\"subscription:select:before\");\n const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);\n\n yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {\n const eventText = current.events.get(suppliedEvent.eventId);\n\n if (eventText === undefined) return [Result.fail(error(\"not-found\", \"event\")), current];\n const decodedEvent = decode(AcceptedEvent, eventText, \"select-event-record\");\n\n if (Result.isFailure(decodedEvent)) return [Result.fail(decodedEvent.failure), current];\n const accepted = decodedEvent.success;\n\n if (\n !sameEventIdentity(accepted, suppliedEvent) ||\n suppliedEvent.cursor !== accepted.cursor\n )\n return [Result.fail(error(\"conflict\", \"event-cursor\")), current];\n if (accepted.routingComplete)\n return [\n complete && cursor === accepted.cursor\n ? Result.void\n : Result.fail(error(\"conflict\", \"routing-complete\")),\n current,\n ];\n if (!Number.isSafeInteger(cursor) || cursor < accepted.cursor || cursor > accepted.cutoff)\n return [Result.fail(error(\"validation\", \"cursor\")), current];\n\n const additions: Array<readonly [string, string]> = [];\n const updates: Array<readonly [string, string]> = [];\n const additionIndex: Array<readonly [string, DeliveryIndex, string]> = [];\n const registrationUpdates: Array<readonly [string, RegistrationIndex]> = [];\n const owners = new Map(current.ownerDeliveryCounts);\n\n for (const delivery of deliveries) {\n const recordText = current.registrations.get(\n subscriptionKeyString(delivery.key.subscription),\n );\n\n if (recordText === undefined)\n return [Result.fail(error(\"not-found\", \"subscription\")), current];\n const record = decode(SubscriptionRecord, recordText, \"select-registration\");\n\n if (Result.isFailure(record)) return [Result.fail(record.failure), current];\n if (\n !deliveryBelongsTo(delivery, record.success, accepted) ||\n !subscriptionDeliveryCanSelect(delivery, record.success, accepted) ||\n record.success.ordinal <= accepted.cursor ||\n record.success.ordinal > cursor\n )\n return [Result.fail(error(\"conflict\", \"selection\")), current];\n if (!subscriptionCanSelect(record.success, accepted, effectiveNowMillis, false))\n continue;\n const deliveryKey = subscriptionDeliveryKeyString(delivery.key);\n const existingText = current.deliveries.get(deliveryKey);\n\n if (existingText !== undefined) {\n const existing = decode(SubscriptionDelivery, existingText, \"select-existing\");\n\n if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];\n if (!sameDeliveryIdentity(existing.success, delivery))\n return [Result.fail(error(\"conflict\", \"delivery-identity\")), current];\n continue;\n }\n\n const encodedDelivery = encode(\n SubscriptionDelivery,\n delivery,\n \"select-delivery-encode\",\n );\n\n if (Result.isFailure(encodedDelivery))\n return [Result.fail(encodedDelivery.failure), current];\n additions.push([deliveryKey, encodedDelivery.success]);\n additionIndex.push([\n deliveryKey,\n {\n key: delivery.key,\n state: delivery.state,\n nextAttemptAtMillis: delivery.retry.nextAttemptAtMillis,\n },\n record.success.key.ownerId,\n ]);\n const ownerId = record.success.key.ownerId;\n\n owners.set(ownerId, (owners.get(ownerId) ?? 0) + 1);\n if ((owners.get(ownerId) ?? 0) > limits.maxDeliveriesPerOwner)\n return [Result.fail(error(\"capacity\", \"owner-deliveries\")), current];\n if (record.success.configuration.mode === \"once\") {\n const consumed = { ...record.success, state: \"consumed\" as const, recovery: null };\n\n const encodedRecord = encode(\n SubscriptionRecord,\n consumed,\n \"select-registration-encode\",\n );\n\n if (Result.isFailure(encodedRecord))\n return [Result.fail(encodedRecord.failure), current];\n const consumedKey = subscriptionKeyString(consumed.key);\n\n updates.push([consumedKey, encodedRecord.success]);\n const indexed = current.registrationIndex.get(consumedKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"selection-index\")), current];\n registrationUpdates.push([\n consumedKey,\n { ...indexed, state: \"consumed\", recoveryAt: null, recoveryKey: null },\n ]);\n }\n }\n if (current.deliveries.size + additions.length > limits.maxDeliveries)\n return [Result.fail(error(\"capacity\", \"deliveries\")), current];\n const registrations = new Map(current.registrations);\n\n for (const [key, value] of updates) registrations.set(key, value);\n const nextDeliveries = new Map(current.deliveries);\n\n for (const [key, value] of additions) nextDeliveries.set(key, value);\n const deliveryIndex = new Map(current.deliveryIndex);\n\n for (const [key, value] of additionIndex) deliveryIndex.set(key, value);\n const registrationIndex = new Map(current.registrationIndex);\n\n for (const [key, value] of registrationUpdates) registrationIndex.set(key, value);\n\n const eventDeliveryCounts = new Map(current.eventDeliveryCounts);\n\n eventDeliveryCounts.set(\n accepted.eventId,\n (eventDeliveryCounts.get(accepted.eventId) ?? 0) + additions.length,\n );\n\n const nextEvent: AcceptedEvent = {\n ...accepted,\n cursor,\n routingComplete: complete,\n routingFailure: null,\n };\n\n const encodedEvent = encode(AcceptedEvent, nextEvent, \"select-event-encode\");\n\n if (Result.isFailure(encodedEvent)) return [Result.fail(encodedEvent.failure), current];\n const events = new Map(current.events);\n\n events.set(nextEvent.eventId, encodedEvent.success);\n const eventIndex = new Map(current.eventIndex);\n\n eventIndex.set(nextEvent.eventId, {\n routingComplete: nextEvent.routingComplete,\n nextAttemptAtMillis: nextEvent.nextAttemptAtMillis,\n });\n\n return [\n Result.void,\n {\n ...current,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(\n current,\n registrationIndex,\n registrationUpdates.map(([key]) => key),\n ),\n eventDeliveryCounts,\n events,\n eventIndex,\n deliveries: nextDeliveries,\n deliveryKeys: additions.reduce(\n (keys, [key]) => insertKey(keys, key),\n current.deliveryKeys,\n ),\n deliveryIndex,\n ownerDeliveryCounts: owners,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n yield* failpoint.hit(\"subscription:select:after\");\n });\n\n const catchUp: SubscriptionStore[\"Service\"][\"catchUp\"] = Effect.fn(\n \"MemorySubscriptionStore.catchUp\",\n )(function* (inputEvent, inputDelivery, nowMillis, inputLimits) {\n const suppliedEvent = yield* validate(AcceptedEvent, inputEvent, \"catch-up-event\");\n const delivery = yield* validate(SubscriptionDelivery, inputDelivery, \"catch-up-delivery\");\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"catch-up-limits\");\n\n yield* requirePartition(suppliedEvent, \"catch-up-partition\");\n yield* failpoint.hit(\"subscription:catch-up:before\");\n const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);\n\n yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {\n const eventText = current.events.get(suppliedEvent.eventId);\n\n const recordText = current.registrations.get(\n subscriptionKeyString(delivery.key.subscription),\n );\n\n if (eventText === undefined || recordText === undefined)\n return [\n Result.fail(error(\"not-found\", eventText === undefined ? \"event\" : \"subscription\")),\n current,\n ];\n const accepted = decode(AcceptedEvent, eventText, \"catch-up-event-record\");\n\n if (Result.isFailure(accepted)) return [Result.fail(accepted.failure), current];\n const record = decode(SubscriptionRecord, recordText, \"catch-up-registration\");\n\n if (Result.isFailure(record)) return [Result.fail(record.failure), current];\n if (\n !sameEventIdentity(accepted.success, suppliedEvent) ||\n !deliveryBelongsTo(delivery, record.success, accepted.success) ||\n !subscriptionDeliveryCanSelect(delivery, record.success, accepted.success) ||\n record.success.configuration.mode !== \"once\"\n )\n return [Result.fail(error(\"conflict\", \"catch-up-identity\")), current];\n const key = subscriptionDeliveryKeyString(delivery.key);\n const existingText = current.deliveries.get(key);\n\n if (existingText !== undefined) {\n const existing = decode(SubscriptionDelivery, existingText, \"catch-up-existing\");\n\n if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];\n\n return sameDeliveryIdentity(existing.success, delivery)\n ? [Result.void, current]\n : [Result.fail(error(\"conflict\", \"delivery-identity\")), current];\n }\n if (!subscriptionCanSelect(record.success, accepted.success, effectiveNowMillis, true))\n return [Result.fail(error(\"conflict\", \"catch-up-eligibility\")), current];\n if (current.deliveries.size >= limits.maxDeliveries)\n return [Result.fail(error(\"capacity\", \"deliveries\")), current];\n const ownerCount = current.ownerDeliveryCounts.get(record.success.key.ownerId) ?? 0;\n\n if (ownerCount >= limits.maxDeliveriesPerOwner)\n return [Result.fail(error(\"capacity\", \"owner-deliveries\")), current];\n\n const encodedDelivery = encode(\n SubscriptionDelivery,\n delivery,\n \"catch-up-delivery-encode\",\n );\n\n if (Result.isFailure(encodedDelivery))\n return [Result.fail(encodedDelivery.failure), current];\n const consumed = { ...record.success, state: \"consumed\" as const, recovery: null };\n\n const encodedRecord = encode(\n SubscriptionRecord,\n consumed,\n \"catch-up-registration-encode\",\n );\n\n if (Result.isFailure(encodedRecord)) return [Result.fail(encodedRecord.failure), current];\n const deliveries = new Map(current.deliveries);\n\n deliveries.set(key, encodedDelivery.success);\n const registrations = new Map(current.registrations);\n const consumedKey = subscriptionKeyString(consumed.key);\n\n registrations.set(consumedKey, encodedRecord.success);\n const registrationIndex = new Map(current.registrationIndex);\n const indexed = registrationIndex.get(consumedKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"catch-up-index\")), current];\n registrationIndex.set(consumedKey, {\n ...indexed,\n state: \"consumed\",\n recoveryAt: null,\n recoveryKey: null,\n });\n const deliveryIndex = new Map(current.deliveryIndex);\n\n deliveryIndex.set(key, {\n key: delivery.key,\n state: delivery.state,\n nextAttemptAtMillis: delivery.retry.nextAttemptAtMillis,\n });\n const ownerDeliveryCounts = new Map(current.ownerDeliveryCounts);\n const eventDeliveryCounts = new Map(current.eventDeliveryCounts);\n\n eventDeliveryCounts.set(\n accepted.success.eventId,\n (eventDeliveryCounts.get(accepted.success.eventId) ?? 0) + 1,\n );\n\n ownerDeliveryCounts.set(consumed.key.ownerId, ownerCount + 1);\n\n return [\n Result.void,\n {\n ...current,\n deliveries,\n deliveryIndex,\n deliveryKeys: insertKey(current.deliveryKeys, key),\n ownerDeliveryCounts,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [consumedKey]),\n eventDeliveryCounts,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n yield* failpoint.hit(\"subscription:catch-up:after\");\n });\n\n const deferEvent: SubscriptionStore[\"Service\"][\"deferEvent\"] = Effect.fn(\n \"MemorySubscriptionStore.deferEvent\",\n )(function* (eventId, nextAttemptAtMillis, code) {\n const routingFailure =\n code === undefined\n ? \"routing-failed\"\n : yield* validate(SubscriptionName, code, \"routing-failure\");\n\n yield* failpoint.hit(\"subscription:defer-event:before\");\n yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {\n const text = current.events.get(eventId);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"event\")), current];\n const accepted = decode(AcceptedEvent, text, \"defer-event-record\");\n\n if (Result.isFailure(accepted)) return [Result.fail(accepted.failure), current];\n const updated = { ...accepted.success, nextAttemptAtMillis, routingFailure };\n const encoded = encode(AcceptedEvent, updated, \"defer-event-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const events = new Map(current.events);\n\n events.set(eventId, encoded.success);\n const eventIndex = new Map(current.eventIndex);\n const indexed = eventIndex.get(eventId);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"defer-event-index\")), current];\n eventIndex.set(eventId, { ...indexed, nextAttemptAtMillis });\n\n return [Result.void, { ...current, events, eventIndex }];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n yield* failpoint.hit(\"subscription:defer-event:after\");\n });\n\n const delivery: SubscriptionStore[\"Service\"][\"delivery\"] = Effect.fn(\n \"MemorySubscriptionStore.delivery\",\n )(function* (input) {\n const key = yield* validate(SubscriptionDeliveryKey, input, \"delivery-key\");\n\n yield* requirePartition(key.subscription, \"delivery-partition\");\n const text = (yield* Ref.get(state)).deliveries.get(subscriptionDeliveryKeyString(key));\n\n return text === undefined\n ? null\n : yield* decodeEffect(SubscriptionDelivery, text, \"delivery-record\");\n });\n\n const pendingDeliveries: SubscriptionStore[\"Service\"][\"pendingDeliveries\"] = Effect.fn(\n \"MemorySubscriptionStore.pendingDeliveries\",\n )(function* (nowMillis, after, limit) {\n const items: Array<SubscriptionDeliveryKey> = [];\n\n for (const [storageKey, item] of (yield* Ref.get(state)).deliveryIndex) {\n if (\n ((item.state !== \"delivered\" && item.state !== \"refused\" && item.parked !== true) ||\n (item.state === \"delivered\" && item.observeSettlement === true)) &&\n item.nextAttemptAtMillis <= nowMillis &&\n compareScheduleNames(storageKey, after) > 0\n )\n items.push(item.key);\n }\n items.sort((a, b) =>\n compareScheduleNames(subscriptionDeliveryKeyString(a), subscriptionDeliveryKeyString(b)),\n );\n\n return items.slice(0, limit);\n });\n\n const listDeliveries: SubscriptionStore[\"Service\"][\"listDeliveries\"] = Effect.fn(\n \"MemorySubscriptionStore.listDeliveries\",\n )(function* (input, after, limit) {\n const key = yield* requireKey(input, \"list-deliveries-key\");\n const items: Array<SubscriptionDelivery> = [];\n\n for (const text of (yield* Ref.get(state)).deliveries.values()) {\n const item = yield* decodeEffect(SubscriptionDelivery, text, \"list-delivery\");\n const itemKey = subscriptionDeliveryKeyString(item.key);\n\n if (\n subscriptionKeyString(item.key.subscription) === subscriptionKeyString(key) &&\n compareScheduleNames(itemKey, after) > 0\n )\n items.push(item);\n }\n items.sort((a, b) =>\n compareScheduleNames(\n subscriptionDeliveryKeyString(a.key),\n subscriptionDeliveryKeyString(b.key),\n ),\n );\n\n return items.slice(0, limit);\n });\n\n const changeDelivery: SubscriptionStore[\"Service\"][\"changeDelivery\"] = Effect.fn(\n \"MemorySubscriptionStore.changeDelivery\",\n )(function* (inputKey, inputDeliveryId, inputChange) {\n const key = yield* validate(SubscriptionDeliveryKey, inputKey, \"change-delivery-key\");\n const deliveryId = yield* validate(Digest, inputDeliveryId, \"change-delivery-id\");\n const change = yield* validate(DeliveryChange, inputChange, \"change-delivery-change\");\n\n yield* requirePartition(key.subscription, \"change-delivery-partition\");\n yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:before`);\n\n const effectiveChange =\n change._tag === \"Prepare\"\n ? { ...change, nowMillis: Math.max(change.nowMillis, yield* Clock.currentTimeMillis) }\n : change;\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<SubscriptionDelivery, SubscriptionError>,\n MemorySubscriptionState,\n ] => {\n const storageKey = subscriptionDeliveryKeyString(key);\n const text = current.deliveries.get(storageKey);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"delivery\")), current];\n const decoded = decode(SubscriptionDelivery, text, \"change-delivery-record\");\n\n if (Result.isFailure(decoded)) return [decoded, current];\n\n const registrationText = current.registrations.get(\n subscriptionKeyString(key.subscription),\n );\n\n if (registrationText === undefined)\n return [Result.fail(error(\"corrupt\", \"delivery-registration\")), current];\n\n const registration = decode(\n SubscriptionRecord,\n registrationText,\n \"delivery-registration\",\n );\n\n if (Result.isFailure(registration)) return [Result.fail(registration.failure), current];\n\n const transition = applySubscriptionDeliveryChange(\n decoded.success,\n registration.success,\n deliveryId,\n effectiveChange,\n );\n\n if (Result.isFailure(transition)) return [Result.fail(transition.failure), current];\n if (transition.success === decoded.success)\n return [Result.succeed(decoded.success), current];\n const updated = transition.success;\n const encoded = encode(SubscriptionDelivery, updated, \"change-delivery-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const deliveries = new Map(current.deliveries);\n\n deliveries.set(storageKey, encoded.success);\n const deliveryIndex = new Map(current.deliveryIndex);\n const indexed = deliveryIndex.get(storageKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"delivery-index\")), current];\n deliveryIndex.set(storageKey, {\n ...indexed,\n state: updated.state,\n parked: updated.retry.parked ?? false,\n observeSettlement: updated.observeSettlement ?? false,\n nextAttemptAtMillis: updated.retry.nextAttemptAtMillis,\n });\n\n return [Result.succeed(updated), { ...current, deliveries, deliveryIndex }];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:after`);\n\n return result;\n });\n\n const recovering: SubscriptionStore[\"Service\"][\"recovering\"] = Effect.fn(\n \"MemorySubscriptionStore.recovering\",\n )(function* (nowMillis, after, limit) {\n const records: Array<{ readonly key: SubscriptionKey; readonly ordinal: number }> = [];\n\n for (const item of (yield* Ref.get(state)).registrationIndex.values()) {\n if (\n item.ordinal > after &&\n item.state === \"active\" &&\n item.recoveryAt !== null &&\n item.recoveryAt <= nowMillis\n )\n records.push({ key: item.key, ordinal: item.ordinal });\n }\n records.sort((a, b) => a.ordinal - b.ordinal);\n\n return records.slice(0, limit);\n });\n\n const deferRecovery: SubscriptionStore[\"Service\"][\"deferRecovery\"] = Effect.fn(\n \"MemorySubscriptionStore.deferRecovery\",\n )(function* (input, expectedRevision, recovery) {\n const key = yield* requireKey(input, \"defer-recovery-key\");\n\n yield* failpoint.hit(\"subscription:defer-recovery:before\");\n yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {\n const storageKey = subscriptionKeyString(key);\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"subscription\")), current];\n const record = decode(SubscriptionRecord, text, \"defer-recovery-record\");\n\n if (Result.isFailure(record)) return [Result.fail(record.failure), current];\n\n if (record.success.configurationRevision !== expectedRevision)\n return [Result.void, current];\n\n const updated = {\n ...record.success,\n recovery:\n record.success.state === \"active\" || record.success.state === \"paused\"\n ? recovery\n : null,\n };\n\n const encoded = encode(SubscriptionRecord, updated, \"defer-recovery-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const registrations = new Map(current.registrations);\n\n registrations.set(storageKey, encoded.success);\n const registrationIndex = new Map(current.registrationIndex);\n const indexed = registrationIndex.get(storageKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"recovery-index\")), current];\n registrationIndex.set(storageKey, {\n ...indexed,\n recoveryKey: updated.recovery === null ? null : candidateIndexKey(updated),\n recoveryAt: updated.recovery?.nextAttemptAtMillis ?? null,\n });\n\n return [\n Result.void,\n {\n ...current,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n yield* failpoint.hit(\"subscription:defer-recovery:after\");\n });\n\n const readScanCursors: SubscriptionStore[\"Service\"][\"readScanCursors\"] = Ref.get(state).pipe(\n Effect.map((current) => current.scanCursors),\n );\n\n const advanceScanCursors: SubscriptionStore[\"Service\"][\"advanceScanCursors\"] = Effect.fn(\n \"MemorySubscriptionStore.advanceScanCursors\",\n )(function* (input) {\n const cursors = yield* validate(SubscriptionScanCursors, input, \"scan-cursors\");\n\n yield* failpoint.hit(\"subscription:advance-scan-cursors:before\");\n yield* Effect.uninterruptible(\n Ref.update(state, (current) => ({ ...current, scanCursors: cursors })),\n );\n yield* failpoint.hit(\"subscription:advance-scan-cursors:after\");\n });\n\n const nextDeadline = Effect.gen(function* () {\n let deadline: number | null = null;\n const current = yield* Ref.get(state);\n\n if (\n current.scanCursors.events !== \"\" ||\n current.scanCursors.deliveries !== \"\" ||\n current.scanCursors.recovery !== 0\n )\n return 0;\n\n const consider = (value: number) => {\n if (deadline === null || value < deadline) deadline = value;\n };\n\n if (current.retentionDeadline !== null) consider(current.retentionDeadline);\n for (const accepted of current.eventIndex.values())\n if (!accepted.routingComplete) consider(accepted.nextAttemptAtMillis);\n for (const item of current.deliveryIndex.values())\n if (\n (item.state !== \"delivered\" && item.state !== \"refused\" && item.parked !== true) ||\n (item.state === \"delivered\" && item.observeSettlement === true)\n )\n consider(item.nextAttemptAtMillis);\n for (const record of current.registrationIndex.values())\n if (record.state === \"active\" && record.recoveryAt !== null) consider(record.recoveryAt);\n\n return deadline;\n }).pipe(Effect.withSpan(\"MemorySubscriptionStore.nextDeadline\"));\n\n const compact: SubscriptionStore[\"Service\"][\"compact\"] = Effect.fn(\n \"MemorySubscriptionStore.compact\",\n )(function* (nowMillis, inputPolicy, requestedLimit) {\n nowMillis = Math.min(nowMillis, yield* Clock.currentTimeMillis);\n const policy = yield* validate(SubscriptionRetentionPolicy, inputPolicy, \"retention-policy\");\n\n const limit = yield* validate(\n Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 })),\n requestedLimit,\n \"maintenance-limit\",\n );\n\n yield* failpoint.hit(\"subscription:compact:before\");\n let corruptCandidates = 0;\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<number, SubscriptionError>, MemorySubscriptionState] => {\n if (\n current.retentionHorizon !== null &&\n current.retentionHorizon !== policy.replayHorizonMillis\n )\n return [Result.fail(error(\"conflict\", \"retention-horizon\")), current];\n const events = new Map(current.events);\n const eventIndex = new Map(current.eventIndex);\n const deliveries = new Map(current.deliveries);\n const deliveryIndex = new Map(current.deliveryIndex);\n const eventDeliveryCounts = new Map(current.eventDeliveryCounts);\n const ownerDeliveryCounts = new Map(current.ownerDeliveryCounts);\n\n // Page indexes before decoding. Each pass reads at most 2 * limit event values and\n // limit delivery values; relationship checks use maintained reference counts.\n const deliveryPage = current.deliveryKeys.slice(\n upperBound(current.deliveryKeys, current.maintenanceDeliveries),\n upperBound(current.deliveryKeys, current.maintenanceDeliveries) + limit,\n );\n\n const eventPage = current.eventKeys.slice(\n upperBound(current.eventKeys, current.maintenanceEvents),\n upperBound(current.eventKeys, current.maintenanceEvents) + limit,\n );\n\n const cutoff = nowMillis - policy.completedRetentionMillis;\n let removed = 0;\n const removedEvents = new Set<string>();\n const removedDeliveries = new Set<string>();\n\n for (const key of deliveryPage) {\n const text = deliveries.get(key);\n\n if (text === undefined) continue;\n const decoded = decode(SubscriptionDelivery, text, \"compact-delivery\");\n\n if (Result.isFailure(decoded)) {\n corruptCandidates++;\n continue;\n }\n const delivery = decoded.success;\n\n if (\n subscriptionDeliveryKeyString(delivery.key) !== key ||\n !samePartition(delivery.key.subscription.partition, partition)\n ) {\n corruptCandidates++;\n continue;\n }\n\n if (\n delivery.state !== \"refused\" &&\n (delivery.state !== \"delivered\" || delivery.settledAtMillis === undefined)\n )\n continue;\n if (\n (delivery.settledAtMillis ??\n delivery.completedAtMillis ??\n delivery.selectedAtMillis) > cutoff\n )\n continue;\n const eventText = events.get(delivery.key.eventId);\n\n if (eventText === undefined) continue;\n const accepted = decode(AcceptedEvent, eventText, \"compact-delivery-event\");\n\n if (Result.isFailure(accepted)) {\n corruptCandidates++;\n continue;\n }\n const event = accepted.success;\n\n if (\n event.eventId !== delivery.key.eventId ||\n !samePartition(event.partition, partition)\n ) {\n corruptCandidates++;\n continue;\n }\n\n if (\n !event.routingComplete ||\n event.occurredAtMillis === undefined ||\n event.acceptedAtMillis > cutoff ||\n (current.recoveryCounts.get(eventCandidateIndexKey(event)) ?? 0) > 0\n )\n continue;\n deliveries.delete(key);\n removedDeliveries.add(key);\n deliveryIndex.delete(key);\n eventDeliveryCounts.set(\n event.eventId,\n (eventDeliveryCounts.get(event.eventId) ?? 1) - 1,\n );\n const owner = delivery.key.subscription.ownerId;\n\n ownerDeliveryCounts.set(owner, (ownerDeliveryCounts.get(owner) ?? 1) - 1);\n }\n let tombstones = current.tombstoneCount;\n\n for (const key of eventPage) {\n const text = events.get(key);\n\n if (text === undefined) continue;\n const decoded = decode(AcceptedEvent, text, \"compact-event\");\n\n if (Result.isFailure(decoded)) {\n corruptCandidates++;\n continue;\n }\n const event = decoded.success;\n\n if (event.eventId !== key || !samePartition(event.partition, partition)) {\n corruptCandidates++;\n continue;\n }\n\n if (!event.routingComplete || event.occurredAtMillis === undefined) continue;\n const expired = event.occurredAtMillis <= nowMillis - policy.replayHorizonMillis;\n\n if (event.tombstone === true && !expired) continue;\n if (\n event.acceptedAtMillis > cutoff ||\n (eventDeliveryCounts.get(key) ?? 0) > 0 ||\n (current.recoveryCounts.get(eventCandidateIndexKey(event)) ?? 0) > 0\n )\n continue;\n if (expired) {\n events.delete(key);\n removedEvents.add(key);\n eventIndex.delete(key);\n eventDeliveryCounts.delete(key);\n if (event.tombstone === true) tombstones--;\n } else {\n if (tombstones >= policy.maxTombstones) continue;\n\n const encoded = encode(\n AcceptedEvent,\n { ...event, payload: null, tombstone: true },\n \"compact-tombstone\",\n );\n\n if (Result.isFailure(encoded)) continue;\n events.set(key, encoded.success);\n tombstones++;\n }\n removed++;\n }\n\n return [\n Result.succeed(removed),\n {\n ...current,\n events,\n eventIndex,\n deliveries,\n deliveryIndex,\n eventDeliveryCounts,\n ownerDeliveryCounts,\n eventKeys: removeKeys(current.eventKeys, removedEvents),\n deliveryKeys: removeKeys(current.deliveryKeys, removedDeliveries),\n tombstoneCount: tombstones,\n maintenanceEvents: eventPage.length < limit ? \"\" : (eventPage.at(-1) ?? \"\"),\n maintenanceDeliveries: deliveryPage.length < limit ? \"\" : (deliveryPage.at(-1) ?? \"\"),\n retentionHorizon: policy.replayHorizonMillis,\n retentionDeadline: events.size === 0 ? null : nowMillis + 60_000,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n if (corruptCandidates > 0)\n yield* Effect.logWarning(\"Subscription retention preserved corrupt candidates\", {\n count: corruptCandidates,\n });\n yield* failpoint.hit(\"subscription:compact:after\");\n\n return result;\n });\n\n return SubscriptionStore.of({\n partition,\n compact,\n register,\n get,\n list,\n cancel,\n change,\n accept,\n event,\n pendingEvents,\n candidates,\n select,\n catchUp,\n deferEvent,\n delivery,\n pendingDeliveries,\n listDeliveries,\n changeDelivery,\n recovering,\n deferRecovery,\n readScanCursors,\n advanceScanCursors,\n nextDeadline,\n });\n});\n\nexport const memorySubscriptionStoreLayer = (\n partition: SourcePartition,\n): Layer.Layer<SubscriptionStore, SubscriptionError> =>\n Layer.effect(SubscriptionStore, makeMemorySubscriptionStore(partition));\n"],"mappings":";;;;;;;;AAwEA,MAAM,SAAS,QAAqC,SAClD,kBAAkB,KAAK;CAAE;CAAQ;AAAK,CAAC;AAEzC,MAAM,iBAAiB,MAAuB,UAC5C,KAAK,aAAa,MAAM,YAAY,KAAK,YAAY,MAAM;AAE7D,MAAM,cAAc,MAA+B,UACjD,KAAK,SAAS,MAAM,QAAQ,KAAK,YAAY,MAAM;AAErD,MAAM,UACJ,QACA,OACA,SAEA,OAAO,IAAI;CACT,WAAW,OAAO,WAAW,OAAO,eAAe,MAAM,CAAC,CAAC,CAAC,KAAK;CACjE,aAAa,MAAM,WAAW,IAAI;AACpC,CAAC;AAEH,MAAM,UACJ,QACA,OACA,SAEA,OAAO,IAAI;CACT,WAAW,OAAO,WAAW,OAAO,eAAe,MAAM,CAAC,CAAC,CAAC,KAAK;CACjE,aAAa,MAAM,WAAW,IAAI;AACpC,CAAC;AAEH,MAAM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M,UAAU,GAAG,EAAE,KAAK;IACxE,uBAAuB,aAAa,SAAS,QAAQ,KAAM,aAAa,GAAG,EAAE,KAAK;IAClF,kBAAkB,OAAO;IACzB,mBAAmB,OAAO,SAAS,IAAI,OAAO,YAAY;GAC5D,CACF;EACF,CACF,CACF,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,UAAU,CAAC;EAExC,IAAI,oBAAoB,GACtB,OAAO,OAAO,WAAW,uDAAuD,EAC9E,OAAO,kBACT,CAAC;EACH,OAAO,UAAU,IAAI,4BAA4B;EAEjD,OAAO;CACT,CAAC;CAED,OAAO,kBAAkB,GAAG;EAC1B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH,CAAC;AAED,MAAa,gCACX,cAEA,MAAM,OAAO,mBAAmB,4BAA4B,SAAS,CAAC"}
1
+ {"version":3,"file":"MemorySubscriptionStore.mjs","names":[],"sources":["../src/MemorySubscriptionStore.ts"],"sourcesContent":["import { Digest } from \"@effect-agent/thread/Records\";\nimport { compareScheduleNames } from \"@effect-agent/thread/ScheduleTransition\";\nimport {\n AcceptedEvent,\n DeliveryChange,\n SubscriptionChange,\n SourcePartition,\n SubscriptionDelivery,\n SubscriptionDeliveryKey,\n SubscriptionError,\n SubscriptionFailpoint,\n SubscriptionKey,\n SubscriptionLimits,\n SubscriptionRetentionPolicy,\n SubscriptionName,\n SubscriptionRecord,\n SubscriptionScanCursors,\n SubscriptionStore,\n subscriptionDeliveryKeyString,\n subscriptionKeyString,\n} from \"@effect-agent/thread/Subscription\";\nimport {\n sameAcceptedEventIdentity,\n applySubscriptionDeliveryChange,\n applySubscriptionChange,\n validateEventRetention,\n subscriptionCanSelect,\n subscriptionDeliveryCanSelect,\n} from \"@effect-agent/thread/SubscriptionTransition\";\nimport { Clock, Effect, Layer, Ref, Result, Schema } from \"effect\";\n\ninterface MemorySubscriptionState {\n readonly sequence: number;\n readonly retentionDeadline: number | null;\n readonly tombstoneCount: number;\n readonly eventKeys: ReadonlyArray<string>;\n readonly deliveryKeys: ReadonlyArray<string>;\n readonly maintenanceEvents: string;\n readonly maintenanceDeliveries: string;\n readonly recoveryCounts: ReadonlyMap<string, number>;\n readonly eventDeliveryCounts: ReadonlyMap<string, number>;\n readonly retentionHorizon: number | null;\n readonly registrations: ReadonlyMap<string, string>;\n readonly events: ReadonlyMap<string, string>;\n readonly deliveries: ReadonlyMap<string, string>;\n readonly registrationIndex: ReadonlyMap<string, RegistrationIndex>;\n readonly candidateIndex: ReadonlyMap<string, ReadonlyArray<string>>;\n readonly ownerRegistrationCounts: ReadonlyMap<string, number>;\n readonly eventIndex: ReadonlyMap<string, EventIndex>;\n readonly deliveryIndex: ReadonlyMap<string, DeliveryIndex>;\n readonly ownerDeliveryCounts: ReadonlyMap<string, number>;\n readonly scanCursors: SubscriptionScanCursors;\n}\n\ninterface RegistrationIndex {\n readonly key: SubscriptionKey;\n readonly ordinal: number;\n readonly state: SubscriptionRecord[\"state\"];\n readonly recoveryKey: string | null;\n readonly recoveryAt: number | null;\n}\ninterface EventIndex {\n readonly routingComplete: boolean;\n readonly nextAttemptAtMillis: number;\n}\ninterface DeliveryIndex {\n readonly key: SubscriptionDeliveryKey;\n readonly state: SubscriptionDelivery[\"state\"];\n readonly parked?: boolean;\n readonly observeSettlement?: boolean;\n readonly nextAttemptAtMillis: number;\n}\n\nconst error = (reason: SubscriptionError[\"reason\"], code: string) =>\n SubscriptionError.make({ reason, code });\n\nconst samePartition = (left: SourcePartition, right: SourcePartition): boolean =>\n left.tenantId === right.tenantId && left.address === right.address;\n\nconst sameSource = (left: AcceptedEvent[\"source\"], right: AcceptedEvent[\"source\"]): boolean =>\n left.name === right.name && left.version === right.version;\n\nconst encode = <A, I>(\n schema: Schema.Codec<A, I>,\n value: A,\n code: string,\n): Result.Result<string, SubscriptionError> =>\n Result.try({\n try: () => Schema.encodeSync(Schema.fromJsonString(schema))(value),\n catch: () => error(\"corrupt\", code),\n });\n\nconst decode = <A, I>(\n schema: Schema.Codec<A, I>,\n value: string,\n code: string,\n): Result.Result<A, SubscriptionError> =>\n Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(schema))(value),\n catch: () => error(\"corrupt\", code),\n });\n\nconst decodeEffect = <A, I>(schema: Schema.Codec<A, I>, value: string, code: string) =>\n Effect.fromResult(decode(schema, value, code));\n\nconst validate = <A, I>(schema: Schema.Codec<A, I>, value: unknown, code: string) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => error(\"validation\", code)));\n\nconst jsonBytes = (value: unknown): number =>\n new TextEncoder().encode(JSON.stringify(value)).byteLength;\n\nconst sameDeliveryIdentity = (left: SubscriptionDelivery, right: SubscriptionDelivery): boolean =>\n subscriptionDeliveryKeyString(left.key) === subscriptionDeliveryKeyString(right.key) &&\n left.deliveryId === right.deliveryId &&\n left.source.name === right.source.name &&\n left.source.version === right.source.version &&\n left.threadId === right.threadId &&\n left.admissionKey === right.admissionKey &&\n left.subscriptionFingerprint === right.subscriptionFingerprint &&\n left.eventDigest === right.eventDigest;\n\nconst candidateIndexKey = (record: SubscriptionRecord): string =>\n JSON.stringify([\n record.configuration.source.name,\n record.configuration.source.version,\n record.configuration.matchingKey,\n ]);\n\nconst eventCandidateIndexKey = (event: AcceptedEvent): string =>\n JSON.stringify([event.source.name, event.source.version, event.matchingKey]);\n\nconst sameEventIdentity = sameAcceptedEventIdentity;\n\nconst deliveryBelongsTo = (\n delivery: SubscriptionDelivery,\n record: SubscriptionRecord,\n event: AcceptedEvent,\n): boolean =>\n subscriptionKeyString(delivery.key.subscription) === subscriptionKeyString(record.key) &&\n delivery.key.eventId === event.eventId &&\n sameSource(delivery.source, event.source);\n\n// Ordered in-memory indexes allow bounded maintenance pages without scanning retained values.\nconst removeKeys = (\n keys: ReadonlyArray<string>,\n removed: ReadonlySet<string>,\n): ReadonlyArray<string> => {\n if (removed.size === 0) return keys;\n const result = [...keys];\n\n for (const key of removed) {\n const index = upperBound(result, key) - 1;\n\n if (result[index] === key) result.splice(index, 1);\n }\n\n return result;\n};\n\nconst upperBound = (keys: ReadonlyArray<string>, after: string): number => {\n let low = 0;\n let high = keys.length;\n\n while (low < high) {\n const middle = Math.floor((low + high) / 2);\n const key = keys[middle];\n\n if (key !== undefined && compareScheduleNames(key, after) <= 0) low = middle + 1;\n else high = middle;\n }\n\n return low;\n};\n\nconst insertKey = (keys: ReadonlyArray<string>, key: string): ReadonlyArray<string> => {\n const at = upperBound(keys, key);\n\n if (at > 0 && keys[at - 1] === key) return keys;\n\n return [...keys.slice(0, at), key, ...keys.slice(at)];\n};\n\nconst recoveryCountsAfter = (\n current: MemorySubscriptionState,\n next: ReadonlyMap<string, RegistrationIndex>,\n keys: ReadonlyArray<string>,\n): ReadonlyMap<string, number> => {\n const counts = new Map(current.recoveryCounts);\n\n for (const key of keys) {\n const before = current.registrationIndex.get(key)?.recoveryKey;\n const after = next.get(key)?.recoveryKey;\n\n if (before === after) continue;\n if (before !== null && before !== undefined) counts.set(before, (counts.get(before) ?? 0) - 1);\n if (after !== null && after !== undefined) counts.set(after, (counts.get(after) ?? 0) + 1);\n }\n\n return counts;\n};\n\nconst makeMemorySubscriptionStore = Effect.fn(\"makeMemorySubscriptionStore\")(function* (\n ownedPartition: SourcePartition,\n) {\n const partition = yield* validate(SourcePartition, ownedPartition, \"partition\");\n\n const state = yield* Ref.make<MemorySubscriptionState>({\n sequence: 0,\n retentionDeadline: null,\n tombstoneCount: 0,\n eventKeys: [],\n deliveryKeys: [],\n maintenanceEvents: \"\",\n maintenanceDeliveries: \"\",\n recoveryCounts: new Map(),\n eventDeliveryCounts: new Map(),\n retentionHorizon: null,\n registrations: new Map(),\n events: new Map(),\n deliveries: new Map(),\n registrationIndex: new Map(),\n candidateIndex: new Map(),\n ownerRegistrationCounts: new Map(),\n eventIndex: new Map(),\n deliveryIndex: new Map(),\n ownerDeliveryCounts: new Map(),\n scanCursors: { events: \"\", deliveries: \"\", recovery: 0 },\n });\n\n const failpoint = yield* SubscriptionFailpoint;\n\n const requirePartition = <A extends { readonly partition: SourcePartition }>(\n value: A,\n code: string,\n ) =>\n samePartition(value.partition, partition)\n ? Effect.succeed(value)\n : Effect.fail(error(\"validation\", code));\n\n const requireKey = (key: SubscriptionKey, code: string) =>\n validate(SubscriptionKey, key, code).pipe(\n Effect.flatMap((decoded) => requirePartition(decoded, code)),\n );\n\n const register: SubscriptionStore[\"Service\"][\"register\"] = Effect.fn(\n \"MemorySubscriptionStore.register\",\n )(function* (input, inputLimits) {\n const record = yield* validate(SubscriptionRecord, input, \"register-record\");\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"register-limits\");\n\n yield* requirePartition(record.key, \"register-partition\");\n yield* failpoint.hit(\"subscription:register:before\");\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<SubscriptionRecord, SubscriptionError>,\n MemorySubscriptionState,\n ] => {\n const key = subscriptionKeyString(record.key);\n const existingText = current.registrations.get(key);\n\n if (existingText !== undefined) {\n const existing = decode(SubscriptionRecord, existingText, \"register-existing\");\n\n if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];\n\n return existing.success.creationFingerprint === record.creationFingerprint\n ? [Result.succeed(existing.success), current]\n : [Result.fail(error(\"conflict\", \"registration-identity\")), current];\n }\n if (jsonBytes(record.configuration.context) > limits.maxContextBytes)\n return [Result.fail(error(\"capacity\", \"context-bytes\")), current];\n if (jsonBytes(record.configuration.parameters) > limits.maxPayloadBytes)\n return [Result.fail(error(\"capacity\", \"parameters-bytes\")), current];\n if (\n record.configuration.expiresAtMillis !== null &&\n record.configuration.expiresAtMillis - record.createdAtMillis > limits.maxLifetimeMillis\n )\n return [Result.fail(error(\"capacity\", \"lifetime\")), current];\n if (current.registrations.size >= limits.maxRegistrations)\n return [Result.fail(error(\"capacity\", \"registrations\")), current];\n const ownerCount = current.ownerRegistrationCounts.get(record.key.ownerId) ?? 0;\n\n if (ownerCount >= limits.maxRegistrationsPerOwner)\n return [Result.fail(error(\"capacity\", \"owner-registrations\")), current];\n const assigned = { ...record, ordinal: current.sequence + 1 };\n const encoded = encode(SubscriptionRecord, assigned, \"register-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const registrations = new Map(current.registrations);\n\n registrations.set(key, encoded.success);\n const registrationIndex = new Map(current.registrationIndex);\n\n registrationIndex.set(key, {\n key: assigned.key,\n ordinal: assigned.ordinal,\n state: assigned.state,\n recoveryKey: assigned.recovery === null ? null : candidateIndexKey(assigned),\n recoveryAt: assigned.recovery?.nextAttemptAtMillis ?? null,\n });\n const candidateIndex = new Map(current.candidateIndex);\n const candidateKey = candidateIndexKey(assigned);\n\n candidateIndex.set(candidateKey, [...(candidateIndex.get(candidateKey) ?? []), key]);\n const ownerRegistrationCounts = new Map(current.ownerRegistrationCounts);\n\n ownerRegistrationCounts.set(assigned.key.ownerId, ownerCount + 1);\n\n return [\n Result.succeed(assigned),\n {\n ...current,\n sequence: assigned.ordinal,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [key]),\n candidateIndex,\n ownerRegistrationCounts,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(\"subscription:register:after\");\n\n return result;\n });\n\n const get: SubscriptionStore[\"Service\"][\"get\"] = Effect.fn(\"MemorySubscriptionStore.get\")(\n function* (input) {\n const key = yield* requireKey(input, \"get-key\");\n const text = (yield* Ref.get(state)).registrations.get(subscriptionKeyString(key));\n\n return text === undefined\n ? null\n : yield* decodeEffect(SubscriptionRecord, text, \"get-record\");\n },\n );\n\n const list: SubscriptionStore[\"Service\"][\"list\"] = Effect.fn(\"MemorySubscriptionStore.list\")(\n function* (ownerId, after, limit) {\n if (!Number.isSafeInteger(after) || after < 0 || !Number.isSafeInteger(limit) || limit <= 0)\n return yield* error(\"validation\", \"list-page\");\n const current = yield* Ref.get(state);\n const records: Array<SubscriptionRecord> = [];\n\n for (const [storageKey, indexed] of current.registrationIndex) {\n if (indexed.key.ownerId !== ownerId || indexed.ordinal <= after) continue;\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return yield* error(\"corrupt\", \"list-index\");\n records.push(yield* decodeEffect(SubscriptionRecord, text, \"list-record\"));\n }\n records.sort((a, b) => a.ordinal - b.ordinal);\n\n return records.slice(0, limit);\n },\n );\n\n const change: SubscriptionStore[\"Service\"][\"change\"] = Effect.fn(\n \"MemorySubscriptionStore.change\",\n )(function* (input, expectedRevision, inputChange) {\n const key = yield* requireKey(input, \"change-key\");\n const change = yield* validate(SubscriptionChange, inputChange, \"change\");\n\n yield* validate(Schema.Int.check(Schema.isGreaterThan(0)), expectedRevision, \"revision\");\n yield* failpoint.hit(\"subscription:change:before\");\n\n const updated = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<SubscriptionRecord, SubscriptionError>,\n MemorySubscriptionState,\n ] => {\n const storageKey = subscriptionKeyString(key);\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"subscription\")), current];\n const existing = decode(SubscriptionRecord, text, \"change-record\");\n\n if (Result.isFailure(existing)) return [existing, current];\n const updated = applySubscriptionChange(existing.success, expectedRevision, change);\n\n if (Result.isFailure(updated)) return [updated, current];\n const revised = { ...updated.success, ordinal: current.sequence + 1 };\n const encoded = encode(SubscriptionRecord, revised, \"change-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const registrations = new Map(current.registrations);\n\n registrations.set(storageKey, encoded.success);\n const registrationIndex = new Map(current.registrationIndex);\n\n registrationIndex.set(storageKey, {\n key,\n ordinal: revised.ordinal,\n state: revised.state,\n recoveryKey: revised.recovery === null ? null : candidateIndexKey(revised),\n recoveryAt: revised.recovery?.nextAttemptAtMillis ?? null,\n });\n const candidateIndex = new Map(current.candidateIndex);\n const oldKey = candidateIndexKey(existing.success);\n const nextKey = candidateIndexKey(revised);\n\n {\n candidateIndex.set(\n oldKey,\n (candidateIndex.get(oldKey) ?? []).filter((key) => key !== storageKey),\n );\n candidateIndex.set(\n nextKey,\n [...(candidateIndex.get(nextKey) ?? []), storageKey].sort(\n (a, b) =>\n (registrationIndex.get(a)?.ordinal ?? 0) -\n (registrationIndex.get(b)?.ordinal ?? 0),\n ),\n );\n }\n\n return [\n Result.succeed(revised),\n {\n ...current,\n sequence: revised.ordinal,\n registrations,\n registrationIndex,\n candidateIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(\"subscription:change:after\");\n\n return updated;\n });\n\n const cancel: SubscriptionStore[\"Service\"][\"cancel\"] = Effect.fn(\n \"MemorySubscriptionStore.cancel\",\n )(function* (input, expectedRevision) {\n const key = yield* requireKey(input, \"cancel-key\");\n\n yield* failpoint.hit(\"subscription:cancel:before\");\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<SubscriptionRecord, SubscriptionError>,\n MemorySubscriptionState,\n ] => {\n const storageKey = subscriptionKeyString(key);\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"subscription\")), current];\n const decoded = decode(SubscriptionRecord, text, \"cancel-record\");\n\n if (Result.isFailure(decoded)) return [decoded, current];\n if (\n expectedRevision !== undefined &&\n expectedRevision !== decoded.success.configurationRevision &&\n !(\n decoded.success.state === \"cancelled\" &&\n expectedRevision + 1 === decoded.success.configurationRevision\n )\n )\n return [\n Result.fail(\n SubscriptionError.make({\n reason: \"conflict\",\n code: \"configuration-revision\",\n currentRevision: decoded.success.configurationRevision,\n currentState: decoded.success.state,\n }),\n ),\n current,\n ];\n if (decoded.success.state === \"cancelled\")\n return [Result.succeed(decoded.success), current];\n\n const cancelled = {\n ...decoded.success,\n configurationRevision: decoded.success.configurationRevision + 1,\n state: \"cancelled\" as const,\n recovery: null,\n };\n\n const encoded = encode(SubscriptionRecord, cancelled, \"cancel-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const registrations = new Map(current.registrations);\n\n registrations.set(storageKey, encoded.success);\n const registrationIndex = new Map(current.registrationIndex);\n const indexed = registrationIndex.get(storageKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"cancel-index\")), current];\n registrationIndex.set(storageKey, {\n ...indexed,\n state: \"cancelled\",\n recoveryAt: null,\n recoveryKey: null,\n });\n\n return [\n Result.succeed(cancelled),\n {\n ...current,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(\"subscription:cancel:after\");\n\n return result;\n });\n\n const accept: SubscriptionStore[\"Service\"][\"accept\"] = Effect.fn(\n \"MemorySubscriptionStore.accept\",\n )(function* (input, inputLimits) {\n const event = yield* validate(AcceptedEvent, input, \"accept-event\");\n const currentTimeMillis = yield* Clock.currentTimeMillis;\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"accept-limits\");\n\n yield* requirePartition(event, \"accept-partition\");\n yield* failpoint.hit(\"subscription:accept:before\");\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [Result.Result<AcceptedEvent, SubscriptionError>, MemorySubscriptionState] => {\n const existingText = current.events.get(event.eventId);\n\n if (existingText !== undefined) {\n const existing = decode(AcceptedEvent, existingText, \"accept-existing\");\n\n if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];\n\n return sameEventIdentity(existing.success, event)\n ? [Result.succeed(existing.success), current]\n : [Result.fail(error(\"conflict\", \"event-identity\")), current];\n }\n if (\n current.retentionHorizon !== null &&\n current.retentionHorizon !== limits.retention?.replayHorizonMillis\n )\n return [Result.fail(error(\"conflict\", \"retention-horizon\")), current];\n const horizon = validateEventRetention(event, limits, currentTimeMillis);\n\n if (Result.isFailure(horizon)) return [Result.fail(horizon.failure), current];\n if (jsonBytes(event.payload) > limits.maxPayloadBytes)\n return [Result.fail(error(\"capacity\", \"payload-bytes\")), current];\n if (current.events.size - current.tombstoneCount >= limits.maxEvents)\n return [Result.fail(error(\"capacity\", \"events\")), current];\n\n const accepted: AcceptedEvent = {\n ...event,\n cutoff: current.sequence + 1,\n cursor: 0,\n routingComplete: false,\n routingFailure: null,\n };\n\n const encoded = encode(AcceptedEvent, accepted, \"accept-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const events = new Map(current.events);\n\n events.set(accepted.eventId, encoded.success);\n const eventIndex = new Map(current.eventIndex);\n\n eventIndex.set(accepted.eventId, {\n routingComplete: false,\n nextAttemptAtMillis: accepted.nextAttemptAtMillis,\n });\n\n return [\n Result.succeed(accepted),\n {\n ...current,\n sequence: accepted.cutoff,\n events,\n eventIndex,\n eventKeys: insertKey(current.eventKeys, accepted.eventId),\n retentionHorizon: limits.retention?.replayHorizonMillis ?? current.retentionHorizon,\n retentionDeadline:\n limits.retention === undefined\n ? current.retentionDeadline\n : accepted.acceptedAtMillis,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(\"subscription:accept:after\");\n\n return result;\n });\n\n const event: SubscriptionStore[\"Service\"][\"event\"] = Effect.fn(\"MemorySubscriptionStore.event\")(\n function* (eventId) {\n const text = (yield* Ref.get(state)).events.get(eventId);\n\n return text === undefined ? null : yield* decodeEffect(AcceptedEvent, text, \"event-record\");\n },\n );\n\n const pendingEvents: SubscriptionStore[\"Service\"][\"pendingEvents\"] = Effect.fn(\n \"MemorySubscriptionStore.pendingEvents\",\n )(function* (nowMillis, after, limit) {\n const events: Array<string> = [];\n\n for (const [eventId, indexed] of (yield* Ref.get(state)).eventIndex) {\n if (\n !indexed.routingComplete &&\n indexed.nextAttemptAtMillis <= nowMillis &&\n compareScheduleNames(eventId, after) > 0\n )\n events.push(eventId);\n }\n events.sort(compareScheduleNames);\n\n return events.slice(0, limit);\n });\n\n const candidates: SubscriptionStore[\"Service\"][\"candidates\"] = Effect.fn(\n \"MemorySubscriptionStore.candidates\",\n )(function* (input, limit) {\n const accepted = yield* validate(AcceptedEvent, input, \"candidates-event\");\n\n yield* requirePartition(accepted, \"candidates-partition\");\n const stored = yield* event(accepted.eventId);\n\n if (stored === null || !sameEventIdentity(stored, accepted))\n return yield* error(stored === null ? \"not-found\" : \"conflict\", \"event\");\n const current = yield* Ref.get(state);\n const records: Array<SubscriptionRecord> = [];\n\n for (const storageKey of current.candidateIndex.get(eventCandidateIndexKey(stored)) ?? []) {\n const indexed = current.registrationIndex.get(storageKey);\n\n if (indexed === undefined) return yield* error(\"corrupt\", \"candidate-index\");\n if (indexed.ordinal <= stored.cursor || indexed.ordinal > stored.cutoff) continue;\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return yield* error(\"corrupt\", \"candidate-record\");\n records.push(yield* decodeEffect(SubscriptionRecord, text, \"candidate-record\"));\n }\n records.sort((a, b) => a.ordinal - b.ordinal);\n\n return records.slice(0, limit);\n });\n\n const select: SubscriptionStore[\"Service\"][\"select\"] = Effect.fn(\n \"MemorySubscriptionStore.select\",\n )(function* (inputEvent, inputDeliveries, cursor, complete, nowMillis, inputLimits) {\n const suppliedEvent = yield* validate(AcceptedEvent, inputEvent, \"select-event\");\n\n const deliveries = yield* validate(\n Schema.Array(SubscriptionDelivery),\n inputDeliveries,\n \"select-deliveries\",\n );\n\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"select-limits\");\n\n yield* requirePartition(suppliedEvent, \"select-partition\");\n yield* failpoint.hit(\"subscription:select:before\");\n const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);\n\n yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {\n const eventText = current.events.get(suppliedEvent.eventId);\n\n if (eventText === undefined) return [Result.fail(error(\"not-found\", \"event\")), current];\n const decodedEvent = decode(AcceptedEvent, eventText, \"select-event-record\");\n\n if (Result.isFailure(decodedEvent)) return [Result.fail(decodedEvent.failure), current];\n const accepted = decodedEvent.success;\n\n if (\n !sameEventIdentity(accepted, suppliedEvent) ||\n suppliedEvent.cursor !== accepted.cursor\n )\n return [Result.fail(error(\"conflict\", \"event-cursor\")), current];\n if (accepted.routingComplete)\n return [\n complete && cursor === accepted.cursor\n ? Result.void\n : Result.fail(error(\"conflict\", \"routing-complete\")),\n current,\n ];\n if (!Number.isSafeInteger(cursor) || cursor < accepted.cursor || cursor > accepted.cutoff)\n return [Result.fail(error(\"validation\", \"cursor\")), current];\n\n const additions: Array<readonly [string, string]> = [];\n const updates: Array<readonly [string, string]> = [];\n const additionIndex: Array<readonly [string, DeliveryIndex, string]> = [];\n const registrationUpdates: Array<readonly [string, RegistrationIndex]> = [];\n const owners = new Map(current.ownerDeliveryCounts);\n\n for (const delivery of deliveries) {\n const recordText = current.registrations.get(\n subscriptionKeyString(delivery.key.subscription),\n );\n\n if (recordText === undefined)\n return [Result.fail(error(\"not-found\", \"subscription\")), current];\n const record = decode(SubscriptionRecord, recordText, \"select-registration\");\n\n if (Result.isFailure(record)) return [Result.fail(record.failure), current];\n if (\n !deliveryBelongsTo(delivery, record.success, accepted) ||\n !subscriptionDeliveryCanSelect(delivery, record.success, accepted) ||\n record.success.ordinal <= accepted.cursor ||\n record.success.ordinal > cursor\n )\n return [Result.fail(error(\"conflict\", \"selection\")), current];\n if (!subscriptionCanSelect(record.success, accepted, effectiveNowMillis, false))\n continue;\n const deliveryKey = subscriptionDeliveryKeyString(delivery.key);\n const existingText = current.deliveries.get(deliveryKey);\n\n if (existingText !== undefined) {\n const existing = decode(SubscriptionDelivery, existingText, \"select-existing\");\n\n if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];\n if (!sameDeliveryIdentity(existing.success, delivery))\n return [Result.fail(error(\"conflict\", \"delivery-identity\")), current];\n continue;\n }\n\n const encodedDelivery = encode(\n SubscriptionDelivery,\n delivery,\n \"select-delivery-encode\",\n );\n\n if (Result.isFailure(encodedDelivery))\n return [Result.fail(encodedDelivery.failure), current];\n additions.push([deliveryKey, encodedDelivery.success]);\n additionIndex.push([\n deliveryKey,\n {\n key: delivery.key,\n state: delivery.state,\n nextAttemptAtMillis: delivery.retry.nextAttemptAtMillis,\n },\n record.success.key.ownerId,\n ]);\n const ownerId = record.success.key.ownerId;\n\n owners.set(ownerId, (owners.get(ownerId) ?? 0) + 1);\n if ((owners.get(ownerId) ?? 0) > limits.maxDeliveriesPerOwner)\n return [Result.fail(error(\"capacity\", \"owner-deliveries\")), current];\n if (record.success.configuration.mode === \"once\") {\n const consumed = { ...record.success, state: \"consumed\" as const, recovery: null };\n\n const encodedRecord = encode(\n SubscriptionRecord,\n consumed,\n \"select-registration-encode\",\n );\n\n if (Result.isFailure(encodedRecord))\n return [Result.fail(encodedRecord.failure), current];\n const consumedKey = subscriptionKeyString(consumed.key);\n\n updates.push([consumedKey, encodedRecord.success]);\n const indexed = current.registrationIndex.get(consumedKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"selection-index\")), current];\n registrationUpdates.push([\n consumedKey,\n { ...indexed, state: \"consumed\", recoveryAt: null, recoveryKey: null },\n ]);\n }\n }\n if (current.deliveries.size + additions.length > limits.maxDeliveries)\n return [Result.fail(error(\"capacity\", \"deliveries\")), current];\n const registrations = new Map(current.registrations);\n\n for (const [key, value] of updates) registrations.set(key, value);\n const nextDeliveries = new Map(current.deliveries);\n\n for (const [key, value] of additions) nextDeliveries.set(key, value);\n const deliveryIndex = new Map(current.deliveryIndex);\n\n for (const [key, value] of additionIndex) deliveryIndex.set(key, value);\n const registrationIndex = new Map(current.registrationIndex);\n\n for (const [key, value] of registrationUpdates) registrationIndex.set(key, value);\n\n const eventDeliveryCounts = new Map(current.eventDeliveryCounts);\n\n eventDeliveryCounts.set(\n accepted.eventId,\n (eventDeliveryCounts.get(accepted.eventId) ?? 0) + additions.length,\n );\n\n const nextEvent: AcceptedEvent = {\n ...accepted,\n cursor,\n routingComplete: complete,\n routingFailure: null,\n };\n\n const encodedEvent = encode(AcceptedEvent, nextEvent, \"select-event-encode\");\n\n if (Result.isFailure(encodedEvent)) return [Result.fail(encodedEvent.failure), current];\n const events = new Map(current.events);\n\n events.set(nextEvent.eventId, encodedEvent.success);\n const eventIndex = new Map(current.eventIndex);\n\n eventIndex.set(nextEvent.eventId, {\n routingComplete: nextEvent.routingComplete,\n nextAttemptAtMillis: nextEvent.nextAttemptAtMillis,\n });\n\n return [\n Result.void,\n {\n ...current,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(\n current,\n registrationIndex,\n registrationUpdates.map(([key]) => key),\n ),\n eventDeliveryCounts,\n events,\n eventIndex,\n deliveries: nextDeliveries,\n deliveryKeys: additions.reduce(\n (keys, [key]) => insertKey(keys, key),\n current.deliveryKeys,\n ),\n deliveryIndex,\n ownerDeliveryCounts: owners,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n yield* failpoint.hit(\"subscription:select:after\");\n });\n\n const catchUp: SubscriptionStore[\"Service\"][\"catchUp\"] = Effect.fn(\n \"MemorySubscriptionStore.catchUp\",\n )(function* (inputEvent, inputDelivery, nowMillis, inputLimits) {\n const suppliedEvent = yield* validate(AcceptedEvent, inputEvent, \"catch-up-event\");\n const delivery = yield* validate(SubscriptionDelivery, inputDelivery, \"catch-up-delivery\");\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"catch-up-limits\");\n\n yield* requirePartition(suppliedEvent, \"catch-up-partition\");\n yield* failpoint.hit(\"subscription:catch-up:before\");\n const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);\n\n yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {\n const eventText = current.events.get(suppliedEvent.eventId);\n\n const recordText = current.registrations.get(\n subscriptionKeyString(delivery.key.subscription),\n );\n\n if (eventText === undefined || recordText === undefined)\n return [\n Result.fail(error(\"not-found\", eventText === undefined ? \"event\" : \"subscription\")),\n current,\n ];\n const accepted = decode(AcceptedEvent, eventText, \"catch-up-event-record\");\n\n if (Result.isFailure(accepted)) return [Result.fail(accepted.failure), current];\n const record = decode(SubscriptionRecord, recordText, \"catch-up-registration\");\n\n if (Result.isFailure(record)) return [Result.fail(record.failure), current];\n if (\n !sameEventIdentity(accepted.success, suppliedEvent) ||\n !deliveryBelongsTo(delivery, record.success, accepted.success) ||\n !subscriptionDeliveryCanSelect(delivery, record.success, accepted.success) ||\n record.success.configuration.mode !== \"once\"\n )\n return [Result.fail(error(\"conflict\", \"catch-up-identity\")), current];\n const key = subscriptionDeliveryKeyString(delivery.key);\n const existingText = current.deliveries.get(key);\n\n if (existingText !== undefined) {\n const existing = decode(SubscriptionDelivery, existingText, \"catch-up-existing\");\n\n if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];\n\n return sameDeliveryIdentity(existing.success, delivery)\n ? [Result.void, current]\n : [Result.fail(error(\"conflict\", \"delivery-identity\")), current];\n }\n if (!subscriptionCanSelect(record.success, accepted.success, effectiveNowMillis, true))\n return [Result.fail(error(\"conflict\", \"catch-up-eligibility\")), current];\n if (current.deliveries.size >= limits.maxDeliveries)\n return [Result.fail(error(\"capacity\", \"deliveries\")), current];\n const ownerCount = current.ownerDeliveryCounts.get(record.success.key.ownerId) ?? 0;\n\n if (ownerCount >= limits.maxDeliveriesPerOwner)\n return [Result.fail(error(\"capacity\", \"owner-deliveries\")), current];\n\n const encodedDelivery = encode(\n SubscriptionDelivery,\n delivery,\n \"catch-up-delivery-encode\",\n );\n\n if (Result.isFailure(encodedDelivery))\n return [Result.fail(encodedDelivery.failure), current];\n const consumed = { ...record.success, state: \"consumed\" as const, recovery: null };\n\n const encodedRecord = encode(\n SubscriptionRecord,\n consumed,\n \"catch-up-registration-encode\",\n );\n\n if (Result.isFailure(encodedRecord)) return [Result.fail(encodedRecord.failure), current];\n const deliveries = new Map(current.deliveries);\n\n deliveries.set(key, encodedDelivery.success);\n const registrations = new Map(current.registrations);\n const consumedKey = subscriptionKeyString(consumed.key);\n\n registrations.set(consumedKey, encodedRecord.success);\n const registrationIndex = new Map(current.registrationIndex);\n const indexed = registrationIndex.get(consumedKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"catch-up-index\")), current];\n registrationIndex.set(consumedKey, {\n ...indexed,\n state: \"consumed\",\n recoveryAt: null,\n recoveryKey: null,\n });\n const deliveryIndex = new Map(current.deliveryIndex);\n\n deliveryIndex.set(key, {\n key: delivery.key,\n state: delivery.state,\n nextAttemptAtMillis: delivery.retry.nextAttemptAtMillis,\n });\n const ownerDeliveryCounts = new Map(current.ownerDeliveryCounts);\n const eventDeliveryCounts = new Map(current.eventDeliveryCounts);\n\n eventDeliveryCounts.set(\n accepted.success.eventId,\n (eventDeliveryCounts.get(accepted.success.eventId) ?? 0) + 1,\n );\n\n ownerDeliveryCounts.set(consumed.key.ownerId, ownerCount + 1);\n\n return [\n Result.void,\n {\n ...current,\n deliveries,\n deliveryIndex,\n deliveryKeys: insertKey(current.deliveryKeys, key),\n ownerDeliveryCounts,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [consumedKey]),\n eventDeliveryCounts,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n yield* failpoint.hit(\"subscription:catch-up:after\");\n });\n\n const deferEvent: SubscriptionStore[\"Service\"][\"deferEvent\"] = Effect.fn(\n \"MemorySubscriptionStore.deferEvent\",\n )(function* (eventId, nextAttemptAtMillis, code) {\n const routingFailure =\n code === undefined\n ? \"routing-failed\"\n : yield* validate(SubscriptionName, code, \"routing-failure\");\n\n yield* failpoint.hit(\"subscription:defer-event:before\");\n yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {\n const text = current.events.get(eventId);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"event\")), current];\n const accepted = decode(AcceptedEvent, text, \"defer-event-record\");\n\n if (Result.isFailure(accepted)) return [Result.fail(accepted.failure), current];\n const updated = { ...accepted.success, nextAttemptAtMillis, routingFailure };\n const encoded = encode(AcceptedEvent, updated, \"defer-event-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const events = new Map(current.events);\n\n events.set(eventId, encoded.success);\n const eventIndex = new Map(current.eventIndex);\n const indexed = eventIndex.get(eventId);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"defer-event-index\")), current];\n eventIndex.set(eventId, { ...indexed, nextAttemptAtMillis });\n\n return [Result.void, { ...current, events, eventIndex }];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n yield* failpoint.hit(\"subscription:defer-event:after\");\n });\n\n const delivery: SubscriptionStore[\"Service\"][\"delivery\"] = Effect.fn(\n \"MemorySubscriptionStore.delivery\",\n )(function* (input) {\n const key = yield* validate(SubscriptionDeliveryKey, input, \"delivery-key\");\n\n yield* requirePartition(key.subscription, \"delivery-partition\");\n const text = (yield* Ref.get(state)).deliveries.get(subscriptionDeliveryKeyString(key));\n\n return text === undefined\n ? null\n : yield* decodeEffect(SubscriptionDelivery, text, \"delivery-record\");\n });\n\n const pendingDeliveries: SubscriptionStore[\"Service\"][\"pendingDeliveries\"] = Effect.fn(\n \"MemorySubscriptionStore.pendingDeliveries\",\n )(function* (nowMillis, after, limit) {\n const items: Array<SubscriptionDeliveryKey> = [];\n\n for (const [storageKey, item] of (yield* Ref.get(state)).deliveryIndex) {\n if (\n ((item.state !== \"delivered\" && item.state !== \"refused\" && item.parked !== true) ||\n (item.state === \"delivered\" && item.observeSettlement === true)) &&\n item.nextAttemptAtMillis <= nowMillis &&\n compareScheduleNames(storageKey, after) > 0\n )\n items.push(item.key);\n }\n items.sort((a, b) =>\n compareScheduleNames(subscriptionDeliveryKeyString(a), subscriptionDeliveryKeyString(b)),\n );\n\n return items.slice(0, limit);\n });\n\n const listDeliveries: SubscriptionStore[\"Service\"][\"listDeliveries\"] = Effect.fn(\n \"MemorySubscriptionStore.listDeliveries\",\n )(function* (input, after, limit) {\n const key = yield* requireKey(input, \"list-deliveries-key\");\n const items: Array<SubscriptionDelivery> = [];\n\n for (const text of (yield* Ref.get(state)).deliveries.values()) {\n const item = yield* decodeEffect(SubscriptionDelivery, text, \"list-delivery\");\n const itemKey = subscriptionDeliveryKeyString(item.key);\n\n if (\n subscriptionKeyString(item.key.subscription) === subscriptionKeyString(key) &&\n compareScheduleNames(itemKey, after) > 0\n )\n items.push(item);\n }\n items.sort((a, b) =>\n compareScheduleNames(\n subscriptionDeliveryKeyString(a.key),\n subscriptionDeliveryKeyString(b.key),\n ),\n );\n\n return items.slice(0, limit);\n });\n\n const changeDelivery: SubscriptionStore[\"Service\"][\"changeDelivery\"] = Effect.fn(\n \"MemorySubscriptionStore.changeDelivery\",\n )(function* (inputKey, inputDeliveryId, inputChange) {\n const key = yield* validate(SubscriptionDeliveryKey, inputKey, \"change-delivery-key\");\n const deliveryId = yield* validate(Digest, inputDeliveryId, \"change-delivery-id\");\n const change = yield* validate(DeliveryChange, inputChange, \"change-delivery-change\");\n\n yield* requirePartition(key.subscription, \"change-delivery-partition\");\n yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:before`);\n\n const effectiveChange =\n change._tag === \"Prepare\"\n ? { ...change, nowMillis: Math.max(change.nowMillis, yield* Clock.currentTimeMillis) }\n : change;\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<SubscriptionDelivery, SubscriptionError>,\n MemorySubscriptionState,\n ] => {\n const storageKey = subscriptionDeliveryKeyString(key);\n const text = current.deliveries.get(storageKey);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"delivery\")), current];\n const decoded = decode(SubscriptionDelivery, text, \"change-delivery-record\");\n\n if (Result.isFailure(decoded)) return [decoded, current];\n\n const registrationText = current.registrations.get(\n subscriptionKeyString(key.subscription),\n );\n\n if (registrationText === undefined)\n return [Result.fail(error(\"corrupt\", \"delivery-registration\")), current];\n\n const registration = decode(\n SubscriptionRecord,\n registrationText,\n \"delivery-registration\",\n );\n\n if (Result.isFailure(registration)) return [Result.fail(registration.failure), current];\n\n const transition = applySubscriptionDeliveryChange(\n decoded.success,\n registration.success,\n deliveryId,\n effectiveChange,\n );\n\n if (Result.isFailure(transition)) return [Result.fail(transition.failure), current];\n if (transition.success === decoded.success)\n return [Result.succeed(decoded.success), current];\n const updated = transition.success;\n const encoded = encode(SubscriptionDelivery, updated, \"change-delivery-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const deliveries = new Map(current.deliveries);\n\n deliveries.set(storageKey, encoded.success);\n const deliveryIndex = new Map(current.deliveryIndex);\n const indexed = deliveryIndex.get(storageKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"delivery-index\")), current];\n deliveryIndex.set(storageKey, {\n ...indexed,\n state: updated.state,\n parked: updated.retry.parked ?? false,\n observeSettlement: updated.observeSettlement ?? false,\n nextAttemptAtMillis: updated.retry.nextAttemptAtMillis,\n });\n\n return [Result.succeed(updated), { ...current, deliveries, deliveryIndex }];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:after`);\n\n return result;\n });\n\n const recovering: SubscriptionStore[\"Service\"][\"recovering\"] = Effect.fn(\n \"MemorySubscriptionStore.recovering\",\n )(function* (nowMillis, after, limit) {\n const records: Array<{ readonly key: SubscriptionKey; readonly ordinal: number }> = [];\n\n for (const item of (yield* Ref.get(state)).registrationIndex.values()) {\n if (\n item.ordinal > after &&\n item.state === \"active\" &&\n item.recoveryAt !== null &&\n item.recoveryAt <= nowMillis\n )\n records.push({ key: item.key, ordinal: item.ordinal });\n }\n records.sort((a, b) => a.ordinal - b.ordinal);\n\n return records.slice(0, limit);\n });\n\n const deferRecovery: SubscriptionStore[\"Service\"][\"deferRecovery\"] = Effect.fn(\n \"MemorySubscriptionStore.deferRecovery\",\n )(function* (input, expectedRevision, recovery) {\n const key = yield* requireKey(input, \"defer-recovery-key\");\n\n yield* failpoint.hit(\"subscription:defer-recovery:before\");\n yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {\n const storageKey = subscriptionKeyString(key);\n const text = current.registrations.get(storageKey);\n\n if (text === undefined) return [Result.fail(error(\"not-found\", \"subscription\")), current];\n const record = decode(SubscriptionRecord, text, \"defer-recovery-record\");\n\n if (Result.isFailure(record)) return [Result.fail(record.failure), current];\n\n if (record.success.configurationRevision !== expectedRevision)\n return [Result.void, current];\n\n const updated = {\n ...record.success,\n recovery:\n record.success.state === \"active\" || record.success.state === \"paused\"\n ? recovery\n : null,\n };\n\n const encoded = encode(SubscriptionRecord, updated, \"defer-recovery-encode\");\n\n if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];\n const registrations = new Map(current.registrations);\n\n registrations.set(storageKey, encoded.success);\n const registrationIndex = new Map(current.registrationIndex);\n const indexed = registrationIndex.get(storageKey);\n\n if (indexed === undefined)\n return [Result.fail(error(\"corrupt\", \"recovery-index\")), current];\n registrationIndex.set(storageKey, {\n ...indexed,\n recoveryKey: updated.recovery === null ? null : candidateIndexKey(updated),\n recoveryAt: updated.recovery?.nextAttemptAtMillis ?? null,\n });\n\n return [\n Result.void,\n {\n ...current,\n registrations,\n registrationIndex,\n recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n yield* failpoint.hit(\"subscription:defer-recovery:after\");\n });\n\n const readScanCursors: SubscriptionStore[\"Service\"][\"readScanCursors\"] = Ref.get(state).pipe(\n Effect.map((current) => current.scanCursors),\n );\n\n const advanceScanCursors: SubscriptionStore[\"Service\"][\"advanceScanCursors\"] = Effect.fn(\n \"MemorySubscriptionStore.advanceScanCursors\",\n )(function* (input) {\n const cursors = yield* validate(SubscriptionScanCursors, input, \"scan-cursors\");\n\n yield* failpoint.hit(\"subscription:advance-scan-cursors:before\");\n yield* Effect.uninterruptible(\n Ref.update(state, (current) => ({ ...current, scanCursors: cursors })),\n );\n yield* failpoint.hit(\"subscription:advance-scan-cursors:after\");\n });\n\n const nextDeadline = Effect.gen(function* () {\n let deadline: number | null = null;\n const current = yield* Ref.get(state);\n\n if (\n current.scanCursors.events !== \"\" ||\n current.scanCursors.deliveries !== \"\" ||\n current.scanCursors.recovery !== 0\n )\n return 0;\n\n const consider = (value: number) => {\n if (deadline === null || value < deadline) deadline = value;\n };\n\n if (current.retentionDeadline !== null) consider(current.retentionDeadline);\n for (const accepted of current.eventIndex.values())\n if (!accepted.routingComplete) consider(accepted.nextAttemptAtMillis);\n for (const item of current.deliveryIndex.values())\n if (\n (item.state !== \"delivered\" && item.state !== \"refused\" && item.parked !== true) ||\n (item.state === \"delivered\" && item.observeSettlement === true)\n )\n consider(item.nextAttemptAtMillis);\n for (const record of current.registrationIndex.values())\n if (record.state === \"active\" && record.recoveryAt !== null) consider(record.recoveryAt);\n\n return deadline;\n }).pipe(Effect.withSpan(\"MemorySubscriptionStore.nextDeadline\"));\n\n const compact: SubscriptionStore[\"Service\"][\"compact\"] = Effect.fn(\n \"MemorySubscriptionStore.compact\",\n )(function* (nowMillis, inputPolicy, requestedLimit) {\n nowMillis = Math.min(nowMillis, yield* Clock.currentTimeMillis);\n const policy = yield* validate(SubscriptionRetentionPolicy, inputPolicy, \"retention-policy\");\n\n const limit = yield* validate(\n Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 })),\n requestedLimit,\n \"maintenance-limit\",\n );\n\n yield* failpoint.hit(\"subscription:compact:before\");\n let corruptCandidates = 0;\n\n const result = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (current): readonly [Result.Result<number, SubscriptionError>, MemorySubscriptionState] => {\n if (\n current.retentionHorizon !== null &&\n current.retentionHorizon !== policy.replayHorizonMillis\n )\n return [Result.fail(error(\"conflict\", \"retention-horizon\")), current];\n const events = new Map(current.events);\n const eventIndex = new Map(current.eventIndex);\n const deliveries = new Map(current.deliveries);\n const deliveryIndex = new Map(current.deliveryIndex);\n const eventDeliveryCounts = new Map(current.eventDeliveryCounts);\n const ownerDeliveryCounts = new Map(current.ownerDeliveryCounts);\n\n // Page indexes before decoding. Each pass reads at most 2 * limit event values and\n // limit delivery values; relationship checks use maintained reference counts.\n const deliveryPage = current.deliveryKeys.slice(\n upperBound(current.deliveryKeys, current.maintenanceDeliveries),\n upperBound(current.deliveryKeys, current.maintenanceDeliveries) + limit,\n );\n\n const eventPage = current.eventKeys.slice(\n upperBound(current.eventKeys, current.maintenanceEvents),\n upperBound(current.eventKeys, current.maintenanceEvents) + limit,\n );\n\n const cutoff = nowMillis - policy.completedRetentionMillis;\n let removed = 0;\n const removedEvents = new Set<string>();\n const removedDeliveries = new Set<string>();\n\n for (const key of deliveryPage) {\n const text = deliveries.get(key);\n\n if (text === undefined) continue;\n const decoded = decode(SubscriptionDelivery, text, \"compact-delivery\");\n\n if (Result.isFailure(decoded)) {\n corruptCandidates++;\n continue;\n }\n const delivery = decoded.success;\n\n if (\n subscriptionDeliveryKeyString(delivery.key) !== key ||\n !samePartition(delivery.key.subscription.partition, partition)\n ) {\n corruptCandidates++;\n continue;\n }\n\n if (\n delivery.state !== \"refused\" &&\n (delivery.state !== \"delivered\" || delivery.settledAtMillis === undefined)\n )\n continue;\n if (\n (delivery.settledAtMillis ??\n delivery.completedAtMillis ??\n delivery.selectedAtMillis) > cutoff\n )\n continue;\n const eventText = events.get(delivery.key.eventId);\n\n if (eventText === undefined) continue;\n const accepted = decode(AcceptedEvent, eventText, \"compact-delivery-event\");\n\n if (Result.isFailure(accepted)) {\n corruptCandidates++;\n continue;\n }\n const event = accepted.success;\n\n if (\n event.eventId !== delivery.key.eventId ||\n !samePartition(event.partition, partition)\n ) {\n corruptCandidates++;\n continue;\n }\n\n if (\n !event.routingComplete ||\n event.occurredAtMillis === undefined ||\n event.acceptedAtMillis > cutoff ||\n (current.recoveryCounts.get(eventCandidateIndexKey(event)) ?? 0) > 0\n )\n continue;\n deliveries.delete(key);\n removedDeliveries.add(key);\n deliveryIndex.delete(key);\n eventDeliveryCounts.set(\n event.eventId,\n (eventDeliveryCounts.get(event.eventId) ?? 1) - 1,\n );\n const owner = delivery.key.subscription.ownerId;\n\n ownerDeliveryCounts.set(owner, (ownerDeliveryCounts.get(owner) ?? 1) - 1);\n }\n let tombstones = current.tombstoneCount;\n\n for (const key of eventPage) {\n const text = events.get(key);\n\n if (text === undefined) continue;\n const decoded = decode(AcceptedEvent, text, \"compact-event\");\n\n if (Result.isFailure(decoded)) {\n corruptCandidates++;\n continue;\n }\n const event = decoded.success;\n\n if (event.eventId !== key || !samePartition(event.partition, partition)) {\n corruptCandidates++;\n continue;\n }\n\n if (!event.routingComplete || event.occurredAtMillis === undefined) continue;\n const expired = event.occurredAtMillis <= nowMillis - policy.replayHorizonMillis;\n\n if (event.tombstone === true && !expired) continue;\n if (\n event.acceptedAtMillis > cutoff ||\n (eventDeliveryCounts.get(key) ?? 0) > 0 ||\n (current.recoveryCounts.get(eventCandidateIndexKey(event)) ?? 0) > 0\n )\n continue;\n if (expired) {\n events.delete(key);\n removedEvents.add(key);\n eventIndex.delete(key);\n eventDeliveryCounts.delete(key);\n if (event.tombstone === true) tombstones--;\n } else {\n if (tombstones >= policy.maxTombstones) continue;\n\n const encoded = encode(\n AcceptedEvent,\n { ...event, payload: null, tombstone: true },\n \"compact-tombstone\",\n );\n\n if (Result.isFailure(encoded)) continue;\n events.set(key, encoded.success);\n tombstones++;\n }\n removed++;\n }\n\n return [\n Result.succeed(removed),\n {\n ...current,\n events,\n eventIndex,\n deliveries,\n deliveryIndex,\n eventDeliveryCounts,\n ownerDeliveryCounts,\n eventKeys: removeKeys(current.eventKeys, removedEvents),\n deliveryKeys: removeKeys(current.deliveryKeys, removedDeliveries),\n tombstoneCount: tombstones,\n maintenanceEvents: eventPage.length < limit ? \"\" : (eventPage.at(-1) ?? \"\"),\n maintenanceDeliveries: deliveryPage.length < limit ? \"\" : (deliveryPage.at(-1) ?? \"\"),\n retentionHorizon: policy.replayHorizonMillis,\n retentionDeadline: events.size === 0 ? null : nowMillis + 60_000,\n },\n ];\n },\n ),\n ).pipe(Effect.flatMap(Effect.fromResult));\n\n if (corruptCandidates > 0)\n yield* Effect.logWarning(\"Subscription retention preserved corrupt candidates\", {\n count: corruptCandidates,\n });\n yield* failpoint.hit(\"subscription:compact:after\");\n\n return result;\n });\n\n return SubscriptionStore.of({\n partition,\n compact,\n register,\n get,\n list,\n cancel,\n change,\n accept,\n event,\n pendingEvents,\n candidates,\n select,\n catchUp,\n deferEvent,\n delivery,\n pendingDeliveries,\n listDeliveries,\n changeDelivery,\n recovering,\n deferRecovery,\n readScanCursors,\n advanceScanCursors,\n nextDeadline,\n });\n});\n\nexport const memorySubscriptionStoreLayer = (\n partition: SourcePartition,\n): Layer.Layer<SubscriptionStore, SubscriptionError> =>\n Layer.effect(SubscriptionStore, makeMemorySubscriptionStore(partition));\n"],"mappings":";;;;;;;;AAyEA,MAAM,SAAS,QAAqC,SAClD,kBAAkB,KAAK;CAAE;CAAQ;AAAK,CAAC;AAEzC,MAAM,iBAAiB,MAAuB,UAC5C,KAAK,aAAa,MAAM,YAAY,KAAK,YAAY,MAAM;AAE7D,MAAM,cAAc,MAA+B,UACjD,KAAK,SAAS,MAAM,QAAQ,KAAK,YAAY,MAAM;AAErD,MAAM,UACJ,QACA,OACA,SAEA,OAAO,IAAI;CACT,WAAW,OAAO,WAAW,OAAO,eAAe,MAAM,CAAC,CAAC,CAAC,KAAK;CACjE,aAAa,MAAM,WAAW,IAAI;AACpC,CAAC;AAEH,MAAM,UACJ,QACA,OACA,SAEA,OAAO,IAAI;CACT,WAAW,OAAO,WAAW,OAAO,eAAe,MA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O;IACzB,mBAAmB,OAAO,SAAS,IAAI,OAAO,YAAY;GAC5D,CACF;EACF,CACF,CACF,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,UAAU,CAAC;EAExC,IAAI,oBAAoB,GACtB,OAAO,OAAO,WAAW,uDAAuD,EAC9E,OAAO,kBACT,CAAC;EACH,OAAO,UAAU,IAAI,4BAA4B;EAEjD,OAAO;CACT,CAAC;CAED,OAAO,kBAAkB,GAAG;EAC1B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH,CAAC;AAED,MAAa,gCACX,cAEA,MAAM,OAAO,mBAAmB,4BAA4B,SAAS,CAAC"}
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@effect-agent/storage-memory","version":"0.1.0-beta.52","dependencies":{"@effect-agent/core":"0.1.0-beta.52","@effect-agent/thread":"0.1.0-beta.52"},"devDependencies":{"@effect-agent/engine":"0.1.0-beta.52","@effect/platform-node":"4.0.0-rc.112","@effect/vitest":"4.0.0-rc.112","effect":"4.0.0-rc.112","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.112"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./MemoryScheduleStore":{"types":"./dist/MemoryScheduleStore.d.mts","default":"./dist/MemoryScheduleStore.mjs"},"./MemorySemanticIndex":{"types":"./dist/MemorySemanticIndex.d.mts","default":"./dist/MemorySemanticIndex.mjs"},"./MemorySubmissionLedger":{"types":"./dist/MemorySubmissionLedger.d.mts","default":"./dist/MemorySubmissionLedger.mjs"},"./MemorySubscriptionStore":{"types":"./dist/MemorySubscriptionStore.d.mts","default":"./dist/MemorySubscriptionStore.mjs"},"./MemoryThreadStore":{"types":"./dist/MemoryThreadStore.d.mts","default":"./dist/MemoryThreadStore.mjs"}},"description":"In-memory Thread store and submission ledger reference adapters for Effect Agent tests and conformance suites.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/storage-memory"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
1
+ {"name":"@effect-agent/storage-memory","version":"0.1.0-beta.54","dependencies":{"@effect-agent/core":"0.1.0-beta.54","@effect-agent/thread":"0.1.0-beta.54"},"devDependencies":{"@effect-agent/engine":"0.1.0-beta.54","@effect/platform-node":"4.0.0-rc.112","@effect/vitest":"4.0.0-rc.112","effect":"4.0.0-rc.112","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.112"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./MemoryScheduleStore":{"types":"./dist/MemoryScheduleStore.d.mts","default":"./dist/MemoryScheduleStore.mjs"},"./MemorySemanticIndex":{"types":"./dist/MemorySemanticIndex.d.mts","default":"./dist/MemorySemanticIndex.mjs"},"./MemorySubmissionLedger":{"types":"./dist/MemorySubmissionLedger.d.mts","default":"./dist/MemorySubmissionLedger.mjs"},"./MemorySubscriptionStore":{"types":"./dist/MemorySubscriptionStore.d.mts","default":"./dist/MemorySubscriptionStore.mjs"},"./MemoryThreadStore":{"types":"./dist/MemoryThreadStore.d.mts","default":"./dist/MemoryThreadStore.mjs"}},"description":"In-memory Thread store and submission ledger reference adapters for Effect Agent tests and conformance suites.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/storage-memory"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
@@ -271,7 +271,7 @@ const admissionKey = (
271
271
  threadId: ThreadId,
272
272
  principal: Principal,
273
273
  idempotencyKey: IdempotencyKey,
274
- ): string => `${threadId}\u001f${principal}\u001f${idempotencyKey}`;
274
+ ): string => JSON.stringify([threadId, principal, idempotencyKey]);
275
275
 
276
276
  const toSnapshot = (row: SubmissionRow): SubmissionSnapshot =>
277
277
  SubmissionSnapshot.make({
@@ -867,6 +867,25 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
867
867
  return [failure(ownershipLost(current, stored)), current];
868
868
  }
869
869
 
870
+ if (stored.inputApplied !== undefined) {
871
+ if (
872
+ stored.inputApplied.recordId === request.recordId &&
873
+ stored.inputApplied.sequence === request.sequence
874
+ ) {
875
+ return [success(undefined), current];
876
+ }
877
+
878
+ return [
879
+ failure(
880
+ ledgerError(
881
+ "markInputApplied",
882
+ `A different canonical input marker is already recorded for Submission ${request.submissionId}`,
883
+ ),
884
+ ),
885
+ current,
886
+ ];
887
+ }
888
+
870
889
  const marker = InputAppliedMarker.make({
871
890
  recordId: request.recordId,
872
891
  sequence: request.sequence,
@@ -20,6 +20,7 @@ import {
20
20
  subscriptionKeyString,
21
21
  } from "@effect-agent/thread/Subscription";
22
22
  import {
23
+ sameAcceptedEventIdentity,
23
24
  applySubscriptionDeliveryChange,
24
25
  applySubscriptionChange,
25
26
  validateEventRetention,
@@ -128,13 +129,7 @@ const candidateIndexKey = (record: SubscriptionRecord): string =>
128
129
  const eventCandidateIndexKey = (event: AcceptedEvent): string =>
129
130
  JSON.stringify([event.source.name, event.source.version, event.matchingKey]);
130
131
 
131
- const sameEventIdentity = (left: AcceptedEvent, right: AcceptedEvent): boolean =>
132
- samePartition(left.partition, right.partition) &&
133
- left.eventId === right.eventId &&
134
- sameSource(left.source, right.source) &&
135
- left.matchingKey === right.matchingKey &&
136
- left.payloadDigest === right.payloadDigest &&
137
- left.occurredAtMillis === right.occurredAtMillis;
132
+ const sameEventIdentity = sameAcceptedEventIdentity;
138
133
 
139
134
  const deliveryBelongsTo = (
140
135
  delivery: SubscriptionDelivery,