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