@smthrs/journal 0.0.0-stage → 1.0.0-rc.13

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.
Files changed (257) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/LICENSE +21 -0
  3. package/README.md +208 -2
  4. package/dist/cjs/CallFact.d.ts +129 -0
  5. package/dist/cjs/CallFact.d.ts.map +1 -0
  6. package/dist/cjs/CallFact.js +106 -0
  7. package/dist/cjs/CallFact.js.map +7 -0
  8. package/dist/cjs/Consensus.d.ts +492 -0
  9. package/dist/cjs/Consensus.d.ts.map +1 -0
  10. package/dist/cjs/Consensus.js +314 -0
  11. package/dist/cjs/Consensus.js.map +7 -0
  12. package/dist/cjs/EngineEvent.d.ts +890 -0
  13. package/dist/cjs/EngineEvent.d.ts.map +1 -0
  14. package/dist/cjs/EngineEvent.js +383 -0
  15. package/dist/cjs/EngineEvent.js.map +7 -0
  16. package/dist/cjs/ExecutionFact.d.ts +216 -0
  17. package/dist/cjs/ExecutionFact.d.ts.map +1 -0
  18. package/dist/cjs/ExecutionFact.js +303 -0
  19. package/dist/cjs/ExecutionFact.js.map +7 -0
  20. package/dist/cjs/Journal.d.ts +617 -0
  21. package/dist/cjs/Journal.d.ts.map +1 -0
  22. package/dist/cjs/Journal.js +190 -0
  23. package/dist/cjs/Journal.js.map +7 -0
  24. package/dist/cjs/JournalEvent.d.ts +421 -0
  25. package/dist/cjs/JournalEvent.d.ts.map +1 -0
  26. package/dist/cjs/JournalEvent.js +281 -0
  27. package/dist/cjs/JournalEvent.js.map +7 -0
  28. package/dist/cjs/JournalGeneration.d.ts +34 -0
  29. package/dist/cjs/JournalGeneration.d.ts.map +1 -0
  30. package/dist/cjs/JournalGeneration.js +73 -0
  31. package/dist/cjs/JournalGeneration.js.map +7 -0
  32. package/dist/cjs/JournalMetrics.d.ts +72 -0
  33. package/dist/cjs/JournalMetrics.d.ts.map +1 -0
  34. package/dist/cjs/JournalMetrics.js +55 -0
  35. package/dist/cjs/JournalMetrics.js.map +7 -0
  36. package/dist/cjs/Migrations.d.ts +42 -0
  37. package/dist/cjs/Migrations.d.ts.map +1 -0
  38. package/dist/cjs/Migrations.js +58 -0
  39. package/dist/cjs/Migrations.js.map +7 -0
  40. package/dist/cjs/OwnerId.d.ts +40 -0
  41. package/dist/cjs/OwnerId.d.ts.map +1 -0
  42. package/dist/cjs/OwnerId.js +40 -0
  43. package/dist/cjs/OwnerId.js.map +7 -0
  44. package/dist/cjs/Projection.d.ts +29 -0
  45. package/dist/cjs/Projection.d.ts.map +1 -0
  46. package/dist/cjs/Projection.js +25 -0
  47. package/dist/cjs/Projection.js.map +7 -0
  48. package/dist/cjs/RedactedLogger.d.ts +121 -0
  49. package/dist/cjs/RedactedLogger.d.ts.map +1 -0
  50. package/dist/cjs/RedactedLogger.js +235 -0
  51. package/dist/cjs/RedactedLogger.js.map +7 -0
  52. package/dist/cjs/Redaction.d.ts +350 -0
  53. package/dist/cjs/Redaction.d.ts.map +1 -0
  54. package/dist/cjs/Redaction.js +962 -0
  55. package/dist/cjs/Redaction.js.map +7 -0
  56. package/dist/cjs/SqlConsensus.d.ts +44 -0
  57. package/dist/cjs/SqlConsensus.d.ts.map +1 -0
  58. package/dist/cjs/SqlConsensus.js +273 -0
  59. package/dist/cjs/SqlConsensus.js.map +7 -0
  60. package/dist/cjs/SqlJournal.d.ts +173 -0
  61. package/dist/cjs/SqlJournal.d.ts.map +1 -0
  62. package/dist/cjs/SqlJournal.js +1568 -0
  63. package/dist/cjs/SqlJournal.js.map +7 -0
  64. package/dist/cjs/StepFact.d.ts +66 -0
  65. package/dist/cjs/StepFact.d.ts.map +1 -0
  66. package/dist/cjs/StepFact.js +68 -0
  67. package/dist/cjs/StepFact.js.map +7 -0
  68. package/dist/cjs/index.d.ts +95 -0
  69. package/dist/cjs/index.d.ts.map +1 -0
  70. package/dist/cjs/index.js +63 -0
  71. package/dist/cjs/index.js.map +7 -0
  72. package/dist/cjs/internal/JournalInternalFault.d.ts +37 -0
  73. package/dist/cjs/internal/JournalInternalFault.d.ts.map +1 -0
  74. package/dist/cjs/internal/JournalInternalFault.js +43 -0
  75. package/dist/cjs/internal/JournalInternalFault.js.map +7 -0
  76. package/dist/cjs/migrations/0001_initial.d.ts +15 -0
  77. package/dist/cjs/migrations/0001_initial.d.ts.map +1 -0
  78. package/dist/cjs/migrations/0001_initial.js +54 -0
  79. package/dist/cjs/migrations/0001_initial.js.map +7 -0
  80. package/dist/cjs/migrations/0002_checkpoints.d.ts +27 -0
  81. package/dist/cjs/migrations/0002_checkpoints.d.ts.map +1 -0
  82. package/dist/cjs/migrations/0002_checkpoints.js +48 -0
  83. package/dist/cjs/migrations/0002_checkpoints.js.map +7 -0
  84. package/dist/cjs/migrations/0003_startup_index.d.ts +15 -0
  85. package/dist/cjs/migrations/0003_startup_index.d.ts.map +1 -0
  86. package/dist/cjs/migrations/0003_startup_index.js +40 -0
  87. package/dist/cjs/migrations/0003_startup_index.js.map +7 -0
  88. package/dist/cjs/migrations/0004_dedup.d.ts +15 -0
  89. package/dist/cjs/migrations/0004_dedup.d.ts.map +1 -0
  90. package/dist/cjs/migrations/0004_dedup.js +57 -0
  91. package/dist/cjs/migrations/0004_dedup.js.map +7 -0
  92. package/dist/cjs/migrations/0005_run_event_type.d.ts +15 -0
  93. package/dist/cjs/migrations/0005_run_event_type.d.ts.map +1 -0
  94. package/dist/cjs/migrations/0005_run_event_type.js +40 -0
  95. package/dist/cjs/migrations/0005_run_event_type.js.map +7 -0
  96. package/dist/cjs/migrations/0006_consensus.d.ts +22 -0
  97. package/dist/cjs/migrations/0006_consensus.d.ts.map +1 -0
  98. package/dist/cjs/migrations/0006_consensus.js +84 -0
  99. package/dist/cjs/migrations/0006_consensus.js.map +7 -0
  100. package/dist/cjs/package.json +1 -0
  101. package/dist/cjs/test/Notifying.d.ts +65 -0
  102. package/dist/cjs/test/Notifying.d.ts.map +1 -0
  103. package/dist/cjs/test/Notifying.js +62 -0
  104. package/dist/cjs/test/Notifying.js.map +7 -0
  105. package/dist/cjs/test/TestJournal.d.ts +43 -0
  106. package/dist/cjs/test/TestJournal.d.ts.map +1 -0
  107. package/dist/cjs/test/TestJournal.js +43 -0
  108. package/dist/cjs/test/TestJournal.js.map +7 -0
  109. package/dist/esm/CallFact.d.ts +129 -0
  110. package/dist/esm/CallFact.d.ts.map +1 -0
  111. package/dist/esm/CallFact.js +96 -0
  112. package/dist/esm/CallFact.js.map +1 -0
  113. package/dist/esm/Consensus.d.ts +492 -0
  114. package/dist/esm/Consensus.d.ts.map +1 -0
  115. package/dist/esm/Consensus.js +548 -0
  116. package/dist/esm/Consensus.js.map +1 -0
  117. package/dist/esm/EngineEvent.d.ts +890 -0
  118. package/dist/esm/EngineEvent.d.ts.map +1 -0
  119. package/dist/esm/EngineEvent.js +614 -0
  120. package/dist/esm/EngineEvent.js.map +1 -0
  121. package/dist/esm/ExecutionFact.d.ts +216 -0
  122. package/dist/esm/ExecutionFact.d.ts.map +1 -0
  123. package/dist/esm/ExecutionFact.js +374 -0
  124. package/dist/esm/ExecutionFact.js.map +1 -0
  125. package/dist/esm/Journal.d.ts +617 -0
  126. package/dist/esm/Journal.d.ts.map +1 -0
  127. package/dist/esm/Journal.js +323 -0
  128. package/dist/esm/Journal.js.map +1 -0
  129. package/dist/esm/JournalEvent.d.ts +421 -0
  130. package/dist/esm/JournalEvent.d.ts.map +1 -0
  131. package/dist/esm/JournalEvent.js +517 -0
  132. package/dist/esm/JournalEvent.js.map +1 -0
  133. package/dist/esm/JournalGeneration.d.ts +34 -0
  134. package/dist/esm/JournalGeneration.d.ts.map +1 -0
  135. package/dist/esm/JournalGeneration.js +71 -0
  136. package/dist/esm/JournalGeneration.js.map +1 -0
  137. package/dist/esm/JournalMetrics.d.ts +72 -0
  138. package/dist/esm/JournalMetrics.d.ts.map +1 -0
  139. package/dist/esm/JournalMetrics.js +79 -0
  140. package/dist/esm/JournalMetrics.js.map +1 -0
  141. package/dist/esm/Migrations.d.ts +42 -0
  142. package/dist/esm/Migrations.d.ts.map +1 -0
  143. package/dist/esm/Migrations.js +59 -0
  144. package/dist/esm/Migrations.js.map +1 -0
  145. package/dist/esm/OwnerId.d.ts +40 -0
  146. package/dist/esm/OwnerId.d.ts.map +1 -0
  147. package/dist/esm/OwnerId.js +33 -0
  148. package/dist/esm/OwnerId.js.map +1 -0
  149. package/dist/esm/Projection.d.ts +29 -0
  150. package/dist/esm/Projection.d.ts.map +1 -0
  151. package/dist/esm/Projection.js +13 -0
  152. package/dist/esm/Projection.js.map +1 -0
  153. package/dist/esm/RedactedLogger.d.ts +121 -0
  154. package/dist/esm/RedactedLogger.d.ts.map +1 -0
  155. package/dist/esm/RedactedLogger.js +445 -0
  156. package/dist/esm/RedactedLogger.js.map +1 -0
  157. package/dist/esm/Redaction.d.ts +350 -0
  158. package/dist/esm/Redaction.d.ts.map +1 -0
  159. package/dist/esm/Redaction.js +1628 -0
  160. package/dist/esm/Redaction.js.map +1 -0
  161. package/dist/esm/SqlConsensus.d.ts +44 -0
  162. package/dist/esm/SqlConsensus.d.ts.map +1 -0
  163. package/dist/esm/SqlConsensus.js +273 -0
  164. package/dist/esm/SqlConsensus.js.map +1 -0
  165. package/dist/esm/SqlJournal.d.ts +173 -0
  166. package/dist/esm/SqlJournal.d.ts.map +1 -0
  167. package/dist/esm/SqlJournal.js +1858 -0
  168. package/dist/esm/SqlJournal.js.map +1 -0
  169. package/dist/esm/StepFact.d.ts +66 -0
  170. package/dist/esm/StepFact.d.ts.map +1 -0
  171. package/dist/esm/StepFact.js +50 -0
  172. package/dist/esm/StepFact.js.map +1 -0
  173. package/dist/esm/index.d.ts +95 -0
  174. package/dist/esm/index.d.ts.map +1 -0
  175. package/dist/esm/index.js +95 -0
  176. package/dist/esm/index.js.map +1 -0
  177. package/dist/esm/internal/JournalInternalFault.d.ts +37 -0
  178. package/dist/esm/internal/JournalInternalFault.d.ts.map +1 -0
  179. package/dist/esm/internal/JournalInternalFault.js +28 -0
  180. package/dist/esm/internal/JournalInternalFault.js.map +1 -0
  181. package/dist/esm/migrations/0001_initial.d.ts +15 -0
  182. package/dist/esm/migrations/0001_initial.d.ts.map +1 -0
  183. package/dist/esm/migrations/0001_initial.js +32 -0
  184. package/dist/esm/migrations/0001_initial.js.map +1 -0
  185. package/dist/esm/migrations/0002_checkpoints.d.ts +27 -0
  186. package/dist/esm/migrations/0002_checkpoints.d.ts.map +1 -0
  187. package/dist/esm/migrations/0002_checkpoints.js +38 -0
  188. package/dist/esm/migrations/0002_checkpoints.js.map +1 -0
  189. package/dist/esm/migrations/0003_startup_index.d.ts +15 -0
  190. package/dist/esm/migrations/0003_startup_index.d.ts.map +1 -0
  191. package/dist/esm/migrations/0003_startup_index.js +18 -0
  192. package/dist/esm/migrations/0003_startup_index.js.map +1 -0
  193. package/dist/esm/migrations/0004_dedup.d.ts +15 -0
  194. package/dist/esm/migrations/0004_dedup.d.ts.map +1 -0
  195. package/dist/esm/migrations/0004_dedup.js +38 -0
  196. package/dist/esm/migrations/0004_dedup.js.map +1 -0
  197. package/dist/esm/migrations/0005_run_event_type.d.ts +15 -0
  198. package/dist/esm/migrations/0005_run_event_type.d.ts.map +1 -0
  199. package/dist/esm/migrations/0005_run_event_type.js +18 -0
  200. package/dist/esm/migrations/0005_run_event_type.js.map +1 -0
  201. package/dist/esm/migrations/0006_consensus.d.ts +22 -0
  202. package/dist/esm/migrations/0006_consensus.d.ts.map +1 -0
  203. package/dist/esm/migrations/0006_consensus.js +69 -0
  204. package/dist/esm/migrations/0006_consensus.js.map +1 -0
  205. package/dist/esm/test/Notifying.d.ts +65 -0
  206. package/dist/esm/test/Notifying.d.ts.map +1 -0
  207. package/dist/esm/test/Notifying.js +62 -0
  208. package/dist/esm/test/Notifying.js.map +1 -0
  209. package/dist/esm/test/TestJournal.d.ts +43 -0
  210. package/dist/esm/test/TestJournal.d.ts.map +1 -0
  211. package/dist/esm/test/TestJournal.js +27 -0
  212. package/dist/esm/test/TestJournal.js.map +1 -0
  213. package/docs/README.md +166 -0
  214. package/docs/api.md +650 -0
  215. package/docs/concepts/compaction.md +157 -0
  216. package/docs/concepts/idempotency.md +127 -0
  217. package/docs/concepts/owner-fence.md +128 -0
  218. package/docs/concepts/redaction.md +222 -0
  219. package/docs/concepts/state-event-authority.md +159 -0
  220. package/docs/concepts/two-channels.md +167 -0
  221. package/docs/guides/commit-state-and-entry.md +114 -0
  222. package/docs/guides/compact-a-run.md +134 -0
  223. package/docs/guides/fold-a-projection.md +106 -0
  224. package/docs/guides/read-a-run.md +139 -0
  225. package/docs/guides/redact-log-output.md +94 -0
  226. package/docs/guides/testing.md +124 -0
  227. package/docs/guides/write-lifecycle-events.md +110 -0
  228. package/docs/installation.md +137 -0
  229. package/docs/quickstart.md +146 -0
  230. package/docs/troubleshooting.md +214 -0
  231. package/package.json +263 -3
  232. package/src/CallFact.ts +117 -0
  233. package/src/Consensus.ts +814 -0
  234. package/src/EngineEvent.ts +823 -0
  235. package/src/ExecutionFact.ts +433 -0
  236. package/src/Journal.ts +688 -0
  237. package/src/JournalEvent.ts +654 -0
  238. package/src/JournalGeneration.ts +83 -0
  239. package/src/JournalMetrics.ts +89 -0
  240. package/src/Migrations.ts +62 -0
  241. package/src/OwnerId.ts +42 -0
  242. package/src/Projection.ts +31 -0
  243. package/src/RedactedLogger.ts +483 -0
  244. package/src/Redaction.ts +1828 -0
  245. package/src/SqlConsensus.ts +384 -0
  246. package/src/SqlJournal.ts +2732 -0
  247. package/src/StepFact.ts +69 -0
  248. package/src/index.ts +109 -0
  249. package/src/internal/JournalInternalFault.ts +40 -0
  250. package/src/migrations/0001_initial.ts +41 -0
  251. package/src/migrations/0002_checkpoints.ts +46 -0
  252. package/src/migrations/0003_startup_index.ts +19 -0
  253. package/src/migrations/0004_dedup.ts +43 -0
  254. package/src/migrations/0005_run_event_type.ts +19 -0
  255. package/src/migrations/0006_consensus.ts +83 -0
  256. package/src/test/Notifying.ts +101 -0
  257. package/src/test/TestJournal.ts +52 -0
