@smthrs/journal 1.0.0-rc.8 → 1.0.0-rc.9

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.
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * The journal owns the consensus rules — single writer per run, fenced and
5
5
  * unfenced appends, commit-time admission, the generation fence, and steal
6
- * only on staleness plus liveness evidence — and this service is how a deployment chooses *how* those rules are
6
+ * only on staleness plus liveness evidence, or on a same-host probe that
7
+ * proves the owner's process gone — and this service is how a deployment chooses *how* those rules are
7
8
  * arbitrated: where the lease lives, how liveness is probed, and how the
8
9
  * fence is checked at commit time. `Consensus` lives here beside `OwnerId`
9
10
  * for the same reason `OwnerId` does: the journal is what it fences.
@@ -105,7 +106,8 @@ export declare const heartbeatWriteTolerance: Duration.Duration;
105
106
  * strategy can check for itself, and `steal` checks it: the takeover refuses
106
107
  * any lease whose heartbeat is still inside the window. It is therefore
107
108
  * accepted from a claimant on any host, while the other two stay bound to the
108
- * host relation that makes them meaningful. The observation must carry the
109
+ * host relation that makes them meaningful. `same-host-pid-dead` alone also
110
+ * admits a steal inside the window; see {@link provesDeath}. The observation must carry the
109
111
  * exact instant supplied to the consuming operation: `checkedAtMs` must equal
110
112
  * that operation's `nowMs`. A caller that probes at T and calls at T+1 is
111
113
  * refused and must build fresh evidence.
@@ -149,6 +151,32 @@ export declare const sameOwner: (left: OwnerId, right: OwnerId) => boolean;
149
151
  * @category predicates
150
152
  */
151
153
  export declare const matchesEvidence: (expectedOwner: OwnerId, observer: OwnerId, nowMs: number, evidence: LivenessEvidence) => boolean;
