@serfab/cadre-core 0.9.0 → 0.11.0

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 (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -0,0 +1,483 @@
1
+ import debug from 'debug';
2
+ import { unwrapError } from '@quereus/quereus';
3
+
4
+ const log = debug('sereus:cadre:control-db');
5
+
6
+ /**
7
+ * Bounded retry for TRANSIENT control-write failures — the classifier and loop behind
8
+ * `ControlDatabase.lockedWithRetry`, the single funnel every local control write passes
9
+ * through.
10
+ *
11
+ * Why this exists: the control database replicates every block to the whole party, so a
12
+ * three-machine party commits control writes unanimously (`ceil(3 × 0.75) = 3` approvals) —
13
+ * and no `superMajorityThreshold` can lower that bar without violating Optimystic's
14
+ * partition-safety condition at the shipped admission fraction (the arithmetic lives in
15
+ * `docs/architecture.md` → "Replication cluster size"). Cadre therefore accepts unanimity
16
+ * and absorbs the transient half of its cost here: a write that failed because the cohort
17
+ * did not ANSWER (a stream reset mid-connection-formation, zero approvals) is re-presented
18
+ * a moment later, which the degraded-cohort-member scenario measured as safe (a failed
19
+ * write rolls back, nothing half-commits) and effective (the next write commits in ~1 s).
20
+ *
21
+ * A write somebody actually REJECTED is never retried — re-presenting it would re-present
22
+ * a spent signature against a cohort that already said no.
23
+ *
24
+ * TWO policies ship from here, and the split is deliberate: the default
25
+ * ({@link isRetriableControlWriteFailure}, {@link CONTROL_WRITE_ATTEMPTS}) sits under every
26
+ * control write, and {@link SCHEMA_INIT_RETRY_POLICY} is opted into by
27
+ * `ControlDatabase.loadSchema` alone. The widened one absorbs one extra failure class whose
28
+ * re-run safety holds for schema DDL and NOT for writes in general; anything added to the default
29
+ * list must be safe for all ~19 callers.
30
+ *
31
+ * Lives outside `control-database.ts` so a spec can drive the classifier against real engine
32
+ * errors without importing the whole database class.
33
+ */
34
+
35
+ /**
36
+ * Attempts allowed per control write: the first, plus two retries of a transiently-failed
37
+ * cluster commit. Bounded so a genuinely unreachable cohort terminates in the transactor's
38
+ * own error rather than spinning; two retries covers the observed failure (a stream still
39
+ * forming when the write fired) with margin.
40
+ */
41
+ export const CONTROL_WRITE_ATTEMPTS = 3;
42
+
43
+ /**
44
+ * Attempts allowed for {@link SCHEMA_INIT_RETRY_POLICY}, the one call site that also absorbs a
45
+ * self-coordination refusal.
46
+ *
47
+ * Two more than {@link CONTROL_WRITE_ATTEMPTS} because what this retry buys is wall-clock for a
48
+ * cold-starting node's bootstrap dials to land, and because the refusal is cheap to re-provoke
49
+ * relative to a cluster round-trip: `findCoordinator` already spends its own bounded wait before
50
+ * raising (3 attempts, 500 ms apart, `db-p2p/src/libp2p-key-network.ts` ~422) and then decides
51
+ * LOCALLY that it may not elect itself, so no peer is contacted and no cohort deadline is
52
+ * consumed.
53
+ *
54
+ * Note that the ~1 s `findCoordinator` spends internally is real, on top of this policy's own
55
+ * backoff — which is exactly why {@link CONTROL_WRITE_RETRY_BUDGET_MS} and not this count is what
56
+ * actually terminates the loop in the worst case.
57
+ */
58
+ export const SCHEMA_INIT_ATTEMPTS = 5;
59
+
60
+ /**
61
+ * Elapsed-time ceiling on the whole retry loop, measured from the START of the first
62
+ * attempt and checked after a failed attempt BEFORE sleeping.
63
+ *
64
+ * This budget — not the attempt count — is what makes the policy safe to sit under every
65
+ * control write. A transient failure (stream reset while a connection is still forming)
66
+ * surfaces in well under a second, so it is retried and the loop adds at most ~2.2 s. A
67
+ * genuinely silent cohort member fails at ~20 s (two 10 s `ClusterClient` response-deadline
68
+ * attempts, measured in `control-write-degraded-cohort-member.integration.ts`), which
69
+ * already exceeds this budget when attempt 1 returns — so that case is surfaced immediately
70
+ * and retry adds ZERO latency to the case where it cannot help.
71
+ */
72
+ export const CONTROL_WRITE_RETRY_BUDGET_MS = 10_000;
73
+
74
+ /**
75
+ * Backoff before retry N, jittered ±50% (so the first sleep is 125–375 ms — the jitter can
76
+ * never floor a delay to zero). Each single sleep is additionally capped at the LARGEST
77
+ * delay in the list, so a `stop()` racing a backoff is never held up by more than ~1 s.
78
+ * There is no `AbortSignal` at this seam to cancel a sleep outright; the cap is the
79
+ * substitute, deliberately not plumbing one through every write path.
80
+ */
81
+ const CONTROL_WRITE_RETRY_DELAYS_MS: readonly number[] = [250, 1_000];
82
+
83
+ /**
84
+ * Backoff for {@link SCHEMA_INIT_RETRY_POLICY}, jittered and capped the same way. Worst case
85
+ * ~4.6 s of sleep across four retries (375 + 750 + 1500 + 2000, each capped at the largest base),
86
+ * which stays inside {@link CONTROL_WRITE_RETRY_BUDGET_MS} — the budget still terminates the loop
87
+ * first if any single attempt is itself slow.
88
+ *
89
+ * Sized against measured facts, not guessed:
90
+ *
91
+ * - the self-coordination guard clears the moment the node has ONE connection again (both
92
+ * branches that raise `grace-period-not-elapsed` require `getConnections().length === 0`), not
93
+ * when the 30 s grace period expires — so this does NOT need to cover the grace period, only
94
+ * the gap until a bootstrap dial completes;
95
+ * - the guard's 30 s `gracePeriodMs` cannot be tuned from this repo anyway: no caller in either
96
+ * repo passes a `SelfCoordinationConfig`, so the default is always in force;
97
+ * - a node that has NEVER connected is waved through as a bootstrap node (network high-water
98
+ * mark of 1), so this retry only ever delays a node that HAS seen peers. One whose peers are
99
+ * gone for good still fails, ~4.6 s later — which is why the budget stays at the shared
100
+ * ceiling rather than stretching to cover the full 30 s window.
101
+ */
102
+ const SCHEMA_INIT_RETRY_DELAYS_MS: readonly number[] = [250, 500, 1_000, 2_000];
103
+
104
+ /** The network transactor's aggregate, raised when some cohort peers gave no usable answer. */
105
+ const TRANSACTOR_AGGREGATE = /Some peers did not complete:/;
106
+
107
+ /**
108
+ * How the aggregate's per-batch details name a SINGLE-block batch — the shape both the block
109
+ * read (`get`) and phase 1 (`pend`) format, and the only shape safe to re-present.
110
+ */
111
+ const SINGLE_BLOCK_BATCH_TOKEN = '[block:';
112
+
113
+ /**
114
+ * How the aggregate's per-batch details name a MULTI-block batch — the shape phase 2
115
+ * (`commitBlocks`) formats, and the marker of an outcome too indeterminate to retry.
116
+ */
117
+ const COMMIT_BATCH_TOKEN = '[blocks:';
118
+
119
+ /**
120
+ * The cluster coordinator's super-majority shortfall (`db-p2p/src/repo/cluster-coordinator.ts`),
121
+ * matched ONLY with a ZERO rejection count. The same message with a non-zero count means a
122
+ * member actually voted no (that branch carries `membership-not-admitted` rejections), and
123
+ * retrying it would re-present a spent signature to a cohort that already refused it. This one
124
+ * is raised while collecting PROMISES, before any commit, so re-presenting it is safe. A
125
+ * decisive rejection is a different error entirely (`ValidatorRejectionError`,
126
+ * `Transaction rejected by validators`), which this classifier also never matches.
127
+ */
128
+ const SUPER_MAJORITY_SHORTFALL_UNANSWERED =
129
+ /Failed to get super-majority: \d+\/\d+ approvals \(needed \d+, 0 rejections\)/;
130
+
131
+ /**
132
+ * Is this a transactor aggregate from a phase where nothing can have committed yet?
133
+ *
134
+ * The transactor raises `Some peers did not complete:` from three sites
135
+ * (`db-core/src/transactor/network-transactor.ts`), and only two of them are safe to
136
+ * re-present:
137
+ *
138
+ * - `get` (a block read, which a write body also performs) and `pend` (phase 1) fail before
139
+ * anything commits, so the write is known not to have landed;
140
+ * - `commitBlocks` (phase 2) is REACHABLE here and NOT safe. `commitBlock` throws the
141
+ * aggregate when a header/tail commit got NO response at all — precisely the transient
142
+ * class this retry targets — and that escapes `commit()`, survives `TransactorSource`'s
143
+ * cancel-and-rethrow (cancel reaches PENDING actions only; a peer that already committed
144
+ * stays committed) and `Collection.syncInternal` (which retries StaleFailure RETURN values,
145
+ * not throws), reaching this funnel QuereusError-wrapped. The tail commit is one batch to
146
+ * one coordinator running consensus internally, so a no-response there is INDETERMINATE:
147
+ * the commit may have completed with only the response lost. Re-running the write body over
148
+ * a write that landed turns a success into a constraint failure (e.g.
149
+ * `UNIQUE constraint failed: CadrePeer.PeerId`). Surfacing the transient error instead lets
150
+ * the caller re-read committed state and decide. Commit-phase messages are vetoed by
151
+ * {@link reportsIndeterminateCommit}, not here.
152
+ *
153
+ * The `cause` chain does not discriminate the phases — a commit-phase aggregate carries the
154
+ * same stream-reset/dial error a pend-phase one does. The per-batch DETAIL text does: `get`
155
+ * and `pend` format `<peerId>[block:<id>](<status>)`, `commitBlocks` formats
156
+ * `<peerId>[blocks:<count>](<status>)`. `[block:` cannot occur inside `[blocks:`, so the two
157
+ * tokens are disjoint and separate the phases.
158
+ *
159
+ * NOTE: the discriminator is a formatting detail of another repo. If Optimystic ever reformats
160
+ * those per-batch details, this fails CLOSED — the aggregate stops matching and control writes
161
+ * simply stop being retried, silently losing the absorption rather than doing anything unsafe.
162
+ * The guard against that is live: `control-write-degraded-cohort-member.integration.ts` asserts
163
+ * this classifier against the real degraded-cohort failure object and asserts the `[block:`
164
+ * token on the live aggregate; if it reddens there, an upstream reformat is the first thing to
165
+ * check.
166
+ *
167
+ * An aggregate whose details came out EMPTY (possible when `formatBatchStatuses` has no
168
+ * batches to format) carries neither token, matches nothing here, and is not retried — an
169
+ * unattributable failure is not a proven non-commit.
170
+ */
171
+ function isUncommittedTransactorAggregate(message: string): boolean {
172
+ return TRANSACTOR_AGGREGATE.test(message) && message.includes(SINGLE_BLOCK_BATCH_TOKEN);
173
+ }
174
+
175
+ /**
176
+ * Does ANY message in the failure's `cause` chain describe a commit-phase batch — i.e. an
177
+ * outcome nobody can call committed or not?
178
+ *
179
+ * Vetoes the whole chain rather than the one message carrying the token, and vetoes it
180
+ * regardless of which matcher would otherwise have claimed it. The narrower per-message rule
181
+ * would already catch every shape the transactor is known to build (a commit-phase aggregate
182
+ * emits `[blocks:` for every batch it formats, and embeds its cause's message inline as
183
+ * `root: …`, so both tokens land in one string) — but "known to build" is an argument about
184
+ * another repo's error assembly, and this way an indeterminate commit anywhere in the chain
185
+ * costs a retry we could have had instead of risking a re-run over a write that landed.
186
+ */
187
+ function reportsIndeterminateCommit(messages: readonly string[]): boolean {
188
+ return messages.some(message => message.includes(COMMIT_BATCH_TOKEN));
189
+ }
190
+
191
+ /** The coordinator's shortfall, raised pre-commit, with nobody having voted no. */
192
+ function isUnansweredSuperMajorityShortfall(message: string): boolean {
193
+ return SUPER_MAJORITY_SHORTFALL_UNANSWERED.test(message);
194
+ }
195
+
196
+ /**
197
+ * Optimystic refusing to let a node elect ITSELF coordinator because its last connection dropped
198
+ * less than the guard's grace period ago (`Libp2pKeyPeerNetwork.shouldAllowSelfCoordination` →
199
+ * `findCoordinator`, `db-p2p/src/libp2p-key-network.ts`).
200
+ *
201
+ * Matched ONLY with the `grace-period-not-elapsed` reason. The same sentence is raised with three
202
+ * other reasons and none of them is worth a retry: `disabled` is static configuration, and
203
+ * `partition-detected` / `suspicious-shrinkage` describe a network condition that will not resolve
204
+ * inside a few seconds of backoff. The grace-period one WILL — it clears as soon as the node holds
205
+ * one connection again, which a cold-starting node dialling its bootstrap peers is actively
206
+ * working on.
207
+ *
208
+ * NOTE: matched by TEXT, not by type, and that is forced rather than chosen.
209
+ * `FindCoordinatorError` (`code: 'SELF_COORDINATION_BLOCKED'`) is exported from `@optimystic/db-p2p`
210
+ * and this package depends on it, but the error OBJECT does not survive the trip:
211
+ * `OptimysticVirtualTable.initialize` catches and rethrows as `new Error(message)` with no `cause`
212
+ * (`quereus-plugin-optimystic/src/optimystic-module.ts`), so only the text reaches this repo. Like
213
+ * every matcher here this fails CLOSED — a rewording upstream stops the retry engaging, it never
214
+ * makes it unsafe.
215
+ */
216
+ const SELF_COORDINATION_GRACE_REFUSAL =
217
+ /Self-coordination blocked: grace-period-not-elapsed\. No coordinator available for key\./;
218
+
219
+ /** Self-coordination refused because the node's last connection dropped moments ago. */
220
+ function isSelfCoordinationGraceRefusal(message: string): boolean {
221
+ return SELF_COORDINATION_GRACE_REFUSAL.test(message);
222
+ }
223
+
224
+ /**
225
+ * Every message in the failure's `cause` chain.
226
+ *
227
+ * `unwrapError` declares its `message` as `string`, but it follows `.cause` without checking what
228
+ * that holds — a chain link that is not an `Error` (a stream rejected with a bare string reason,
229
+ * an `AbortSignal.reason` that is a plain object) yields `undefined` there, and calling
230
+ * `.includes` on it would throw a `TypeError` out of this classifier, INSIDE `retryControlWrite`'s
231
+ * catch, replacing the real control-write failure with a confusing one. Non-strings are dropped:
232
+ * a link nobody can read is a link that matches nothing, which is already the conservative answer.
233
+ *
234
+ * NOTE: a cause chain with a CYCLE would spin forever inside `unwrapError` itself. No error in
235
+ * this repo builds one; if a hang ever localises to a control-write failure path, look there.
236
+ */
237
+ function chainMessages(error: Error): string[] {
238
+ return unwrapError(error)
239
+ .map(({ message }) => message)
240
+ .filter(message => typeof message === 'string');
241
+ }
242
+
243
+ /**
244
+ * The error messages that mean "the cohort did not answer AND nothing committed", and nothing
245
+ * else. The observed one-shot failure was `registerSelf()` racing a connection still forming:
246
+ * a read/pend-phase transactor aggregate with `cause=The stream has been reset`.
247
+ *
248
+ * Deliberately NOT matched: every constraint / authorization failure
249
+ * (`CHECK constraint failed:`, `UNIQUE constraint failed:`) — those reach the same funnel
250
+ * and must be retried zero times: the cohort REFUSED the write, so re-presenting it
251
+ * re-presents a spent signature and can never commit.
252
+ */
253
+ const RETRIABLE_CONTROL_WRITE_MATCHERS: readonly ((message: string) => boolean)[] = [
254
+ isUncommittedTransactorAggregate,
255
+ isUnansweredSuperMajorityShortfall,
256
+ ];
257
+
258
+ /**
259
+ * The above PLUS the self-coordination grace refusal — the classifier for schema init ONLY
260
+ * ({@link SCHEMA_INIT_RETRY_POLICY}), deliberately not folded into the list above.
261
+ *
262
+ * Why this class is safe HERE and not everywhere: a write refused at coordinator SELECTION never
263
+ * reached a peer, so re-presenting it is a proven non-commit. But `findCoordinator` is also
264
+ * reached from `NetworkTransactor.commitBlock` during PHASE 2 (`resolveCoordinator`,
265
+ * `db-core/src/transactor/network-transactor.ts`), and `commit()` commits the header block before
266
+ * the rest — so a general control write refused there can be refused AFTER something already
267
+ * committed. Worse, that error carries no `[blocks:` batch token, so
268
+ * {@link reportsIndeterminateCommit} would not veto it, and re-running an insert body over a write
269
+ * that landed is exactly the `UNIQUE constraint failed: CadrePeer.PeerId` failure that veto exists
270
+ * to prevent.
271
+ *
272
+ * Schema init does not have that problem: `apply schema` is a diff rather than a replay and a
273
+ * failed `create table` leaves the catalog clean, so a re-run emits only the tables that did not
274
+ * land (the full argument is at the `loadSchema` call site in `control-database.ts`).
275
+ */
276
+ const RETRIABLE_SCHEMA_INIT_MATCHERS: readonly ((message: string) => boolean)[] = [
277
+ ...RETRIABLE_CONTROL_WRITE_MATCHERS,
278
+ isSelfCoordinationGraceRefusal,
279
+ ];
280
+
281
+ /**
282
+ * Did this control write fail because the cluster cohort did not ANSWER — i.e. is
283
+ * re-presenting the SAME signed write a moment later the right response?
284
+ *
285
+ * Classifies by MESSAGE, walking the `cause` chain with Quereus' own {@link unwrapError} —
286
+ * the failure surface is not recognisable by type. The transactor and the coordinator both throw bare `Error`s, and by
287
+ * the time one reaches `ControlDatabase` it is wrapped in a `QuereusError` (the real chain
288
+ * is `QuereusError` → `Error` → `Error`), so the match must work at any depth. Anything
289
+ * that is not an `Error` is never retried.
290
+ *
291
+ * {@link reportsIndeterminateCommit} vetoes the whole chain before any matcher runs, so a
292
+ * failure that reports a commit-phase batch anywhere is never retried on the strength of some
293
+ * other level looking transient.
294
+ *
295
+ * NOTE: this depends on engine/transactor error TEXT. The messages producible without a
296
+ * network are driven from the REAL engine in `control-formation-seat-budget.spec.ts`, so
297
+ * a rewording reddens a spec rather than silently disabling the retry. The two RETRIABLE
298
+ * messages need a real multi-node cluster to produce; the degraded-cohort scenario
299
+ * (`control-write-degraded-cohort-member.integration.ts`) asserts this classifier against
300
+ * both LIVE — the super-majority shortfall from a real silent member, and the transactor
301
+ * aggregate from a real stream reset, which the retry there absorbs end to end.
302
+ */
303
+ export function isRetriableControlWriteFailure(error: unknown): boolean {
304
+ return matchesRetriableMessage(error, RETRIABLE_CONTROL_WRITE_MATCHERS);
305
+ }
306
+
307
+ /**
308
+ * {@link isRetriableControlWriteFailure} widened by exactly one class — the self-coordination
309
+ * grace refusal ({@link RETRIABLE_SCHEMA_INIT_MATCHERS}) — for `ControlDatabase.loadSchema`.
310
+ *
311
+ * Opt-in per call site, via {@link SCHEMA_INIT_RETRY_POLICY}. Every other control write keeps the
312
+ * default classifier untouched.
313
+ */
314
+ export function isRetriableSchemaInitFailure(error: unknown): boolean {
315
+ return matchesRetriableMessage(error, RETRIABLE_SCHEMA_INIT_MATCHERS);
316
+ }
317
+
318
+ /**
319
+ * Shared body of both classifiers: walk the `cause` chain, let
320
+ * {@link reportsIndeterminateCommit} veto it, then ask `matchers`. The veto runs BEFORE any
321
+ * matcher for every policy — a chain reporting a commit-phase batch is never retried, however
322
+ * transient some other level looks.
323
+ */
324
+ function matchesRetriableMessage(
325
+ error: unknown,
326
+ matchers: readonly ((message: string) => boolean)[]
327
+ ): boolean {
328
+ if (!(error instanceof Error)) {
329
+ return false;
330
+ }
331
+ const messages = chainMessages(error);
332
+ if (reportsIndeterminateCommit(messages)) {
333
+ return false;
334
+ }
335
+ return messages.some(message => matchers.some(matches => matches(message)));
336
+ }
337
+
338
+ /**
339
+ * Policy and pacing for {@link retryControlWrite}. Production callers pass nothing (or a named
340
+ * policy such as {@link SCHEMA_INIT_RETRY_POLICY}); specs inject a recorded `sleep`, a shorter
341
+ * delay list, or a fake clock so no test ever waits out a real backoff.
342
+ *
343
+ * Every field defaults to the shipped control-write policy, so an omitted field is byte-identical
344
+ * to the behaviour before per-call-site policies existed.
345
+ */
346
+ export interface ControlWriteRetryOptions {
347
+ /**
348
+ * Total attempts, first included. Default {@link CONTROL_WRITE_ATTEMPTS}, floored at 1 —
349
+ * below that the loop would run the body zero times and rethrow a `lastError` nobody set.
350
+ */
351
+ attempts?: number;
352
+ /** Backoff base before retry N (last entry repeats). Default {@link CONTROL_WRITE_RETRY_DELAYS_MS}. */
353
+ delaysMs?: readonly number[];
354
+ /**
355
+ * Which failures are transient enough to re-present. Default
356
+ * {@link isRetriableControlWriteFailure}; the only other shipped value is
357
+ * {@link isRetriableSchemaInitFailure}, via {@link SCHEMA_INIT_RETRY_POLICY}.
358
+ */
359
+ isRetriable?: (error: unknown) => boolean;
360
+ /**
361
+ * Operation label stamped into every log line this loop emits (rendered as
362
+ * `Control write [<label>] …`), and NOTHING else — no behavioural effect. The debug
363
+ * log is the only surface where the loop's decisions are observable (the rethrown
364
+ * error is unchanged and no attempt counter is exposed), and several writes retry
365
+ * CONCURRENTLY in a real party, so an unlabelled line cannot be attributed to a
366
+ * write. The degraded-cohort scenario asserts on these lines per-operation.
367
+ */
368
+ label?: string;
369
+ /** The sleep primitive. Default: `setTimeout`. */
370
+ sleep?: (ms: number) => Promise<void>;
371
+ /** Clock for the elapsed-budget check. Default: `Date.now`. */
372
+ now?: () => number;
373
+ }
374
+
375
+ /**
376
+ * The one non-default retry policy: `ControlDatabase.loadSchema`'s distributed DDL, which
377
+ * additionally absorbs optimystic's self-coordination grace refusal and gets more attempts over a
378
+ * longer backoff to do it (see {@link SCHEMA_INIT_ATTEMPTS} and
379
+ * {@link SCHEMA_INIT_RETRY_DELAYS_MS}). Still bounded by the shared
380
+ * {@link CONTROL_WRITE_RETRY_BUDGET_MS}.
381
+ *
382
+ * NOTE: exactly one call site opts in today, and the re-run safety this policy assumes is that
383
+ * site's, not a general property — `apply schema` is a diff and a failed `create table` leaves the
384
+ * catalog clean. A second opt-in must re-derive that argument for its own write body first; if this
385
+ * policy ever grows a third consumer, rename it for what the callers share rather than widening it
386
+ * by default.
387
+ */
388
+ export const SCHEMA_INIT_RETRY_POLICY: Readonly<ControlWriteRetryOptions> = {
389
+ attempts: SCHEMA_INIT_ATTEMPTS,
390
+ delaysMs: SCHEMA_INIT_RETRY_DELAYS_MS,
391
+ isRetriable: isRetriableSchemaInitFailure,
392
+ };
393
+
394
+ /**
395
+ * Run `attempt` up to {@link CONTROL_WRITE_ATTEMPTS} times (or `options.attempts`), retrying only
396
+ * failures the policy's classifier — {@link isRetriableControlWriteFailure} by default —
397
+ * calls transient, and only while {@link CONTROL_WRITE_RETRY_BUDGET_MS} has not elapsed.
398
+ *
399
+ * `attempt` must be atomic and re-runnable: a failed cluster write rolls back (nothing is
400
+ * half-applied), and re-running the body re-runs its reads too — `ControlDatabase`'s
401
+ * locked write bodies all satisfy this (see the contract on
402
+ * `ControlDatabase.withWriteLock`). The backoff sleeps happen with NO lock held; the caller
403
+ * takes and releases its lock inside `attempt`.
404
+ *
405
+ * On exhaustion (attempts or budget) the LAST error is rethrown unchanged — never wrapped,
406
+ * so the exact messages downstream code and the degraded-cohort-member scenario assert on
407
+ * survive. A non-retriable failure propagates from the attempt that raised it.
408
+ */
409
+ export async function retryControlWrite<T>(
410
+ attempt: () => Promise<T>,
411
+ options: ControlWriteRetryOptions = {}
412
+ ): Promise<T> {
413
+ const attempts = Math.max(1, options.attempts ?? CONTROL_WRITE_ATTEMPTS);
414
+ const delays = options.delaysMs ?? CONTROL_WRITE_RETRY_DELAYS_MS;
415
+ const isRetriable = options.isRetriable ?? isRetriableControlWriteFailure;
416
+ const sleep = options.sleep ?? defaultSleep;
417
+ const now = options.now ?? Date.now;
418
+ // Empty when unlabelled, so an unlabelled line is byte-identical to what this loop
419
+ // logged before labels existed.
420
+ const tag = options.label ? ` [${options.label}]` : '';
421
+ const start = now();
422
+ let lastError: unknown;
423
+ let attemptsMade = 0;
424
+ for (let attemptNumber = 1; attemptNumber <= attempts; attemptNumber++) {
425
+ attemptsMade = attemptNumber;
426
+ try {
427
+ const result = await attempt();
428
+ if (attemptNumber > 1) {
429
+ log('Control write%s committed on attempt %d/%d', tag, attemptNumber, attempts);
430
+ }
431
+ return result;
432
+ } catch (error) {
433
+ if (!isRetriable(error)) {
434
+ // The ONLY trace that this funnel saw a failure and declined it. Without it the
435
+ // log is silent either way, so "the classifier vetoed this one" is
436
+ // indistinguishable from "the retry is not wired into this path at all".
437
+ log('Control write%s failed non-transiently on attempt %d/%d, not retried here: %s',
438
+ tag, attemptNumber, attempts, error);
439
+ throw error;
440
+ }
441
+ lastError = error;
442
+ if (attemptNumber === attempts) {
443
+ break;
444
+ }
445
+ const elapsed = now() - start;
446
+ if (elapsed >= CONTROL_WRITE_RETRY_BUDGET_MS) {
447
+ break;
448
+ }
449
+ const delay = jitteredDelay(delays, attemptNumber);
450
+ log('Control write%s failed transiently (attempt %d/%d), retrying in %d ms: %s',
451
+ tag, attemptNumber, attempts, delay, error);
452
+ await sleep(delay);
453
+ }
454
+ }
455
+ log('Control write%s failed after %d/%d attempt(s): %s', tag, attemptsMade, attempts, lastError);
456
+ throw lastError;
457
+ }
458
+
459
+ /**
460
+ * Backoff for the retry that follows attempt `attemptNumber`: the matching base delay
461
+ * (last entry repeats), jittered ±50%, then capped at the list's largest base so no single
462
+ * sleep exceeds it (see {@link CONTROL_WRITE_RETRY_DELAYS_MS} for why). `Math.random` is
463
+ * fine here — the jitter only de-synchronizes concurrent retriers, nothing is derived
464
+ * from it.
465
+ *
466
+ * NOTE: the cap bites on the LAST delay, whose base IS the largest, so ~half of those sleeps
467
+ * land exactly on the cap rather than spread — de-synchronization is only partial there.
468
+ * Harmless while retriers are a handful of party nodes whose attempts already start seconds
469
+ * apart; if a party ever retries in a tight synchronized herd, raise the cap above the
470
+ * largest base instead of jittering about it.
471
+ */
472
+ function jitteredDelay(delays: readonly number[], attemptNumber: number): number {
473
+ if (delays.length === 0) {
474
+ return 0;
475
+ }
476
+ const base = delays[Math.min(attemptNumber - 1, delays.length - 1)]!;
477
+ const jittered = base * (0.5 + Math.random());
478
+ return Math.min(jittered, Math.max(...delays));
479
+ }
480
+
481
+ function defaultSleep(ms: number): Promise<void> {
482
+ return new Promise(resolve => setTimeout(resolve, ms));
483
+ }