@@ -0,0 +1,548 @@
1
+ /**
2
+ * The injectable consensus strategy arbitrating the journal's ownership rules.
3
+ *
4
+ * The journal owns the consensus rules — single writer per run, fenced and
5
+ * unfenced appends, commit-time admission, the generation fence, and steal
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
8
+ * arbitrated: where the lease lives, how liveness is probed, and how the
9
+ * fence is checked at commit time. `Consensus` lives here beside `OwnerId`
10
+ * for the same reason `OwnerId` does: the journal is what it fences.
11
+ * `@smthrs/run-store`'s `Ownership` keeps its public API and rules but
12
+ * delegates arbitration to this strategy.
13
+ *
14
+ * Every operation that reasons about staleness takes the caller's clock
15
+ * reading (`nowMs`) rather than reading a clock itself: staleness (R5) and
16
+ * the monotonic lease stamp are defined against the arbitrating caller's
17
+ * reading, exactly as `RunStore`'s compare-and-swap operations always were,
18
+ * so the recorded lease never differs from the outcome the caller observed.
19
+ *
20
+ * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.
21
+ * Rule constants and their provenance:
22
+ * `packages/smithers/flows/run-store/docs/concepts/leases.md`.
23
+ *
24
+ * Prior art: Effect `EventJournal` (`reference/effect` `unstable/eventlog`)
25
+ * resolves multi-writer by merge with conflict surfacing; driving a run is not
26
+ * mergeable, so this surface deviates to exclusive-writer admission. The
27
+ * fencing and generation semantics follow Temporal's shard `rangeID`
28
+ * (`reference/temporal/service/history/shard/context_impl.go`).
29
+ *
30
+ * @since 1.0.0
31
+ */
32
+ import * as Clock from "effect/Clock";
33
+ import * as Context from "effect/Context";
34
+ import * as Duration from "effect/Duration";
35
+ import * as Effect from "effect/Effect";
36
+ import * as Layer from "effect/Layer";
37
+ import * as Schema from "effect/Schema";
38
+ import { OwnerId } from "./OwnerId.js";
39
+ /**
40
+ * How often the supervision loop pulses to renew the owner's lease.
41
+ *
42
+ * @since 1.0.0
43
+ * @category constants
44
+ */
45
+ export const heartbeatInterval = Duration.seconds(1);
46
+ /**
47
+ * How old a persisted heartbeat must be before a peer may steal the run.
48
+ * Every strategy judges R5 staleness against this one definition.
49
+ *
50
+ * @since 1.0.0
51
+ * @category constants
52
+ */
53
+ export const heartbeatStaleAfter = Duration.seconds(30);
54
+ /**
55
+ * How far the owner's wall clock may run behind a peer's before the lease
56
+ * reasoning stops holding.
57
+ *
58
+ * The owner stamps its heartbeat from *its* clock and a would-be stealer
59
+ * compares that stamp against *its own*, so the two hosts' clock offset is
60
+ * subtracted directly from the owner's real safety margin. This constant names
61
+ * that allowance instead of leaving it implicit in a "two ticks" arithmetic
62
+ * accident, and it is a budgeted allowance, not a guarantee: see
63
+ * {@link heartbeatWriteTolerance} for what happens once it is exceeded.
64
+ *
65
+ * @since 1.0.0
66
+ * @category constants
67
+ */
68
+ export const heartbeatSkewAllowance = Duration.seconds(10);
69
+ /**
70
+ * How long heartbeat writes may go unconfirmed before ownership must be reconfirmed.
71
+ *
72
+ * A peer judges staleness by the persisted heartbeat and may steal the run the
73
+ * instant it is {@link heartbeatStaleAfter} old, so an owner that tolerated
74
+ * write failures for exactly that long would still be executing side effects
75
+ * when the steal is admitted. The budget is therefore
76
+ * {@link heartbeatStaleAfter} minus {@link heartbeatSkewAllowance} (the peer's
77
+ * clock may already read that much later than the owner's) minus one
78
+ * {@link heartbeatInterval} (reserved for one bounded compare-and-swap
79
+ * reconfirmation before the owner interrupts).
80
+ *
81
+ * This bounds, but does not eliminate, overlap. Beyond
82
+ * {@link heartbeatSkewAllowance} of clock offset a peer can be admitted while
83
+ * the old owner is still running. *Durable* writes stay safe regardless — they
84
+ * are fenced by the strategy's commit-time admission, so the displaced owner's
85
+ * writes fail rather than corrupt. Non-durable external side effects (an HTTP
86
+ * call, a spawned process) can genuinely overlap. That is inherent to any
87
+ * wall-clock lease and is stated here rather than asserted away; a caller that
88
+ * cannot tolerate any overlap needs an external fencing token at the side
89
+ * effect itself, not a larger timeout.
90
+ *
91
+ * @since 1.0.0
92
+ * @category constants
93
+ */
94
+ export const heartbeatWriteTolerance = Duration.millis(Duration.toMillis(heartbeatStaleAfter) -
95
+ Duration.toMillis(heartbeatSkewAllowance) -
96
+ Duration.toMillis(heartbeatInterval));
97
+ const staleAfterMs = Duration.toMillis(heartbeatStaleAfter);
98
+ /**
99
+ * Evidence that the owner in an exact run snapshot is no longer live.
100
+ *
101
+ * Defined here because R5 — steal requires staleness plus liveness evidence —
102
+ * is a consensus rule every strategy validates. `@smthrs/run-store`'s
103
+ * `Ownership` re-exports it alongside the probes that mint it.
104
+ *
105
+ * Two of the three kinds are collected outside the strategy:
106
+ * `same-host-pid-dead` is a local process probe, and
107
+ * `cross-host-unreachable-stale` is a reachability judgement the deployment
108
+ * makes. `lease-expired` is different — it asserts only that the persisted
109
+ * heartbeat is older than the staleness cutoff, which is the one claim a
110
+ * strategy can check for itself, and `steal` checks it: the takeover refuses
111
+ * any lease whose heartbeat is still inside the window. It is therefore
112
+ * accepted from a claimant on any host, while the other two stay bound to the
113
+ * host relation that makes them meaningful. `same-host-pid-dead` alone also
114
+ * admits a steal inside the window; see {@link provesDeath}. The observation must carry the
115
+ * exact instant supplied to the consuming operation: `checkedAtMs` must equal
116
+ * that operation's `nowMs`. A caller that probes at T and calls at T+1 is
117
+ * refused and must build fresh evidence.
118
+ *
119
+ * @since 1.0.0
120
+ * @category models
121
+ */
122
+ export const LivenessEvidence = Schema.Struct({
123
+ expectedOwner: OwnerId,
124
+ checkedAtMs: Schema.Number,
125
+ kind: Schema.Literals(["same-host-pid-dead", "cross-host-unreachable-stale", "lease-expired"])
126
+ });
127
+ /**
128
+ * Structural equality on the process identity tuple.
129
+ *
130
+ * @since 1.0.0
131
+ * @category predicates
132
+ */
133
+ export const sameOwner = (left, right) => left.hostId === right.hostId && left.pid === right.pid && left.nonce === right.nonce;
134
+ /**
135
+ * Validates liveness evidence against the owner it claims to disprove.
136
+ *
137
+ * The evidence must name the expected owner, carry the observer's current
138
+ * clock reading, and respect the host rule: a `same-host-pid-dead` probe is
139
+ * only meaningful from the same host, a `cross-host-unreachable-stale`
140
+ * observation only from a different one, and `lease-expired` is host-neutral
141
+ * because the strategy verifies the cutoff it names for itself.
142
+ *
143
+ * @since 1.0.0
144
+ * @category predicates
145
+ */
146
+ export const matchesEvidence = (expectedOwner, observer, nowMs, evidence) => {
147
+ if (!sameOwner(expectedOwner, evidence.expectedOwner) || evidence.checkedAtMs !== nowMs)
148
+ return false;
149
+ switch (evidence.kind) {
150
+ // A pid means nothing outside the host that owns the process namespace.
151
+ case "same-host-pid-dead":
152
+ return expectedOwner.hostId === observer.hostId;
153
+ // Unreachability is what a peer host observes; on the owner's own host it
154
+ // would be an unprobed guess dressed as evidence.
155
+ case "cross-host-unreachable-stale":
156
+ return expectedOwner.hostId !== observer.hostId;
157
+ // The lease is host-neutral, and the strategy verifies the same
158
+ // caller-clock cutoff named by this evidence.
159
+ case "lease-expired":
160
+ return true;
161
+ }
162
+ };
163
+ /**
164
+ * Whether evidence proves the owner gone, so a steal need not wait for its
165
+ * lease to go stale.
166
+ *
167
+ * The lease stands in for a question a peer cannot ask directly: is the owner
168
+ * still running? A `same-host-pid-dead` probe asks it. The claimant read its
169
+ * own host's process table and found no process behind the owner's pid, and a
170
+ * process that does not exist renews no lease and writes nothing, so waiting
171
+ * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with
172
+ * `SIGKILL` is therefore reclaimed by the next process on the same host at
173
+ * once.
174
+ *
175
+ * The evidence must still pass {@link matchesEvidence}, which binds the kind
176
+ * to the same host. One more case is excluded here: an owner recorded with the
177
+ * claimant's own pid names the claimant's process, which is running, so a
178
+ * probe of that pid cannot report it gone. Such evidence keeps the staleness
179
+ * cutoff.
180
+ *
181
+ * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a
182
+ * judgement about a host this process cannot inspect, and `lease-expired` is
183
+ * the cutoff itself.
184
+ *
185
+ * @since 1.0.0
186
+ * @category predicates
187
+ */
188
+ export const provesDeath = (evidence, claimant) => evidence.kind === "same-host-pid-dead" && evidence.expectedOwner.pid !== claimant.pid;
189
+ /**
190
+ * Why a strategy refused a claim, steal, or recovery.
191
+ *
192
+ * @since 1.0.0
193
+ * @category models
194
+ */
195
+ export const RejectionReason = Schema.Literals([
196
+ "already_claimed",
197
+ "owner_held",
198
+ "owner_live",
199
+ "evidence_invalid",
200
+ "claim_fresh",
201
+ "claim_changed",
202
+ "unavailable"
203
+ ]);
204
+ /**
205
+ * A granted claim, carrying the grant timestamp the later activation must
206
+ * present (R4 — the generation fence).
207
+ *
208
+ * @since 1.0.0
209
+ * @category models
210
+ */
211
+ export const Claimed = Schema.TaggedStruct("Claimed", {
212
+ grantedAtMs: Schema.Number
213
+ });
214
+ /**
215
+ * A refused claim, steal, or recovery, with the strategy's typed reason.
216
+ *
217
+ * @since 1.0.0
218
+ * @category models
219
+ */
220
+ export const Rejected = Schema.TaggedStruct("Rejected", {
221
+ reason: RejectionReason
222
+ });
223
+ /**
224
+ * Outcome of `claim` and `steal`.
225
+ *
226
+ * @since 1.0.0
227
+ * @category models
228
+ */
229
+ export const ClaimOutcome = Schema.Union([Claimed, Rejected]);
230
+ /**
231
+ * A claim promoted to ownership.
232
+ *
233
+ * @since 1.0.0
234
+ * @category models
235
+ */
236
+ export const Activated = Schema.TaggedStruct("Activated", {});
237
+ /**
238
+ * The claim or lease the caller presented no longer exists.
239
+ *
240
+ * @since 1.0.0
241
+ * @category models
242
+ */
243
+ export const Lost = Schema.TaggedStruct("Lost", {});
244
+ /**
245
+ * Outcome of `activate`.
246
+ *
247
+ * @since 1.0.0
248
+ * @category models
249
+ */
250
+ export const ActivateOutcome = Schema.Union([Activated, Lost]);
251
+ /**
252
+ * A renewed lease, carrying the monotonic heartbeat stamp the strategy
253
+ * recorded — the maximum of the stored stamp and the caller's reading, so a
254
+ * late pulse never moves the lease backwards.
255
+ *
256
+ * @since 1.0.0
257
+ * @category models
258
+ */
259
+ export const Renewed = Schema.TaggedStruct("Renewed", {
260
+ heartbeatAtMs: Schema.Number
261
+ });
262
+ /**
263
+ * Outcome of `heartbeat` and `reconfirm`.
264
+ *
265
+ * @since 1.0.0
266
+ * @category models
267
+ */
268
+ export const HeartbeatOutcome = Schema.Union([Renewed, Lost]);
269
+ /**
270
+ * A stale claim cleared after its claimant was proven dead.
271
+ *
272
+ * @since 1.0.0
273
+ * @category models
274
+ */
275
+ export const Recovered = Schema.TaggedStruct("Recovered", {});
276
+ /**
277
+ * Outcome of `recover`.
278
+ *
279
+ * @since 1.0.0
280
+ * @category models
281
+ */
282
+ export const RecoverOutcome = Schema.Union([Recovered, Rejected]);
283
+ /**
284
+ * Failure raised by a consensus strategy.
285
+ *
286
+ * `fence_lost` is `guard`'s refusal: the supplied owner no longer holds the
287
+ * run, so the fenced write it joins must not commit. `persistence_failed`
288
+ * wraps a strategy's storage failure; the original cause is preserved so the
289
+ * durable writer's retry classification still sees a transient conflict
290
+ * through the wrapper.
291
+ *
292
+ * @since 1.0.0
293
+ * @category errors
294
+ */
295
+ export class ConsensusError extends Schema.TaggedError()("@smthrs/journal/ConsensusError", {
296
+ code: Schema.Literals(["fence_lost", "persistence_failed"]),
297
+ message: Schema.String,
298
+ cause: Schema.optional(Schema.Unknown)
299
+ }) {
300
+ }
301
+ /**
302
+ * Context service for the injected consensus strategy.
303
+ *
304
+ * @since 1.0.0
305
+ * @category services
306
+ */
307
+ export class Consensus extends Context.Service()("@smthrs/journal/Consensus") {
308
+ }
309
+ /**
310
+ * Constructs a consensus service from an implementation.
311
+ *
312
+ * @since 1.0.0
313
+ * @category constructors
314
+ */
315
+ export const make = (implementation) => Consensus.of(implementation);
316
+ const rejected = (reason) => ({ _tag: "Rejected", reason });
317
+ const claimed = (grantedAtMs) => ({ _tag: "Claimed", grantedAtMs });
318
+ const lost = { _tag: "Lost" };
319
+ const activated = { _tag: "Activated" };
320
+ const recovered = { _tag: "Recovered" };
321
+ /**
322
+ * The refusal `guard` raises for an owner that no longer holds the run.
323
+ *
324
+ * @since 1.0.0
325
+ * @category errors
326
+ */
327
+ export const fenceLost = (runId, owner) => new ConsensusError({
328
+ code: "fence_lost",
329
+ message: `run ${runId} is no longer owned by ${owner.hostId}:${owner.pid}:${owner.nonce}`
330
+ });
331
+ /**
332
+ * Constructs a strategy that arbitrates nothing: claims are refused, leases
333
+ * are never held, and every fenced write is rejected.
334
+ *
335
+ * @since 1.0.0
336
+ * @category constructors
337
+ */
338
+ export const makeNoop = (overrides = {}) => Consensus.of({
339
+ claim: Effect.fn("Consensus.claim")(() => Effect.succeed(rejected("unavailable"))),
340
+ activate: Effect.fn("Consensus.activate")(() => Effect.succeed(lost)),
341
+ heartbeat: Effect.fn("Consensus.heartbeat")(() => Effect.succeed(lost)),
342
+ reconfirm: Effect.fn("Consensus.reconfirm")(() => Effect.succeed(lost)),
343
+ release: Effect.fn("Consensus.release")(() => Effect.void),
344
+ steal: Effect.fn("Consensus.steal")(() => Effect.succeed(rejected("unavailable"))),
345
+ recover: Effect.fn("Consensus.recover")(() => Effect.succeed(rejected("unavailable"))),
346
+ guard: Effect.fn("Consensus.guard")((runId, owner) => Effect.fail(fenceLost(runId, owner))),
347
+ withPermit: () => Effect.fail(new ConsensusError({ code: "persistence_failed", message: "resource leases unavailable" })),
348
+ ...overrides
349
+ });
350
+ /**
351
+ * Provides the refusing strategy stub.
352
+ *
353
+ * @since 1.0.0
354
+ * @category layers
355
+ */
356
+ export const layerNoop = (overrides = {}) => Layer.succeed(Consensus)(makeNoop(overrides));
357
+ /**
358
+ * Constructs the in-memory single-process strategy.
359
+ *
360
+ * @since 1.0.0
361
+ * @category constructors
362
+ */
363
+ export const makeLocal = Effect.sync(() => {
364
+ const leases = new Map();
365
+ const leaseOf = (runId) => {
366
+ const existing = leases.get(runId);
367
+ if (existing !== undefined)
368
+ return existing;
369
+ const fresh = { owner: undefined, claim: undefined };
370
+ leases.set(runId, fresh);
371
+ return fresh;
372
+ };
373
+ const prune = (runId, lease) => {
374
+ if (lease.owner === undefined && lease.claim === undefined) {
375
+ leases.delete(runId);
376
+ }
377
+ };
378
+ const service = Consensus.of({
379
+ withPermit: (key, owner, isAlive, effect) => resourcePermit(service, () => Effect.sync(() => leases.get(key)), key, owner, isAlive, effect),
380
+ claim: Effect.fn("Consensus.claim")((runId, claimant, nowMs) => Effect.sync(() => {
381
+ const lease = leaseOf(runId);
382
+ if (lease.claim !== undefined)
383
+ return rejected("already_claimed");
384
+ if (lease.owner !== undefined)
385
+ return rejected("owner_held");
386
+ lease.claim = { id: claimant, claimedAtMs: nowMs };
387
+ return claimed(nowMs);
388
+ })),
389
+ activate: Effect.fn("Consensus.activate")((runId, owner, grantedAtMs, nowMs) => Effect.sync(() => {
390
+ const lease = leaseOf(runId);
391
+ if (lease.claim === undefined ||
392
+ !sameOwner(lease.claim.id, owner) ||
393
+ lease.claim.claimedAtMs !== grantedAtMs) {
394
+ prune(runId, lease);
395
+ return lost;
396
+ }
397
+ lease.claim = undefined;
398
+ lease.owner = { id: owner, grantedAtMs, heartbeatAtMs: nowMs };
399
+ return activated;
400
+ })),
401
+ heartbeat: Effect.fn("Consensus.heartbeat")((runId, owner, nowMs) => Effect.sync(() => {
402
+ const lease = leases.get(runId);
403
+ if (lease?.owner === undefined || !sameOwner(lease.owner.id, owner))
404
+ return lost;
405
+ lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs);
406
+ return { _tag: "Renewed", heartbeatAtMs: lease.owner.heartbeatAtMs };
407
+ })),
408
+ reconfirm: Effect.fn("Consensus.reconfirm")((runId, owner, nowMs) => Effect.sync(() => {
409
+ const lease = leases.get(runId);
410
+ if (lease?.owner === undefined || lease.claim !== undefined || !sameOwner(lease.owner.id, owner))
411
+ return lost;
412
+ lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs);
413
+ return { _tag: "Renewed", heartbeatAtMs: lease.owner.heartbeatAtMs };
414
+ })),
415
+ release: Effect.fn("Consensus.release")((runId, owner) => Effect.sync(() => {
416
+ const lease = leases.get(runId);
417
+ if (lease === undefined)
418
+ return;
419
+ if (lease.claim !== undefined && sameOwner(lease.claim.id, owner)) {
420
+ lease.claim = undefined;
421
+ }
422
+ if (lease.owner !== undefined && sameOwner(lease.owner.id, owner)) {
423
+ lease.owner = undefined;
424
+ }
425
+ prune(runId, lease);
426
+ })),
427
+ steal: Effect.fn("Consensus.steal")((runId, claimant, nowMs, evidence) => Effect.sync(() => {
428
+ if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {
429
+ return rejected("evidence_invalid");
430
+ }
431
+ const lease = leases.get(runId);
432
+ if (lease?.claim !== undefined)
433
+ return rejected("already_claimed");
434
+ if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {
435
+ return rejected("evidence_invalid");
436
+ }
437
+ if (!provesDeath(evidence, claimant) && lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) {
438
+ return rejected("owner_live");
439
+ }
440
+ lease.claim = { id: claimant, claimedAtMs: nowMs };
441
+ return claimed(nowMs);
442
+ })),
443
+ recover: Effect.fn("Consensus.recover")((runId, staleClaimant, grantedAtMs, observer, nowMs, evidence) => Effect.sync(() => {
444
+ if (!matchesEvidence(staleClaimant, observer, nowMs, evidence))
445
+ return rejected("evidence_invalid");
446
+ const lease = leases.get(runId);
447
+ if (lease?.claim === undefined ||
448
+ !sameOwner(lease.claim.id, staleClaimant) ||
449
+ lease.claim.claimedAtMs !== grantedAtMs) {
450
+ return rejected("claim_changed");
451
+ }
452
+ if (lease.claim.claimedAtMs >= nowMs - staleAfterMs)
453
+ return rejected("claim_fresh");
454
+ lease.claim = undefined;
455
+ prune(runId, lease);
456
+ return recovered;
457
+ })),
458
+ guard: Effect.fn("Consensus.guard")((runId, owner) => Effect.suspend(() => {
459
+ const lease = leases.get(runId);
460
+ return lease?.owner !== undefined && sameOwner(lease.owner.id, owner)
461
+ ? Effect.void
462
+ : Effect.fail(fenceLost(runId, owner));
463
+ }))
464
+ });
465
+ return service;
466
+ });
467
+ /**
468
+ * Provides the in-memory single-process strategy.
469
+ *
470
+ * The lease lives in process memory, so R3 is exact within the process — the
471
+ * strategy's transitions and the serialized append transactions interleave
472
+ * atomically on one event loop — and browser support needs nothing beyond
473
+ * this layer plus the browser-safe journal. State is per layer build: provide
474
+ * one instance to every service that must agree on it, which is what
475
+ * `SqlJournal.layerWith` and `RunStore.layerWith` exist for.
476
+ *
477
+ * The lease is not part of any database transaction: a transition made inside
478
+ * a `Journal.transact` that later rolls back stays applied in memory, so the
479
+ * lease and a rolled-back run row can disagree until the next transition.
480
+ * `SqlConsensus` keeps the two in one transaction; prefer it wherever a
481
+ * database is present.
482
+ *
483
+ * @since 1.0.0
484
+ * @category layers
485
+ */
486
+ export const layerLocal = Layer.effect(Consensus, makeLocal);
487
+ /**
488
+ * Shares the existing consensus lease lifecycle with named engine resources.
489
+ * The reader is private to the strategy; resource leases never create runs.
490
+ * @since 1.0.0
491
+ * @category constructors
492
+ */
493
+ export const resourcePermit = (strategy, read, key, owner, isAlive, effect) => Effect.uninterruptibleMask((restore) => {
494
+ const acquire = Effect.gen(function* () {
495
+ while (true) {
496
+ const admitted = yield* Effect.uninterruptible(Effect.gen(function* () {
497
+ const nowMs = yield* Clock.currentTimeMillis;
498
+ // A held resource needs a read, not a rejected write transaction on
499
+ // every poll. Leave the writer available for its owner's heartbeat.
500
+ const lease = yield* read();
501
+ let grant = lease?.owner === undefined && lease?.claim === undefined
502
+ ? yield* strategy.claim(key, owner, nowMs)
503
+ : rejected("owner_held");
504
+ if (grant._tag === "Rejected") {
505
+ const held = lease?.claim === undefined
506
+ ? lease?.owner
507
+ : { id: lease.claim.id, heartbeatAtMs: lease.claim.claimedAtMs };
508
+ if (held !== undefined &&
509
+ (held.heartbeatAtMs < nowMs - staleAfterMs ||
510
+ (lease?.claim === undefined && held.id.hostId === owner.hostId && held.id.pid !== owner.pid)) &&
511
+ !(yield* isAlive(held.id, { claimant: owner, heartbeatAtMs: held.heartbeatAtMs, nowMs }))) {
512
+ const evidence = {
513
+ expectedOwner: held.id,
514
+ checkedAtMs: nowMs,
515
+ kind: held.id.hostId === owner.hostId && held.id.pid !== owner.pid
516
+ ? "same-host-pid-dead"
517
+ : "lease-expired"
518
+ };
519
+ if (lease?.claim !== undefined) {
520
+ yield* strategy.recover(key, held.id, lease.claim.claimedAtMs, owner, nowMs, evidence);
521
+ }
522
+ else {
523
+ grant = yield* strategy.steal(key, owner, nowMs, evidence);
524
+ }
525
+ }
526
+ }
527
+ if (grant._tag !== "Claimed")
528
+ return false;
529
+ const activated = yield* strategy.activate(key, owner, grant.grantedAtMs, nowMs).pipe(Effect.onError(() => strategy.release(key, owner).pipe(Effect.orDie)));
530
+ if (activated._tag === "Activated")
531
+ return true;
532
+ yield* strategy.release(key, owner);
533
+ return false;
534
+ }));
535
+ if (admitted)
536
+ return;
537
+ yield* restore(Effect.sleep("50 millis"));
538
+ }
539
+ });
540
+ const pulse = Effect.forever(Effect.sleep(heartbeatInterval).pipe(Effect.andThen(Effect.gen(function* () {
541
+ const nowMs = yield* Clock.currentTimeMillis;
542
+ const renewed = yield* strategy.reconfirm(key, owner, nowMs).pipe(Effect.timeout(heartbeatInterval));
543
+ if (renewed._tag !== "Renewed")
544
+ return yield* Effect.fail(fenceLost(key, owner));
545
+ })), Effect.mapError((cause) => new ConsensusError({ code: "fence_lost", message: fenceLost(key, owner).message, cause }))));
546
+ return acquire.pipe(Effect.andThen(() => restore(Effect.raceFirst(effect, pulse)).pipe(Effect.ensuring(strategy.release(key, owner).pipe(Effect.orDie)))));
547
+ });
548
+ //# sourceMappingURL=Consensus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Consensus.js","sourceRoot":"","sources":["../../src/Consensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM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AAI,CAClC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;QACjC,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,iBAAiB,CAAA;QAC5C,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAA;QACpG,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAA;IAClF,CAAC,CAAC,CAAC,EACH,MAAM,CAAC,QAAQ,CAAC,CAAC,KAAK,EAAE,EAAE,CACxB,IAAI,cAAc,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC,CAC1F,CACF,CACF,CAAA;IACD,OAAO,OAAO,CAAC,IAAI,CACjB,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAClB,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAC3C,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CACjE,CACF,CACF,CAAA;AACH,CAAC,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 Clock from \"effect/Clock\"\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 /** Holds a named durable resource lease through work, with heartbeat supervision. */\n readonly withPermit: <A, E, R>(\n key: string,\n owner: OwnerId,\n isAlive: (\n owner: OwnerId,\n context: { readonly claimant: OwnerId; readonly heartbeatAtMs: number | null; readonly nowMs: number }\n ) => Effect.Effect<boolean>,\n effect: Effect.Effect<A, E, R>\n ) => Effect.Effect<A, E | ConsensusError, R>\n\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 withPermit: () =>\n Effect.fail(new ConsensusError({ code: \"persistence_failed\", message: \"resource leases unavailable\" })),\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 const service: Service = Consensus.of({\n withPermit: (key, owner, isAlive, effect) =>\n resourcePermit(service, () => Effect.sync(() => leases.get(key)), key, owner, isAlive, effect),\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 return service\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\n/**\n * Shares the existing consensus lease lifecycle with named engine resources.\n * The reader is private to the strategy; resource leases never create runs.\n * @since 1.0.0\n * @category constructors\n */\nexport const resourcePermit = <A, E, R>(\n strategy: Omit<Service, \"withPermit\">,\n read: () => Effect.Effect<LocalLease | undefined, ConsensusError>,\n key: string,\n owner: OwnerId,\n isAlive: Parameters<Service[\"withPermit\"]>[2],\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E | ConsensusError, R> =>\n Effect.uninterruptibleMask((restore) => {\n const acquire = Effect.gen(function*() {\n while (true) {\n const admitted = yield* Effect.uninterruptible(Effect.gen(function*() {\n const nowMs = yield* Clock.currentTimeMillis\n // A held resource needs a read, not a rejected write transaction on\n // every poll. Leave the writer available for its owner's heartbeat.\n const lease = yield* read()\n let grant = lease?.owner === undefined && lease?.claim === undefined\n ? yield* strategy.claim(key, owner, nowMs)\n : rejected(\"owner_held\")\n if (grant._tag === \"Rejected\") {\n const held = lease?.claim === undefined\n ? lease?.owner\n : { id: lease.claim.id, heartbeatAtMs: lease.claim.claimedAtMs }\n if (\n held !== undefined &&\n (held.heartbeatAtMs < nowMs - staleAfterMs ||\n (lease?.claim === undefined && held.id.hostId === owner.hostId && held.id.pid !== owner.pid)) &&\n !(yield* isAlive(held.id, { claimant: owner, heartbeatAtMs: held.heartbeatAtMs, nowMs }))\n ) {\n const evidence: LivenessEvidence = {\n expectedOwner: held.id,\n checkedAtMs: nowMs,\n kind: held.id.hostId === owner.hostId && held.id.pid !== owner.pid\n ? \"same-host-pid-dead\"\n : \"lease-expired\"\n }\n if (lease?.claim !== undefined) {\n yield* strategy.recover(key, held.id, lease.claim.claimedAtMs, owner, nowMs, evidence)\n } else {\n grant = yield* strategy.steal(key, owner, nowMs, evidence)\n }\n }\n }\n if (grant._tag !== \"Claimed\") return false\n const activated = yield* strategy.activate(key, owner, grant.grantedAtMs, nowMs).pipe(\n Effect.onError(() => strategy.release(key, owner).pipe(Effect.orDie))\n )\n if (activated._tag === \"Activated\") return true\n yield* strategy.release(key, owner)\n return false\n }))\n if (admitted) return\n yield* restore(Effect.sleep(\"50 millis\"))\n }\n })\n const pulse = Effect.forever(\n Effect.sleep(heartbeatInterval).pipe(\n Effect.andThen(Effect.gen(function*() {\n const nowMs = yield* Clock.currentTimeMillis\n const renewed = yield* strategy.reconfirm(key, owner, nowMs).pipe(Effect.timeout(heartbeatInterval))\n if (renewed._tag !== \"Renewed\") return yield* Effect.fail(fenceLost(key, owner))\n })),\n Effect.mapError((cause) =>\n new ConsensusError({ code: \"fence_lost\", message: fenceLost(key, owner).message, cause })\n )\n )\n )\n return acquire.pipe(\n Effect.andThen(() =>\n restore(Effect.raceFirst(effect, pulse)).pipe(\n Effect.ensuring(strategy.release(key, owner).pipe(Effect.orDie))\n )\n )\n )\n })\n"]}