154
+ /**
155
+ * Whether evidence proves the owner gone, so a steal need not wait for its
156
+ * lease to go stale.
157
+ *
158
+ * The lease stands in for a question a peer cannot ask directly: is the owner
159
+ * still running? A `same-host-pid-dead` probe asks it. The claimant read its
160
+ * own host's process table and found no process behind the owner's pid, and a
161
+ * process that does not exist renews no lease and writes nothing, so waiting
162
+ * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with
163
+ * `SIGKILL` is therefore reclaimed by the next process on the same host at
164
+ * once.
165
+ *
166
+ * The evidence must still pass {@link matchesEvidence}, which binds the kind
167
+ * to the same host. One more case is excluded here: an owner recorded with the
168
+ * claimant's own pid names the claimant's process, which is running, so a
169
+ * probe of that pid cannot report it gone. Such evidence keeps the staleness
170
+ * cutoff.
171
+ *
172
+ * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a
173
+ * judgement about a host this process cannot inspect, and `lease-expired` is
174
+ * the cutoff itself.
175
+ *
176
+ * @since 1.0.0
177
+ * @category predicates
178
+ */
179
+ export declare const provesDeath: (evidence: LivenessEvidence, claimant: OwnerId) => boolean;
152
180
  /**
153
181
  * Why a strategy refused a claim, steal, or recovery.
154
182
  *
@@ -1 +1 @@
1
- {"version":3,"file":"Consensus.d.ts","sourceRoot":"","sources":["../../src/Consensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAEtC;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,EAAE,QAAQ,CAAC,QAA8B,CAAA;AAEvE;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,QAA+B,CAAA;AAE1E;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,QAA+B,CAAA;AAE7E;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,QAI9C,CAAA;AAID;;;;;;;;;;;;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H,eAAO,MAAM,SAAS,GAAI,YAAW,OAAO,CAAC,OAAO,CAAM,KAAG,KAAK,CAAC,KAAK,CAAC,SAAS,CACnC,CAAA;AAO/C;;;;;GAKG;AACH,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAoI3C,CAAA;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,CAAsC,CAAA"}
@@ -53,6 +53,7 @@ __export(Consensus_exports, {
53
53
  makeLocal: () => makeLocal,
54
54
  makeNoop: () => makeNoop,
55
55
  matchesEvidence: () => matchesEvidence,
56
+ provesDeath: () => provesDeath,
56
57
  sameOwner: () => sameOwner
57
58
  });
58
59
  module.exports = __toCommonJS(Consensus_exports);
@@ -91,6 +92,7 @@ const matchesEvidence = (expectedOwner, observer, nowMs, evidence) => {
91
92
  return true;
92
93
  }
93
94
  };
95
+ const provesDeath = (evidence, claimant) => evidence.kind === "same-host-pid-dead" && evidence.expectedOwner.pid !== claimant.pid;
94
96
  const RejectionReason = Schema.Literals([
95
97
  "already_claimed",
96
98
  "owner_held",
@@ -221,7 +223,9 @@ const makeLocal = Effect.sync(() => {
221
223
  if (lease?.owner === void 0 || !sameOwner(lease.owner.id, evidence.expectedOwner)) {
222
224
  return rejected("evidence_invalid");
223
225
  }
224
- if (lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) return rejected("owner_live");
226
+ if (!provesDeath(evidence, claimant) && lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) {
227
+ return rejected("owner_live");
228
+ }
225
229
  lease.claim = { id: claimant, claimedAtMs: nowMs };
226
230
  return claimed(nowMs);
227
231
  })
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/Consensus.ts"],
4
- "sourcesContent": ["/**\n * The injectable consensus strategy arbitrating the journal's ownership rules.\n *\n * The journal owns the consensus rules \u2014 single writer per run, fenced and\n * unfenced appends, commit-time admission, the generation fence, and steal\n * only on staleness plus liveness evidence \u2014 and this service is how a deployment chooses *how* those rules are\n * arbitrated: where the lease lives, how liveness is probed, and how the\n * fence is checked at commit time. `Consensus` lives here beside `OwnerId`\n * for the same reason `OwnerId` does: the journal is what it fences.\n * `@smthrs/run-store`'s `Ownership` keeps its public API and rules but\n * delegates arbitration to this strategy.\n *\n * Every operation that reasons about staleness takes the caller's clock\n * reading (`nowMs`) rather than reading a clock itself: staleness (R5) and\n * the monotonic lease stamp are defined against the arbitrating caller's\n * reading, exactly as `RunStore`'s compare-and-swap operations always were,\n * so the recorded lease never differs from the outcome the caller observed.\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n * Rule constants and their provenance:\n * `packages/smithers/flows/run-store/docs/concepts/leases.md`.\n *\n * Prior art: Effect `EventJournal` (`reference/effect` `unstable/eventlog`)\n * resolves multi-writer by merge with conflict surfacing; driving a run is not\n * mergeable, so this surface deviates to exclusive-writer admission. The\n * fencing and generation semantics follow Temporal's shard `rangeID`\n * (`reference/temporal/service/history/shard/context_impl.go`).\n *\n * @since 1.0.0\n */\n\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport { OwnerId } from \"./OwnerId.ts\"\n\n/**\n * How often the supervision loop pulses to renew the owner's lease.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatInterval: Duration.Duration = Duration.seconds(1)\n\n/**\n * How old a persisted heartbeat must be before a peer may steal the run.\n * Every strategy judges R5 staleness against this one definition.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatStaleAfter: Duration.Duration = Duration.seconds(30)\n\n/**\n * How far the owner's wall clock may run behind a peer's before the lease\n * reasoning stops holding.\n *\n * The owner stamps its heartbeat from *its* clock and a would-be stealer\n * compares that stamp against *its own*, so the two hosts' clock offset is\n * subtracted directly from the owner's real safety margin. This constant names\n * that allowance instead of leaving it implicit in a \"two ticks\" arithmetic\n * accident, and it is a budgeted allowance, not a guarantee: see\n * {@link heartbeatWriteTolerance} for what happens once it is exceeded.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatSkewAllowance: Duration.Duration = Duration.seconds(10)\n\n/**\n * How long heartbeat writes may go unconfirmed before ownership must be reconfirmed.\n *\n * A peer judges staleness by the persisted heartbeat and may steal the run the\n * instant it is {@link heartbeatStaleAfter} old, so an owner that tolerated\n * write failures for exactly that long would still be executing side effects\n * when the steal is admitted. The budget is therefore\n * {@link heartbeatStaleAfter} minus {@link heartbeatSkewAllowance} (the peer's\n * clock may already read that much later than the owner's) minus one\n * {@link heartbeatInterval} (reserved for one bounded compare-and-swap\n * reconfirmation before the owner interrupts).\n *\n * This bounds, but does not eliminate, overlap. Beyond\n * {@link heartbeatSkewAllowance} of clock offset a peer can be admitted while\n * the old owner is still running. *Durable* writes stay safe regardless \u2014 they\n * are fenced by the strategy's commit-time admission, so the displaced owner's\n * writes fail rather than corrupt. Non-durable external side effects (an HTTP\n * call, a spawned process) can genuinely overlap. That is inherent to any\n * wall-clock lease and is stated here rather than asserted away; a caller that\n * cannot tolerate any overlap needs an external fencing token at the side\n * effect itself, not a larger timeout.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatWriteTolerance: Duration.Duration = Duration.millis(\n Duration.toMillis(heartbeatStaleAfter) -\n Duration.toMillis(heartbeatSkewAllowance) -\n Duration.toMillis(heartbeatInterval)\n)\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\n/**\n * Evidence that the owner in an exact run snapshot is no longer live.\n *\n * Defined here because R5 \u2014 steal requires staleness plus liveness evidence \u2014\n * is a consensus rule every strategy validates. `@smthrs/run-store`'s\n * `Ownership` re-exports it alongside the probes that mint it.\n *\n * Two of the three kinds are collected outside the strategy:\n * `same-host-pid-dead` is a local process probe, and\n * `cross-host-unreachable-stale` is a reachability judgement the deployment\n * makes. `lease-expired` is different \u2014 it asserts only that the persisted\n * heartbeat is older than the staleness cutoff, which is the one claim a\n * strategy can check for itself, and `steal` checks it: the takeover refuses\n * any lease whose heartbeat is still inside the window. It is therefore\n * accepted from a claimant on any host, while the other two stay bound to the\n * host relation that makes them meaningful. The observation must carry the\n * exact instant supplied to the consuming operation: `checkedAtMs` must equal\n * that operation's `nowMs`. A caller that probes at T and calls at T+1 is\n * refused and must build fresh evidence.\n *\n * @since 1.0.0\n * @category models\n */\nexport const LivenessEvidence = Schema.Struct({\n expectedOwner: OwnerId,\n checkedAtMs: Schema.Number,\n kind: Schema.Literals([\"same-host-pid-dead\", \"cross-host-unreachable-stale\", \"lease-expired\"])\n})\n\n/**\n * Evidence that the owner in an exact run snapshot is no longer live.\n *\n * @since 1.0.0\n * @category models\n */\nexport type LivenessEvidence = typeof LivenessEvidence.Type\n\n/**\n * Structural equality on the process identity tuple.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const sameOwner = (left: OwnerId, right: OwnerId): boolean =>\n left.hostId === right.hostId && left.pid === right.pid && left.nonce === right.nonce\n\n/**\n * Validates liveness evidence against the owner it claims to disprove.\n *\n * The evidence must name the expected owner, carry the observer's current\n * clock reading, and respect the host rule: a `same-host-pid-dead` probe is\n * only meaningful from the same host, a `cross-host-unreachable-stale`\n * observation only from a different one, and `lease-expired` is host-neutral\n * because the strategy verifies the cutoff it names for itself.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const matchesEvidence = (\n expectedOwner: OwnerId,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n): boolean => {\n if (!sameOwner(expectedOwner, evidence.expectedOwner) || evidence.checkedAtMs !== nowMs) return false\n switch (evidence.kind) {\n // A pid means nothing outside the host that owns the process namespace.\n case \"same-host-pid-dead\":\n return expectedOwner.hostId === observer.hostId\n // Unreachability is what a peer host observes; on the owner's own host it\n // would be an unprobed guess dressed as evidence.\n case \"cross-host-unreachable-stale\":\n return expectedOwner.hostId !== observer.hostId\n // The lease is host-neutral, and the strategy verifies the same\n // caller-clock cutoff named by this evidence.\n case \"lease-expired\":\n return true\n }\n}\n\n/**\n * Why a strategy refused a claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport const RejectionReason = Schema.Literals([\n \"already_claimed\",\n \"owner_held\",\n \"owner_live\",\n \"evidence_invalid\",\n \"claim_fresh\",\n \"claim_changed\",\n \"unavailable\"\n])\n\n/**\n * Why a strategy refused a claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport type RejectionReason = typeof RejectionReason.Type\n\n/**\n * A granted claim, carrying the grant timestamp the later activation must\n * present (R4 \u2014 the generation fence).\n *\n * @since 1.0.0\n * @category models\n */\nexport const Claimed = Schema.TaggedStruct(\"Claimed\", {\n grantedAtMs: Schema.Number\n})\n\n/**\n * A granted claim.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Claimed = typeof Claimed.Type\n\n/**\n * A refused claim, steal, or recovery, with the strategy's typed reason.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Rejected = Schema.TaggedStruct(\"Rejected\", {\n reason: RejectionReason\n})\n\n/**\n * A refused claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Rejected = typeof Rejected.Type\n\n/**\n * Outcome of `claim` and `steal`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const ClaimOutcome = Schema.Union([Claimed, Rejected])\n\n/**\n * Outcome of `claim` and `steal`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ClaimOutcome = typeof ClaimOutcome.Type\n\n/**\n * A claim promoted to ownership.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Activated = Schema.TaggedStruct(\"Activated\", {})\n\n/**\n * A claim promoted to ownership.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Activated = typeof Activated.Type\n\n/**\n * The claim or lease the caller presented no longer exists.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Lost = Schema.TaggedStruct(\"Lost\", {})\n\n/**\n * The claim or lease the caller presented no longer exists.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Lost = typeof Lost.Type\n\n/**\n * Outcome of `activate`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const ActivateOutcome = Schema.Union([Activated, Lost])\n\n/**\n * Outcome of `activate`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ActivateOutcome = typeof ActivateOutcome.Type\n\n/**\n * A renewed lease, carrying the monotonic heartbeat stamp the strategy\n * recorded \u2014 the maximum of the stored stamp and the caller's reading, so a\n * late pulse never moves the lease backwards.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Renewed = Schema.TaggedStruct(\"Renewed\", {\n heartbeatAtMs: Schema.Number\n})\n\n/**\n * A renewed lease.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Renewed = typeof Renewed.Type\n\n/**\n * Outcome of `heartbeat` and `reconfirm`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const HeartbeatOutcome = Schema.Union([Renewed, Lost])\n\n/**\n * Outcome of `heartbeat` and `reconfirm`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type HeartbeatOutcome = typeof HeartbeatOutcome.Type\n\n/**\n * A stale claim cleared after its claimant was proven dead.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Recovered = Schema.TaggedStruct(\"Recovered\", {})\n\n/**\n * A stale claim cleared after its claimant was proven dead.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Recovered = typeof Recovered.Type\n\n/**\n * Outcome of `recover`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const RecoverOutcome = Schema.Union([Recovered, Rejected])\n\n/**\n * Outcome of `recover`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type RecoverOutcome = typeof RecoverOutcome.Type\n\n/**\n * Failure raised by a consensus strategy.\n *\n * `fence_lost` is `guard`'s refusal: the supplied owner no longer holds the\n * run, so the fenced write it joins must not commit. `persistence_failed`\n * wraps a strategy's storage failure; the original cause is preserved so the\n * durable writer's retry classification still sees a transient conflict\n * through the wrapper.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class ConsensusError extends Schema.TaggedError<ConsensusError>()(\"@smthrs/journal/ConsensusError\", {\n code: Schema.Literals([\"fence_lost\", \"persistence_failed\"]),\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown)\n}) {}\n\n/**\n * Consensus operations.\n *\n * The rules being arbitrated are strategy-independent; a strategy\n * chooses where the lease lives and how the fence is checked at commit time.\n * The claim lifecycle is two-phase, exactly as `RunStore`'s always was:\n * `claim` (or `steal`, its evidence-gated form) reserves the run and returns\n * the grant timestamp, `activate` presents that grant to take ownership, and\n * `release` clears whichever of the caller's claim or ownership still stands.\n * `recover` clears a *third party's* stale claim after its claimant was proven\n * dead \u2014 the relocated `recoverClaim` mechanic. `guard` is the commit-time\n * admission check (R3) `Journal.emitDurable`, `checkpoint`, and `compact`\n * join: it succeeds while the owner holds the run and fails with `fence_lost`\n * otherwise.\n *\n * Heartbeats and lease state are the strategy's private evidence and never\n * enter the journal.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface Service {\n readonly claim: (\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) => Effect.Effect<ClaimOutcome, ConsensusError>\n readonly activate: (\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) => Effect.Effect<ActivateOutcome, ConsensusError>\n readonly heartbeat: (\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) => Effect.Effect<HeartbeatOutcome, ConsensusError>\n /** Renews only while this owner holds the lease and no takeover claim is pending. */\n readonly reconfirm: (\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) => Effect.Effect<HeartbeatOutcome, ConsensusError>\n readonly release: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>\n readonly steal: (\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) => Effect.Effect<ClaimOutcome, ConsensusError>\n readonly recover: (\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) => Effect.Effect<RecoverOutcome, ConsensusError>\n readonly guard: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>\n}\n\n/**\n * Context service for the injected consensus strategy.\n *\n * @since 1.0.0\n * @category services\n */\nexport class Consensus extends Context.Service<Consensus, Service>()(\"@smthrs/journal/Consensus\") {}\n\n/**\n * Constructs a consensus service from an implementation.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (implementation: Service): Service => Consensus.of(implementation)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost: Lost = { _tag: \"Lost\" }\nconst activated: Activated = { _tag: \"Activated\" }\nconst recovered: Recovered = { _tag: \"Recovered\" }\n\n/**\n * The refusal `guard` raises for an owner that no longer holds the run.\n *\n * @since 1.0.0\n * @category errors\n */\nexport const fenceLost = (runId: string, owner: OwnerId): ConsensusError =>\n new ConsensusError({\n code: \"fence_lost\",\n message: `run ${runId} is no longer owned by ${owner.hostId}:${owner.pid}:${owner.nonce}`\n })\n\n/**\n * Constructs a strategy that arbitrates nothing: claims are refused, leases\n * are never held, and every fenced write is rejected.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const makeNoop = (overrides: Partial<Service> = {}): Service =>\n Consensus.of({\n claim: Effect.fn(\"Consensus.claim\")(() => Effect.succeed(rejected(\"unavailable\"))),\n activate: Effect.fn(\"Consensus.activate\")(() => Effect.succeed(lost)),\n heartbeat: Effect.fn(\"Consensus.heartbeat\")(() => Effect.succeed(lost)),\n reconfirm: Effect.fn(\"Consensus.reconfirm\")(() => Effect.succeed(lost)),\n release: Effect.fn(\"Consensus.release\")(() => Effect.void),\n steal: Effect.fn(\"Consensus.steal\")(() => Effect.succeed(rejected(\"unavailable\"))),\n recover: Effect.fn(\"Consensus.recover\")(() => Effect.succeed(rejected(\"unavailable\"))),\n guard: Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) => Effect.fail(fenceLost(runId, owner))),\n ...overrides\n })\n\n/**\n * Provides the refusing strategy stub.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerNoop = (overrides: Partial<Service> = {}): Layer.Layer<Consensus> =>\n Layer.succeed(Consensus)(makeNoop(overrides))\n\ninterface LocalLease {\n owner: { readonly id: OwnerId; readonly grantedAtMs: number; heartbeatAtMs: number } | undefined\n claim: { readonly id: OwnerId; readonly claimedAtMs: number } | undefined\n}\n\n/**\n * Constructs the in-memory single-process strategy.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const makeLocal: Effect.Effect<Service> = Effect.sync(() => {\n const leases = new Map<string, LocalLease>()\n\n const leaseOf = (runId: string): LocalLease => {\n const existing = leases.get(runId)\n if (existing !== undefined) return existing\n const fresh: LocalLease = { owner: undefined, claim: undefined }\n leases.set(runId, fresh)\n return fresh\n }\n\n const prune = (runId: string, lease: LocalLease): void => {\n if (lease.owner === undefined && lease.claim === undefined) {\n leases.delete(runId)\n }\n }\n\n return Consensus.of({\n claim: Effect.fn(\"Consensus.claim\")((runId: string, claimant: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leaseOf(runId)\n if (lease.claim !== undefined) return rejected(\"already_claimed\")\n if (lease.owner !== undefined) return rejected(\"owner_held\")\n lease.claim = { id: claimant, claimedAtMs: nowMs }\n return claimed(nowMs)\n })\n ),\n activate: Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n Effect.sync(() => {\n const lease = leaseOf(runId)\n if (\n lease.claim === undefined ||\n !sameOwner(lease.claim.id, owner) ||\n lease.claim.claimedAtMs !== grantedAtMs\n ) {\n prune(runId, lease)\n return lost\n }\n lease.claim = undefined\n lease.owner = { id: owner, grantedAtMs, heartbeatAtMs: nowMs }\n return activated\n })\n ),\n heartbeat: Effect.fn(\"Consensus.heartbeat\")((runId: string, owner: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease?.owner === undefined || !sameOwner(lease.owner.id, owner)) return lost\n lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)\n return ({ _tag: \"Renewed\", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)\n })\n ),\n reconfirm: Effect.fn(\"Consensus.reconfirm\")((runId: string, owner: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease?.owner === undefined || lease.claim !== undefined || !sameOwner(lease.owner.id, owner)) return lost\n lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)\n return ({ _tag: \"Renewed\", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)\n })\n ),\n release: Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease === undefined) return\n if (lease.claim !== undefined && sameOwner(lease.claim.id, owner)) {\n lease.claim = undefined\n }\n if (lease.owner !== undefined && sameOwner(lease.owner.id, owner)) {\n lease.owner = undefined\n }\n prune(runId, lease)\n })\n ),\n steal: Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.sync(() => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return rejected(\"evidence_invalid\")\n }\n const lease = leases.get(runId)\n if (lease?.claim !== undefined) return rejected(\"already_claimed\")\n if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {\n return rejected(\"evidence_invalid\")\n }\n if (lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) return rejected(\"owner_live\")\n lease.claim = { id: claimant, claimedAtMs: nowMs }\n return claimed(nowMs)\n })\n ),\n recover: Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.sync(() => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) return rejected(\"evidence_invalid\")\n const lease = leases.get(runId)\n if (\n lease?.claim === undefined ||\n !sameOwner(lease.claim.id, staleClaimant) ||\n lease.claim.claimedAtMs !== grantedAtMs\n ) {\n return rejected(\"claim_changed\")\n }\n if (lease.claim.claimedAtMs >= nowMs - staleAfterMs) return rejected(\"claim_fresh\")\n lease.claim = undefined\n prune(runId, lease)\n return recovered\n })\n ),\n guard: Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n Effect.suspend(() => {\n const lease = leases.get(runId)\n return lease?.owner !== undefined && sameOwner(lease.owner.id, owner)\n ? Effect.void\n : Effect.fail(fenceLost(runId, owner))\n })\n )\n })\n})\n\n/**\n * Provides the in-memory single-process strategy.\n *\n * The lease lives in process memory, so R3 is exact within the process \u2014 the\n * strategy's transitions and the serialized append transactions interleave\n * atomically on one event loop \u2014 and browser support needs nothing beyond\n * this layer plus the browser-safe journal. State is per layer build: provide\n * one instance to every service that must agree on it, which is what\n * `SqlJournal.layerWith` and `RunStore.layerWith` exist for.\n *\n * The lease is not part of any database transaction: a transition made inside\n * a `Journal.transact` that later rolls back stays applied in memory, so the\n * lease and a rolled-back run row can disagree until the next transition.\n * `SqlConsensus` keeps the two in one transaction; prefer it wherever a\n * database is present.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerLocal: Layer.Layer<Consensus> = Layer.effect(Consensus, makeLocal)\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BA,cAAyB;AACzB,eAA0B;AAC1B,aAAwB;AACxB,YAAuB;AACvB,aAAwB;AACxB,qBAAwB;AAQjB,MAAM,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AAI,KAAK;AAC9B,YACE,OAAO,UAAU,UACjB,CAAC,UAAU,MAAM,MAAM,IAAI,aAAa,KACxC,MAAM,MAAM,gBAAgB,aAC5B;AACA,iBAAO,SAAS,eAAe;AAAA,QACjC;AACA,YAAI,MAAM,MAAM,eAAe,QAAQ,aAAc,QAAO,SAAS,aAAa;AAClF,cAAM,QAAQ;AACd,cAAM,OAAO,KAAK;AAClB,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,IACA,OAAO,OAAO,GAAG,iBAAiB;AAAA,MAAE,CAAC,OAAe,UAClD,OAAO,QAAQ,MAAM;AACnB,cAAM,QAAQ,OAAO,IAAI,KAAK;AAC9B,eAAO,OAAO,UAAU,UAAa,UAAU,MAAM,MAAM,IAAI,KAAK,IAChE,OAAO,OACP,OAAO,KAAK,UAAU,OAAO,KAAK,CAAC;AAAA,MACzC,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH,CAAC;AAqBM,MAAM,aAAqC,MAAM,OAAO,WAAW,SAAS;",
4
+ "sourcesContent": ["/**\n * The injectable consensus strategy arbitrating the journal's ownership rules.\n *\n * The journal owns the consensus rules \u2014 single writer per run, fenced and\n * unfenced appends, commit-time admission, the generation fence, and steal\n * only on staleness plus liveness evidence, or on a same-host probe that\n * proves the owner's process gone \u2014 and this service is how a deployment chooses *how* those rules are\n * arbitrated: where the lease lives, how liveness is probed, and how the\n * fence is checked at commit time. `Consensus` lives here beside `OwnerId`\n * for the same reason `OwnerId` does: the journal is what it fences.\n * `@smthrs/run-store`'s `Ownership` keeps its public API and rules but\n * delegates arbitration to this strategy.\n *\n * Every operation that reasons about staleness takes the caller's clock\n * reading (`nowMs`) rather than reading a clock itself: staleness (R5) and\n * the monotonic lease stamp are defined against the arbitrating caller's\n * reading, exactly as `RunStore`'s compare-and-swap operations always were,\n * so the recorded lease never differs from the outcome the caller observed.\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n * Rule constants and their provenance:\n * `packages/smithers/flows/run-store/docs/concepts/leases.md`.\n *\n * Prior art: Effect `EventJournal` (`reference/effect` `unstable/eventlog`)\n * resolves multi-writer by merge with conflict surfacing; driving a run is not\n * mergeable, so this surface deviates to exclusive-writer admission. The\n * fencing and generation semantics follow Temporal's shard `rangeID`\n * (`reference/temporal/service/history/shard/context_impl.go`).\n *\n * @since 1.0.0\n */\n\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport { OwnerId } from \"./OwnerId.ts\"\n\n/**\n * How often the supervision loop pulses to renew the owner's lease.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatInterval: Duration.Duration = Duration.seconds(1)\n\n/**\n * How old a persisted heartbeat must be before a peer may steal the run.\n * Every strategy judges R5 staleness against this one definition.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatStaleAfter: Duration.Duration = Duration.seconds(30)\n\n/**\n * How far the owner's wall clock may run behind a peer's before the lease\n * reasoning stops holding.\n *\n * The owner stamps its heartbeat from *its* clock and a would-be stealer\n * compares that stamp against *its own*, so the two hosts' clock offset is\n * subtracted directly from the owner's real safety margin. This constant names\n * that allowance instead of leaving it implicit in a \"two ticks\" arithmetic\n * accident, and it is a budgeted allowance, not a guarantee: see\n * {@link heartbeatWriteTolerance} for what happens once it is exceeded.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatSkewAllowance: Duration.Duration = Duration.seconds(10)\n\n/**\n * How long heartbeat writes may go unconfirmed before ownership must be reconfirmed.\n *\n * A peer judges staleness by the persisted heartbeat and may steal the run the\n * instant it is {@link heartbeatStaleAfter} old, so an owner that tolerated\n * write failures for exactly that long would still be executing side effects\n * when the steal is admitted. The budget is therefore\n * {@link heartbeatStaleAfter} minus {@link heartbeatSkewAllowance} (the peer's\n * clock may already read that much later than the owner's) minus one\n * {@link heartbeatInterval} (reserved for one bounded compare-and-swap\n * reconfirmation before the owner interrupts).\n *\n * This bounds, but does not eliminate, overlap. Beyond\n * {@link heartbeatSkewAllowance} of clock offset a peer can be admitted while\n * the old owner is still running. *Durable* writes stay safe regardless \u2014 they\n * are fenced by the strategy's commit-time admission, so the displaced owner's\n * writes fail rather than corrupt. Non-durable external side effects (an HTTP\n * call, a spawned process) can genuinely overlap. That is inherent to any\n * wall-clock lease and is stated here rather than asserted away; a caller that\n * cannot tolerate any overlap needs an external fencing token at the side\n * effect itself, not a larger timeout.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatWriteTolerance: Duration.Duration = Duration.millis(\n Duration.toMillis(heartbeatStaleAfter) -\n Duration.toMillis(heartbeatSkewAllowance) -\n Duration.toMillis(heartbeatInterval)\n)\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\n/**\n * Evidence that the owner in an exact run snapshot is no longer live.\n *\n * Defined here because R5 \u2014 steal requires staleness plus liveness evidence \u2014\n * is a consensus rule every strategy validates. `@smthrs/run-store`'s\n * `Ownership` re-exports it alongside the probes that mint it.\n *\n * Two of the three kinds are collected outside the strategy:\n * `same-host-pid-dead` is a local process probe, and\n * `cross-host-unreachable-stale` is a reachability judgement the deployment\n * makes. `lease-expired` is different \u2014 it asserts only that the persisted\n * heartbeat is older than the staleness cutoff, which is the one claim a\n * strategy can check for itself, and `steal` checks it: the takeover refuses\n * any lease whose heartbeat is still inside the window. It is therefore\n * accepted from a claimant on any host, while the other two stay bound to the\n * host relation that makes them meaningful. `same-host-pid-dead` alone also\n * admits a steal inside the window; see {@link provesDeath}. The observation must carry the\n * exact instant supplied to the consuming operation: `checkedAtMs` must equal\n * that operation's `nowMs`. A caller that probes at T and calls at T+1 is\n * refused and must build fresh evidence.\n *\n * @since 1.0.0\n * @category models\n */\nexport const LivenessEvidence = Schema.Struct({\n expectedOwner: OwnerId,\n checkedAtMs: Schema.Number,\n kind: Schema.Literals([\"same-host-pid-dead\", \"cross-host-unreachable-stale\", \"lease-expired\"])\n})\n\n/**\n * Evidence that the owner in an exact run snapshot is no longer live.\n *\n * @since 1.0.0\n * @category models\n */\nexport type LivenessEvidence = typeof LivenessEvidence.Type\n\n/**\n * Structural equality on the process identity tuple.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const sameOwner = (left: OwnerId, right: OwnerId): boolean =>\n left.hostId === right.hostId && left.pid === right.pid && left.nonce === right.nonce\n\n/**\n * Validates liveness evidence against the owner it claims to disprove.\n *\n * The evidence must name the expected owner, carry the observer's current\n * clock reading, and respect the host rule: a `same-host-pid-dead` probe is\n * only meaningful from the same host, a `cross-host-unreachable-stale`\n * observation only from a different one, and `lease-expired` is host-neutral\n * because the strategy verifies the cutoff it names for itself.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const matchesEvidence = (\n expectedOwner: OwnerId,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n): boolean => {\n if (!sameOwner(expectedOwner, evidence.expectedOwner) || evidence.checkedAtMs !== nowMs) return false\n switch (evidence.kind) {\n // A pid means nothing outside the host that owns the process namespace.\n case \"same-host-pid-dead\":\n return expectedOwner.hostId === observer.hostId\n // Unreachability is what a peer host observes; on the owner's own host it\n // would be an unprobed guess dressed as evidence.\n case \"cross-host-unreachable-stale\":\n return expectedOwner.hostId !== observer.hostId\n // The lease is host-neutral, and the strategy verifies the same\n // caller-clock cutoff named by this evidence.\n case \"lease-expired\":\n return true\n }\n}\n\n/**\n * Whether evidence proves the owner gone, so a steal need not wait for its\n * lease to go stale.\n *\n * The lease stands in for a question a peer cannot ask directly: is the owner\n * still running? A `same-host-pid-dead` probe asks it. The claimant read its\n * own host's process table and found no process behind the owner's pid, and a\n * process that does not exist renews no lease and writes nothing, so waiting\n * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with\n * `SIGKILL` is therefore reclaimed by the next process on the same host at\n * once.\n *\n * The evidence must still pass {@link matchesEvidence}, which binds the kind\n * to the same host. One more case is excluded here: an owner recorded with the\n * claimant's own pid names the claimant's process, which is running, so a\n * probe of that pid cannot report it gone. Such evidence keeps the staleness\n * cutoff.\n *\n * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a\n * judgement about a host this process cannot inspect, and `lease-expired` is\n * the cutoff itself.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const provesDeath = (evidence: LivenessEvidence, claimant: OwnerId): boolean =>\n evidence.kind === \"same-host-pid-dead\" && evidence.expectedOwner.pid !== claimant.pid\n\n/**\n * Why a strategy refused a claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport const RejectionReason = Schema.Literals([\n \"already_claimed\",\n \"owner_held\",\n \"owner_live\",\n \"evidence_invalid\",\n \"claim_fresh\",\n \"claim_changed\",\n \"unavailable\"\n])\n\n/**\n * Why a strategy refused a claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport type RejectionReason = typeof RejectionReason.Type\n\n/**\n * A granted claim, carrying the grant timestamp the later activation must\n * present (R4 \u2014 the generation fence).\n *\n * @since 1.0.0\n * @category models\n */\nexport const Claimed = Schema.TaggedStruct(\"Claimed\", {\n grantedAtMs: Schema.Number\n})\n\n/**\n * A granted claim.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Claimed = typeof Claimed.Type\n\n/**\n * A refused claim, steal, or recovery, with the strategy's typed reason.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Rejected = Schema.TaggedStruct(\"Rejected\", {\n reason: RejectionReason\n})\n\n/**\n * A refused claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Rejected = typeof Rejected.Type\n\n/**\n * Outcome of `claim` and `steal`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const ClaimOutcome = Schema.Union([Claimed, Rejected])\n\n/**\n * Outcome of `claim` and `steal`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ClaimOutcome = typeof ClaimOutcome.Type\n\n/**\n * A claim promoted to ownership.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Activated = Schema.TaggedStruct(\"Activated\", {})\n\n/**\n * A claim promoted to ownership.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Activated = typeof Activated.Type\n\n/**\n * The claim or lease the caller presented no longer exists.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Lost = Schema.TaggedStruct(\"Lost\", {})\n\n/**\n * The claim or lease the caller presented no longer exists.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Lost = typeof Lost.Type\n\n/**\n * Outcome of `activate`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const ActivateOutcome = Schema.Union([Activated, Lost])\n\n/**\n * Outcome of `activate`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ActivateOutcome = typeof ActivateOutcome.Type\n\n/**\n * A renewed lease, carrying the monotonic heartbeat stamp the strategy\n * recorded \u2014 the maximum of the stored stamp and the caller's reading, so a\n * late pulse never moves the lease backwards.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Renewed = Schema.TaggedStruct(\"Renewed\", {\n heartbeatAtMs: Schema.Number\n})\n\n/**\n * A renewed lease.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Renewed = typeof Renewed.Type\n\n/**\n * Outcome of `heartbeat` and `reconfirm`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const HeartbeatOutcome = Schema.Union([Renewed, Lost])\n\n/**\n * Outcome of `heartbeat` and `reconfirm`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type HeartbeatOutcome = typeof HeartbeatOutcome.Type\n\n/**\n * A stale claim cleared after its claimant was proven dead.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Recovered = Schema.TaggedStruct(\"Recovered\", {})\n\n/**\n * A stale claim cleared after its claimant was proven dead.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Recovered = typeof Recovered.Type\n\n/**\n * Outcome of `recover`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const RecoverOutcome = Schema.Union([Recovered, Rejected])\n\n/**\n * Outcome of `recover`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type RecoverOutcome = typeof RecoverOutcome.Type\n\n/**\n * Failure raised by a consensus strategy.\n *\n * `fence_lost` is `guard`'s refusal: the supplied owner no longer holds the\n * run, so the fenced write it joins must not commit. `persistence_failed`\n * wraps a strategy's storage failure; the original cause is preserved so the\n * durable writer's retry classification still sees a transient conflict\n * through the wrapper.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class ConsensusError extends Schema.TaggedError<ConsensusError>()(\"@smthrs/journal/ConsensusError\", {\n code: Schema.Literals([\"fence_lost\", \"persistence_failed\"]),\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown)\n}) {}\n\n/**\n * Consensus operations.\n *\n * The rules being arbitrated are strategy-independent; a strategy\n * chooses where the lease lives and how the fence is checked at commit time.\n * The claim lifecycle is two-phase, exactly as `RunStore`'s always was:\n * `claim` (or `steal`, its evidence-gated form) reserves the run and returns\n * the grant timestamp, `activate` presents that grant to take ownership, and\n * `release` clears whichever of the caller's claim or ownership still stands.\n * `recover` clears a *third party's* stale claim after its claimant was proven\n * dead \u2014 the relocated `recoverClaim` mechanic. `guard` is the commit-time\n * admission check (R3) `Journal.emitDurable`, `checkpoint`, and `compact`\n * join: it succeeds while the owner holds the run and fails with `fence_lost`\n * otherwise.\n *\n * Heartbeats and lease state are the strategy's private evidence and never\n * enter the journal.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface Service {\n readonly claim: (\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) => Effect.Effect<ClaimOutcome, ConsensusError>\n readonly activate: (\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) => Effect.Effect<ActivateOutcome, ConsensusError>\n readonly heartbeat: (\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) => Effect.Effect<HeartbeatOutcome, ConsensusError>\n /** Renews only while this owner holds the lease and no takeover claim is pending. */\n readonly reconfirm: (\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) => Effect.Effect<HeartbeatOutcome, ConsensusError>\n readonly release: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>\n readonly steal: (\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) => Effect.Effect<ClaimOutcome, ConsensusError>\n readonly recover: (\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) => Effect.Effect<RecoverOutcome, ConsensusError>\n readonly guard: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>\n}\n\n/**\n * Context service for the injected consensus strategy.\n *\n * @since 1.0.0\n * @category services\n */\nexport class Consensus extends Context.Service<Consensus, Service>()(\"@smthrs/journal/Consensus\") {}\n\n/**\n * Constructs a consensus service from an implementation.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (implementation: Service): Service => Consensus.of(implementation)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost: Lost = { _tag: \"Lost\" }\nconst activated: Activated = { _tag: \"Activated\" }\nconst recovered: Recovered = { _tag: \"Recovered\" }\n\n/**\n * The refusal `guard` raises for an owner that no longer holds the run.\n *\n * @since 1.0.0\n * @category errors\n */\nexport const fenceLost = (runId: string, owner: OwnerId): ConsensusError =>\n new ConsensusError({\n code: \"fence_lost\",\n message: `run ${runId} is no longer owned by ${owner.hostId}:${owner.pid}:${owner.nonce}`\n })\n\n/**\n * Constructs a strategy that arbitrates nothing: claims are refused, leases\n * are never held, and every fenced write is rejected.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const makeNoop = (overrides: Partial<Service> = {}): Service =>\n Consensus.of({\n claim: Effect.fn(\"Consensus.claim\")(() => Effect.succeed(rejected(\"unavailable\"))),\n activate: Effect.fn(\"Consensus.activate\")(() => Effect.succeed(lost)),\n heartbeat: Effect.fn(\"Consensus.heartbeat\")(() => Effect.succeed(lost)),\n reconfirm: Effect.fn(\"Consensus.reconfirm\")(() => Effect.succeed(lost)),\n release: Effect.fn(\"Consensus.release\")(() => Effect.void),\n steal: Effect.fn(\"Consensus.steal\")(() => Effect.succeed(rejected(\"unavailable\"))),\n recover: Effect.fn(\"Consensus.recover\")(() => Effect.succeed(rejected(\"unavailable\"))),\n guard: Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) => Effect.fail(fenceLost(runId, owner))),\n ...overrides\n })\n\n/**\n * Provides the refusing strategy stub.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerNoop = (overrides: Partial<Service> = {}): Layer.Layer<Consensus> =>\n Layer.succeed(Consensus)(makeNoop(overrides))\n\ninterface LocalLease {\n owner: { readonly id: OwnerId; readonly grantedAtMs: number; heartbeatAtMs: number } | undefined\n claim: { readonly id: OwnerId; readonly claimedAtMs: number } | undefined\n}\n\n/**\n * Constructs the in-memory single-process strategy.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const makeLocal: Effect.Effect<Service> = Effect.sync(() => {\n const leases = new Map<string, LocalLease>()\n\n const leaseOf = (runId: string): LocalLease => {\n const existing = leases.get(runId)\n if (existing !== undefined) return existing\n const fresh: LocalLease = { owner: undefined, claim: undefined }\n leases.set(runId, fresh)\n return fresh\n }\n\n const prune = (runId: string, lease: LocalLease): void => {\n if (lease.owner === undefined && lease.claim === undefined) {\n leases.delete(runId)\n }\n }\n\n return Consensus.of({\n claim: Effect.fn(\"Consensus.claim\")((runId: string, claimant: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leaseOf(runId)\n if (lease.claim !== undefined) return rejected(\"already_claimed\")\n if (lease.owner !== undefined) return rejected(\"owner_held\")\n lease.claim = { id: claimant, claimedAtMs: nowMs }\n return claimed(nowMs)\n })\n ),\n activate: Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n Effect.sync(() => {\n const lease = leaseOf(runId)\n if (\n lease.claim === undefined ||\n !sameOwner(lease.claim.id, owner) ||\n lease.claim.claimedAtMs !== grantedAtMs\n ) {\n prune(runId, lease)\n return lost\n }\n lease.claim = undefined\n lease.owner = { id: owner, grantedAtMs, heartbeatAtMs: nowMs }\n return activated\n })\n ),\n heartbeat: Effect.fn(\"Consensus.heartbeat\")((runId: string, owner: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease?.owner === undefined || !sameOwner(lease.owner.id, owner)) return lost\n lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)\n return ({ _tag: \"Renewed\", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)\n })\n ),\n reconfirm: Effect.fn(\"Consensus.reconfirm\")((runId: string, owner: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease?.owner === undefined || lease.claim !== undefined || !sameOwner(lease.owner.id, owner)) return lost\n lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)\n return ({ _tag: \"Renewed\", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)\n })\n ),\n release: Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease === undefined) return\n if (lease.claim !== undefined && sameOwner(lease.claim.id, owner)) {\n lease.claim = undefined\n }\n if (lease.owner !== undefined && sameOwner(lease.owner.id, owner)) {\n lease.owner = undefined\n }\n prune(runId, lease)\n })\n ),\n steal: Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.sync(() => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return rejected(\"evidence_invalid\")\n }\n const lease = leases.get(runId)\n if (lease?.claim !== undefined) return rejected(\"already_claimed\")\n if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {\n return rejected(\"evidence_invalid\")\n }\n if (!provesDeath(evidence, claimant) && lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) {\n return rejected(\"owner_live\")\n }\n lease.claim = { id: claimant, claimedAtMs: nowMs }\n return claimed(nowMs)\n })\n ),\n recover: Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.sync(() => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) return rejected(\"evidence_invalid\")\n const lease = leases.get(runId)\n if (\n lease?.claim === undefined ||\n !sameOwner(lease.claim.id, staleClaimant) ||\n lease.claim.claimedAtMs !== grantedAtMs\n ) {\n return rejected(\"claim_changed\")\n }\n if (lease.claim.claimedAtMs >= nowMs - staleAfterMs) return rejected(\"claim_fresh\")\n lease.claim = undefined\n prune(runId, lease)\n return recovered\n })\n ),\n guard: Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n Effect.suspend(() => {\n const lease = leases.get(runId)\n return lease?.owner !== undefined && sameOwner(lease.owner.id, owner)\n ? Effect.void\n : Effect.fail(fenceLost(runId, owner))\n })\n )\n })\n})\n\n/**\n * Provides the in-memory single-process strategy.\n *\n * The lease lives in process memory, so R3 is exact within the process \u2014 the\n * strategy's transitions and the serialized append transactions interleave\n * atomically on one event loop \u2014 and browser support needs nothing beyond\n * this layer plus the browser-safe journal. State is per layer build: provide\n * one instance to every service that must agree on it, which is what\n * `SqlJournal.layerWith` and `RunStore.layerWith` exist for.\n *\n * The lease is not part of any database transaction: a transition made inside\n * a `Journal.transact` that later rolls back stays applied in memory, so the\n * lease and a rolled-back run row can disagree until the next transition.\n * `SqlConsensus` keeps the two in one transaction; prefer it wherever a\n * database is present.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerLocal: Layer.Layer<Consensus> = Layer.effect(Consensus, makeLocal)\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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Ae,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA;AACjD,OAAO,EAIL,SAAS,EAUT,KAAK,OAAO,EACb,MAAM,gBAAgB,CAAA;AAoBvB;;;;;;GAMG;AACH,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC,SAAS,CAuQlF,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC,SAAS,CAAiC,CAAA"}
1
+ {"version":3,"file":"SqlConsensus.d.ts","sourceRoot":"","sources":["../../src/SqlConsensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAA;AAE9D,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA;AACjD,OAAO,EAIL,SAAS,EAWT,KAAK,OAAO,EACb,MAAM,gBAAgB,CAAA;AAoBvB;;;;;;GAMG;AACH,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC,SAAS,CAuQlF,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC,SAAS,CAAiC,CAAA"}
@@ -176,7 +176,7 @@ const make = Effect.gen(function* () {
176
176
  AND owner_host_id = ${evidence.expectedOwner.hostId}
177
177
  AND owner_pid = ${evidence.expectedOwner.pid}
178
178
  AND owner_nonce = ${evidence.expectedOwner.nonce}
179
- AND heartbeat_at_ms < ${nowMs - staleAfterMs}
179
+ AND ${(0, import_Consensus.provesDeath)(evidence, claimant) ? sql`TRUE` : sql`heartbeat_at_ms < ${nowMs - staleAfterMs}`}
180
180
  AND claim_host_id IS NULL
181
181
  RETURNING run_id
182
182
  `;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/SqlConsensus.ts"],
4
- "sourcesContent": ["/**\n * The default database-backed consensus strategy.\n *\n * This is the run store's former `flows_runs` ownership compare-and-swap\n * relocated: the owner tuple, the two-phase claim columns, claim recovery, and\n * the grant timestamp are the private schema of one strategy \u2014 the\n * `flows_consensus_leases` table \u2014 instead of a public contract on the run\n * row. The run row still mirrors the outcome, but the lease is what\n * arbitrates.\n *\n * Commit-time admission (R3) is exact: `guard` is a plain SELECT that joins\n * the caller's open write transaction \u2014 `DurableWriter` serializes write\n * transactions, so no reclaim can commit between the guard read and the\n * statements beside it \u2014 and every mutating operation runs through\n * `DurableWriter.write`, joining an enclosing transaction as a savepoint.\n * Prior art: Temporal's shard `rangeID` check\n * (`reference/temporal/service/history/shard/context_impl.go`,\n * `renewRangeLocked`).\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n *\n * @since 1.0.0\n */\n\nimport * as Dialect from \"@smthrs/database/Dialect\"\nimport { DurableWriter } from \"@smthrs/database/DurableWriter\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as SqlClient from \"effect/sql/SqlClient\"\nimport {\n type ActivateOutcome,\n type Claimed,\n type ClaimOutcome,\n Consensus,\n ConsensusError,\n fenceLost,\n type HeartbeatOutcome,\n heartbeatStaleAfter,\n type LivenessEvidence,\n matchesEvidence,\n type RecoverOutcome,\n type Rejected,\n type RejectionReason,\n type Service\n} from \"./Consensus.ts\"\nimport type { OwnerId } from \"./OwnerId.ts\"\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost = { _tag: \"Lost\" } as const\nconst activated = { _tag: \"Activated\" } as const\nconst recovered = { _tag: \"Recovered\" } as const\n\ninterface LeaseRow {\n readonly owner_host_id: string | null\n readonly owner_pid: number | null\n readonly owner_nonce: string | null\n readonly claim_host_id: string | null\n readonly claim_pid: number | null\n readonly claim_nonce: string | null\n}\n\n/**\n * Constructs the database-backed strategy over the context's SQL client and\n * durable writer.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect.Effect<Service, never, DurableWriter | SqlClient.SqlClient> = Effect.gen(function*() {\n const sql = yield* Effect.service(SqlClient.SqlClient)\n const writer = yield* DurableWriter\n\n const strategyError = (cause: unknown): ConsensusError =>\n new ConsensusError({\n code: \"persistence_failed\",\n message: \"consensus lease operation failed\",\n cause\n })\n\n // The original cause is preserved through the wrapper so an enclosing\n // `DurableWriter.write`'s retry classification still sees a transient\n // conflict raised by a savepoint-nested lease statement.\n const write = <A>(\n body: Effect.Effect<A, unknown>\n ): Effect.Effect<A, ConsensusError> =>\n writer.write(body).pipe(Effect.mapError((cause) => cause instanceof ConsensusError ? cause : strategyError(cause)))\n\n const leaseOf = (runId: string) =>\n sql<LeaseRow>`\n SELECT owner_host_id, owner_pid, owner_nonce, claim_host_id, claim_pid, claim_nonce\n FROM flows_consensus_leases\n WHERE run_id = ${runId}\n `\n\n const prune = (runId: string) =>\n sql`\n DELETE FROM flows_consensus_leases\n WHERE run_id = ${runId} AND owner_host_id IS NULL AND claim_host_id IS NULL\n `\n\n const claim: Service[\"claim\"] = Effect.fn(\"Consensus.claim\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n INSERT INTO flows_consensus_leases (run_id, claim_host_id, claim_pid, claim_nonce, claimed_at_ms)\n VALUES (${runId}, ${claimant.hostId}, ${claimant.pid}, ${claimant.nonce}, ${nowMs})\n ON CONFLICT (run_id) DO UPDATE SET\n claim_host_id = excluded.claim_host_id,\n claim_pid = excluded.claim_pid,\n claim_nonce = excluded.claim_nonce,\n claimed_at_ms = excluded.claimed_at_ms\n WHERE flows_consensus_leases.claim_host_id IS NULL\n AND flows_consensus_leases.owner_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n // The upsert only misses on a conflicting row, so the lease exists and\n // holds a claim, an owner, or both.\n const lease = (yield* leaseOf(runId))[0]!\n return lease.claim_host_id !== null ? rejected(\"already_claimed\") : rejected(\"owner_held\")\n }))\n )\n\n const activate: Service[\"activate\"] = Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n owner_host_id = ${owner.hostId},\n owner_pid = ${owner.pid},\n owner_nonce = ${owner.nonce},\n granted_at_ms = ${grantedAtMs},\n heartbeat_at_ms = ${nowMs},\n claim_host_id = NULL,\n claim_pid = NULL,\n claim_nonce = NULL,\n claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n RETURNING run_id\n `\n return (rows.length > 0 ? activated : lost) satisfies ActivateOutcome\n }))\n )\n\n const heartbeat: Service[\"heartbeat\"] = Effect.fn(\"Consensus.heartbeat\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // Monotonic: a pulse delayed past a newer one from the same owner never\n // moves the lease backwards and never makes a live run look stale.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const reconfirm: Service[\"reconfirm\"] = Effect.fn(\"Consensus.reconfirm\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // A pending steal has already reserved the lease, even before activation.\n // Compare both owner and claim in the same update as the renewal.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n AND claim_host_id IS NULL\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const release: Service[\"release\"] = Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n yield* sql`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n `\n yield* sql`\n UPDATE flows_consensus_leases\n SET owner_host_id = NULL, owner_pid = NULL, owner_nonce = NULL,\n granted_at_ms = NULL, heartbeat_at_ms = NULL\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n yield* prune(runId)\n }))\n )\n\n const steal: Service[\"steal\"] = Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<ClaimOutcome, ConsensusError> => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n claim_host_id = ${claimant.hostId},\n claim_pid = ${claimant.pid},\n claim_nonce = ${claimant.nonce},\n claimed_at_ms = ${nowMs}\n WHERE run_id = ${runId}\n AND owner_host_id = ${evidence.expectedOwner.hostId}\n AND owner_pid = ${evidence.expectedOwner.pid}\n AND owner_nonce = ${evidence.expectedOwner.nonce}\n AND heartbeat_at_ms < ${nowMs - staleAfterMs}\n AND claim_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n const lease = (yield* leaseOf(runId))[0]\n if (lease !== undefined && lease.claim_host_id !== null) return rejected(\"already_claimed\")\n if (\n lease === undefined ||\n lease.owner_host_id !== evidence.expectedOwner.hostId ||\n Number(lease.owner_pid) !== evidence.expectedOwner.pid ||\n lease.owner_nonce !== evidence.expectedOwner.nonce\n ) {\n // A run nobody owns, or one owned by somebody else, has no owner\n // this evidence could disprove.\n return rejected(\"evidence_invalid\")\n }\n return rejected(\"owner_live\")\n }))\n })\n )\n\n const recover: Service[\"recover\"] = Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<RecoverOutcome, ConsensusError> => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n AND claimed_at_ms < ${nowMs - staleAfterMs}\n RETURNING run_id\n `\n if (rows.length > 0) {\n yield* prune(runId)\n return recovered\n }\n const matches = yield* sql<{ readonly run_id: string }>`\n SELECT run_id FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n `\n // The exact claim survived the compare-and-swap only because it is\n // not yet stale; anything else means the claim moved on.\n return matches.length > 0 ? rejected(\"claim_fresh\") : rejected(\"claim_changed\")\n }))\n })\n )\n\n const guard: Service[\"guard\"] = Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n const held = yield* sql<{ readonly ok: number }>`\n SELECT 1 AS ok FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n if (held.length === 0) {\n return yield* Effect.fail(fenceLost(runId, owner))\n }\n }))\n )\n\n return Consensus.of({ claim, activate, heartbeat, reconfirm, release, steal, recover, guard })\n})\n\n/**\n * Provides the database-backed strategy.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<Consensus, never, DurableWriter | SqlClient.SqlClient> = Layer.effect(Consensus, make)\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBA,cAAyB;AACzB,2BAA8B;AAC9B,eAA0B;AAC1B,aAAwB;AACxB,YAAuB;AACvB,gBAA2B;AAC3B,uBAe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MAAM,KAAK;AAAA;AAEnC,UAAI,KAAK,WAAW,GAAG;AACrB,eAAO,OAAO,OAAO,SAAK,4BAAU,OAAO,KAAK,CAAC;AAAA,MACnD;AAAA,IACF,CAAC,CAAC;AAAA,EACJ;AAEA,SAAO,2BAAU,GAAG,EAAE,OAAO,UAAU,WAAW,WAAW,SAAS,OAAO,SAAS,MAAM,CAAC;AAC/F,CAAC;AAQM,MAAM,QAA4E,MAAM,OAAO,4BAAW,IAAI;",
4
+ "sourcesContent": ["/**\n * The default database-backed consensus strategy.\n *\n * This is the run store's former `flows_runs` ownership compare-and-swap\n * relocated: the owner tuple, the two-phase claim columns, claim recovery, and\n * the grant timestamp are the private schema of one strategy \u2014 the\n * `flows_consensus_leases` table \u2014 instead of a public contract on the run\n * row. The run row still mirrors the outcome, but the lease is what\n * arbitrates.\n *\n * Commit-time admission (R3) is exact: `guard` is a plain SELECT that joins\n * the caller's open write transaction \u2014 `DurableWriter` serializes write\n * transactions, so no reclaim can commit between the guard read and the\n * statements beside it \u2014 and every mutating operation runs through\n * `DurableWriter.write`, joining an enclosing transaction as a savepoint.\n * Prior art: Temporal's shard `rangeID` check\n * (`reference/temporal/service/history/shard/context_impl.go`,\n * `renewRangeLocked`).\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n *\n * @since 1.0.0\n */\n\nimport * as Dialect from \"@smthrs/database/Dialect\"\nimport { DurableWriter } from \"@smthrs/database/DurableWriter\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as SqlClient from \"effect/sql/SqlClient\"\nimport {\n type ActivateOutcome,\n type Claimed,\n type ClaimOutcome,\n Consensus,\n ConsensusError,\n fenceLost,\n type HeartbeatOutcome,\n heartbeatStaleAfter,\n type LivenessEvidence,\n matchesEvidence,\n provesDeath,\n type RecoverOutcome,\n type Rejected,\n type RejectionReason,\n type Service\n} from \"./Consensus.ts\"\nimport type { OwnerId } from \"./OwnerId.ts\"\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost = { _tag: \"Lost\" } as const\nconst activated = { _tag: \"Activated\" } as const\nconst recovered = { _tag: \"Recovered\" } as const\n\ninterface LeaseRow {\n readonly owner_host_id: string | null\n readonly owner_pid: number | null\n readonly owner_nonce: string | null\n readonly claim_host_id: string | null\n readonly claim_pid: number | null\n readonly claim_nonce: string | null\n}\n\n/**\n * Constructs the database-backed strategy over the context's SQL client and\n * durable writer.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect.Effect<Service, never, DurableWriter | SqlClient.SqlClient> = Effect.gen(function*() {\n const sql = yield* Effect.service(SqlClient.SqlClient)\n const writer = yield* DurableWriter\n\n const strategyError = (cause: unknown): ConsensusError =>\n new ConsensusError({\n code: \"persistence_failed\",\n message: \"consensus lease operation failed\",\n cause\n })\n\n // The original cause is preserved through the wrapper so an enclosing\n // `DurableWriter.write`'s retry classification still sees a transient\n // conflict raised by a savepoint-nested lease statement.\n const write = <A>(\n body: Effect.Effect<A, unknown>\n ): Effect.Effect<A, ConsensusError> =>\n writer.write(body).pipe(Effect.mapError((cause) => cause instanceof ConsensusError ? cause : strategyError(cause)))\n\n const leaseOf = (runId: string) =>\n sql<LeaseRow>`\n SELECT owner_host_id, owner_pid, owner_nonce, claim_host_id, claim_pid, claim_nonce\n FROM flows_consensus_leases\n WHERE run_id = ${runId}\n `\n\n const prune = (runId: string) =>\n sql`\n DELETE FROM flows_consensus_leases\n WHERE run_id = ${runId} AND owner_host_id IS NULL AND claim_host_id IS NULL\n `\n\n const claim: Service[\"claim\"] = Effect.fn(\"Consensus.claim\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n INSERT INTO flows_consensus_leases (run_id, claim_host_id, claim_pid, claim_nonce, claimed_at_ms)\n VALUES (${runId}, ${claimant.hostId}, ${claimant.pid}, ${claimant.nonce}, ${nowMs})\n ON CONFLICT (run_id) DO UPDATE SET\n claim_host_id = excluded.claim_host_id,\n claim_pid = excluded.claim_pid,\n claim_nonce = excluded.claim_nonce,\n claimed_at_ms = excluded.claimed_at_ms\n WHERE flows_consensus_leases.claim_host_id IS NULL\n AND flows_consensus_leases.owner_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n // The upsert only misses on a conflicting row, so the lease exists and\n // holds a claim, an owner, or both.\n const lease = (yield* leaseOf(runId))[0]!\n return lease.claim_host_id !== null ? rejected(\"already_claimed\") : rejected(\"owner_held\")\n }))\n )\n\n const activate: Service[\"activate\"] = Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n owner_host_id = ${owner.hostId},\n owner_pid = ${owner.pid},\n owner_nonce = ${owner.nonce},\n granted_at_ms = ${grantedAtMs},\n heartbeat_at_ms = ${nowMs},\n claim_host_id = NULL,\n claim_pid = NULL,\n claim_nonce = NULL,\n claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n RETURNING run_id\n `\n return (rows.length > 0 ? activated : lost) satisfies ActivateOutcome\n }))\n )\n\n const heartbeat: Service[\"heartbeat\"] = Effect.fn(\"Consensus.heartbeat\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // Monotonic: a pulse delayed past a newer one from the same owner never\n // moves the lease backwards and never makes a live run look stale.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const reconfirm: Service[\"reconfirm\"] = Effect.fn(\"Consensus.reconfirm\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // A pending steal has already reserved the lease, even before activation.\n // Compare both owner and claim in the same update as the renewal.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n AND claim_host_id IS NULL\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const release: Service[\"release\"] = Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n yield* sql`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n `\n yield* sql`\n UPDATE flows_consensus_leases\n SET owner_host_id = NULL, owner_pid = NULL, owner_nonce = NULL,\n granted_at_ms = NULL, heartbeat_at_ms = NULL\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n yield* prune(runId)\n }))\n )\n\n const steal: Service[\"steal\"] = Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<ClaimOutcome, ConsensusError> => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n claim_host_id = ${claimant.hostId},\n claim_pid = ${claimant.pid},\n claim_nonce = ${claimant.nonce},\n claimed_at_ms = ${nowMs}\n WHERE run_id = ${runId}\n AND owner_host_id = ${evidence.expectedOwner.hostId}\n AND owner_pid = ${evidence.expectedOwner.pid}\n AND owner_nonce = ${evidence.expectedOwner.nonce}\n AND ${provesDeath(evidence, claimant) ? sql`TRUE` : sql`heartbeat_at_ms < ${nowMs - staleAfterMs}`}\n AND claim_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n const lease = (yield* leaseOf(runId))[0]\n if (lease !== undefined && lease.claim_host_id !== null) return rejected(\"already_claimed\")\n if (\n lease === undefined ||\n lease.owner_host_id !== evidence.expectedOwner.hostId ||\n Number(lease.owner_pid) !== evidence.expectedOwner.pid ||\n lease.owner_nonce !== evidence.expectedOwner.nonce\n ) {\n // A run nobody owns, or one owned by somebody else, has no owner\n // this evidence could disprove.\n return rejected(\"evidence_invalid\")\n }\n return rejected(\"owner_live\")\n }))\n })\n )\n\n const recover: Service[\"recover\"] = Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<RecoverOutcome, ConsensusError> => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n AND claimed_at_ms < ${nowMs - staleAfterMs}\n RETURNING run_id\n `\n if (rows.length > 0) {\n yield* prune(runId)\n return recovered\n }\n const matches = yield* sql<{ readonly run_id: string }>`\n SELECT run_id FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n `\n // The exact claim survived the compare-and-swap only because it is\n // not yet stale; anything else means the claim moved on.\n return matches.length > 0 ? rejected(\"claim_fresh\") : rejected(\"claim_changed\")\n }))\n })\n )\n\n const guard: Service[\"guard\"] = Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n const held = yield* sql<{ readonly ok: number }>`\n SELECT 1 AS ok FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n if (held.length === 0) {\n return yield* Effect.fail(fenceLost(runId, owner))\n }\n }))\n )\n\n return Consensus.of({ claim, activate, heartbeat, reconfirm, release, steal, recover, guard })\n})\n\n/**\n * Provides the database-backed strategy.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<Consensus, never, DurableWriter | SqlClient.SqlClient> = Layer.effect(Consensus, make)\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBA,cAAyB;AAC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OAAO,IAAI,aAAY;AAC3B,YAAM,OAAO,OAAO;AAAA;AAAA,yBAED,KAAK;AAAA,gCACE,MAAM,MAAM;AAAA,4BAChB,MAAM,GAAG;AAAA,8BACP,MAAM,KAAK;AAAA;AAEnC,UAAI,KAAK,WAAW,GAAG;AACrB,eAAO,OAAO,OAAO,SAAK,4BAAU,OAAO,KAAK,CAAC;AAAA,MACnD;AAAA,IACF,CAAC,CAAC;AAAA,EACJ;AAEA,SAAO,2BAAU,GAAG,EAAE,OAAO,UAAU,WAAW,WAAW,SAAS,OAAO,SAAS,MAAM,CAAC;AAC/F,CAAC;AAQM,MAAM,QAA4E,MAAM,OAAO,4BAAW,IAAI;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/test/Notifying.ts"],
4
- "sourcesContent": ["/**\n * Effect-native analogue of Bazel Skyframe's `NotifyingHelper` and\n * `NotifyingInMemoryGraph`: wrap a record-of-Effect-methods service so a listener hook fires around\n * every operation. The hook runs in the calling fiber, so a hook that dies,\n * interrupts, or awaits a `Latch` injects crashes, fence loss, and exact\n * sequencing at any durable transition point, the mechanism that makes\n * interstitial interleaving bugs testable at all.\n *\n * Deliberately NOT ported from Skyframe: `DeterministicHelper`'s\n * deterministic-scheduler machinery, `ChainedFunction`, and `TrackingAwaiter`.\n * Effect already gives us deterministic fibers, `TestClock`, `Latch`, and\n * failure propagation across fiber joins, so those helpers have no residue\n * here.\n *\n * @since 0.1.0\n */\n\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\n\n/**\n * Whether the hook is firing before or after the delegated operation.\n * Skyframe's `NotifyingHelper.Order`, minus its `BEFORE_AND_AFTER` (pass the\n * same hook body for both firings instead).\n *\n * @category models\n * @since 0.1.0\n */\nexport type Order = \"before\" | \"after\"\n\n/**\n * Listener invoked around every delegated operation. `op` is the service\n * method name (Skyframe's `EventType`, but open-world), `args` the call\n * arguments. Express crash injection as `Effect.die` or `Effect.interrupt`\n * inside the hook, the hook's type stays `Effect<void>` so the wrapped\n * service is structurally identical to the real one.\n *\n * The `after` firing only happens when the operation succeeds; a failed\n * operation already is the interesting event.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Hook = (\n op: string,\n order: Order,\n args: ReadonlyArray<unknown>\n) => Effect.Effect<void>\n\n/**\n * Wraps a service so `hook(op, \"before\" | \"after\", args)` fires around every\n * Effect-valued operation, delegating to the real implementation in between.\n *\n * Generic over any record-of-Effect-methods service (`Journal`, `CacheStore`,\n * `AttemptStore`, `RunStore`, ...): Effect-returning methods and plain Effect\n * properties are hooked; non-Effect members (e.g. `Stream`-returning methods)\n * delegate untouched.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const wrap = <S extends object>(service: S, hook: Hook): S => {\n const wrapped: Record<string, unknown> = {}\n for (const key of Object.keys(service)) {\n const value = (service as Record<string, unknown>)[key]\n if (Effect.isEffect(value)) {\n wrapped[key] = hook(key, \"before\", []).pipe(\n Effect.andThen(value as Effect.Effect<unknown, unknown, unknown>),\n Effect.tap(() => hook(key, \"after\", []))\n )\n } else if (typeof value === \"function\") {\n const method = value as (...args: Array<unknown>) => unknown\n wrapped[key] = (...args: Array<unknown>) => {\n const result = method.apply(service, args)\n return Effect.isEffect(result)\n ? hook(key, \"before\", args).pipe(\n Effect.andThen(result as Effect.Effect<unknown, unknown, unknown>),\n Effect.tap(() => hook(key, \"after\", args))\n )\n : result\n }\n } else {\n wrapped[key] = value\n }\n }\n return wrapped as S\n}\n\n/**\n * Layer form of {@link wrap}: reads the real service from the environment and\n * re-provides the notifying wrapper under the same key, so an existing stack\n * gains a listener without touching its construction.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer = <Id, S extends object>(\n tag: Context.Key<Id, S>,\n hook: Hook\n): Layer.Layer<Id, never, Id> => Layer.effect(tag)(Effect.map(tag, (service) => wrap(service, hook)))\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,aAAwB;AACxB,YAAuB;AA2ChB,MAAM,OAAO,CAAmB,SAAY,SAAkB;AACnE,QAAM,UAAmC,CAAC;AAC1C,aAAW,OAAO,OAAO,KAAK,OAAO,GAAG;AACtC,UAAM,QAAS,QAAoC,GAAG;AACtD,QAAI,OAAO,SAAS,KAAK,GAAG;AAC1B,cAAQ,GAAG,IAAI,KAAK,KAAK,UAAU,CAAC,CAAC,EAAE;AAAA,QACrC,OAAO,QAAQ,KAAiD;AAAA,QAChE,OAAO,IAAI,MAAM,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;AAAA,MACzC;AAAA,IACF,WAAW,OAAO,UAAU,YAAY;AACtC,YAAM,SAAS;AACf,cAAQ,GAAG,IAAI,IAAI,SAAyB;AAC1C,cAAM,SAAS,OAAO,MAAM,SAAS,IAAI;AACzC,eAAO,OAAO,SAAS,MAAM,IACzB,KAAK,KAAK,UAAU,IAAI,EAAE;AAAA,UAC1B,OAAO,QAAQ,MAAkD;AAAA,UACjE,OAAO,IAAI,MAAM,KAAK,KAAK,SAAS,IAAI,CAAC;AAAA,QAC3C,IACE;AAAA,MACN;AAAA,IACF,OAAO;AACL,cAAQ,GAAG,IAAI;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;AAUO,MAAM,QAAQ,CACnB,KACA,SAC+B,MAAM,OAAO,GAAG,EAAE,OAAO,IAAI,KAAK,CAAC,YAAY,KAAK,SAAS,IAAI,CAAC,CAAC;",
4
+ "sourcesContent": ["/**\n * Effect-native analogue of Bazel Skyframe's `NotifyingHelper` and\n * `NotifyingInMemoryGraph`: wrap a record-of-Effect-methods service so a listener hook fires around\n * every operation. The hook runs in the calling fiber, so a hook that dies,\n * interrupts, or awaits a `Latch` injects crashes, fence loss, and exact\n * sequencing at any durable transition point, the mechanism that makes\n * interstitial interleaving bugs testable at all.\n *\n * Deliberately NOT ported from Skyframe: `DeterministicHelper`'s\n * deterministic-scheduler machinery, `ChainedFunction`, and `TrackingAwaiter`.\n * Effect already gives us deterministic fibers, `TestClock`, `Latch`, and\n * failure propagation across fiber joins, so those helpers have no residue\n * here.\n *\n * @since 0.1.0\n */\n\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\n\n/**\n * Whether the hook is firing before or after the delegated operation.\n * Skyframe's `NotifyingHelper.Order`, minus its `BEFORE_AND_AFTER` (pass the\n * same hook body for both firings instead).\n *\n * @category models\n * @since 0.1.0\n */\nexport type Order = \"before\" | \"after\"\n\n/**\n * Listener invoked around every delegated operation. `op` is the service\n * method name (Skyframe's `EventType`, but open-world), `args` the call\n * arguments. Express crash injection as `Effect.die` or `Effect.interrupt`\n * inside the hook, the hook's type stays `Effect<void>` so the wrapped\n * service is structurally identical to the real one.\n *\n * The `after` firing only happens when the operation succeeds; a failed\n * operation already is the interesting event.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Hook = (\n op: string,\n order: Order,\n args: ReadonlyArray<unknown>\n) => Effect.Effect<void>\n\n/**\n * Wraps a service so `hook(op, \"before\" | \"after\", args)` fires around every\n * Effect-valued operation, delegating to the real implementation in between.\n *\n * Generic over any record-of-Effect-methods service (`Journal`, `CacheStore`,\n * `AttemptStore`, `RunStore`, ...): Effect-returning methods and plain Effect\n * properties are hooked; non-Effect members (e.g. `Stream`-returning methods)\n * delegate untouched.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const wrap = <S extends object>(service: S, hook: Hook): S => {\n const wrapped: Record<string, unknown> = {}\n for (const key of Object.keys(service)) {\n const value = (service as Record<string, unknown>)[key]\n if (Effect.isEffect(value)) {\n wrapped[key] = hook(key, \"before\", []).pipe(\n Effect.andThen(value),\n Effect.tap(() => hook(key, \"after\", []))\n )\n } else if (typeof value === \"function\") {\n const method = value as (...args: Array<unknown>) => unknown\n wrapped[key] = (...args: Array<unknown>) => {\n const result = method.apply(service, args)\n return Effect.isEffect(result)\n ? hook(key, \"before\", args).pipe(\n Effect.andThen(result),\n Effect.tap(() => hook(key, \"after\", args))\n )\n : result\n }\n } else {\n wrapped[key] = value\n }\n }\n return wrapped as S\n}\n\n/**\n * Layer form of {@link wrap}: reads the real service from the environment and\n * re-provides the notifying wrapper under the same key, so an existing stack\n * gains a listener without touching its construction.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer = <Id, S extends object>(\n tag: Context.Key<Id, S>,\n hook: Hook\n): Layer.Layer<Id, never, Id> => Layer.effect(tag)(Effect.map(tag, (service) => wrap(service, hook)))\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,aAAwB;AACxB,YAAuB;AA2ChB,MAAM,OAAO,CAAmB,SAAY,SAAkB;AACnE,QAAM,UAAmC,CAAC;AAC1C,aAAW,OAAO,OAAO,KAAK,OAAO,GAAG;AACtC,UAAM,QAAS,QAAoC,GAAG;AACtD,QAAI,OAAO,SAAS,KAAK,GAAG;AAC1B,cAAQ,GAAG,IAAI,KAAK,KAAK,UAAU,CAAC,CAAC,EAAE;AAAA,QACrC,OAAO,QAAQ,KAAK;AAAA,QACpB,OAAO,IAAI,MAAM,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;AAAA,MACzC;AAAA,IACF,WAAW,OAAO,UAAU,YAAY;AACtC,YAAM,SAAS;AACf,cAAQ,GAAG,IAAI,IAAI,SAAyB;AAC1C,cAAM,SAAS,OAAO,MAAM,SAAS,IAAI;AACzC,eAAO,OAAO,SAAS,MAAM,IACzB,KAAK,KAAK,UAAU,IAAI,EAAE;AAAA,UAC1B,OAAO,QAAQ,MAAM;AAAA,UACrB,OAAO,IAAI,MAAM,KAAK,KAAK,SAAS,IAAI,CAAC;AAAA,QAC3C,IACE;AAAA,MACN;AAAA,IACF,OAAO;AACL,cAAQ,GAAG,IAAI;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;AAUO,MAAM,QAAQ,CACnB,KACA,SAC+B,MAAM,OAAO,GAAG,EAAE,OAAO,IAAI,KAAK,CAAC,YAAY,KAAK,SAAS,IAAI,CAAC,CAAC;",
6
6
  "names": []
7
7
  }
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * The journal owns the consensus rules — single writer per run, fenced and
5
5
  * unfenced appends, commit-time admission, the generation fence, and steal
6
- * only on staleness plus liveness evidence — and this service is how a deployment chooses *how* those rules are
6
+ * only on staleness plus liveness evidence, or on a same-host probe that
7
+ * proves the owner's process gone — and this service is how a deployment chooses *how* those rules are
7
8
  * arbitrated: where the lease lives, how liveness is probed, and how the
8
9
  * fence is checked at commit time. `Consensus` lives here beside `OwnerId`
9
10
  * for the same reason `OwnerId` does: the journal is what it fences.
@@ -105,7 +106,8 @@ export declare const heartbeatWriteTolerance: Duration.Duration;
105
106
  * strategy can check for itself, and `steal` checks it: the takeover refuses
106
107
  * any lease whose heartbeat is still inside the window. It is therefore
107
108
  * accepted from a claimant on any host, while the other two stay bound to the
108
- * host relation that makes them meaningful. The observation must carry the
109
+ * host relation that makes them meaningful. `same-host-pid-dead` alone also
110
+ * admits a steal inside the window; see {@link provesDeath}. The observation must carry the
109
111
  * exact instant supplied to the consuming operation: `checkedAtMs` must equal
110
112
  * that operation's `nowMs`. A caller that probes at T and calls at T+1 is
111
113
  * refused and must build fresh evidence.
@@ -149,6 +151,32 @@ export declare const sameOwner: (left: OwnerId, right: OwnerId) => boolean;
149
151
  * @category predicates
150
152
  */
151
153
  export declare const matchesEvidence: (expectedOwner: OwnerId, observer: OwnerId, nowMs: number, evidence: LivenessEvidence) => boolean;
154
+ /**
155
+ * Whether evidence proves the owner gone, so a steal need not wait for its
156
+ * lease to go stale.
157
+ *
158
+ * The lease stands in for a question a peer cannot ask directly: is the owner
159
+ * still running? A `same-host-pid-dead` probe asks it. The claimant read its
160
+ * own host's process table and found no process behind the owner's pid, and a
161
+ * process that does not exist renews no lease and writes nothing, so waiting
162
+ * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with
163
+ * `SIGKILL` is therefore reclaimed by the next process on the same host at
164
+ * once.
165
+ *
166
+ * The evidence must still pass {@link matchesEvidence}, which binds the kind
167
+ * to the same host. One more case is excluded here: an owner recorded with the
168
+ * claimant's own pid names the claimant's process, which is running, so a
169
+ * probe of that pid cannot report it gone. Such evidence keeps the staleness
170
+ * cutoff.
171
+ *
172
+ * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a
173
+ * judgement about a host this process cannot inspect, and `lease-expired` is
174
+ * the cutoff itself.
175
+ *
176
+ * @since 1.0.0
177
+ * @category predicates
178
+ */
179
+ export declare const provesDeath: (evidence: LivenessEvidence, claimant: OwnerId) => boolean;
152
180
  /**
153
181
  * Why a strategy refused a claim, steal, or recovery.
154
182
  *
@@ -1 +1 @@
1
- {"version":3,"file":"Consensus.d.ts","sourceRoot":"","sources":["../../src/Consensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAEtC;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,EAAE,QAAQ,CAAC,QAA8B,CAAA;AAEvE;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,QAA+B,CAAA;AAE1E;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,QAA+B,CAAA;AAE7E;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,QAI9C,CAAA;AAID;;;;;;;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KG;AACH,eAAO,MAAM,SAAS,GAAI,YAAW,OAAO,CAAC,OAAO,CAAM,KAAG,KAAK,CAAC,KAAK,CAAC,SAAS,CACnC,CAAA;AAO/C;;;;;GAKG;AACH,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAoI3C,CAAA;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,CAAsC,CAAA"}
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * The journal owns the consensus rules — single writer per run, fenced and
5
5
  * unfenced appends, commit-time admission, the generation fence, and steal
6
- * only on staleness plus liveness evidence — and this service is how a deployment chooses *how* those rules are
6
+ * only on staleness plus liveness evidence, or on a same-host probe that
7
+ * proves the owner's process gone — and this service is how a deployment chooses *how* those rules are
7
8
  * arbitrated: where the lease lives, how liveness is probed, and how the
8
9
  * fence is checked at commit time. `Consensus` lives here beside `OwnerId`
9
10
  * for the same reason `OwnerId` does: the journal is what it fences.
@@ -108,7 +109,8 @@ const staleAfterMs = Duration.toMillis(heartbeatStaleAfter);
108
109
  * strategy can check for itself, and `steal` checks it: the takeover refuses
109
110
  * any lease whose heartbeat is still inside the window. It is therefore
110
111
  * accepted from a claimant on any host, while the other two stay bound to the
111
- * host relation that makes them meaningful. The observation must carry the
112
+ * host relation that makes them meaningful. `same-host-pid-dead` alone also
113
+ * admits a steal inside the window; see {@link provesDeath}. The observation must carry the
112
114
  * exact instant supplied to the consuming operation: `checkedAtMs` must equal
113
115
  * that operation's `nowMs`. A caller that probes at T and calls at T+1 is
114
116
  * refused and must build fresh evidence.
@@ -157,6 +159,32 @@ export const matchesEvidence = (expectedOwner, observer, nowMs, evidence) => {
157
159
  return true;
158
160
  }
159
161
  };
162
+ /**
163
+ * Whether evidence proves the owner gone, so a steal need not wait for its
164
+ * lease to go stale.
165
+ *
166
+ * The lease stands in for a question a peer cannot ask directly: is the owner
167
+ * still running? A `same-host-pid-dead` probe asks it. The claimant read its
168
+ * own host's process table and found no process behind the owner's pid, and a
169
+ * process that does not exist renews no lease and writes nothing, so waiting
170
+ * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with
171
+ * `SIGKILL` is therefore reclaimed by the next process on the same host at
172
+ * once.
173
+ *
174
+ * The evidence must still pass {@link matchesEvidence}, which binds the kind
175
+ * to the same host. One more case is excluded here: an owner recorded with the
176
+ * claimant's own pid names the claimant's process, which is running, so a
177
+ * probe of that pid cannot report it gone. Such evidence keeps the staleness
178
+ * cutoff.
179
+ *
180
+ * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a
181
+ * judgement about a host this process cannot inspect, and `lease-expired` is
182
+ * the cutoff itself.
183
+ *
184
+ * @since 1.0.0
185
+ * @category predicates
186
+ */
187
+ export const provesDeath = (evidence, claimant) => evidence.kind === "same-host-pid-dead" && evidence.expectedOwner.pid !== claimant.pid;
160
188
  /**
161
189
  * Why a strategy refused a claim, steal, or recovery.
162
190
  *
@@ -403,8 +431,9 @@ export const makeLocal = Effect.sync(() => {
403
431
  if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {
404
432
  return rejected("evidence_invalid");
405
433
  }
406
- if (lease.owner.heartbeatAtMs >= nowMs - staleAfterMs)
434
+ if (!provesDeath(evidence, claimant) && lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) {
407
435
  return rejected("owner_live");
436
+ }
408
437
  lease.claim = { id: claimant, claimedAtMs: nowMs };
409
438
  return claimed(nowMs);
410
439
  })),
@@ -1 +1 @@
1
- {"version":3,"file":"Consensus.js","sourceRoot":"","sources":["../../src/Consensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK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AAC,CAAA;YAC/B,IACE,KAAK,EAAE,KAAK,KAAK,SAAS;gBAC1B,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,EAAE,aAAa,CAAC;gBACzC,KAAK,CAAC,KAAK,CAAC,WAAW,KAAK,WAAW,EACvC,CAAC;gBACD,OAAO,QAAQ,CAAC,eAAe,CAAC,CAAA;YAClC,CAAC;YACD,IAAI,KAAK,CAAC,KAAK,CAAC,WAAW,IAAI,KAAK,GAAG,YAAY;gBAAE,OAAO,QAAQ,CAAC,aAAa,CAAC,CAAA;YACnF,KAAK,CAAC,KAAK,GAAG,SAAS,CAAA;YACvB,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;YACnB,OAAO,SAAS,CAAA;QAClB,CAAC,CAAC,CACH;QACD,KAAK,EAAE,MAAM,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,KAAa,EAAE,KAAc,EAAE,EAAE,CACpE,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE;YAClB,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;YAC/B,OAAO,KAAK,EAAE,KAAK,KAAK,SAAS,IAAI,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC;gBACnE,CAAC,CAAC,MAAM,CAAC,IAAI;gBACb,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAA;QAC1C,CAAC,CAAC,CACH;KACF,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,UAAU,GAA2B,KAAK,CAAC,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA","sourcesContent":["/**\n * The injectable consensus strategy arbitrating the journal's ownership rules.\n *\n * The journal owns the consensus rules — single writer per run, fenced and\n * unfenced appends, commit-time admission, the generation fence, and steal\n * only on staleness plus liveness evidence — and this service is how a deployment chooses *how* those rules are\n * arbitrated: where the lease lives, how liveness is probed, and how the\n * fence is checked at commit time. `Consensus` lives here beside `OwnerId`\n * for the same reason `OwnerId` does: the journal is what it fences.\n * `@smthrs/run-store`'s `Ownership` keeps its public API and rules but\n * delegates arbitration to this strategy.\n *\n * Every operation that reasons about staleness takes the caller's clock\n * reading (`nowMs`) rather than reading a clock itself: staleness (R5) and\n * the monotonic lease stamp are defined against the arbitrating caller's\n * reading, exactly as `RunStore`'s compare-and-swap operations always were,\n * so the recorded lease never differs from the outcome the caller observed.\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n * Rule constants and their provenance:\n * `packages/smithers/flows/run-store/docs/concepts/leases.md`.\n *\n * Prior art: Effect `EventJournal` (`reference/effect` `unstable/eventlog`)\n * resolves multi-writer by merge with conflict surfacing; driving a run is not\n * mergeable, so this surface deviates to exclusive-writer admission. The\n * fencing and generation semantics follow Temporal's shard `rangeID`\n * (`reference/temporal/service/history/shard/context_impl.go`).\n *\n * @since 1.0.0\n */\n\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport { OwnerId } from \"./OwnerId.ts\"\n\n/**\n * How often the supervision loop pulses to renew the owner's lease.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatInterval: Duration.Duration = Duration.seconds(1)\n\n/**\n * How old a persisted heartbeat must be before a peer may steal the run.\n * Every strategy judges R5 staleness against this one definition.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatStaleAfter: Duration.Duration = Duration.seconds(30)\n\n/**\n * How far the owner's wall clock may run behind a peer's before the lease\n * reasoning stops holding.\n *\n * The owner stamps its heartbeat from *its* clock and a would-be stealer\n * compares that stamp against *its own*, so the two hosts' clock offset is\n * subtracted directly from the owner's real safety margin. This constant names\n * that allowance instead of leaving it implicit in a \"two ticks\" arithmetic\n * accident, and it is a budgeted allowance, not a guarantee: see\n * {@link heartbeatWriteTolerance} for what happens once it is exceeded.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatSkewAllowance: Duration.Duration = Duration.seconds(10)\n\n/**\n * How long heartbeat writes may go unconfirmed before ownership must be reconfirmed.\n *\n * A peer judges staleness by the persisted heartbeat and may steal the run the\n * instant it is {@link heartbeatStaleAfter} old, so an owner that tolerated\n * write failures for exactly that long would still be executing side effects\n * when the steal is admitted. The budget is therefore\n * {@link heartbeatStaleAfter} minus {@link heartbeatSkewAllowance} (the peer's\n * clock may already read that much later than the owner's) minus one\n * {@link heartbeatInterval} (reserved for one bounded compare-and-swap\n * reconfirmation before the owner interrupts).\n *\n * This bounds, but does not eliminate, overlap. Beyond\n * {@link heartbeatSkewAllowance} of clock offset a peer can be admitted while\n * the old owner is still running. *Durable* writes stay safe regardless — they\n * are fenced by the strategy's commit-time admission, so the displaced owner's\n * writes fail rather than corrupt. Non-durable external side effects (an HTTP\n * call, a spawned process) can genuinely overlap. That is inherent to any\n * wall-clock lease and is stated here rather than asserted away; a caller that\n * cannot tolerate any overlap needs an external fencing token at the side\n * effect itself, not a larger timeout.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatWriteTolerance: Duration.Duration = Duration.millis(\n Duration.toMillis(heartbeatStaleAfter) -\n Duration.toMillis(heartbeatSkewAllowance) -\n Duration.toMillis(heartbeatInterval)\n)\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\n/**\n * Evidence that the owner in an exact run snapshot is no longer live.\n *\n * Defined here because R5 — steal requires staleness plus liveness evidence —\n * is a consensus rule every strategy validates. `@smthrs/run-store`'s\n * `Ownership` re-exports it alongside the probes that mint it.\n *\n * Two of the three kinds are collected outside the strategy:\n * `same-host-pid-dead` is a local process probe, and\n * `cross-host-unreachable-stale` is a reachability judgement the deployment\n * makes. `lease-expired` is different — it asserts only that the persisted\n * heartbeat is older than the staleness cutoff, which is the one claim a\n * strategy can check for itself, and `steal` checks it: the takeover refuses\n * any lease whose heartbeat is still inside the window. It is therefore\n * accepted from a claimant on any host, while the other two stay bound to the\n * host relation that makes them meaningful. The observation must carry the\n * exact instant supplied to the consuming operation: `checkedAtMs` must equal\n * that operation's `nowMs`. A caller that probes at T and calls at T+1 is\n * refused and must build fresh evidence.\n *\n * @since 1.0.0\n * @category models\n */\nexport const LivenessEvidence = Schema.Struct({\n expectedOwner: OwnerId,\n checkedAtMs: Schema.Number,\n kind: Schema.Literals([\"same-host-pid-dead\", \"cross-host-unreachable-stale\", \"lease-expired\"])\n})\n\n/**\n * Evidence that the owner in an exact run snapshot is no longer live.\n *\n * @since 1.0.0\n * @category models\n */\nexport type LivenessEvidence = typeof LivenessEvidence.Type\n\n/**\n * Structural equality on the process identity tuple.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const sameOwner = (left: OwnerId, right: OwnerId): boolean =>\n left.hostId === right.hostId && left.pid === right.pid && left.nonce === right.nonce\n\n/**\n * Validates liveness evidence against the owner it claims to disprove.\n *\n * The evidence must name the expected owner, carry the observer's current\n * clock reading, and respect the host rule: a `same-host-pid-dead` probe is\n * only meaningful from the same host, a `cross-host-unreachable-stale`\n * observation only from a different one, and `lease-expired` is host-neutral\n * because the strategy verifies the cutoff it names for itself.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const matchesEvidence = (\n expectedOwner: OwnerId,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n): boolean => {\n if (!sameOwner(expectedOwner, evidence.expectedOwner) || evidence.checkedAtMs !== nowMs) return false\n switch (evidence.kind) {\n // A pid means nothing outside the host that owns the process namespace.\n case \"same-host-pid-dead\":\n return expectedOwner.hostId === observer.hostId\n // Unreachability is what a peer host observes; on the owner's own host it\n // would be an unprobed guess dressed as evidence.\n case \"cross-host-unreachable-stale\":\n return expectedOwner.hostId !== observer.hostId\n // The lease is host-neutral, and the strategy verifies the same\n // caller-clock cutoff named by this evidence.\n case \"lease-expired\":\n return true\n }\n}\n\n/**\n * Why a strategy refused a claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport const RejectionReason = Schema.Literals([\n \"already_claimed\",\n \"owner_held\",\n \"owner_live\",\n \"evidence_invalid\",\n \"claim_fresh\",\n \"claim_changed\",\n \"unavailable\"\n])\n\n/**\n * Why a strategy refused a claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport type RejectionReason = typeof RejectionReason.Type\n\n/**\n * A granted claim, carrying the grant timestamp the later activation must\n * present (R4 — the generation fence).\n *\n * @since 1.0.0\n * @category models\n */\nexport const Claimed = Schema.TaggedStruct(\"Claimed\", {\n grantedAtMs: Schema.Number\n})\n\n/**\n * A granted claim.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Claimed = typeof Claimed.Type\n\n/**\n * A refused claim, steal, or recovery, with the strategy's typed reason.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Rejected = Schema.TaggedStruct(\"Rejected\", {\n reason: RejectionReason\n})\n\n/**\n * A refused claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Rejected = typeof Rejected.Type\n\n/**\n * Outcome of `claim` and `steal`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const ClaimOutcome = Schema.Union([Claimed, Rejected])\n\n/**\n * Outcome of `claim` and `steal`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ClaimOutcome = typeof ClaimOutcome.Type\n\n/**\n * A claim promoted to ownership.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Activated = Schema.TaggedStruct(\"Activated\", {})\n\n/**\n * A claim promoted to ownership.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Activated = typeof Activated.Type\n\n/**\n * The claim or lease the caller presented no longer exists.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Lost = Schema.TaggedStruct(\"Lost\", {})\n\n/**\n * The claim or lease the caller presented no longer exists.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Lost = typeof Lost.Type\n\n/**\n * Outcome of `activate`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const ActivateOutcome = Schema.Union([Activated, Lost])\n\n/**\n * Outcome of `activate`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ActivateOutcome = typeof ActivateOutcome.Type\n\n/**\n * A renewed lease, carrying the monotonic heartbeat stamp the strategy\n * recorded — the maximum of the stored stamp and the caller's reading, so a\n * late pulse never moves the lease backwards.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Renewed = Schema.TaggedStruct(\"Renewed\", {\n heartbeatAtMs: Schema.Number\n})\n\n/**\n * A renewed lease.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Renewed = typeof Renewed.Type\n\n/**\n * Outcome of `heartbeat` and `reconfirm`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const HeartbeatOutcome = Schema.Union([Renewed, Lost])\n\n/**\n * Outcome of `heartbeat` and `reconfirm`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type HeartbeatOutcome = typeof HeartbeatOutcome.Type\n\n/**\n * A stale claim cleared after its claimant was proven dead.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Recovered = Schema.TaggedStruct(\"Recovered\", {})\n\n/**\n * A stale claim cleared after its claimant was proven dead.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Recovered = typeof Recovered.Type\n\n/**\n * Outcome of `recover`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const RecoverOutcome = Schema.Union([Recovered, Rejected])\n\n/**\n * Outcome of `recover`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type RecoverOutcome = typeof RecoverOutcome.Type\n\n/**\n * Failure raised by a consensus strategy.\n *\n * `fence_lost` is `guard`'s refusal: the supplied owner no longer holds the\n * run, so the fenced write it joins must not commit. `persistence_failed`\n * wraps a strategy's storage failure; the original cause is preserved so the\n * durable writer's retry classification still sees a transient conflict\n * through the wrapper.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class ConsensusError extends Schema.TaggedError<ConsensusError>()(\"@smthrs/journal/ConsensusError\", {\n code: Schema.Literals([\"fence_lost\", \"persistence_failed\"]),\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown)\n}) {}\n\n/**\n * Consensus operations.\n *\n * The rules being arbitrated are strategy-independent; a strategy\n * chooses where the lease lives and how the fence is checked at commit time.\n * The claim lifecycle is two-phase, exactly as `RunStore`'s always was:\n * `claim` (or `steal`, its evidence-gated form) reserves the run and returns\n * the grant timestamp, `activate` presents that grant to take ownership, and\n * `release` clears whichever of the caller's claim or ownership still stands.\n * `recover` clears a *third party's* stale claim after its claimant was proven\n * dead — the relocated `recoverClaim` mechanic. `guard` is the commit-time\n * admission check (R3) `Journal.emitDurable`, `checkpoint`, and `compact`\n * join: it succeeds while the owner holds the run and fails with `fence_lost`\n * otherwise.\n *\n * Heartbeats and lease state are the strategy's private evidence and never\n * enter the journal.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface Service {\n readonly claim: (\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) => Effect.Effect<ClaimOutcome, ConsensusError>\n readonly activate: (\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) => Effect.Effect<ActivateOutcome, ConsensusError>\n readonly heartbeat: (\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) => Effect.Effect<HeartbeatOutcome, ConsensusError>\n /** Renews only while this owner holds the lease and no takeover claim is pending. */\n readonly reconfirm: (\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) => Effect.Effect<HeartbeatOutcome, ConsensusError>\n readonly release: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>\n readonly steal: (\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) => Effect.Effect<ClaimOutcome, ConsensusError>\n readonly recover: (\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) => Effect.Effect<RecoverOutcome, ConsensusError>\n readonly guard: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>\n}\n\n/**\n * Context service for the injected consensus strategy.\n *\n * @since 1.0.0\n * @category services\n */\nexport class Consensus extends Context.Service<Consensus, Service>()(\"@smthrs/journal/Consensus\") {}\n\n/**\n * Constructs a consensus service from an implementation.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (implementation: Service): Service => Consensus.of(implementation)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost: Lost = { _tag: \"Lost\" }\nconst activated: Activated = { _tag: \"Activated\" }\nconst recovered: Recovered = { _tag: \"Recovered\" }\n\n/**\n * The refusal `guard` raises for an owner that no longer holds the run.\n *\n * @since 1.0.0\n * @category errors\n */\nexport const fenceLost = (runId: string, owner: OwnerId): ConsensusError =>\n new ConsensusError({\n code: \"fence_lost\",\n message: `run ${runId} is no longer owned by ${owner.hostId}:${owner.pid}:${owner.nonce}`\n })\n\n/**\n * Constructs a strategy that arbitrates nothing: claims are refused, leases\n * are never held, and every fenced write is rejected.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const makeNoop = (overrides: Partial<Service> = {}): Service =>\n Consensus.of({\n claim: Effect.fn(\"Consensus.claim\")(() => Effect.succeed(rejected(\"unavailable\"))),\n activate: Effect.fn(\"Consensus.activate\")(() => Effect.succeed(lost)),\n heartbeat: Effect.fn(\"Consensus.heartbeat\")(() => Effect.succeed(lost)),\n reconfirm: Effect.fn(\"Consensus.reconfirm\")(() => Effect.succeed(lost)),\n release: Effect.fn(\"Consensus.release\")(() => Effect.void),\n steal: Effect.fn(\"Consensus.steal\")(() => Effect.succeed(rejected(\"unavailable\"))),\n recover: Effect.fn(\"Consensus.recover\")(() => Effect.succeed(rejected(\"unavailable\"))),\n guard: Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) => Effect.fail(fenceLost(runId, owner))),\n ...overrides\n })\n\n/**\n * Provides the refusing strategy stub.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerNoop = (overrides: Partial<Service> = {}): Layer.Layer<Consensus> =>\n Layer.succeed(Consensus)(makeNoop(overrides))\n\ninterface LocalLease {\n owner: { readonly id: OwnerId; readonly grantedAtMs: number; heartbeatAtMs: number } | undefined\n claim: { readonly id: OwnerId; readonly claimedAtMs: number } | undefined\n}\n\n/**\n * Constructs the in-memory single-process strategy.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const makeLocal: Effect.Effect<Service> = Effect.sync(() => {\n const leases = new Map<string, LocalLease>()\n\n const leaseOf = (runId: string): LocalLease => {\n const existing = leases.get(runId)\n if (existing !== undefined) return existing\n const fresh: LocalLease = { owner: undefined, claim: undefined }\n leases.set(runId, fresh)\n return fresh\n }\n\n const prune = (runId: string, lease: LocalLease): void => {\n if (lease.owner === undefined && lease.claim === undefined) {\n leases.delete(runId)\n }\n }\n\n return Consensus.of({\n claim: Effect.fn(\"Consensus.claim\")((runId: string, claimant: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leaseOf(runId)\n if (lease.claim !== undefined) return rejected(\"already_claimed\")\n if (lease.owner !== undefined) return rejected(\"owner_held\")\n lease.claim = { id: claimant, claimedAtMs: nowMs }\n return claimed(nowMs)\n })\n ),\n activate: Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n Effect.sync(() => {\n const lease = leaseOf(runId)\n if (\n lease.claim === undefined ||\n !sameOwner(lease.claim.id, owner) ||\n lease.claim.claimedAtMs !== grantedAtMs\n ) {\n prune(runId, lease)\n return lost\n }\n lease.claim = undefined\n lease.owner = { id: owner, grantedAtMs, heartbeatAtMs: nowMs }\n return activated\n })\n ),\n heartbeat: Effect.fn(\"Consensus.heartbeat\")((runId: string, owner: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease?.owner === undefined || !sameOwner(lease.owner.id, owner)) return lost\n lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)\n return ({ _tag: \"Renewed\", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)\n })\n ),\n reconfirm: Effect.fn(\"Consensus.reconfirm\")((runId: string, owner: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease?.owner === undefined || lease.claim !== undefined || !sameOwner(lease.owner.id, owner)) return lost\n lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)\n return ({ _tag: \"Renewed\", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)\n })\n ),\n release: Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease === undefined) return\n if (lease.claim !== undefined && sameOwner(lease.claim.id, owner)) {\n lease.claim = undefined\n }\n if (lease.owner !== undefined && sameOwner(lease.owner.id, owner)) {\n lease.owner = undefined\n }\n prune(runId, lease)\n })\n ),\n steal: Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.sync(() => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return rejected(\"evidence_invalid\")\n }\n const lease = leases.get(runId)\n if (lease?.claim !== undefined) return rejected(\"already_claimed\")\n if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {\n return rejected(\"evidence_invalid\")\n }\n if (lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) return rejected(\"owner_live\")\n lease.claim = { id: claimant, claimedAtMs: nowMs }\n return claimed(nowMs)\n })\n ),\n recover: Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.sync(() => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) return rejected(\"evidence_invalid\")\n const lease = leases.get(runId)\n if (\n lease?.claim === undefined ||\n !sameOwner(lease.claim.id, staleClaimant) ||\n lease.claim.claimedAtMs !== grantedAtMs\n ) {\n return rejected(\"claim_changed\")\n }\n if (lease.claim.claimedAtMs >= nowMs - staleAfterMs) return rejected(\"claim_fresh\")\n lease.claim = undefined\n prune(runId, lease)\n return recovered\n })\n ),\n guard: Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n Effect.suspend(() => {\n const lease = leases.get(runId)\n return lease?.owner !== undefined && sameOwner(lease.owner.id, owner)\n ? Effect.void\n : Effect.fail(fenceLost(runId, owner))\n })\n )\n })\n})\n\n/**\n * Provides the in-memory single-process strategy.\n *\n * The lease lives in process memory, so R3 is exact within the process — the\n * strategy's transitions and the serialized append transactions interleave\n * atomically on one event loop — and browser support needs nothing beyond\n * this layer plus the browser-safe journal. State is per layer build: provide\n * one instance to every service that must agree on it, which is what\n * `SqlJournal.layerWith` and `RunStore.layerWith` exist for.\n *\n * The lease is not part of any database transaction: a transition made inside\n * a `Journal.transact` that later rolls back stays applied in memory, so the\n * lease and a rolled-back run row can disagree until the next transition.\n * `SqlConsensus` keeps the two in one transaction; prefer it wherever a\n * database is present.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerLocal: Layer.Layer<Consensus> = Layer.effect(Consensus, makeLocal)\n"]}
1
+ {"version":3,"file":"Consensus.js","sourceRoot":"","sources":["../../src/Consensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAEtC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M,UAAU,GAA2B,KAAK,CAAC,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA","sourcesContent":["/**\n * The injectable consensus strategy arbitrating the journal's ownership rules.\n *\n * The journal owns the consensus rules — single writer per run, fenced and\n * unfenced appends, commit-time admission, the generation fence, and steal\n * only on staleness plus liveness evidence, or on a same-host probe that\n * proves the owner's process gone — and this service is how a deployment chooses *how* those rules are\n * arbitrated: where the lease lives, how liveness is probed, and how the\n * fence is checked at commit time. `Consensus` lives here beside `OwnerId`\n * for the same reason `OwnerId` does: the journal is what it fences.\n * `@smthrs/run-store`'s `Ownership` keeps its public API and rules but\n * delegates arbitration to this strategy.\n *\n * Every operation that reasons about staleness takes the caller's clock\n * reading (`nowMs`) rather than reading a clock itself: staleness (R5) and\n * the monotonic lease stamp are defined against the arbitrating caller's\n * reading, exactly as `RunStore`'s compare-and-swap operations always were,\n * so the recorded lease never differs from the outcome the caller observed.\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n * Rule constants and their provenance:\n * `packages/smithers/flows/run-store/docs/concepts/leases.md`.\n *\n * Prior art: Effect `EventJournal` (`reference/effect` `unstable/eventlog`)\n * resolves multi-writer by merge with conflict surfacing; driving a run is not\n * mergeable, so this surface deviates to exclusive-writer admission. The\n * fencing and generation semantics follow Temporal's shard `rangeID`\n * (`reference/temporal/service/history/shard/context_impl.go`).\n *\n * @since 1.0.0\n */\n\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport { OwnerId } from \"./OwnerId.ts\"\n\n/**\n * How often the supervision loop pulses to renew the owner's lease.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatInterval: Duration.Duration = Duration.seconds(1)\n\n/**\n * How old a persisted heartbeat must be before a peer may steal the run.\n * Every strategy judges R5 staleness against this one definition.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatStaleAfter: Duration.Duration = Duration.seconds(30)\n\n/**\n * How far the owner's wall clock may run behind a peer's before the lease\n * reasoning stops holding.\n *\n * The owner stamps its heartbeat from *its* clock and a would-be stealer\n * compares that stamp against *its own*, so the two hosts' clock offset is\n * subtracted directly from the owner's real safety margin. This constant names\n * that allowance instead of leaving it implicit in a \"two ticks\" arithmetic\n * accident, and it is a budgeted allowance, not a guarantee: see\n * {@link heartbeatWriteTolerance} for what happens once it is exceeded.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatSkewAllowance: Duration.Duration = Duration.seconds(10)\n\n/**\n * How long heartbeat writes may go unconfirmed before ownership must be reconfirmed.\n *\n * A peer judges staleness by the persisted heartbeat and may steal the run the\n * instant it is {@link heartbeatStaleAfter} old, so an owner that tolerated\n * write failures for exactly that long would still be executing side effects\n * when the steal is admitted. The budget is therefore\n * {@link heartbeatStaleAfter} minus {@link heartbeatSkewAllowance} (the peer's\n * clock may already read that much later than the owner's) minus one\n * {@link heartbeatInterval} (reserved for one bounded compare-and-swap\n * reconfirmation before the owner interrupts).\n *\n * This bounds, but does not eliminate, overlap. Beyond\n * {@link heartbeatSkewAllowance} of clock offset a peer can be admitted while\n * the old owner is still running. *Durable* writes stay safe regardless — they\n * are fenced by the strategy's commit-time admission, so the displaced owner's\n * writes fail rather than corrupt. Non-durable external side effects (an HTTP\n * call, a spawned process) can genuinely overlap. That is inherent to any\n * wall-clock lease and is stated here rather than asserted away; a caller that\n * cannot tolerate any overlap needs an external fencing token at the side\n * effect itself, not a larger timeout.\n *\n * @since 1.0.0\n * @category constants\n */\nexport const heartbeatWriteTolerance: Duration.Duration = Duration.millis(\n Duration.toMillis(heartbeatStaleAfter) -\n Duration.toMillis(heartbeatSkewAllowance) -\n Duration.toMillis(heartbeatInterval)\n)\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\n/**\n * Evidence that the owner in an exact run snapshot is no longer live.\n *\n * Defined here because R5 — steal requires staleness plus liveness evidence —\n * is a consensus rule every strategy validates. `@smthrs/run-store`'s\n * `Ownership` re-exports it alongside the probes that mint it.\n *\n * Two of the three kinds are collected outside the strategy:\n * `same-host-pid-dead` is a local process probe, and\n * `cross-host-unreachable-stale` is a reachability judgement the deployment\n * makes. `lease-expired` is different — it asserts only that the persisted\n * heartbeat is older than the staleness cutoff, which is the one claim a\n * strategy can check for itself, and `steal` checks it: the takeover refuses\n * any lease whose heartbeat is still inside the window. It is therefore\n * accepted from a claimant on any host, while the other two stay bound to the\n * host relation that makes them meaningful. `same-host-pid-dead` alone also\n * admits a steal inside the window; see {@link provesDeath}. The observation must carry the\n * exact instant supplied to the consuming operation: `checkedAtMs` must equal\n * that operation's `nowMs`. A caller that probes at T and calls at T+1 is\n * refused and must build fresh evidence.\n *\n * @since 1.0.0\n * @category models\n */\nexport const LivenessEvidence = Schema.Struct({\n expectedOwner: OwnerId,\n checkedAtMs: Schema.Number,\n kind: Schema.Literals([\"same-host-pid-dead\", \"cross-host-unreachable-stale\", \"lease-expired\"])\n})\n\n/**\n * Evidence that the owner in an exact run snapshot is no longer live.\n *\n * @since 1.0.0\n * @category models\n */\nexport type LivenessEvidence = typeof LivenessEvidence.Type\n\n/**\n * Structural equality on the process identity tuple.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const sameOwner = (left: OwnerId, right: OwnerId): boolean =>\n left.hostId === right.hostId && left.pid === right.pid && left.nonce === right.nonce\n\n/**\n * Validates liveness evidence against the owner it claims to disprove.\n *\n * The evidence must name the expected owner, carry the observer's current\n * clock reading, and respect the host rule: a `same-host-pid-dead` probe is\n * only meaningful from the same host, a `cross-host-unreachable-stale`\n * observation only from a different one, and `lease-expired` is host-neutral\n * because the strategy verifies the cutoff it names for itself.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const matchesEvidence = (\n expectedOwner: OwnerId,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n): boolean => {\n if (!sameOwner(expectedOwner, evidence.expectedOwner) || evidence.checkedAtMs !== nowMs) return false\n switch (evidence.kind) {\n // A pid means nothing outside the host that owns the process namespace.\n case \"same-host-pid-dead\":\n return expectedOwner.hostId === observer.hostId\n // Unreachability is what a peer host observes; on the owner's own host it\n // would be an unprobed guess dressed as evidence.\n case \"cross-host-unreachable-stale\":\n return expectedOwner.hostId !== observer.hostId\n // The lease is host-neutral, and the strategy verifies the same\n // caller-clock cutoff named by this evidence.\n case \"lease-expired\":\n return true\n }\n}\n\n/**\n * Whether evidence proves the owner gone, so a steal need not wait for its\n * lease to go stale.\n *\n * The lease stands in for a question a peer cannot ask directly: is the owner\n * still running? A `same-host-pid-dead` probe asks it. The claimant read its\n * own host's process table and found no process behind the owner's pid, and a\n * process that does not exist renews no lease and writes nothing, so waiting\n * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with\n * `SIGKILL` is therefore reclaimed by the next process on the same host at\n * once.\n *\n * The evidence must still pass {@link matchesEvidence}, which binds the kind\n * to the same host. One more case is excluded here: an owner recorded with the\n * claimant's own pid names the claimant's process, which is running, so a\n * probe of that pid cannot report it gone. Such evidence keeps the staleness\n * cutoff.\n *\n * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a\n * judgement about a host this process cannot inspect, and `lease-expired` is\n * the cutoff itself.\n *\n * @since 1.0.0\n * @category predicates\n */\nexport const provesDeath = (evidence: LivenessEvidence, claimant: OwnerId): boolean =>\n evidence.kind === \"same-host-pid-dead\" && evidence.expectedOwner.pid !== claimant.pid\n\n/**\n * Why a strategy refused a claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport const RejectionReason = Schema.Literals([\n \"already_claimed\",\n \"owner_held\",\n \"owner_live\",\n \"evidence_invalid\",\n \"claim_fresh\",\n \"claim_changed\",\n \"unavailable\"\n])\n\n/**\n * Why a strategy refused a claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport type RejectionReason = typeof RejectionReason.Type\n\n/**\n * A granted claim, carrying the grant timestamp the later activation must\n * present (R4 — the generation fence).\n *\n * @since 1.0.0\n * @category models\n */\nexport const Claimed = Schema.TaggedStruct(\"Claimed\", {\n grantedAtMs: Schema.Number\n})\n\n/**\n * A granted claim.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Claimed = typeof Claimed.Type\n\n/**\n * A refused claim, steal, or recovery, with the strategy's typed reason.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Rejected = Schema.TaggedStruct(\"Rejected\", {\n reason: RejectionReason\n})\n\n/**\n * A refused claim, steal, or recovery.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Rejected = typeof Rejected.Type\n\n/**\n * Outcome of `claim` and `steal`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const ClaimOutcome = Schema.Union([Claimed, Rejected])\n\n/**\n * Outcome of `claim` and `steal`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ClaimOutcome = typeof ClaimOutcome.Type\n\n/**\n * A claim promoted to ownership.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Activated = Schema.TaggedStruct(\"Activated\", {})\n\n/**\n * A claim promoted to ownership.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Activated = typeof Activated.Type\n\n/**\n * The claim or lease the caller presented no longer exists.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Lost = Schema.TaggedStruct(\"Lost\", {})\n\n/**\n * The claim or lease the caller presented no longer exists.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Lost = typeof Lost.Type\n\n/**\n * Outcome of `activate`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const ActivateOutcome = Schema.Union([Activated, Lost])\n\n/**\n * Outcome of `activate`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ActivateOutcome = typeof ActivateOutcome.Type\n\n/**\n * A renewed lease, carrying the monotonic heartbeat stamp the strategy\n * recorded — the maximum of the stored stamp and the caller's reading, so a\n * late pulse never moves the lease backwards.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Renewed = Schema.TaggedStruct(\"Renewed\", {\n heartbeatAtMs: Schema.Number\n})\n\n/**\n * A renewed lease.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Renewed = typeof Renewed.Type\n\n/**\n * Outcome of `heartbeat` and `reconfirm`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const HeartbeatOutcome = Schema.Union([Renewed, Lost])\n\n/**\n * Outcome of `heartbeat` and `reconfirm`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type HeartbeatOutcome = typeof HeartbeatOutcome.Type\n\n/**\n * A stale claim cleared after its claimant was proven dead.\n *\n * @since 1.0.0\n * @category models\n */\nexport const Recovered = Schema.TaggedStruct(\"Recovered\", {})\n\n/**\n * A stale claim cleared after its claimant was proven dead.\n *\n * @since 1.0.0\n * @category models\n */\nexport type Recovered = typeof Recovered.Type\n\n/**\n * Outcome of `recover`.\n *\n * @since 1.0.0\n * @category models\n */\nexport const RecoverOutcome = Schema.Union([Recovered, Rejected])\n\n/**\n * Outcome of `recover`.\n *\n * @since 1.0.0\n * @category models\n */\nexport type RecoverOutcome = typeof RecoverOutcome.Type\n\n/**\n * Failure raised by a consensus strategy.\n *\n * `fence_lost` is `guard`'s refusal: the supplied owner no longer holds the\n * run, so the fenced write it joins must not commit. `persistence_failed`\n * wraps a strategy's storage failure; the original cause is preserved so the\n * durable writer's retry classification still sees a transient conflict\n * through the wrapper.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class ConsensusError extends Schema.TaggedError<ConsensusError>()(\"@smthrs/journal/ConsensusError\", {\n code: Schema.Literals([\"fence_lost\", \"persistence_failed\"]),\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown)\n}) {}\n\n/**\n * Consensus operations.\n *\n * The rules being arbitrated are strategy-independent; a strategy\n * chooses where the lease lives and how the fence is checked at commit time.\n * The claim lifecycle is two-phase, exactly as `RunStore`'s always was:\n * `claim` (or `steal`, its evidence-gated form) reserves the run and returns\n * the grant timestamp, `activate` presents that grant to take ownership, and\n * `release` clears whichever of the caller's claim or ownership still stands.\n * `recover` clears a *third party's* stale claim after its claimant was proven\n * dead — the relocated `recoverClaim` mechanic. `guard` is the commit-time\n * admission check (R3) `Journal.emitDurable`, `checkpoint`, and `compact`\n * join: it succeeds while the owner holds the run and fails with `fence_lost`\n * otherwise.\n *\n * Heartbeats and lease state are the strategy's private evidence and never\n * enter the journal.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface Service {\n readonly claim: (\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) => Effect.Effect<ClaimOutcome, ConsensusError>\n readonly activate: (\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) => Effect.Effect<ActivateOutcome, ConsensusError>\n readonly heartbeat: (\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) => Effect.Effect<HeartbeatOutcome, ConsensusError>\n /** Renews only while this owner holds the lease and no takeover claim is pending. */\n readonly reconfirm: (\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) => Effect.Effect<HeartbeatOutcome, ConsensusError>\n readonly release: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>\n readonly steal: (\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) => Effect.Effect<ClaimOutcome, ConsensusError>\n readonly recover: (\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) => Effect.Effect<RecoverOutcome, ConsensusError>\n readonly guard: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>\n}\n\n/**\n * Context service for the injected consensus strategy.\n *\n * @since 1.0.0\n * @category services\n */\nexport class Consensus extends Context.Service<Consensus, Service>()(\"@smthrs/journal/Consensus\") {}\n\n/**\n * Constructs a consensus service from an implementation.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (implementation: Service): Service => Consensus.of(implementation)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost: Lost = { _tag: \"Lost\" }\nconst activated: Activated = { _tag: \"Activated\" }\nconst recovered: Recovered = { _tag: \"Recovered\" }\n\n/**\n * The refusal `guard` raises for an owner that no longer holds the run.\n *\n * @since 1.0.0\n * @category errors\n */\nexport const fenceLost = (runId: string, owner: OwnerId): ConsensusError =>\n new ConsensusError({\n code: \"fence_lost\",\n message: `run ${runId} is no longer owned by ${owner.hostId}:${owner.pid}:${owner.nonce}`\n })\n\n/**\n * Constructs a strategy that arbitrates nothing: claims are refused, leases\n * are never held, and every fenced write is rejected.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const makeNoop = (overrides: Partial<Service> = {}): Service =>\n Consensus.of({\n claim: Effect.fn(\"Consensus.claim\")(() => Effect.succeed(rejected(\"unavailable\"))),\n activate: Effect.fn(\"Consensus.activate\")(() => Effect.succeed(lost)),\n heartbeat: Effect.fn(\"Consensus.heartbeat\")(() => Effect.succeed(lost)),\n reconfirm: Effect.fn(\"Consensus.reconfirm\")(() => Effect.succeed(lost)),\n release: Effect.fn(\"Consensus.release\")(() => Effect.void),\n steal: Effect.fn(\"Consensus.steal\")(() => Effect.succeed(rejected(\"unavailable\"))),\n recover: Effect.fn(\"Consensus.recover\")(() => Effect.succeed(rejected(\"unavailable\"))),\n guard: Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) => Effect.fail(fenceLost(runId, owner))),\n ...overrides\n })\n\n/**\n * Provides the refusing strategy stub.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerNoop = (overrides: Partial<Service> = {}): Layer.Layer<Consensus> =>\n Layer.succeed(Consensus)(makeNoop(overrides))\n\ninterface LocalLease {\n owner: { readonly id: OwnerId; readonly grantedAtMs: number; heartbeatAtMs: number } | undefined\n claim: { readonly id: OwnerId; readonly claimedAtMs: number } | undefined\n}\n\n/**\n * Constructs the in-memory single-process strategy.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const makeLocal: Effect.Effect<Service> = Effect.sync(() => {\n const leases = new Map<string, LocalLease>()\n\n const leaseOf = (runId: string): LocalLease => {\n const existing = leases.get(runId)\n if (existing !== undefined) return existing\n const fresh: LocalLease = { owner: undefined, claim: undefined }\n leases.set(runId, fresh)\n return fresh\n }\n\n const prune = (runId: string, lease: LocalLease): void => {\n if (lease.owner === undefined && lease.claim === undefined) {\n leases.delete(runId)\n }\n }\n\n return Consensus.of({\n claim: Effect.fn(\"Consensus.claim\")((runId: string, claimant: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leaseOf(runId)\n if (lease.claim !== undefined) return rejected(\"already_claimed\")\n if (lease.owner !== undefined) return rejected(\"owner_held\")\n lease.claim = { id: claimant, claimedAtMs: nowMs }\n return claimed(nowMs)\n })\n ),\n activate: Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n Effect.sync(() => {\n const lease = leaseOf(runId)\n if (\n lease.claim === undefined ||\n !sameOwner(lease.claim.id, owner) ||\n lease.claim.claimedAtMs !== grantedAtMs\n ) {\n prune(runId, lease)\n return lost\n }\n lease.claim = undefined\n lease.owner = { id: owner, grantedAtMs, heartbeatAtMs: nowMs }\n return activated\n })\n ),\n heartbeat: Effect.fn(\"Consensus.heartbeat\")((runId: string, owner: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease?.owner === undefined || !sameOwner(lease.owner.id, owner)) return lost\n lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)\n return ({ _tag: \"Renewed\", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)\n })\n ),\n reconfirm: Effect.fn(\"Consensus.reconfirm\")((runId: string, owner: OwnerId, nowMs: number) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease?.owner === undefined || lease.claim !== undefined || !sameOwner(lease.owner.id, owner)) return lost\n lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)\n return ({ _tag: \"Renewed\", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)\n })\n ),\n release: Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n Effect.sync(() => {\n const lease = leases.get(runId)\n if (lease === undefined) return\n if (lease.claim !== undefined && sameOwner(lease.claim.id, owner)) {\n lease.claim = undefined\n }\n if (lease.owner !== undefined && sameOwner(lease.owner.id, owner)) {\n lease.owner = undefined\n }\n prune(runId, lease)\n })\n ),\n steal: Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.sync(() => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return rejected(\"evidence_invalid\")\n }\n const lease = leases.get(runId)\n if (lease?.claim !== undefined) return rejected(\"already_claimed\")\n if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {\n return rejected(\"evidence_invalid\")\n }\n if (!provesDeath(evidence, claimant) && lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) {\n return rejected(\"owner_live\")\n }\n lease.claim = { id: claimant, claimedAtMs: nowMs }\n return claimed(nowMs)\n })\n ),\n recover: Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.sync(() => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) return rejected(\"evidence_invalid\")\n const lease = leases.get(runId)\n if (\n lease?.claim === undefined ||\n !sameOwner(lease.claim.id, staleClaimant) ||\n lease.claim.claimedAtMs !== grantedAtMs\n ) {\n return rejected(\"claim_changed\")\n }\n if (lease.claim.claimedAtMs >= nowMs - staleAfterMs) return rejected(\"claim_fresh\")\n lease.claim = undefined\n prune(runId, lease)\n return recovered\n })\n ),\n guard: Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n Effect.suspend(() => {\n const lease = leases.get(runId)\n return lease?.owner !== undefined && sameOwner(lease.owner.id, owner)\n ? Effect.void\n : Effect.fail(fenceLost(runId, owner))\n })\n )\n })\n})\n\n/**\n * Provides the in-memory single-process strategy.\n *\n * The lease lives in process memory, so R3 is exact within the process — the\n * strategy's transitions and the serialized append transactions interleave\n * atomically on one event loop — and browser support needs nothing beyond\n * this layer plus the browser-safe journal. State is per layer build: provide\n * one instance to every service that must agree on it, which is what\n * `SqlJournal.layerWith` and `RunStore.layerWith` exist for.\n *\n * The lease is not part of any database transaction: a transition made inside\n * a `Journal.transact` that later rolls back stays applied in memory, so the\n * lease and a rolled-back run row can disagree until the next transition.\n * `SqlConsensus` keeps the two in one transaction; prefer it wherever a\n * database is present.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerLocal: Layer.Layer<Consensus> = Layer.effect(Consensus, makeLocal)\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"SqlConsensus.d.ts","sourceRoot":"","sources":["../../src/SqlConsensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAA;AAE9D,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA;AACjD,OAAO,EAIL,SAAS,EAUT,KAAK,OAAO,EACb,MAAM,gBAAgB,CAAA;AAoBvB;;;;;;GAMG;AACH,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC,SAAS,CAuQlF,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC,SAAS,CAAiC,CAAA"}
1
+ {"version":3,"file":"SqlConsensus.d.ts","sourceRoot":"","sources":["../../src/SqlConsensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAA;AAE9D,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA;AACjD,OAAO,EAIL,SAAS,EAWT,KAAK,OAAO,EACb,MAAM,gBAAgB,CAAA;AAoBvB;;;;;;GAMG;AACH,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC,SAAS,CAuQlF,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC,SAAS,CAAiC,CAAA"}
@@ -27,7 +27,7 @@ import * as Duration from "effect/Duration";
27
27
  import * as Effect from "effect/Effect";
28
28
  import * as Layer from "effect/Layer";
29
29
  import * as SqlClient from "effect/sql/SqlClient";
30
- import { Consensus, ConsensusError, fenceLost, heartbeatStaleAfter, matchesEvidence } from "./Consensus.js";
30
+ import { Consensus, ConsensusError, fenceLost, heartbeatStaleAfter, matchesEvidence, provesDeath } from "./Consensus.js";
31
31
  const staleAfterMs = Duration.toMillis(heartbeatStaleAfter);
32
32
  const rejected = (reason) => ({ _tag: "Rejected", reason });
33
33
  const claimed = (grantedAtMs) => ({ _tag: "Claimed", grantedAtMs });
@@ -175,7 +175,7 @@ export const make = Effect.gen(function* () {
175
175
  AND owner_host_id = ${evidence.expectedOwner.hostId}
176
176
  AND owner_pid = ${evidence.expectedOwner.pid}
177
177
  AND owner_nonce = ${evidence.expectedOwner.nonce}
178
- AND heartbeat_at_ms < ${nowMs - staleAfterMs}
178
+ AND ${provesDeath(evidence, claimant) ? sql `TRUE` : sql `heartbeat_at_ms < ${nowMs - staleAfterMs}`}
179
179
  AND claim_host_id IS NULL
180
180
  RETURNING run_id
181
181
  `;
@@ -1 +1 @@
1
- {"version":3,"file":"SqlConsensus.js","sourceRoot":"","sources":["../../src/SqlConsensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,OAAO,MAAM,0BAA0B,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAA;AAC9D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA;AACjD,OAAO,EAIL,SAAS,EACT,cAAc,EACd,SAAS,EAET,mBAAmB,EAEnB,eAAe,EAKhB,MAAM,gBAAgB,CAAA;AAGvB,MAAM,YAAY,GAAG,QAAQ,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAA;AAE3D,MAAM,QAAQ,GAAG,CAAC,MAAuB,EAAY,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAA;AACtF,MAAM,OAAO,GAAG,CAAC,WAAmB,EAAW,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC,CAAA;AACpF,MAAM,IAAI,GAAG,EAAE,IAAI,EAAE,MAAM,EAAW,CAAA;AACtC,MAAM,SAAS,GAAG,EAAE,IAAI,EAAE,WAAW,EAAW,CAAA;AAChD,MAAM,SAAS,GAAG,EAAE,IAAI,EAAE,WAAW,EAAW,CAAA;AAWhD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,IAAI,GAAuE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;IAC1G,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,SAA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AAI,CAAC,CAAA","sourcesContent":["/**\n * The default database-backed consensus strategy.\n *\n * This is the run store's former `flows_runs` ownership compare-and-swap\n * relocated: the owner tuple, the two-phase claim columns, claim recovery, and\n * the grant timestamp are the private schema of one strategy — the\n * `flows_consensus_leases` table — instead of a public contract on the run\n * row. The run row still mirrors the outcome, but the lease is what\n * arbitrates.\n *\n * Commit-time admission (R3) is exact: `guard` is a plain SELECT that joins\n * the caller's open write transaction — `DurableWriter` serializes write\n * transactions, so no reclaim can commit between the guard read and the\n * statements beside it — and every mutating operation runs through\n * `DurableWriter.write`, joining an enclosing transaction as a savepoint.\n * Prior art: Temporal's shard `rangeID` check\n * (`reference/temporal/service/history/shard/context_impl.go`,\n * `renewRangeLocked`).\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n *\n * @since 1.0.0\n */\n\nimport * as Dialect from \"@smthrs/database/Dialect\"\nimport { DurableWriter } from \"@smthrs/database/DurableWriter\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as SqlClient from \"effect/sql/SqlClient\"\nimport {\n type ActivateOutcome,\n type Claimed,\n type ClaimOutcome,\n Consensus,\n ConsensusError,\n fenceLost,\n type HeartbeatOutcome,\n heartbeatStaleAfter,\n type LivenessEvidence,\n matchesEvidence,\n type RecoverOutcome,\n type Rejected,\n type RejectionReason,\n type Service\n} from \"./Consensus.ts\"\nimport type { OwnerId } from \"./OwnerId.ts\"\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost = { _tag: \"Lost\" } as const\nconst activated = { _tag: \"Activated\" } as const\nconst recovered = { _tag: \"Recovered\" } as const\n\ninterface LeaseRow {\n readonly owner_host_id: string | null\n readonly owner_pid: number | null\n readonly owner_nonce: string | null\n readonly claim_host_id: string | null\n readonly claim_pid: number | null\n readonly claim_nonce: string | null\n}\n\n/**\n * Constructs the database-backed strategy over the context's SQL client and\n * durable writer.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect.Effect<Service, never, DurableWriter | SqlClient.SqlClient> = Effect.gen(function*() {\n const sql = yield* Effect.service(SqlClient.SqlClient)\n const writer = yield* DurableWriter\n\n const strategyError = (cause: unknown): ConsensusError =>\n new ConsensusError({\n code: \"persistence_failed\",\n message: \"consensus lease operation failed\",\n cause\n })\n\n // The original cause is preserved through the wrapper so an enclosing\n // `DurableWriter.write`'s retry classification still sees a transient\n // conflict raised by a savepoint-nested lease statement.\n const write = <A>(\n body: Effect.Effect<A, unknown>\n ): Effect.Effect<A, ConsensusError> =>\n writer.write(body).pipe(Effect.mapError((cause) => cause instanceof ConsensusError ? cause : strategyError(cause)))\n\n const leaseOf = (runId: string) =>\n sql<LeaseRow>`\n SELECT owner_host_id, owner_pid, owner_nonce, claim_host_id, claim_pid, claim_nonce\n FROM flows_consensus_leases\n WHERE run_id = ${runId}\n `\n\n const prune = (runId: string) =>\n sql`\n DELETE FROM flows_consensus_leases\n WHERE run_id = ${runId} AND owner_host_id IS NULL AND claim_host_id IS NULL\n `\n\n const claim: Service[\"claim\"] = Effect.fn(\"Consensus.claim\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n INSERT INTO flows_consensus_leases (run_id, claim_host_id, claim_pid, claim_nonce, claimed_at_ms)\n VALUES (${runId}, ${claimant.hostId}, ${claimant.pid}, ${claimant.nonce}, ${nowMs})\n ON CONFLICT (run_id) DO UPDATE SET\n claim_host_id = excluded.claim_host_id,\n claim_pid = excluded.claim_pid,\n claim_nonce = excluded.claim_nonce,\n claimed_at_ms = excluded.claimed_at_ms\n WHERE flows_consensus_leases.claim_host_id IS NULL\n AND flows_consensus_leases.owner_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n // The upsert only misses on a conflicting row, so the lease exists and\n // holds a claim, an owner, or both.\n const lease = (yield* leaseOf(runId))[0]!\n return lease.claim_host_id !== null ? rejected(\"already_claimed\") : rejected(\"owner_held\")\n }))\n )\n\n const activate: Service[\"activate\"] = Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n owner_host_id = ${owner.hostId},\n owner_pid = ${owner.pid},\n owner_nonce = ${owner.nonce},\n granted_at_ms = ${grantedAtMs},\n heartbeat_at_ms = ${nowMs},\n claim_host_id = NULL,\n claim_pid = NULL,\n claim_nonce = NULL,\n claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n RETURNING run_id\n `\n return (rows.length > 0 ? activated : lost) satisfies ActivateOutcome\n }))\n )\n\n const heartbeat: Service[\"heartbeat\"] = Effect.fn(\"Consensus.heartbeat\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // Monotonic: a pulse delayed past a newer one from the same owner never\n // moves the lease backwards and never makes a live run look stale.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const reconfirm: Service[\"reconfirm\"] = Effect.fn(\"Consensus.reconfirm\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // A pending steal has already reserved the lease, even before activation.\n // Compare both owner and claim in the same update as the renewal.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n AND claim_host_id IS NULL\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const release: Service[\"release\"] = Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n yield* sql`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n `\n yield* sql`\n UPDATE flows_consensus_leases\n SET owner_host_id = NULL, owner_pid = NULL, owner_nonce = NULL,\n granted_at_ms = NULL, heartbeat_at_ms = NULL\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n yield* prune(runId)\n }))\n )\n\n const steal: Service[\"steal\"] = Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<ClaimOutcome, ConsensusError> => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n claim_host_id = ${claimant.hostId},\n claim_pid = ${claimant.pid},\n claim_nonce = ${claimant.nonce},\n claimed_at_ms = ${nowMs}\n WHERE run_id = ${runId}\n AND owner_host_id = ${evidence.expectedOwner.hostId}\n AND owner_pid = ${evidence.expectedOwner.pid}\n AND owner_nonce = ${evidence.expectedOwner.nonce}\n AND heartbeat_at_ms < ${nowMs - staleAfterMs}\n AND claim_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n const lease = (yield* leaseOf(runId))[0]\n if (lease !== undefined && lease.claim_host_id !== null) return rejected(\"already_claimed\")\n if (\n lease === undefined ||\n lease.owner_host_id !== evidence.expectedOwner.hostId ||\n Number(lease.owner_pid) !== evidence.expectedOwner.pid ||\n lease.owner_nonce !== evidence.expectedOwner.nonce\n ) {\n // A run nobody owns, or one owned by somebody else, has no owner\n // this evidence could disprove.\n return rejected(\"evidence_invalid\")\n }\n return rejected(\"owner_live\")\n }))\n })\n )\n\n const recover: Service[\"recover\"] = Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<RecoverOutcome, ConsensusError> => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n AND claimed_at_ms < ${nowMs - staleAfterMs}\n RETURNING run_id\n `\n if (rows.length > 0) {\n yield* prune(runId)\n return recovered\n }\n const matches = yield* sql<{ readonly run_id: string }>`\n SELECT run_id FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n `\n // The exact claim survived the compare-and-swap only because it is\n // not yet stale; anything else means the claim moved on.\n return matches.length > 0 ? rejected(\"claim_fresh\") : rejected(\"claim_changed\")\n }))\n })\n )\n\n const guard: Service[\"guard\"] = Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n const held = yield* sql<{ readonly ok: number }>`\n SELECT 1 AS ok FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n if (held.length === 0) {\n return yield* Effect.fail(fenceLost(runId, owner))\n }\n }))\n )\n\n return Consensus.of({ claim, activate, heartbeat, reconfirm, release, steal, recover, guard })\n})\n\n/**\n * Provides the database-backed strategy.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<Consensus, never, DurableWriter | SqlClient.SqlClient> = Layer.effect(Consensus, make)\n"]}
1
+ {"version":3,"file":"SqlConsensus.js","sourceRoot":"","sources":["../../src/SqlConsensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,OAAO,MAAM,0BAA0B,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAA;AAC9D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA;AACjD,OAAO,EAIL,SAAS,EACT,cAAc,EACd,SAAS,EAET,mBAAmB,EAEnB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AC,CAAC,CAAA;IACL,CAAC,CAAC,CACH,CAAA;IAED,MAAM,KAAK,GAAqB,MAAM,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,KAAa,EAAE,KAAc,EAAE,EAAE,CAC7F,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;QACxB,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,GAAG,CAAyB;;yBAE7B,KAAK;gCACE,KAAK,CAAC,MAAM;4BAChB,KAAK,CAAC,GAAG;8BACP,KAAK,CAAC,KAAK;OAClC,CAAA;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAA;QACpD,CAAC;IACH,CAAC,CAAC,CAAC,CACJ,CAAA;IAED,OAAO,SAAS,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAA;AAChG,CAAC,CAAC,CAAA;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAuE,KAAK,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA","sourcesContent":["/**\n * The default database-backed consensus strategy.\n *\n * This is the run store's former `flows_runs` ownership compare-and-swap\n * relocated: the owner tuple, the two-phase claim columns, claim recovery, and\n * the grant timestamp are the private schema of one strategy — the\n * `flows_consensus_leases` table — instead of a public contract on the run\n * row. The run row still mirrors the outcome, but the lease is what\n * arbitrates.\n *\n * Commit-time admission (R3) is exact: `guard` is a plain SELECT that joins\n * the caller's open write transaction — `DurableWriter` serializes write\n * transactions, so no reclaim can commit between the guard read and the\n * statements beside it — and every mutating operation runs through\n * `DurableWriter.write`, joining an enclosing transaction as a savepoint.\n * Prior art: Temporal's shard `rangeID` check\n * (`reference/temporal/service/history/shard/context_impl.go`,\n * `renewRangeLocked`).\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n *\n * @since 1.0.0\n */\n\nimport * as Dialect from \"@smthrs/database/Dialect\"\nimport { DurableWriter } from \"@smthrs/database/DurableWriter\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as SqlClient from \"effect/sql/SqlClient\"\nimport {\n type ActivateOutcome,\n type Claimed,\n type ClaimOutcome,\n Consensus,\n ConsensusError,\n fenceLost,\n type HeartbeatOutcome,\n heartbeatStaleAfter,\n type LivenessEvidence,\n matchesEvidence,\n provesDeath,\n type RecoverOutcome,\n type Rejected,\n type RejectionReason,\n type Service\n} from \"./Consensus.ts\"\nimport type { OwnerId } from \"./OwnerId.ts\"\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost = { _tag: \"Lost\" } as const\nconst activated = { _tag: \"Activated\" } as const\nconst recovered = { _tag: \"Recovered\" } as const\n\ninterface LeaseRow {\n readonly owner_host_id: string | null\n readonly owner_pid: number | null\n readonly owner_nonce: string | null\n readonly claim_host_id: string | null\n readonly claim_pid: number | null\n readonly claim_nonce: string | null\n}\n\n/**\n * Constructs the database-backed strategy over the context's SQL client and\n * durable writer.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect.Effect<Service, never, DurableWriter | SqlClient.SqlClient> = Effect.gen(function*() {\n const sql = yield* Effect.service(SqlClient.SqlClient)\n const writer = yield* DurableWriter\n\n const strategyError = (cause: unknown): ConsensusError =>\n new ConsensusError({\n code: \"persistence_failed\",\n message: \"consensus lease operation failed\",\n cause\n })\n\n // The original cause is preserved through the wrapper so an enclosing\n // `DurableWriter.write`'s retry classification still sees a transient\n // conflict raised by a savepoint-nested lease statement.\n const write = <A>(\n body: Effect.Effect<A, unknown>\n ): Effect.Effect<A, ConsensusError> =>\n writer.write(body).pipe(Effect.mapError((cause) => cause instanceof ConsensusError ? cause : strategyError(cause)))\n\n const leaseOf = (runId: string) =>\n sql<LeaseRow>`\n SELECT owner_host_id, owner_pid, owner_nonce, claim_host_id, claim_pid, claim_nonce\n FROM flows_consensus_leases\n WHERE run_id = ${runId}\n `\n\n const prune = (runId: string) =>\n sql`\n DELETE FROM flows_consensus_leases\n WHERE run_id = ${runId} AND owner_host_id IS NULL AND claim_host_id IS NULL\n `\n\n const claim: Service[\"claim\"] = Effect.fn(\"Consensus.claim\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n INSERT INTO flows_consensus_leases (run_id, claim_host_id, claim_pid, claim_nonce, claimed_at_ms)\n VALUES (${runId}, ${claimant.hostId}, ${claimant.pid}, ${claimant.nonce}, ${nowMs})\n ON CONFLICT (run_id) DO UPDATE SET\n claim_host_id = excluded.claim_host_id,\n claim_pid = excluded.claim_pid,\n claim_nonce = excluded.claim_nonce,\n claimed_at_ms = excluded.claimed_at_ms\n WHERE flows_consensus_leases.claim_host_id IS NULL\n AND flows_consensus_leases.owner_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n // The upsert only misses on a conflicting row, so the lease exists and\n // holds a claim, an owner, or both.\n const lease = (yield* leaseOf(runId))[0]!\n return lease.claim_host_id !== null ? rejected(\"already_claimed\") : rejected(\"owner_held\")\n }))\n )\n\n const activate: Service[\"activate\"] = Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n owner_host_id = ${owner.hostId},\n owner_pid = ${owner.pid},\n owner_nonce = ${owner.nonce},\n granted_at_ms = ${grantedAtMs},\n heartbeat_at_ms = ${nowMs},\n claim_host_id = NULL,\n claim_pid = NULL,\n claim_nonce = NULL,\n claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n RETURNING run_id\n `\n return (rows.length > 0 ? activated : lost) satisfies ActivateOutcome\n }))\n )\n\n const heartbeat: Service[\"heartbeat\"] = Effect.fn(\"Consensus.heartbeat\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // Monotonic: a pulse delayed past a newer one from the same owner never\n // moves the lease backwards and never makes a live run look stale.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const reconfirm: Service[\"reconfirm\"] = Effect.fn(\"Consensus.reconfirm\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // A pending steal has already reserved the lease, even before activation.\n // Compare both owner and claim in the same update as the renewal.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n AND claim_host_id IS NULL\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const release: Service[\"release\"] = Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n yield* sql`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n `\n yield* sql`\n UPDATE flows_consensus_leases\n SET owner_host_id = NULL, owner_pid = NULL, owner_nonce = NULL,\n granted_at_ms = NULL, heartbeat_at_ms = NULL\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n yield* prune(runId)\n }))\n )\n\n const steal: Service[\"steal\"] = Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<ClaimOutcome, ConsensusError> => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n claim_host_id = ${claimant.hostId},\n claim_pid = ${claimant.pid},\n claim_nonce = ${claimant.nonce},\n claimed_at_ms = ${nowMs}\n WHERE run_id = ${runId}\n AND owner_host_id = ${evidence.expectedOwner.hostId}\n AND owner_pid = ${evidence.expectedOwner.pid}\n AND owner_nonce = ${evidence.expectedOwner.nonce}\n AND ${provesDeath(evidence, claimant) ? sql`TRUE` : sql`heartbeat_at_ms < ${nowMs - staleAfterMs}`}\n AND claim_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n const lease = (yield* leaseOf(runId))[0]\n if (lease !== undefined && lease.claim_host_id !== null) return rejected(\"already_claimed\")\n if (\n lease === undefined ||\n lease.owner_host_id !== evidence.expectedOwner.hostId ||\n Number(lease.owner_pid) !== evidence.expectedOwner.pid ||\n lease.owner_nonce !== evidence.expectedOwner.nonce\n ) {\n // A run nobody owns, or one owned by somebody else, has no owner\n // this evidence could disprove.\n return rejected(\"evidence_invalid\")\n }\n return rejected(\"owner_live\")\n }))\n })\n )\n\n const recover: Service[\"recover\"] = Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<RecoverOutcome, ConsensusError> => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n AND claimed_at_ms < ${nowMs - staleAfterMs}\n RETURNING run_id\n `\n if (rows.length > 0) {\n yield* prune(runId)\n return recovered\n }\n const matches = yield* sql<{ readonly run_id: string }>`\n SELECT run_id FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n `\n // The exact claim survived the compare-and-swap only because it is\n // not yet stale; anything else means the claim moved on.\n return matches.length > 0 ? rejected(\"claim_fresh\") : rejected(\"claim_changed\")\n }))\n })\n )\n\n const guard: Service[\"guard\"] = Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n const held = yield* sql<{ readonly ok: number }>`\n SELECT 1 AS ok FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n if (held.length === 0) {\n return yield* Effect.fail(fenceLost(runId, owner))\n }\n }))\n )\n\n return Consensus.of({ claim, activate, heartbeat, reconfirm, release, steal, recover, guard })\n})\n\n/**\n * Provides the database-backed strategy.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<Consensus, never, DurableWriter | SqlClient.SqlClient> = Layer.effect(Consensus, make)\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"Notifying.js","sourceRoot":"","sources":["../../../src/test/Notifying.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AA+BrC;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAAmB,OAAU,EAAE,IAAU,EAAK,EAAE;IAClE,MAAM,OAAO,GAA4B,EAAE,CAAA;IAC3C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACvC,MAAM,KAAK,GAAI,OAAmC,CAAC,GAAG,CAAC,CAAA;QACvD,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YAC3B,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC,IAAI,CACzC,MAAM,CAAC,OAAO,CAAC,KAAiD,CAAC,EACjE,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,CACzC,CAAA;QACH,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;YACvC,MAAM,MAAM,GAAG,KAA6C,CAAA;YAC5D,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,IAAoB,EAAE,EAAE;gBACzC,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;gBAC1C,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;oBAC5B,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC,IAAI,CAC9B,MAAM,CAAC,OAAO,CAAC,MAAkD,CAAC,EAClE,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAC3C;oBACD,CAAC,CAAC,MAAM,CAAA;YACZ,CAAC,CAAA;QACH,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACtB,CAAC;IACH,CAAC;IACD,OAAO,OAAY,CAAA;AACrB,CAAC,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CACnB,GAAuB,EACvB,IAAU,EACkB,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,CAAA","sourcesContent":["/**\n * Effect-native analogue of Bazel Skyframe's `NotifyingHelper` and\n * `NotifyingInMemoryGraph`: wrap a record-of-Effect-methods service so a listener hook fires around\n * every operation. The hook runs in the calling fiber, so a hook that dies,\n * interrupts, or awaits a `Latch` injects crashes, fence loss, and exact\n * sequencing at any durable transition point, the mechanism that makes\n * interstitial interleaving bugs testable at all.\n *\n * Deliberately NOT ported from Skyframe: `DeterministicHelper`'s\n * deterministic-scheduler machinery, `ChainedFunction`, and `TrackingAwaiter`.\n * Effect already gives us deterministic fibers, `TestClock`, `Latch`, and\n * failure propagation across fiber joins, so those helpers have no residue\n * here.\n *\n * @since 0.1.0\n */\n\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\n\n/**\n * Whether the hook is firing before or after the delegated operation.\n * Skyframe's `NotifyingHelper.Order`, minus its `BEFORE_AND_AFTER` (pass the\n * same hook body for both firings instead).\n *\n * @category models\n * @since 0.1.0\n */\nexport type Order = \"before\" | \"after\"\n\n/**\n * Listener invoked around every delegated operation. `op` is the service\n * method name (Skyframe's `EventType`, but open-world), `args` the call\n * arguments. Express crash injection as `Effect.die` or `Effect.interrupt`\n * inside the hook, the hook's type stays `Effect<void>` so the wrapped\n * service is structurally identical to the real one.\n *\n * The `after` firing only happens when the operation succeeds; a failed\n * operation already is the interesting event.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Hook = (\n op: string,\n order: Order,\n args: ReadonlyArray<unknown>\n) => Effect.Effect<void>\n\n/**\n * Wraps a service so `hook(op, \"before\" | \"after\", args)` fires around every\n * Effect-valued operation, delegating to the real implementation in between.\n *\n * Generic over any record-of-Effect-methods service (`Journal`, `CacheStore`,\n * `AttemptStore`, `RunStore`, ...): Effect-returning methods and plain Effect\n * properties are hooked; non-Effect members (e.g. `Stream`-returning methods)\n * delegate untouched.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const wrap = <S extends object>(service: S, hook: Hook): S => {\n const wrapped: Record<string, unknown> = {}\n for (const key of Object.keys(service)) {\n const value = (service as Record<string, unknown>)[key]\n if (Effect.isEffect(value)) {\n wrapped[key] = hook(key, \"before\", []).pipe(\n Effect.andThen(value as Effect.Effect<unknown, unknown, unknown>),\n Effect.tap(() => hook(key, \"after\", []))\n )\n } else if (typeof value === \"function\") {\n const method = value as (...args: Array<unknown>) => unknown\n wrapped[key] = (...args: Array<unknown>) => {\n const result = method.apply(service, args)\n return Effect.isEffect(result)\n ? hook(key, \"before\", args).pipe(\n Effect.andThen(result as Effect.Effect<unknown, unknown, unknown>),\n Effect.tap(() => hook(key, \"after\", args))\n )\n : result\n }\n } else {\n wrapped[key] = value\n }\n }\n return wrapped as S\n}\n\n/**\n * Layer form of {@link wrap}: reads the real service from the environment and\n * re-provides the notifying wrapper under the same key, so an existing stack\n * gains a listener without touching its construction.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer = <Id, S extends object>(\n tag: Context.Key<Id, S>,\n hook: Hook\n): Layer.Layer<Id, never, Id> => Layer.effect(tag)(Effect.map(tag, (service) => wrap(service, hook)))\n"]}
1
+ {"version":3,"file":"Notifying.js","sourceRoot":"","sources":["../../../src/test/Notifying.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AA+BrC;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAAmB,OAAU,EAAE,IAAU,EAAK,EAAE;IAClE,MAAM,OAAO,GAA4B,EAAE,CAAA;IAC3C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACvC,MAAM,KAAK,GAAI,OAAmC,CAAC,GAAG,CAAC,CAAA;QACvD,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YAC3B,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC,IAAI,CACzC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EACrB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,CACzC,CAAA;QACH,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;YACvC,MAAM,MAAM,GAAG,KAA6C,CAAA;YAC5D,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,IAAoB,EAAE,EAAE;gBACzC,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;gBAC1C,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;oBAC5B,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC,IAAI,CAC9B,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EACtB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAC3C;oBACD,CAAC,CAAC,MAAM,CAAA;YACZ,CAAC,CAAA;QACH,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACtB,CAAC;IACH,CAAC;IACD,OAAO,OAAY,CAAA;AACrB,CAAC,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CACnB,GAAuB,EACvB,IAAU,EACkB,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,CAAA","sourcesContent":["/**\n * Effect-native analogue of Bazel Skyframe's `NotifyingHelper` and\n * `NotifyingInMemoryGraph`: wrap a record-of-Effect-methods service so a listener hook fires around\n * every operation. The hook runs in the calling fiber, so a hook that dies,\n * interrupts, or awaits a `Latch` injects crashes, fence loss, and exact\n * sequencing at any durable transition point, the mechanism that makes\n * interstitial interleaving bugs testable at all.\n *\n * Deliberately NOT ported from Skyframe: `DeterministicHelper`'s\n * deterministic-scheduler machinery, `ChainedFunction`, and `TrackingAwaiter`.\n * Effect already gives us deterministic fibers, `TestClock`, `Latch`, and\n * failure propagation across fiber joins, so those helpers have no residue\n * here.\n *\n * @since 0.1.0\n */\n\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\n\n/**\n * Whether the hook is firing before or after the delegated operation.\n * Skyframe's `NotifyingHelper.Order`, minus its `BEFORE_AND_AFTER` (pass the\n * same hook body for both firings instead).\n *\n * @category models\n * @since 0.1.0\n */\nexport type Order = \"before\" | \"after\"\n\n/**\n * Listener invoked around every delegated operation. `op` is the service\n * method name (Skyframe's `EventType`, but open-world), `args` the call\n * arguments. Express crash injection as `Effect.die` or `Effect.interrupt`\n * inside the hook, the hook's type stays `Effect<void>` so the wrapped\n * service is structurally identical to the real one.\n *\n * The `after` firing only happens when the operation succeeds; a failed\n * operation already is the interesting event.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Hook = (\n op: string,\n order: Order,\n args: ReadonlyArray<unknown>\n) => Effect.Effect<void>\n\n/**\n * Wraps a service so `hook(op, \"before\" | \"after\", args)` fires around every\n * Effect-valued operation, delegating to the real implementation in between.\n *\n * Generic over any record-of-Effect-methods service (`Journal`, `CacheStore`,\n * `AttemptStore`, `RunStore`, ...): Effect-returning methods and plain Effect\n * properties are hooked; non-Effect members (e.g. `Stream`-returning methods)\n * delegate untouched.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const wrap = <S extends object>(service: S, hook: Hook): S => {\n const wrapped: Record<string, unknown> = {}\n for (const key of Object.keys(service)) {\n const value = (service as Record<string, unknown>)[key]\n if (Effect.isEffect(value)) {\n wrapped[key] = hook(key, \"before\", []).pipe(\n Effect.andThen(value),\n Effect.tap(() => hook(key, \"after\", []))\n )\n } else if (typeof value === \"function\") {\n const method = value as (...args: Array<unknown>) => unknown\n wrapped[key] = (...args: Array<unknown>) => {\n const result = method.apply(service, args)\n return Effect.isEffect(result)\n ? hook(key, \"before\", args).pipe(\n Effect.andThen(result),\n Effect.tap(() => hook(key, \"after\", args))\n )\n : result\n }\n } else {\n wrapped[key] = value\n }\n }\n return wrapped as S\n}\n\n/**\n * Layer form of {@link wrap}: reads the real service from the environment and\n * re-provides the notifying wrapper under the same key, so an existing stack\n * gains a listener without touching its construction.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer = <Id, S extends object>(\n tag: Context.Key<Id, S>,\n hook: Hook\n): Layer.Layer<Id, never, Id> => Layer.effect(tag)(Effect.map(tag, (service) => wrap(service, hook)))\n"]}
package/docs/api.md CHANGED
@@ -236,30 +236,32 @@ That package's `Ownership` re-exports it alongside `LivenessEvidence`,
236
236
  The injectable strategy that arbitrates who holds a run. The journal owns the
237
237
  rules (one writer per run, fenced and unfenced appends, commit-time
238
238
  admission, the generation fence, steal only on staleness plus liveness
239
- evidence, and ownership transitions as events), and a strategy chooses where
239
+ evidence or on a same-host probe that proves the owner's pid gone, and
240
+ ownership transitions as events), and a strategy chooses where
240
241
  the lease lives and how the fence is checked at commit time.
241
242
 
242
- | Export | Signature |
243
- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
244
- | `Consensus` | `Context.Service<Consensus, Service>` |
245
- | `Service.claim` | `(runId, claimant: OwnerId, nowMs) => Effect<ClaimOutcome, ConsensusError>` |
246
- | `Service.activate` | `(runId, owner: OwnerId, grantedAtMs, nowMs) => Effect<ActivateOutcome, ConsensusError>` |
247
- | `Service.heartbeat` | `(runId, owner: OwnerId, nowMs) => Effect<HeartbeatOutcome, ConsensusError>` |
248
- | `Service.reconfirm` | `(runId, owner: OwnerId, nowMs) => Effect<HeartbeatOutcome, ConsensusError>`; renews only while the owner matches and no claim is pending |
249
- | `Service.release` | `(runId, owner: OwnerId) => Effect<void, ConsensusError>` |
250
- | `Service.steal` | `(runId, claimant: OwnerId, nowMs, evidence: LivenessEvidence) => Effect<ClaimOutcome, ConsensusError>` |
251
- | `Service.recover` | `(runId, staleClaimant: OwnerId, grantedAtMs, observer: OwnerId, nowMs, evidence: LivenessEvidence) => Effect<RecoverOutcome, ConsensusError>` |
252
- | `Service.guard` | `(runId, owner: OwnerId) => Effect<void, ConsensusError>`; fails `fence_lost` unless `owner` holds the run |
253
- | `ClaimOutcome` | `Claimed { grantedAtMs }` or `Rejected { reason }` |
254
- | `ActivateOutcome` | `Activated` or `Lost` |
255
- | `HeartbeatOutcome` | `Renewed { heartbeatAtMs }` or `Lost` |
256
- | `RecoverOutcome` | `Recovered` or `Rejected { reason }` |
257
- | `RejectionReason` | `already_claimed`, `owner_held`, `owner_live`, `evidence_invalid`, `claim_fresh`, `claim_changed`, `unavailable` |
258
- | `ConsensusError` | `{ code: "fence_lost" \| "persistence_failed", message, cause? }` |
259
- | `LivenessEvidence` | `{ expectedOwner: OwnerId, checkedAtMs, kind }` with `kind` one of `same-host-pid-dead`, `cross-host-unreachable-stale`, `lease-expired` |
260
- | `matchesEvidence`, `sameOwner` | The evidence and identity predicates every strategy applies |
261
- | `heartbeatInterval`, `heartbeatStaleAfter`, `heartbeatSkewAllowance`, `heartbeatWriteTolerance` | The lease durations every strategy judges staleness against |
262
- | `make`, `makeNoop`, `makeLocal`, `layerNoop`, `layerLocal` | Constructors and layers; `layerLocal` is the in-memory single-process strategy |
243
+ | Export | Signature |
244
+ | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
245
+ | `Consensus` | `Context.Service<Consensus, Service>` |
246
+ | `Service.claim` | `(runId, claimant: OwnerId, nowMs) => Effect<ClaimOutcome, ConsensusError>` |
247
+ | `Service.activate` | `(runId, owner: OwnerId, grantedAtMs, nowMs) => Effect<ActivateOutcome, ConsensusError>` |
248
+ | `Service.heartbeat` | `(runId, owner: OwnerId, nowMs) => Effect<HeartbeatOutcome, ConsensusError>` |
249
+ | `Service.reconfirm` | `(runId, owner: OwnerId, nowMs) => Effect<HeartbeatOutcome, ConsensusError>`; renews only while the owner matches and no claim is pending |
250
+ | `Service.release` | `(runId, owner: OwnerId) => Effect<void, ConsensusError>` |
251
+ | `Service.steal` | `(runId, claimant: OwnerId, nowMs, evidence: LivenessEvidence) => Effect<ClaimOutcome, ConsensusError>` |
252
+ | `Service.recover` | `(runId, staleClaimant: OwnerId, grantedAtMs, observer: OwnerId, nowMs, evidence: LivenessEvidence) => Effect<RecoverOutcome, ConsensusError>` |
253
+ | `Service.guard` | `(runId, owner: OwnerId) => Effect<void, ConsensusError>`; fails `fence_lost` unless `owner` holds the run |
254
+ | `ClaimOutcome` | `Claimed { grantedAtMs }` or `Rejected { reason }` |
255
+ | `ActivateOutcome` | `Activated` or `Lost` |
256
+ | `HeartbeatOutcome` | `Renewed { heartbeatAtMs }` or `Lost` |
257
+ | `RecoverOutcome` | `Recovered` or `Rejected { reason }` |
258
+ | `RejectionReason` | `already_claimed`, `owner_held`, `owner_live`, `evidence_invalid`, `claim_fresh`, `claim_changed`, `unavailable` |
259
+ | `ConsensusError` | `{ code: "fence_lost" \| "persistence_failed", message, cause? }` |
260
+ | `LivenessEvidence` | `{ expectedOwner: OwnerId, checkedAtMs, kind }` with `kind` one of `same-host-pid-dead`, `cross-host-unreachable-stale`, `lease-expired` |
261
+ | `matchesEvidence`, `sameOwner` | The evidence and identity predicates every strategy applies |
262
+ | `provesDeath` | `(evidence, claimant: OwnerId) => boolean`; `true` for `same-host-pid-dead` about a pid other than the claimant's, which `steal` admits at once |
263
+ | `heartbeatInterval`, `heartbeatStaleAfter`, `heartbeatSkewAllowance`, `heartbeatWriteTolerance` | The lease durations every strategy judges staleness against |
264
+ | `make`, `makeNoop`, `makeLocal`, `layerNoop`, `layerLocal` | Constructors and layers; `layerLocal` is the in-memory single-process strategy |
263
265
 
264
266
  The claim lifecycle is two-phase: `claim` (or `steal`, its evidence-gated
265
267
  form) reserves the run and returns the grant timestamp, `activate` presents
@@ -62,7 +62,11 @@ is why `RunStore.layerWith` takes the strategy too.
62
62
 
63
63
  The journal owns the rules: one writer per run, fenced and unfenced appends,
64
64
  commit-time admission, the generation fence, steal only on staleness plus
65
- liveness evidence, and ownership transitions as events. A strategy chooses
65
+ liveness evidence, and ownership transitions as events. One kind of evidence
66
+ needs no staleness: `same-host-pid-dead` about a pid other than the
67
+ claimant's (`Consensus.provesDeath`). The claimant found no process behind the
68
+ owner's pid on its own host, and a process that does not exist renews no lease
69
+ and writes nothing, so waiting out the lease adds no safety. A strategy chooses
66
70
  where the lease lives and how the fence is checked. The claim lifecycle is
67
71
  two-phase — `claim` or `steal` reserves the run and returns a grant
68
72
  timestamp, `activate` presents that grant to take ownership, `release` gives
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@smthrs/journal",
3
3
  "type": "module",
4
- "version": "1.0.0-rc.8",
4
+ "version": "1.0.0-rc.9",
5
5
  "license": "MIT",
6
6
  "smthrs": {
7
7
  "group": "engine"
@@ -226,14 +226,14 @@
226
226
  "tag": "next"
227
227
  },
228
228
  "dependencies": {
229
- "@smthrs/database": "1.0.0-rc.8"
229
+ "@smthrs/database": "1.0.0-rc.9"
230
230
  },
231
231
  "devDependencies": {
232
232
  "@effect/language-service": "0.87.2",
233
233
  "@effect/sql-sqlite-node": "4.0.4",
234
234
  "@effect/vitest": "4.0.4",
235
235
  "@eslint/js": "9.39.5",
236
- "@smthrs/flow": "1.0.0-rc.8",
236
+ "@smthrs/flow": "1.0.0-rc.9",
237
237
  "@types/node": "26.4.1",
238
238
  "@vitest/coverage-v8": "5.0.0",
239
239
  "dprint": "0.57.1",
package/src/Consensus.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * The journal owns the consensus rules — single writer per run, fenced and
5
5
  * unfenced appends, commit-time admission, the generation fence, and steal
6
- * only on staleness plus liveness evidence — and this service is how a deployment chooses *how* those rules are
6
+ * only on staleness plus liveness evidence, or on a same-host probe that
7
+ * proves the owner's process gone — and this service is how a deployment chooses *how* those rules are
7
8
  * arbitrated: where the lease lives, how liveness is probed, and how the
8
9
  * fence is checked at commit time. `Consensus` lives here beside `OwnerId`
9
10
  * for the same reason `OwnerId` does: the journal is what it fences.
@@ -117,7 +118,8 @@ const staleAfterMs = Duration.toMillis(heartbeatStaleAfter)
117
118
  * strategy can check for itself, and `steal` checks it: the takeover refuses
118
119
  * any lease whose heartbeat is still inside the window. It is therefore
119
120
  * accepted from a claimant on any host, while the other two stay bound to the
120
- * host relation that makes them meaningful. The observation must carry the
121
+ * host relation that makes them meaningful. `same-host-pid-dead` alone also
122
+ * admits a steal inside the window; see {@link provesDeath}. The observation must carry the
121
123
  * exact instant supplied to the consuming operation: `checkedAtMs` must equal
122
124
  * that operation's `nowMs`. A caller that probes at T and calls at T+1 is
123
125
  * refused and must build fresh evidence.
@@ -182,6 +184,34 @@ export const matchesEvidence = (
182
184
  }
183
185
  }
184
186
 
187
+ /**
188
+ * Whether evidence proves the owner gone, so a steal need not wait for its
189
+ * lease to go stale.
190
+ *
191
+ * The lease stands in for a question a peer cannot ask directly: is the owner
192
+ * still running? A `same-host-pid-dead` probe asks it. The claimant read its
193
+ * own host's process table and found no process behind the owner's pid, and a
194
+ * process that does not exist renews no lease and writes nothing, so waiting
195
+ * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with
196
+ * `SIGKILL` is therefore reclaimed by the next process on the same host at
197
+ * once.
198
+ *
199
+ * The evidence must still pass {@link matchesEvidence}, which binds the kind
200
+ * to the same host. One more case is excluded here: an owner recorded with the
201
+ * claimant's own pid names the claimant's process, which is running, so a
202
+ * probe of that pid cannot report it gone. Such evidence keeps the staleness
203
+ * cutoff.
204
+ *
205
+ * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a
206
+ * judgement about a host this process cannot inspect, and `lease-expired` is
207
+ * the cutoff itself.
208
+ *
209
+ * @since 1.0.0
210
+ * @category predicates
211
+ */
212
+ export const provesDeath = (evidence: LivenessEvidence, claimant: OwnerId): boolean =>
213
+ evidence.kind === "same-host-pid-dead" && evidence.expectedOwner.pid !== claimant.pid
214
+
185
215
  /**
186
216
  * Why a strategy refused a claim, steal, or recovery.
187
217
  *
@@ -621,7 +651,9 @@ export const makeLocal: Effect.Effect<Service> = Effect.sync(() => {
621
651
  if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {
622
652
  return rejected("evidence_invalid")
623
653
  }
624
- if (lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) return rejected("owner_live")
654
+ if (!provesDeath(evidence, claimant) && lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) {
655
+ return rejected("owner_live")
656
+ }
625
657
  lease.claim = { id: claimant, claimedAtMs: nowMs }
626
658
  return claimed(nowMs)
627
659
  })
@@ -39,6 +39,7 @@ import {
39
39
  heartbeatStaleAfter,
40
40
  type LivenessEvidence,
41
41
  matchesEvidence,
42
+ provesDeath,
42
43
  type RecoverOutcome,
43
44
  type Rejected,
44
45
  type RejectionReason,
@@ -252,7 +253,7 @@ export const make: Effect.Effect<Service, never, DurableWriter | SqlClient.SqlCl
252
253
  AND owner_host_id = ${evidence.expectedOwner.hostId}
253
254
  AND owner_pid = ${evidence.expectedOwner.pid}
254
255
  AND owner_nonce = ${evidence.expectedOwner.nonce}
255
- AND heartbeat_at_ms < ${nowMs - staleAfterMs}
256
+ AND ${provesDeath(evidence, claimant) ? sql`TRUE` : sql`heartbeat_at_ms < ${nowMs - staleAfterMs}`}
256
257
  AND claim_host_id IS NULL
257
258
  RETURNING run_id
258
259
  `
@@ -66,7 +66,7 @@ export const wrap = <S extends object>(service: S, hook: Hook): S => {
66
66
  const value = (service as Record<string, unknown>)[key]
67
67
  if (Effect.isEffect(value)) {
68
68
  wrapped[key] = hook(key, "before", []).pipe(
69
- Effect.andThen(value as Effect.Effect<unknown, unknown, unknown>),
69
+ Effect.andThen(value),
70
70
  Effect.tap(() => hook(key, "after", []))
71
71
  )
72
72
  } else if (typeof value === "function") {
@@ -75,7 +75,7 @@ export const wrap = <S extends object>(service: S, hook: Hook): S => {
75
75
  const result = method.apply(service, args)
76
76
  return Effect.isEffect(result)
77
77
  ? hook(key, "before", args).pipe(
78
- Effect.andThen(result as Effect.Effect<unknown, unknown, unknown>),
78
+ Effect.andThen(result),
79
79
  Effect.tap(() => hook(key, "after", args))
80
80
  )
81
81
  : result