@serfab/cadre-core 1.23.0 → 1.24.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 (313) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +145 -44
  8. package/dist/cadre-node.js +239 -79
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +2 -2
  82. package/dist/node-claim-payload.d.ts +15 -7
  83. package/dist/node-claim-payload.js +25 -9
  84. package/dist/node-claim-payload.js.map +1 -1
  85. package/dist/node-class.d.ts +36 -0
  86. package/dist/node-class.js +26 -0
  87. package/dist/node-class.js.map +1 -0
  88. package/dist/node-default-transports.d.ts +50 -3
  89. package/dist/node-default-transports.js +48 -3
  90. package/dist/node-default-transports.js.map +1 -1
  91. package/dist/node-roles.d.ts +118 -0
  92. package/dist/node-roles.js +142 -0
  93. package/dist/node-roles.js.map +1 -0
  94. package/dist/node-transports.d.ts +6 -2
  95. package/dist/node-transports.js +39 -7
  96. package/dist/node-transports.js.map +1 -1
  97. package/dist/owner-anchor-sync.js +1 -1
  98. package/dist/owner-key-export.js +1 -1
  99. package/dist/owner-key-flows.d.ts +1 -1
  100. package/dist/owner-key-store.js +1 -1
  101. package/dist/owner-signer.js +1 -1
  102. package/dist/peer-authorization.d.ts +3 -1
  103. package/dist/peer-authorization.js +3 -1
  104. package/dist/peer-authorization.js.map +1 -1
  105. package/dist/peer-dial.d.ts +74 -10
  106. package/dist/peer-dial.js +89 -17
  107. package/dist/peer-dial.js.map +1 -1
  108. package/dist/peer-join-backfill.js +4 -4
  109. package/dist/peer-join-backfill.js.map +1 -1
  110. package/dist/peer-record.d.ts +34 -9
  111. package/dist/peer-record.js +66 -13
  112. package/dist/peer-record.js.map +1 -1
  113. package/dist/pending-join-runner.d.ts +1 -1
  114. package/dist/pending-join-runner.js +1 -1
  115. package/dist/provider/client.d.ts +6 -5
  116. package/dist/provider/client.js +3 -3
  117. package/dist/provider/client.js.map +1 -1
  118. package/dist/provider/descriptor.d.ts +1 -1
  119. package/dist/provider/descriptor.js +1 -1
  120. package/dist/provider/oauth.d.ts +1 -1
  121. package/dist/provider/oauth.js +1 -1
  122. package/dist/provider/rent-node.d.ts +4 -3
  123. package/dist/provider/rent-node.js +3 -3
  124. package/dist/provider/rent-node.js.map +1 -1
  125. package/dist/relay-addrs.d.ts +62 -7
  126. package/dist/relay-addrs.js +74 -11
  127. package/dist/relay-addrs.js.map +1 -1
  128. package/dist/relay-reservation.d.ts +1 -1
  129. package/dist/relay-reservation.js +1 -1
  130. package/dist/relay-server.d.ts +6 -5
  131. package/dist/relay-server.js +5 -5
  132. package/dist/relay-server.js.map +1 -1
  133. package/dist/schema-verification.d.ts +13 -10
  134. package/dist/schema-verification.js +32 -24
  135. package/dist/schema-verification.js.map +1 -1
  136. package/dist/sealed-party-key.js +1 -1
  137. package/dist/seed-bootstrap.d.ts +4 -3
  138. package/dist/seed-bootstrap.js +6 -7
  139. package/dist/seed-bootstrap.js.map +1 -1
  140. package/dist/strand-addr-protocol.d.ts +8 -6
  141. package/dist/strand-addr-protocol.js +12 -10
  142. package/dist/strand-addr-protocol.js.map +1 -1
  143. package/dist/strand-app-schema-report.d.ts +16 -2
  144. package/dist/strand-app-schema-report.js +15 -0
  145. package/dist/strand-app-schema-report.js.map +1 -1
  146. package/dist/strand-cohort.d.ts +1 -4
  147. package/dist/strand-cohort.js.map +1 -1
  148. package/dist/strand-commit-durability.d.ts +1 -1
  149. package/dist/strand-database.d.ts +13 -6
  150. package/dist/strand-database.js +17 -9
  151. package/dist/strand-database.js.map +1 -1
  152. package/dist/strand-first-sync-gate.d.ts +3 -2
  153. package/dist/strand-first-sync-gate.js +3 -2
  154. package/dist/strand-first-sync-gate.js.map +1 -1
  155. package/dist/strand-formation-deadlines.d.ts +2 -2
  156. package/dist/strand-formation-deadlines.js +2 -2
  157. package/dist/strand-formation-protocol.d.ts +1 -1
  158. package/dist/strand-formation-protocol.js +51 -16
  159. package/dist/strand-formation-protocol.js.map +1 -1
  160. package/dist/strand-instance-manager.d.ts +67 -33
  161. package/dist/strand-instance-manager.js +164 -55
  162. package/dist/strand-instance-manager.js.map +1 -1
  163. package/dist/strand-membership-reconciler.d.ts +8 -3
  164. package/dist/strand-membership-reconciler.js +8 -3
  165. package/dist/strand-membership-reconciler.js.map +1 -1
  166. package/dist/strand-membership-writer.d.ts +2 -2
  167. package/dist/strand-membership-writer.js +41 -39
  168. package/dist/strand-membership-writer.js.map +1 -1
  169. package/dist/strand-move.js +1 -1
  170. package/dist/strand-network-config.d.ts +15 -5
  171. package/dist/strand-network-config.js +7 -6
  172. package/dist/strand-network-config.js.map +1 -1
  173. package/dist/strand-party-key-rotation.d.ts +7 -3
  174. package/dist/strand-party-key-rotation.js +7 -3
  175. package/dist/strand-party-key-rotation.js.map +1 -1
  176. package/dist/strand-party-machines.d.ts +19 -8
  177. package/dist/strand-party-machines.js +26 -11
  178. package/dist/strand-party-machines.js.map +1 -1
  179. package/dist/strand-party-peers.d.ts +36 -14
  180. package/dist/strand-party-peers.js +24 -15
  181. package/dist/strand-party-peers.js.map +1 -1
  182. package/dist/strand-peer-redial.d.ts +1 -1
  183. package/dist/strand-peer-redial.js +1 -1
  184. package/dist/strand-reactivity.d.ts +20 -17
  185. package/dist/strand-reactivity.js +31 -18
  186. package/dist/strand-reactivity.js.map +1 -1
  187. package/dist/strand-revocation-enforcer.d.ts +3 -3
  188. package/dist/strand-revocation-enforcer.js +3 -3
  189. package/dist/strand-wake-protocol.d.ts +19 -7
  190. package/dist/strand-wake-protocol.js +22 -10
  191. package/dist/strand-wake-protocol.js.map +1 -1
  192. package/dist/strand-watcher.d.ts +1 -1
  193. package/dist/strand-watcher.js +1 -1
  194. package/dist/table-change-watch.js +1 -1
  195. package/dist/types.d.ts +116 -55
  196. package/dist/types.js.map +1 -1
  197. package/dist/webrtc-upgrade.d.ts +254 -0
  198. package/dist/webrtc-upgrade.js +355 -0
  199. package/dist/webrtc-upgrade.js.map +1 -0
  200. package/package.json +9 -9
  201. package/src/announce-addrs.ts +93 -93
  202. package/src/arachnode-stub.ts +18 -10
  203. package/src/bootstrap-peer-store-file.ts +44 -44
  204. package/src/bootstrap-peer-store.ts +214 -214
  205. package/src/cadre-invite-protocol.ts +741 -740
  206. package/src/cadre-node.ts +12462 -12280
  207. package/src/claim-proof.ts +147 -147
  208. package/src/control-authorization.ts +290 -276
  209. package/src/control-cohort.ts +223 -204
  210. package/src/control-database.ts +72 -28
  211. package/src/control-formation-recorder.ts +359 -359
  212. package/src/control-protocol-guard.ts +370 -366
  213. package/src/control-read-retry.ts +222 -180
  214. package/src/control-retry.ts +36 -4
  215. package/src/control-schema-version.ts +301 -301
  216. package/src/control-schema.ts +1108 -1087
  217. package/src/control-write-retry.ts +639 -669
  218. package/src/delegate-admission.ts +351 -351
  219. package/src/describe-thrown.ts +60 -60
  220. package/src/ed25519-key.ts +185 -185
  221. package/src/edge-node/config.ts +13 -10
  222. package/src/edge-node/dissolve.ts +252 -252
  223. package/src/edge-node/edge-join.ts +320 -320
  224. package/src/edge-node/edge-node.ts +1095 -1095
  225. package/src/edge-node/index.ts +60 -59
  226. package/src/edge-node/join-credential.ts +16 -16
  227. package/src/edge-node/lazy-raw-storage.ts +194 -178
  228. package/src/edge-node/listen-addrs.ts +26 -0
  229. package/src/edge-node/node-local.ts +84 -84
  230. package/src/edge-node/options.ts +195 -195
  231. package/src/edge-node/owner-grant.ts +63 -63
  232. package/src/edge-node/platform.ts +5 -4
  233. package/src/edge-node/strand-move.ts +266 -266
  234. package/src/edge-node/strands.ts +27 -12
  235. package/src/enrolled-machine-store-file.ts +43 -43
  236. package/src/enrolled-machine-store.ts +280 -280
  237. package/src/fetch-impl.ts +23 -23
  238. package/src/file-durable-slot.ts +64 -64
  239. package/src/file-safe-name.ts +32 -32
  240. package/src/formation-approval.ts +604 -604
  241. package/src/formation-token.ts +63 -63
  242. package/src/fs-atomic.ts +92 -92
  243. package/src/index.ts +987 -957
  244. package/src/invitation-bootstrap.ts +152 -118
  245. package/src/joined-strand-store.ts +553 -553
  246. package/src/key-store-file.ts +142 -142
  247. package/src/link-budget.ts +61 -5
  248. package/src/machine-removal.ts +211 -210
  249. package/src/member-redemption.ts +643 -643
  250. package/src/membership-connection-gater.ts +650 -650
  251. package/src/membership-view.ts +147 -147
  252. package/src/node-claim-payload.ts +34 -12
  253. package/src/node-class.ts +47 -0
  254. package/src/node-default-transports.ts +65 -3
  255. package/src/node-roles.ts +220 -0
  256. package/src/node-transports.ts +86 -49
  257. package/src/owner-anchor-sync.ts +172 -172
  258. package/src/owner-grant-protocol.ts +547 -547
  259. package/src/owner-key-export.ts +348 -348
  260. package/src/owner-key-flows.ts +109 -109
  261. package/src/owner-key-store.ts +1 -1
  262. package/src/owner-keys.ts +179 -179
  263. package/src/owner-signer.ts +92 -92
  264. package/src/peer-addr-book.ts +252 -252
  265. package/src/peer-authorization.ts +584 -582
  266. package/src/peer-dial.ts +698 -605
  267. package/src/peer-join-backfill.ts +961 -961
  268. package/src/peer-record.ts +71 -16
  269. package/src/pending-join-runner.ts +798 -798
  270. package/src/primary-lan-address.ts +47 -47
  271. package/src/provider/client.ts +327 -326
  272. package/src/provider/descriptor.ts +129 -129
  273. package/src/provider/index.ts +59 -59
  274. package/src/provider/oauth.ts +285 -285
  275. package/src/provider/rent-node.ts +276 -275
  276. package/src/relay-addrs.ts +90 -12
  277. package/src/relay-reservation.ts +1 -1
  278. package/src/relay-server.ts +99 -98
  279. package/src/schema-verification.ts +38 -23
  280. package/src/sealed-party-key.ts +190 -190
  281. package/src/seed-bootstrap.ts +8 -11
  282. package/src/seed-trust-policy.ts +353 -353
  283. package/src/self-address-update.ts +19 -19
  284. package/src/strand-addr-protocol.ts +17 -14
  285. package/src/strand-app-schema-report.ts +147 -122
  286. package/src/strand-cohort.ts +1 -5
  287. package/src/strand-commit-durability.ts +165 -165
  288. package/src/strand-database.ts +522 -510
  289. package/src/strand-first-sync-gate.ts +3 -2
  290. package/src/strand-formation-deadlines.ts +227 -227
  291. package/src/strand-formation-manager.ts +731 -731
  292. package/src/strand-formation-protocol.ts +1174 -1138
  293. package/src/strand-fret-addrs.ts +179 -179
  294. package/src/strand-instance-manager.ts +188 -63
  295. package/src/strand-membership-reconciler.ts +1315 -1310
  296. package/src/strand-membership-writer.ts +2152 -2150
  297. package/src/strand-move.ts +1 -1
  298. package/src/strand-network-config.ts +16 -6
  299. package/src/strand-offline.ts +178 -178
  300. package/src/strand-party-key-rotation.ts +440 -436
  301. package/src/strand-party-machines.ts +308 -293
  302. package/src/strand-party-peers.ts +151 -129
  303. package/src/strand-peer-redial.ts +1 -1
  304. package/src/strand-reactivity.ts +36 -19
  305. package/src/strand-revocation-enforcer.ts +758 -758
  306. package/src/strand-wake-protocol.ts +406 -394
  307. package/src/strand-watcher.ts +1 -1
  308. package/src/table-change-watch.ts +285 -285
  309. package/src/timed-step.ts +28 -28
  310. package/src/timeout-scheduler.ts +29 -29
  311. package/src/trusted-owner-store.ts +242 -242
  312. package/src/types.ts +3182 -3121
  313. package/src/webrtc-upgrade.ts +439 -0
@@ -1,669 +1,639 @@
1
- import { CoordinatorPartialCommitError, SyncRetryExhaustedError, TornActionError } from '@optimystic/db-core';
2
- import { ConcurrentModificationError, PartialCommitError } from '@optimystic/quereus-plugin-optimystic';
3
- import { causeChain, chainMessages, reportsUnreachableCohort, retryControlOperation } from './control-retry.js';
4
- import type { ControlRetryOptions } from './control-retry.js';
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 on the strength of the rejection itself —
22
- * no matcher here claims a rejection message, at any phase, because re-presenting one would
23
- * re-present a spent signature against a cohort that already said no. Rejections are re-presented
24
- * anyway when they arrive inside the transactor's promise-phase `[block:` aggregate, which
25
- * {@link isUncommittedTransactorAggregate} claims on the WRAPPER alone, whatever the cause inside
26
- * says. Safe because nothing has committed at that phase, and deliberately kept — one of the
27
- * remaining promise-phase rejections is exactly the kind a re-presentation fixes. See the
28
- * accepted-tradeoff `NOTE:` there for which, and why no blanket rejection veto is wanted.
29
- *
30
- * A failure that says some of the write may be STORED is a different matter, and never
31
- * re-presented whatever text it carries: {@link reportsPossiblyStoredWrite} vetoes it by type
32
- * before any matcher runs. The one half-landed write that IS re-presented is a torn write the
33
- * library marks final — not saved and unable to land ({@link isFinalTornWrite}).
34
- *
35
- * THREE policies ship from here, and the split is deliberate: the default
36
- * ({@link isRetriableControlWriteFailure}, {@link CONTROL_WRITE_ATTEMPTS}) sits under every
37
- * control write; {@link SCHEMA_INIT_RETRY_POLICY} is opted into by
38
- * `ControlDatabase.applyControlSchema` alone; {@link LOST_UPDATE_RETRY_POLICY} is opted into by
39
- * the `CadrePeer` writers whose bodies re-read the row and decide again. Each widened one absorbs
40
- * one extra failure class whose re-run safety holds for its opted-in bodies and NOT for writes in
41
- * general; anything added to the default list must be safe for all ~19 callers.
42
- *
43
- * Lives outside `control-database.ts` so a spec can drive the classifier against real engine
44
- * errors without importing the whole database class. The loop itself lives in
45
- * `control-retry.ts`, shared with the READ policy (`control-read-retry.ts`) — this module
46
- * owns the write policies: their classifiers, attempt counts, backoff and budget.
47
- */
48
-
49
- /**
50
- * Attempts allowed per control write: the first, plus two retries of a transiently-failed
51
- * cluster commit. Bounded so a genuinely unreachable cohort terminates in the transactor's
52
- * own error rather than spinning; two retries covers the observed failure (a stream still
53
- * forming when the write fired) with margin.
54
- */
55
- export const CONTROL_WRITE_ATTEMPTS = 3;
56
-
57
- /**
58
- * Attempts allowed for {@link SCHEMA_INIT_RETRY_POLICY}, the one call site that also absorbs a
59
- * self-coordination refusal.
60
- *
61
- * Two more than {@link CONTROL_WRITE_ATTEMPTS} because what this retry buys is wall-clock for a
62
- * cold-starting node's bootstrap dials to land, and because the refusal is cheap to re-provoke
63
- * relative to a cluster round-trip: `findCoordinator` already spends its own bounded wait before
64
- * raising (3 attempts, 500 ms apart, `db-p2p/src/libp2p-key-network.ts` ~422) and then decides
65
- * LOCALLY that it may not elect itself, so no peer is contacted and no cohort deadline is
66
- * consumed.
67
- *
68
- * Note that the ~1 s `findCoordinator` spends internally is real, on top of this policy's own
69
- * backoff — which is exactly why {@link CONTROL_WRITE_RETRY_BUDGET_MS} and not this count is what
70
- * actually terminates the loop in the worst case.
71
- */
72
- export const SCHEMA_INIT_ATTEMPTS = 5;
73
-
74
- /**
75
- * Elapsed-time ceiling on the whole retry loop, measured from the START of the first
76
- * attempt and checked after a failed attempt BEFORE sleeping.
77
- *
78
- * This budget — not the attempt count — is what makes the policy safe to sit under every
79
- * control write. A transient failure (stream reset while a connection is still forming)
80
- * surfaces in well under a second, so it is retried and the loop adds at most ~2.2 s. A
81
- * genuinely silent cohort member costs ~21 s per consensus round (two `ClusterClient`
82
- * response-deadline attempts, 10.5 s each at the default declared link): one pend round plus
83
- * the cancel discharge's three rounds, about 84 s for one write in
84
- * `control-write-degraded-cohort-member.integration.ts`, which already exceeds this budget
85
- * when attempt 1 returns — so that case is surfaced immediately and retry adds ZERO latency
86
- * to the case where it cannot help.
87
- *
88
- * It cuts the loop off by design, so it does not grow with the link: its job is to end the
89
- * retries of slow attempts, and the caller gets the last attempt's error unchanged. An attempt
90
- * whose read phase consulted a silent peer ends at about one per-peer read deadline
91
- * (`cohortReadDeadlineMs` in `link-budget.ts`: 7 s at the default declared link, 5 s before it
92
- * was derived, 1 s at Optimystic's own default), so it still gets one retry inside this budget
93
- * where it once got two; an attempt that runs into the `ClusterClient` response deadline
94
- * (10.5 s at the default declared link) still gets none. See `docs/cadre-consistency.md` →
95
- * "Deadlines Over Optimystic's Reads and Commits".
96
- *
97
- * NOTE: a failed commit attempt also pays a cancel discharge before its error returns
98
- * (optimystic `TransactorSource.transact`'s catch) — bounded by six rounds and
99
- * `abortOrCancelTimeoutMs`, which every collection this repo opens sets to the larger of 5 s
100
- * and the RPC dial deadline: 42.5 s at the default declared link (`optimysticDialLimits` in
101
- * `link-budget.ts`;
102
- * `../optimystic/packages/quereus-plugin-optimystic/src/optimystic-adapter/collection-factory.ts`).
103
- * One cancel that runs its full budget therefore ends the retries on its own, cutting the
104
- * three-attempt policy to however many attempts came before it. A cancel only runs that long
105
- * when a peer stays silent, and that attempt has already spent its pend round past this
106
- * budget, so the cut loses nothing there. After a transient fault the cancel is either
107
- * answered or gives up after its six rounds against a dead transport, in about a second
108
- * either way (optimystic `NetworkTransactor.MAX_CANCEL_ROUNDS`). Not observed — every
109
- * measured round of the transient-reset case committed on attempt 3 of 3 — so this is a
110
- * condition to watch, not work to do: if that case ever starts failing with
111
- * `failed after 2/3 attempt(s)`, the cancel discharge is where the time went.
112
- */
113
- // eslint-disable-next-line no-restricted-syntax -- cuts off by design: it ends the retries of slow attempts rather than waiting them out; see docs/cadre-consistency.md → "Deadlines Over Optimystic's Reads and Commits"
114
- export const CONTROL_WRITE_RETRY_BUDGET_MS = 10_000;
115
-
116
- /**
117
- * Backoff before retry N, jittered ±50% (so the first sleep is 125–375 ms — the jitter can
118
- * never floor a delay to zero). Each single sleep is additionally capped at the LARGEST
119
- * delay in the list, so a `stop()` racing a backoff is never held up by more than ~1 s.
120
- * There is no `AbortSignal` at this seam to cancel a sleep outright; the cap is the
121
- * substitute, deliberately not plumbing one through every write path.
122
- */
123
- const CONTROL_WRITE_RETRY_DELAYS_MS: readonly number[] = [250, 1_000];
124
-
125
- /**
126
- * Backoff for {@link SCHEMA_INIT_RETRY_POLICY}, jittered and capped the same way. Worst case
127
- * ~4.6 s of sleep across four retries (375 + 750 + 1500 + 2000, each capped at the largest base),
128
- * which stays inside {@link CONTROL_WRITE_RETRY_BUDGET_MS} — the budget still terminates the loop
129
- * first if any single attempt is itself slow.
130
- *
131
- * Sized against measured facts, not guessed:
132
- *
133
- * - the self-coordination guard clears the moment the node has ONE connection again (both
134
- * branches that raise `grace-period-not-elapsed` require `getConnections().length === 0`), not
135
- * when the 30 s grace period expires — so this does NOT need to cover the grace period, only
136
- * the gap until a bootstrap dial completes;
137
- * - the guard's 30 s `gracePeriodMs` cannot be tuned from this repo anyway: no caller in either
138
- * repo passes a `SelfCoordinationConfig`, so the default is always in force;
139
- * - a node that has NEVER connected is waved through as a bootstrap node (network high-water
140
- * mark of 1), so this retry only ever delays a node that HAS seen peers. One whose peers are
141
- * gone for good still fails, ~4.6 s later — which is why the budget stays at the shared
142
- * ceiling rather than stretching to cover the full 30 s window.
143
- */
144
- const SCHEMA_INIT_RETRY_DELAYS_MS: readonly number[] = [250, 500, 1_000, 2_000];
145
-
146
- /** The network transactor's aggregate, raised when some cohort peers gave no usable answer. */
147
- const TRANSACTOR_AGGREGATE = /Some peers did not complete:/;
148
-
149
- /**
150
- * How the aggregate's per-batch details name a SINGLE-block batch — the shape both the block
151
- * read (`get`) and phase 1 (`pend`) format, and the only shape safe to re-present.
152
- */
153
- const SINGLE_BLOCK_BATCH_TOKEN = '[block:';
154
-
155
- /**
156
- * How the aggregate's per-batch details name a MULTI-block batch — the shape phase 2
157
- * (`commitBlocks`) formats, and the marker of an outcome too indeterminate to retry.
158
- */
159
- const COMMIT_BATCH_TOKEN = '[blocks:';
160
-
161
- /**
162
- * The cluster coordinator's super-majority shortfall (`PromiseShortfallError`, db-core), matched
163
- * ONLY with a ZERO rejection count. The same message with a non-zero count means a member actually
164
- * voted no (that branch carries `membership-not-admitted` rejections), and retrying it would
165
- * re-present a spent signature to a cohort that already refused it. A pend's shortfall reaches this
166
- * funnel as that error on its own, before any commit, so re-presenting it is safe; a commit's
167
- * arrives inside the `[blocks:` aggregate, which {@link reportsIndeterminateCommit} vetoes (both
168
- * seen live in `control-write-degraded-cohort-member`).
169
- *
170
- * NOTE: matched by TEXT although the error is typed. Upstream keeps this sentence byte for byte as a
171
- * downstream contract, so the regex is stable; moving to `instanceof PromiseShortfallError` with
172
- * `rejections === 0` is backlog `debt-control-write-retry-matches-the-shortfall-by-type`.
173
- *
174
- * This regex itself never matches a decisive rejection (`ValidatorRejectionError`, `Transaction
175
- * rejected by validators`) — that text carries no `Failed to get super-majority:` prefix. But the
176
- * composite classifier is not this matcher alone: a rejection raised while promises are still
177
- * being collected reaches this repo wrapped in the transactor's `Some peers did not complete:
178
- * …[block:…]` aggregate, and {@link isUncommittedTransactorAggregate} matches that wrapper on its
179
- * own, whatever the cause inside it says — see the accepted-tradeoff `NOTE:` there.
180
- */
181
- const SUPER_MAJORITY_SHORTFALL_UNANSWERED =
182
- /Failed to get super-majority: \d+\/\d+ approvals \(needed \d+, 0 rejections\)/;
183
-
184
- /**
185
- * Is this a transactor aggregate from a phase where nothing can have committed yet?
186
- *
187
- * The transactor raises `Some peers did not complete:` from three sites
188
- * (`db-core/src/transactor/network-transactor.ts`), and only two of them are safe to
189
- * re-present:
190
- *
191
- * - `get` (a block read, which a write body also performs) and `pend` (phase 1) fail before
192
- * anything commits, so the write is known not to have landed. `get` raises it only when a
193
- * coordinator answered and left a block out; a block nobody answered for fails typed
194
- * instead, which {@link matchesRetriableFailure} claims ({@link reportsUnreachableCohort});
195
- * - `commitBlocks` (phase 2) is REACHABLE here and NOT safe. `commitBlock` throws the
196
- * aggregate when a header/tail commit got NO response at all — precisely the transient
197
- * class this retry targets — and that escapes `commit()`, survives `TransactorSource`'s
198
- * cancel-and-rethrow (cancel reaches PENDING actions only; a peer that already committed
199
- * stays committed) and `Collection.syncInternal` (which retries StaleFailure RETURN values,
200
- * not throws), reaching this funnel QuereusError-wrapped. The tail commit is one batch to
201
- * one coordinator running consensus internally, so a no-response there is INDETERMINATE:
202
- * the commit may have completed with only the response lost. Re-running the write body over
203
- * a write that landed turns a success into a constraint failure (e.g.
204
- * `UNIQUE constraint failed: CadrePeer.PeerId`). Surfacing the transient error instead lets
205
- * the caller re-read committed state and decide. Commit-phase messages are vetoed by
206
- * {@link reportsIndeterminateCommit}, not here.
207
- *
208
- * The `cause` chain does not discriminate the phases — a commit-phase aggregate carries the
209
- * same stream-reset/dial error a pend-phase one does. The per-batch DETAIL text does: `get`
210
- * and `pend` format `<peerId>[block:<id>](<status>)`, `commitBlocks` formats
211
- * `<peerId>[blocks:<count>](<status>)`. `[block:` cannot occur inside `[blocks:`, so the two
212
- * tokens are disjoint and separate the phases.
213
- *
214
- * NOTE: the discriminator is a formatting detail of another repo. If Optimystic ever reformats
215
- * those per-batch details, this fails CLOSED — the aggregate stops matching and control writes
216
- * simply stop being retried, silently losing the absorption rather than doing anything unsafe.
217
- * The guard is `control-write-degraded-cohort-member.integration.ts`, which asserts the `[block:`
218
- * token on any live aggregate a degraded case produces; if it reddens there, an upstream reformat
219
- * is the first thing to check. NOTE: on Optimystic 1.20.0 none of its cases produced this form
220
- * (2026-10-28: the injected reset failed the write's read typed, and a pend's shortfall arrives on
221
- * its own), so the guard can pass without seeing it; if the form is ever needed live again, inject
222
- * the reset at the pend's batch rather than the read's.
223
- *
224
- * NOTE: the discriminator is the prefix AND the token within ONE message — never relax it to
225
- * "contains `[block:`". Beyond the `get` and `pend` sites above, Optimystic renders `[block:` in
226
- * one further place — a third formatter, outside the aggregate's three sites — `dischargeCancel`
227
- * (`Cancel of action <id> did not discharge <n> block(s): …`), which does not raise the
228
- * `Some peers did not complete:` prefix; only the conjunction keeps a cancel fault from
229
- * classifying as a retriable get/pend (checked against optimystic `c56c2bd4`, 2026-09-16).
230
- *
231
- * NOTE: accepted tradeoff — a REJECTION raised while promises are still being collected reaches
232
- * this repo wrapped in this same aggregate, and this matcher claims it on the wrapper alone,
233
- * whatever the cause inside says. That re-presents such a rejection up to two more times inside
234
- * the 10 s budget. Kept deliberately, and re-decided on 2026-09-17 against the current upstream
235
- * behaviour rather than inherited:
236
- *
237
- * - Contention is no longer a rejection at all. "Another write holds this block right now"
238
- * (`pending conflict`) is now a `held` verdict that counts toward neither approvals nor
239
- * rejections (`validatePendOperations`,
240
- * `../optimystic/packages/db-p2p/src/cluster/cluster-repo.ts`), so the rejection this tradeoff
241
- * was originally written about does not arrive any more. It reaches this funnel as
242
- * `SyncRetryExhaustedError` instead, which {@link reportsPossiblyStoredWrite} declines by type
243
- * — upstream documents resubmitting after it as unsafe (the attempt that spent the budget may
244
- * have left its log entry standing), and its collection sync has already spent ten retries on
245
- * the race. The torn-write rule beside it: a `TornActionError` is re-presented only when
246
- * `final` is true; any other torn write is declined.
247
- * - What remains rejectable at the promise phase is stale revision, membership-not-admitted, an
248
- * expired transaction, and a configured validator's refusal (`ClusterMember.evaluatePromise`).
249
- * A block whose revision a member cannot establish is approved, not refused: the member logs
250
- * `validation-block-unavailable` and votes on (`judgeStaleRevisions`). Stale revision is worth
251
- * a retry: this loop re-runs the WHOLE write body, reads included
252
- * (`ControlDatabase.withWriteLock`'s contract), so attempt 2 presents a pend against the
253
- * revision that made attempt 1 stale. A blanket "decline any chain reporting a validator
254
- * rejection" rule would remove that retry to save two wasted attempts on the others.
255
- *
256
- * Revisit if a re-presentation ever becomes expensive relative to what it buys — a rejection class
257
- * that costs a full cohort round-trip to re-present, or a write body whose reads are no longer
258
- * cheap — or when upstream offers a typed refusal surface to classify on instead of this text
259
- * (`../optimystic/tickets/backlog/debt-a-downstream-repo-classifies-retries-by-parsing-our-error-text`).
260
- * Contention is no longer the reason to revisit.
261
- *
262
- * An aggregate whose details came out EMPTY (possible when `formatBatchStatuses` has no
263
- * batches to format) carries neither token, matches nothing here, and is not retried — an
264
- * unattributable failure is not a proven non-commit.
265
- *
266
- * Exported for the READ classifier (`control-read-retry.ts`), which reuses it verbatim: a
267
- * `get` batch formats the same single-block `[block:` token, and a read can never produce
268
- * the commit-phase `[blocks:` shape at all.
269
- */
270
- export function isUncommittedTransactorAggregate(message: string): boolean {
271
- return TRANSACTOR_AGGREGATE.test(message) && message.includes(SINGLE_BLOCK_BATCH_TOKEN);
272
- }
273
-
274
- /**
275
- * Does ANY message in the failure's `cause` chain describe a commit-phase batch — i.e. an
276
- * outcome nobody can call committed or not?
277
- *
278
- * Vetoes the whole chain rather than the one message carrying the token, and vetoes it
279
- * regardless of which matcher would otherwise have claimed it. The narrower per-message rule
280
- * would already catch every shape the transactor is known to build (a commit-phase aggregate
281
- * emits `[blocks:` for every batch it formats, and embeds its cause's message inline as
282
- * `root: …`, so both tokens land in one string) — but "known to build" is an argument about
283
- * another repo's error assembly, and this way an indeterminate commit anywhere in the chain
284
- * costs a retry we could have had instead of risking a re-run over a write that landed.
285
- */
286
- function reportsIndeterminateCommit(messages: readonly string[]): boolean {
287
- return messages.some(message => message.includes(COMMIT_BATCH_TOKEN));
288
- }
289
-
290
- /**
291
- * Does any link of the `cause` chain say some of this write may be stored, or may still be?
292
- * Such a failure is never re-presented — a re-run could store the write twice.
293
- *
294
- * - `SyncRetryExhaustedError` (and its `SyncRevisionStalledError` subclass): upstream documents
295
- * resubmitting as unsafe, because the attempt that spent the budget may have left its log
296
- * entry standing.
297
- * - `TornActionError` without `final: true`: the write's log entry is stored and nobody could
298
- * establish that the rest can never land — it may be saved already, or land later.
299
- * - `CoordinatorPartialCommitError` / `PartialCommitError`: another collection or tree of the
300
- * same transaction is already durable, and re-running the whole body would apply it twice.
301
- *
302
- * Every one of these embeds text from elsewhere in its message (a responder's refusal, the
303
- * underlying failure), which can carry the pend-phase aggregate's prefix and `[block:` token —
304
- * so this veto runs before any text matcher.
305
- *
306
- * Matched by TYPE: each survives the bridge's and Quereus' rewraps on `cause`. An error built by a
307
- * second loaded copy of `@optimystic/db-core` (or of the plugin, for `PartialCommitError`) fails
308
- * `instanceof`, and then this veto does not fire — falling back to the text classifiers, which is
309
- * how these failures were classified before the veto existed. The asymmetry with
310
- * {@link isFinalTornWrite} is deliberate: there, a missed `instanceof` means no retry, which is the
311
- * safe side. No text fallback parses `TornActionError`'s closing sentence, since upstream says its
312
- * wording is for log lines only.
313
- *
314
- * NOTE: the plugin is registered through its `/plugin` entry (`control-database.ts`) but
315
- * `PartialCommitError` is imported from its root entry; the two are one class only because the
316
- * plugin's build emits both entries over one shared chunk. If upstream ever bundles the entries
317
- * separately, this `instanceof` stops matching with every spec still green — import the class from
318
- * the entry the plugin is registered through.
319
- */
320
- function reportsPossiblyStoredWrite(links: readonly Error[]): boolean {
321
- return links.some(link =>
322
- link instanceof SyncRetryExhaustedError
323
- || (link instanceof TornActionError && link.final !== true)
324
- || link instanceof CoordinatorPartialCommitError
325
- || link instanceof PartialCommitError);
326
- }
327
-
328
- /**
329
- * A torn write the library marks FINAL: not saved, unable to land, its pending records confirmed
330
- * cancelled — so submitting it again stores it once.
331
- *
332
- * Worth re-presenting, not merely safe to: upstream raises it mostly when a rival holds the
333
- * revision this write's log entry claimed, which is contention, and the loop re-runs the write
334
- * body's reads, so the next attempt builds on the rival's revision — the same argument that keeps
335
- * stale-revision rejections retried (the accepted-tradeoff `NOTE:` on
336
- * {@link isUncommittedTransactorAggregate}).
337
- *
338
- * NOTE: `CoordinatorStaleLossError` (db-core; "nothing durably committed, safe to re-drive") is not
339
- * claimed, so it falls to the text matchers; it escapes only after the coordinator's own retry budget
340
- * ran out. Seen abandoning a control write on 2026-09-18 (`control-delete-while-alone-convergence`,
341
- * under load): a node's own storage refused its own pend as a `stale conflict` for the ~14 s the
342
- * coordinator spent re-driving, then gave up. Still not claimed here — the failing attempt already
343
- * ran past {@link CONTROL_WRITE_RETRY_BUDGET_MS}, so a retry from this loop would never get to run,
344
- * and the refusal came from the node's OWN storage disagreeing with its own revision view, which does
345
- * not change while the node is alone; re-driving the same write body again would hit the same
346
- * refusal. The cause (a commit torn by a sibling that stopped mid-commit, leaving the node with a
347
- * revision view its own storage disputes) is `tickets/blocked/forked-control-collection-sync-livelocks.md`
348
- * → "Second trigger".
349
- */
350
- function isFinalTornWrite(link: Error): boolean {
351
- return link instanceof TornActionError && link.final === true;
352
- }
353
-
354
- /** The coordinator's shortfall, raised pre-commit, with nobody having voted no. */
355
- function isUnansweredSuperMajorityShortfall(message: string): boolean {
356
- return SUPER_MAJORITY_SHORTFALL_UNANSWERED.test(message);
357
- }
358
-
359
- /**
360
- * A LOST UPDATE: the optimystic bridge refusing a commit because another writer changed or
361
- * removed a row this statement read (`TransactionBridge.mapCommitRefusal` over a
362
- * `TreeEntryChangedError`, `quereus-plugin-optimystic/src/optimystic-adapter/txn-bridge.ts`).
363
- * Claimed by TYPE for {@link LOST_UPDATE_RETRY_POLICY} only.
364
- *
365
- * Why it is a proven non-commit: the refusal is raised inside the action's atomic handler, so
366
- * none of that action's entries land. A refusal after a sibling tree or collection of the same
367
- * transaction already synced is not delivered bare — the per-tree sweep wraps it in
368
- * `PartialCommitError`, the coordinator path in `CoordinatorPartialCommitError` — and
369
- * {@link reportsPossiblyStoredWrite} vetoes both by type before this predicate runs. A bare chain
370
- * carrying this class therefore means nothing of the write is durable.
371
- *
372
- * Why it is not in the default list: the rejection is of the write's READ SET, not of its
373
- * signature, so re-presenting the same statement is only right when the body re-reads the row and
374
- * decides again over what it finds. That is a property of each opted-in body (see the policy's
375
- * `NOTE:`), not of control writes in general.
376
- *
377
- * Not matched by text: `ConcurrentModificationError` is exported from both the plugin's root and
378
- * `/plugin` entries over one shared chunk, as `PartialCommitError` is, so the one `instanceof`
379
- * covers both (the `NOTE:` on {@link reportsPossiblyStoredWrite} applies to it too). A second
380
- * loaded copy of the plugin would fail the `instanceof` and the lost update would then simply not
381
- * be retried — the safe side.
382
- */
383
- function isLostUpdate(link: Error): boolean {
384
- return link instanceof ConcurrentModificationError;
385
- }
386
-
387
- /**
388
- * Optimystic refusing to let a node elect ITSELF coordinator because its last connection dropped
389
- * less than the guard's grace period ago (`Libp2pKeyPeerNetwork.shouldAllowSelfCoordination` →
390
- * `findCoordinator`, `db-p2p/src/libp2p-key-network.ts`).
391
- *
392
- * Matched ONLY with the `grace-period-not-elapsed` reason. The same sentence is raised with three
393
- * other reasons and none of them is worth a retry: `disabled` is static configuration, and
394
- * `partition-detected` / `suspicious-shrinkage` describe a network condition that will not resolve
395
- * inside a few seconds of backoff. The grace-period one WILL — it clears as soon as the node holds
396
- * one connection again, which a cold-starting node dialling its bootstrap peers is actively
397
- * working on.
398
- *
399
- * NOTE: matched by TEXT, not by type. `FindCoordinatorError` (`code: 'SELF_COORDINATION_BLOCKED'`)
400
- * is exported from `@optimystic/db-p2p`, and when this matcher was written the error OBJECT did not
401
- * survive the trip: `OptimysticVirtualTable.initialize` rethrew as `new Error(message)` with no
402
- * `cause`. It now rethrows through `rewrapAsQueryError`, which keeps `cause`
403
- * (`quereus-plugin-optimystic/src/optimystic-module.ts`); whether every Quereus wrapper above it on
404
- * the schema-init path keeps it too has not been checked, and the text still arrives either way.
405
- * Like every matcher here this fails CLOSED — a rewording upstream stops the retry engaging, it
406
- * never makes it unsafe.
407
- */
408
- const SELF_COORDINATION_GRACE_REFUSAL =
409
- /Self-coordination blocked: grace-period-not-elapsed\. No coordinator available for key\./;
410
-
411
- /** Self-coordination refused because the node's last connection dropped moments ago. */
412
- function isSelfCoordinationGraceRefusal(message: string): boolean {
413
- return SELF_COORDINATION_GRACE_REFUSAL.test(message);
414
- }
415
-
416
- /**
417
- * The error messages that mean "the cohort did not answer AND nothing committed", and nothing
418
- * else. The observed one-shot failure was `registerSelf()` racing a connection still forming:
419
- * a read/pend-phase transactor aggregate with `cause=The stream has been reset`. When none of
420
- * the cohort answers the read at all, that failure arrives typed instead, and is claimed by
421
- * type in {@link matchesRetriableFailure} ({@link reportsUnreachableCohort}), not here.
422
- *
423
- * Deliberately NOT matched: every constraint / authorization failure
424
- * (`CHECK constraint failed:`, `UNIQUE constraint failed:`) — those reach the same funnel
425
- * and must be retried zero times: the cohort REFUSED the write, so re-presenting it
426
- * re-presents a spent signature and can never commit.
427
- */
428
- const RETRIABLE_CONTROL_WRITE_MATCHERS: readonly ((message: string) => boolean)[] = [
429
- isUncommittedTransactorAggregate,
430
- isUnansweredSuperMajorityShortfall,
431
- ];
432
-
433
- /**
434
- * The above PLUS the self-coordination grace refusal — the classifier for schema init ONLY
435
- * ({@link SCHEMA_INIT_RETRY_POLICY}), deliberately not folded into the list above.
436
- *
437
- * Why this class is safe HERE and not everywhere: a write refused at coordinator SELECTION never
438
- * reached a peer, so re-presenting it is a proven non-commit. But `findCoordinator` is also
439
- * reached from `NetworkTransactor.commitBlock` during PHASE 2 (`resolveCoordinator`,
440
- * `db-core/src/transactor/network-transactor.ts`), and `commit()` commits the header block before
441
- * the rest — so a general control write refused there can be refused AFTER something already
442
- * committed. Worse, that error carries no `[blocks:` batch token, so
443
- * {@link reportsIndeterminateCommit} would not veto it, and re-running an insert body over a write
444
- * that landed is exactly the `UNIQUE constraint failed: CadrePeer.PeerId` failure that veto exists
445
- * to prevent.
446
- *
447
- * Schema init does not have that problem: `apply schema` is a diff rather than a replay, and a
448
- * failed apply is taken back whole — Quereus unwinds every step it ran and verifies the catalog
449
- * against a pre-apply fingerprint — so a re-run emits exactly the DDL the live catalog is missing.
450
- * The full argument, including the plugin-side dependency that unwind carries, is at the
451
- * `applyControlSchema` call site in `control-database.ts`.
452
- *
453
- * RETRIED DELIBERATELY, not by oversight: the failures Quereus cannot take back. When the unwind
454
- * does not complete — an undo statement threw, the post-unwind catalog did not match the pre-apply
455
- * fingerprint, that catalog could not be re-collected to check, or a step the differ marks
456
- * irreversible because it discards data (dropping a table or a column, narrowing a column's type —
457
- * of which only dropping a column reaches a `CadreControl` apply, as the catalog-only migration
458
- * step `refuseIncompatibleControlStore` in `control-schema-version.ts` lets through; it discards
459
- * nothing there, since rows keep the field) poisoned the journal before it
460
- * ran, leaving nothing unwound — Quereus keeps the failing step's own message, APPENDS the reason the
461
- * schema could not be restored, and carries the original as `cause`. So a transient cause
462
- * underneath still matches here, and neither veto ({@link reportsPossiblyStoredWrite},
463
- * {@link reportsIndeterminateCommit}) looks for that reason text. Retrying over a partially migrated
464
- * schema is safe for the same reason the ordinary re-run is: the plugin commits whatever its write
465
- * batch holds, so storage and the catalog are left in step either way, and the next apply diffs
466
- * against what is really there. Vetoing it instead would turn a healable transient outage into a
467
- * dead start.
468
- */
469
- const RETRIABLE_SCHEMA_INIT_MATCHERS: readonly ((message: string) => boolean)[] = [
470
- ...RETRIABLE_CONTROL_WRITE_MATCHERS,
471
- isSelfCoordinationGraceRefusal,
472
- ];
473
-
474
- /**
475
- * Did this control write fail because the cluster cohort did not ANSWER — i.e. is
476
- * re-presenting the SAME signed write a moment later the right response?
477
- *
478
- * Classifies the transient cases by MESSAGE, walking the `cause` chain with the shared
479
- * {@link chainMessages} (Quereus' own `unwrapError` underneath) — the transactor and the
480
- * coordinator both throw bare `Error`s, not recognisable by type. By the time one reaches
481
- * `ControlDatabase` it is wrapped in a `QuereusError` (the real chain is `QuereusError` → `Error`
482
- * → `Error`), so the match must work at any depth. Anything that is not an `Error` is never
483
- * retried.
484
- *
485
- * Two vetoes run over the whole chain before any matcher: {@link reportsPossiblyStoredWrite}
486
- * (by type — a spent sync budget, a non-final torn write, a partial commit) and
487
- * {@link reportsIndeterminateCommit} (by text — a commit-phase batch). A chain either veto flags,
488
- * at any level, is never retried on the strength of some other level looking transient. Two typed
489
- * failures are claimed as retriable: a block read the cohort could not answer
490
- * ({@link reportsUnreachableCohort}, shared with the read classifier) and a final torn write
491
- * ({@link isFinalTornWrite}).
492
- *
493
- * NOTE: this depends on engine/transactor error TEXT. The messages producible without a
494
- * network are driven from the REAL engine in `control-formation-seat-budget.spec.ts`, so
495
- * a rewording reddens a spec rather than silently disabling the retry. The RETRIABLE failures
496
- * need a real multi-node cluster to produce; the degraded-cohort scenario
497
- * (`control-write-degraded-cohort-member.integration.ts`) asserts this classifier against the
498
- * super-majority shortfall from a real silent member, and absorbs a real stream reset end to end
499
- * (on Optimystic 1.20.0 the reset fails the write's read as an unanswered block, claimed by type).
500
- */
501
- export function isRetriableControlWriteFailure(error: unknown): boolean {
502
- return matchesRetriableFailure(error, RETRIABLE_CONTROL_WRITE_MATCHERS);
503
- }
504
-
505
- /**
506
- * {@link isRetriableControlWriteFailure} widened by exactly one class — the self-coordination
507
- * grace refusal ({@link RETRIABLE_SCHEMA_INIT_MATCHERS}) — for `ControlDatabase.applyControlSchema`.
508
- *
509
- * Opt-in per call site, via {@link SCHEMA_INIT_RETRY_POLICY}. Every other control write keeps the
510
- * default classifier untouched.
511
- */
512
- export function isRetriableSchemaInitFailure(error: unknown): boolean {
513
- return matchesRetriableFailure(error, RETRIABLE_SCHEMA_INIT_MATCHERS);
514
- }
515
-
516
- /**
517
- * {@link isRetriableControlWriteFailure} widened by exactly one class — a lost update
518
- * ({@link isLostUpdate}), claimed by type — for the `CadrePeer` writers that re-read the row inside
519
- * their locked body. Opt-in per call site, via {@link LOST_UPDATE_RETRY_POLICY}; both vetoes still
520
- * run first, so a lost update carried inside a partial commit, a spent sync budget or a non-final
521
- * torn write stays declined.
522
- */
523
- export function isRetriableLostUpdateFailure(error: unknown): boolean {
524
- return matchesRetriableFailure(error, RETRIABLE_CONTROL_WRITE_MATCHERS, isLostUpdate);
525
- }
526
-
527
- /**
528
- * Shared body of the three classifiers: walk the `cause` chain, let
529
- * {@link reportsPossiblyStoredWrite} and then {@link reportsIndeterminateCommit} veto it, then claim
530
- * a block read the cohort could not answer ({@link reportsUnreachableCohort}), a final torn write
531
- * ({@link isFinalTornWrite}) or any link `claimsLink` names, then ask `matchers`. The vetoes run
532
- * BEFORE any claim for every policy — a chain reporting a possibly-stored write or a commit-phase
533
- * batch is never retried, however transient some other level looks, and a final torn write or a
534
- * lost update carried by a partial commit is still declined because a sibling collection landed.
535
- * `claimsLink` is the one typed claim a policy may add; it sits here beside the shared typed claims
536
- * so the vetoes stay in one place above all of them.
537
- */
538
- function matchesRetriableFailure(
539
- error: unknown,
540
- matchers: readonly ((message: string) => boolean)[],
541
- claimsLink?: (link: Error) => boolean
542
- ): boolean {
543
- if (!(error instanceof Error)) {
544
- return false;
545
- }
546
- const links = causeChain(error);
547
- if (reportsPossiblyStoredWrite(links)) {
548
- return false;
549
- }
550
- const messages = chainMessages(error);
551
- if (reportsIndeterminateCommit(messages)) {
552
- return false;
553
- }
554
- // NOTE: an unanswered read can fail AFTER this write's log entry is stored: the refresh between
555
- // commit attempts reads the collection's log ends, and finishing the write's own entry
556
- // (`Collection.completeOwnEntry`) asks `getStatus` when no attempt is retained at the entry's
557
- // revision (a forked lineage — both commit paths retain the failed attempt before refreshing).
558
- // Either throw escapes the refresh loop unwrapped. Claimed anyway, because the `[block:`
559
- // aggregate those same reads raise is already claimed by the text matcher, so the typed form
560
- // adds no new case: the re-run is a new transaction whose body re-reads the blocks, so it diffs
561
- // to nothing or fails on `UNIQUE` where the earlier write landed, and writes it once where it did
562
- // not. A refresh that already saved a sibling collection arrives as
563
- // `CoordinatorPartialCommitError`, which the veto above declines.
564
- if (reportsUnreachableCohort(links)
565
- || links.some(link => isFinalTornWrite(link) || claimsLink?.(link) === true)) {
566
- return true;
567
- }
568
- return messages.some(message => matchers.some(matches => matches(message)));
569
- }
570
-
571
- /**
572
- * Policy and pacing overrides for {@link retryControlWrite}. Production callers pass nothing
573
- * (or a named policy such as {@link SCHEMA_INIT_RETRY_POLICY}); specs inject a recorded
574
- * `sleep`, a shorter delay list, or a fake clock so no test ever waits out a real backoff.
575
- *
576
- * Every field defaults to the shipped control-write policy ({@link CONTROL_WRITE_ATTEMPTS},
577
- * {@link CONTROL_WRITE_RETRY_DELAYS_MS}, {@link isRetriableControlWriteFailure}), so an
578
- * omitted field is byte-identical to the behaviour before per-call-site policies existed.
579
- * The field shapes and semantics live on the shared {@link ControlRetryOptions}.
580
- */
581
- export type ControlWriteRetryOptions = ControlRetryOptions;
582
-
583
- /**
584
- * The schema-init policy: `ControlDatabase.applyControlSchema`'s distributed DDL, which
585
- * additionally absorbs optimystic's self-coordination grace refusal and gets more attempts over a
586
- * longer backoff to do it (see {@link SCHEMA_INIT_ATTEMPTS} and
587
- * {@link SCHEMA_INIT_RETRY_DELAYS_MS}). Still bounded by the shared
588
- * {@link CONTROL_WRITE_RETRY_BUDGET_MS}.
589
- *
590
- * NOTE: exactly one call site opts in today, and the re-run safety this policy assumes is that
591
- * site's, not a general property — `apply schema` is a diff, and a failed apply is unwound whole
592
- * and verified against the pre-apply catalog (full argument at the `applyControlSchema` call site
593
- * in `control-database.ts`). A second opt-in must re-derive that argument for its own write body
594
- * first; if this policy ever grows a third consumer, rename it for what the callers share rather
595
- * than widening it by default. {@link LOST_UPDATE_RETRY_POLICY} is a separate policy for a
596
- * separate class, not a second consumer of this one.
597
- */
598
- export const SCHEMA_INIT_RETRY_POLICY: Readonly<ControlWriteRetryOptions> = {
599
- attempts: SCHEMA_INIT_ATTEMPTS,
600
- delaysMs: SCHEMA_INIT_RETRY_DELAYS_MS,
601
- isRetriable: isRetriableSchemaInitFailure,
602
- };
603
-
604
- /**
605
- * The lost-update policy: the default classifier plus a lost update claimed by type
606
- * ({@link isRetriableLostUpdateFailure}), over the default attempts, backoff and budget. A re-run
607
- * here is a RE-DECISION, not a re-presentation: the body reads the row again under the lock and
608
- * signs over what it finds, so the write that lost to a rival is replaced by one made over the
609
- * rival's result. The budget bounds it as it bounds every write — a losing attempt whose read
610
- * phase waited out one per-peer read deadline (~7.5 s measured in the degraded-cohort scenario's
611
- * trio boot) gets exactly one retry, which is the ceiling to expect; one that waited out two
612
- * (14.7 s, measured once in 18 of that scenario's boots, on the member that cannot reach one
613
- * sibling) gets none and is abandoned on the budget, and the lost publish is then the reconcile
614
- * pass's or the heartbeat's to redo, as every abandoned self-publish is.
615
- *
616
- * NOTE: the re-run safety this policy assumes is each opted-in body's, not a general property. A
617
- * body may opt in only when its read of the row, its decision and its signature ALL run inside
618
- * the locked body, so that the re-run presents a write made over the row as it now stands rather
619
- * than the first attempt's signed record (which the rival may have stamped past, or which may
620
- * overwrite what the rival wrote). Three `CadrePeer` writers opt in, through
621
- * `ControlDatabase.mutateCadrePeer`'s policy parameter or `lockedWithRetry` directly:
622
- * `updateSelfPeerRecord` (re-reads and re-signs the node's own record), `reauthorizeCadrePeer`
623
- * (re-reads the stamp and decides again whether the row is still the owner's to re-touch) and
624
- * the two removals `deleteCadrePeer` / `removeMachine` (stamp read and signature already inside
625
- * the body, and a self-publish never changes the stamp the `'remove'` digest binds). A new opt-in
626
- * must re-derive that argument for its own body first.
627
- */
628
- export const LOST_UPDATE_RETRY_POLICY: Readonly<ControlWriteRetryOptions> = {
629
- isRetriable: isRetriableLostUpdateFailure,
630
- };
631
-
632
- /**
633
- * Run `attempt` up to {@link CONTROL_WRITE_ATTEMPTS} times (or `options.attempts`), retrying only
634
- * failures the policy's classifier — {@link isRetriableControlWriteFailure} by default —
635
- * calls transient, and only while {@link CONTROL_WRITE_RETRY_BUDGET_MS} has not elapsed.
636
- *
637
- * `attempt` must be atomic and re-runnable: a failed cluster write rolls back (nothing is
638
- * half-applied), and re-running the body re-runs its reads too — `ControlDatabase`'s
639
- * locked write bodies all satisfy this (see the contract on
640
- * `ControlDatabase.withWriteLock`). The backoff sleeps happen with NO lock held; the caller
641
- * takes and releases its lock inside `attempt`.
642
- *
643
- * On exhaustion (attempts or budget) the LAST error is rethrown unchanged — never wrapped,
644
- * so the exact messages downstream code and the degraded-cohort-member scenario assert on
645
- * survive. A non-retriable failure propagates from the attempt that raised it.
646
- *
647
- * Either way — declined or exhausted — an `options.onAbandon` observer is notified exactly
648
- * once before the rethrow (a `ControlRetryAbandonment`). Only WRITES pass one: an abandoned
649
- * read throws to a caller that is awaiting it, so nothing is lost silently there
650
- * (`control-read-retry.ts` says so at its own seam), while an abandoned write may have no
651
- * caller at all — a background self-record republish is `void`-ed with a `debug` catch, so
652
- * its failure reaches nobody unless something is listening here.
653
- * `ControlDatabase.setControlWriteAbandonedListener` is the only thing that passes one in
654
- * production; `retryControlWrite` itself neither supplies nor requires an observer.
655
- */
656
- export function retryControlWrite<T>(
657
- attempt: () => Promise<T>,
658
- options: ControlWriteRetryOptions = {}
659
- ): Promise<T> {
660
- return retryControlOperation(attempt, {
661
- attempts: CONTROL_WRITE_ATTEMPTS,
662
- delaysMs: CONTROL_WRITE_RETRY_DELAYS_MS,
663
- budgetMs: CONTROL_WRITE_RETRY_BUDGET_MS,
664
- isRetriable: isRetriableControlWriteFailure,
665
- // The default prefix, named anyway: the degraded-cohort scenario asserts on
666
- // `Control write [<label>] …` lines byte-for-byte.
667
- logPrefix: 'Control write',
668
- }, options);
669
- }
1
+ import { CoordinatorPartialCommitError, PeersIncompleteError, SyncRetryExhaustedError, TornActionError } from '@optimystic/db-core';
2
+ import { ConcurrentModificationError, PartialCommitError } from '@optimystic/quereus-plugin-optimystic';
3
+ import { causeChain, chainMessages, reportsUnansweredShortfall, reportsUnreachableCohort, retryControlOperation } from './control-retry.js';
4
+ import type { ControlRetryOptions } from './control-retry.js';
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/cadre/control-replication.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 on the strength of the rejection itself —
22
+ * nothing here claims a rejection, at any phase (the shortfall claim reads the vote count for
23
+ * exactly this reason), because re-presenting one would re-present a spent signature against a
24
+ * cohort that already said no. Rejections are re-presented anyway when they arrive inside the
25
+ * transactor's promise-phase aggregate, which {@link isUncommittedTransactorAggregate}
26
+ * claims on the PHASE alone, whatever the cause inside says. Safe because nothing has committed
27
+ * at that phase, and deliberately kept — one of the remaining promise-phase rejections is exactly
28
+ * the kind a re-presentation fixes. See the accepted-tradeoff `NOTE:` there for which, and why no
29
+ * blanket rejection veto is wanted.
30
+ *
31
+ * A failure that says some of the write may be STORED is a different matter, and never
32
+ * re-presented whatever text it carries: {@link reportsPossiblyStoredWrite} vetoes it by type
33
+ * before any matcher runs. The one half-landed write that IS re-presented is a torn write the
34
+ * library marks final — not saved and unable to land ({@link isFinalTornWrite}).
35
+ *
36
+ * THREE policies ship from here, and the split is deliberate: the default
37
+ * ({@link isRetriableControlWriteFailure}, {@link CONTROL_WRITE_ATTEMPTS}) sits under every
38
+ * control write; {@link SCHEMA_INIT_RETRY_POLICY} is opted into by
39
+ * `ControlDatabase.applyControlSchema` alone; {@link LOST_UPDATE_RETRY_POLICY} is opted into by
40
+ * the `CadrePeer` writers whose bodies re-read the row and decide again. Each widened one absorbs
41
+ * one extra failure class whose re-run safety holds for its opted-in bodies and NOT for writes in
42
+ * general; anything added to the default list must be safe for all ~19 callers.
43
+ *
44
+ * Lives outside `control-database.ts` so a spec can drive the classifier against real engine
45
+ * errors without importing the whole database class. The loop itself lives in
46
+ * `control-retry.ts`, shared with the READ policy (`control-read-retry.ts`) — this module
47
+ * owns the write policies: their classifiers, attempt counts, backoff and budget.
48
+ */
49
+
50
+ /**
51
+ * Attempts allowed per control write: the first, plus two retries of a transiently-failed
52
+ * cluster commit. Bounded so a genuinely unreachable cohort terminates in the transactor's
53
+ * own error rather than spinning; two retries covers the observed failure (a stream still
54
+ * forming when the write fired) with margin.
55
+ */
56
+ export const CONTROL_WRITE_ATTEMPTS = 3;
57
+
58
+ /**
59
+ * Attempts allowed for {@link SCHEMA_INIT_RETRY_POLICY}, the one call site that also absorbs a
60
+ * self-coordination refusal.
61
+ *
62
+ * Two more than {@link CONTROL_WRITE_ATTEMPTS} because what this retry buys is wall-clock for a
63
+ * cold-starting node's bootstrap dials to land, and because the refusal is cheap to re-provoke
64
+ * relative to a cluster round-trip: `findCoordinator` already spends its own bounded wait before
65
+ * raising (3 attempts, 500 ms apart, `db-p2p/src/libp2p-key-network.ts` ~422) and then decides
66
+ * LOCALLY that it may not elect itself, so no peer is contacted and no cohort deadline is
67
+ * consumed.
68
+ *
69
+ * Note that the ~1 s `findCoordinator` spends internally is real, on top of this policy's own
70
+ * backoff — which is exactly why {@link CONTROL_WRITE_RETRY_BUDGET_MS} and not this count is what
71
+ * actually terminates the loop in the worst case.
72
+ */
73
+ export const SCHEMA_INIT_ATTEMPTS = 5;
74
+
75
+ /**
76
+ * Elapsed-time ceiling on the whole retry loop, measured from the START of the first
77
+ * attempt and checked after a failed attempt BEFORE sleeping.
78
+ *
79
+ * This budget — not the attempt count — is what makes the policy safe to sit under every
80
+ * control write. A transient failure (stream reset while a connection is still forming)
81
+ * surfaces in well under a second, so it is retried and the loop adds at most ~2.2 s. A
82
+ * genuinely silent cohort member costs ~21 s per consensus round (two `ClusterClient`
83
+ * response-deadline attempts, 10.5 s each at the default declared link): one pend round plus
84
+ * the cancel discharge's three rounds, about 84 s for one write in
85
+ * `control-write-degraded-cohort-member.integration.ts`, which already exceeds this budget
86
+ * when attempt 1 returns — so that case is surfaced immediately and retry adds ZERO latency
87
+ * to the case where it cannot help.
88
+ *
89
+ * It cuts the loop off by design, so it does not grow with the link: its job is to end the
90
+ * retries of slow attempts, and the caller gets the last attempt's error unchanged. An attempt
91
+ * whose read phase consulted a silent peer ends at about one per-peer read deadline
92
+ * (`cohortReadDeadlineMs` in `link-budget.ts`: 7 s at the default declared link, 5 s before it
93
+ * was derived, 1 s at Optimystic's own default), so it still gets one retry inside this budget
94
+ * where it once got two; an attempt that runs into the `ClusterClient` response deadline
95
+ * (10.5 s at the default declared link) still gets none. See `docs/network/deadlines.md` →
96
+ * "Deadlines over Optimystic's reads and commits".
97
+ *
98
+ * NOTE: a failed commit attempt also pays a cancel discharge before its error returns
99
+ * (optimystic `TransactorSource.transact`'s catch) — bounded by six rounds and
100
+ * `abortOrCancelTimeoutMs`, which every collection this repo opens sets to the larger of 5 s
101
+ * and the RPC dial deadline: 42.5 s at the default declared link (`optimysticDialLimits` in
102
+ * `link-budget.ts`;
103
+ * `../optimystic/packages/quereus-plugin-optimystic/src/optimystic-adapter/collection-factory.ts`).
104
+ * One cancel that runs its full budget therefore ends the retries on its own, cutting the
105
+ * three-attempt policy to however many attempts came before it. A cancel only runs that long
106
+ * when a peer stays silent, and that attempt has already spent its pend round past this
107
+ * budget, so the cut loses nothing there. After a transient fault the cancel is either
108
+ * answered or gives up after its six rounds against a dead transport, in about a second
109
+ * either way (optimystic `NetworkTransactor.MAX_CANCEL_ROUNDS`). Not observed — every
110
+ * measured round of the transient-reset case committed on attempt 3 of 3 — so this is a
111
+ * condition to watch, not work to do: if that case ever starts failing with
112
+ * `failed after 2/3 attempt(s)`, the cancel discharge is where the time went.
113
+ */
114
+ // eslint-disable-next-line no-restricted-syntax -- cuts off by design: it ends the retries of slow attempts rather than waiting them out; see docs/network/deadlines.md → "Deadlines over Optimystic's reads and commits"
115
+ export const CONTROL_WRITE_RETRY_BUDGET_MS = 10_000;
116
+
117
+ /**
118
+ * Backoff before retry N, jittered ±50% (so the first sleep is 125–375 ms — the jitter can
119
+ * never floor a delay to zero). Each single sleep is additionally capped at the LARGEST
120
+ * delay in the list, so a `stop()` racing a backoff is never held up by more than ~1 s.
121
+ * There is no `AbortSignal` at this seam to cancel a sleep outright; the cap is the
122
+ * substitute, deliberately not plumbing one through every write path.
123
+ */
124
+ const CONTROL_WRITE_RETRY_DELAYS_MS: readonly number[] = [250, 1_000];
125
+
126
+ /**
127
+ * Backoff for {@link SCHEMA_INIT_RETRY_POLICY}, jittered and capped the same way. Worst case
128
+ * ~4.6 s of sleep across four retries (375 + 750 + 1500 + 2000, each capped at the largest base),
129
+ * which stays inside {@link CONTROL_WRITE_RETRY_BUDGET_MS} — the budget still terminates the loop
130
+ * first if any single attempt is itself slow.
131
+ *
132
+ * Sized against measured facts, not guessed:
133
+ *
134
+ * - the self-coordination guard clears the moment the node has ONE connection again (both
135
+ * branches that raise `grace-period-not-elapsed` require `getConnections().length === 0`), not
136
+ * when the 30 s grace period expires — so this does NOT need to cover the grace period, only
137
+ * the gap until a bootstrap dial completes;
138
+ * - the guard's 30 s `gracePeriodMs` cannot be tuned from this repo anyway: no caller in either
139
+ * repo passes a `SelfCoordinationConfig`, so the default is always in force;
140
+ * - a node that has NEVER connected is waved through as a bootstrap node (network high-water
141
+ * mark of 1), so this retry only ever delays a node that HAS seen peers. One whose peers are
142
+ * gone for good still fails, ~4.6 s later — which is why the budget stays at the shared
143
+ * ceiling rather than stretching to cover the full 30 s window.
144
+ */
145
+ const SCHEMA_INIT_RETRY_DELAYS_MS: readonly number[] = [250, 500, 1_000, 2_000];
146
+
147
+ /**
148
+ * Does any link of the `cause` chain report a transactor aggregate from a phase where nothing can
149
+ * have committed yet?
150
+ *
151
+ * `NetworkTransactor` composes one `PeersIncompleteError` for all four of its operations and says
152
+ * which in `phase` (`db-core/src/transactor/peers-incomplete-error.ts`). Only two of the four are
153
+ * safe to re-present:
154
+ *
155
+ * - `get` (a block read, which a write body also performs) and `pend` (phase 1) fail before
156
+ * anything commits, so the write is known not to have landed. `get` raises it only when a
157
+ * coordinator answered and left a block out; a block nobody answered for fails typed
158
+ * instead, which {@link matchesRetriableFailure} claims ({@link reportsUnreachableCohort});
159
+ * - `commit` (phase 2) is REACHABLE here and NOT safe. `commitBlock` throws the
160
+ * aggregate when a header/tail commit got NO response at all — precisely the transient
161
+ * class this retry targets — and that escapes `commit()`, survives `TransactorSource`'s
162
+ * cancel-and-rethrow (cancel reaches PENDING actions only; a peer that already committed
163
+ * stays committed) and `Collection.syncInternal` (which retries StaleFailure RETURN values,
164
+ * not throws), reaching this funnel QuereusError-wrapped. The tail commit is one batch to
165
+ * one coordinator running consensus internally, so a no-response there is INDETERMINATE:
166
+ * the commit may have completed with only the response lost. Re-running the write body over
167
+ * a write that landed turns a success into a constraint failure (e.g.
168
+ * `UNIQUE constraint failed: CadrePeer.PeerId`). Surfacing the transient error instead lets
169
+ * the caller re-read committed state and decide. The commit phase is vetoed by
170
+ * {@link reportsIndeterminateCommit}, not here;
171
+ * - `cancel` — a failed attempt's own cancel that could not discharge the pend it left behind —
172
+ * is neither claimed here nor vetoed there, so it falls through unmatched and is not retried.
173
+ * Per LINK, not per chain: a cancel aggregate carrying a `get`/`pend` one below it is still
174
+ * claimed on that lower link, which is right for the same reason the lower link alone is
175
+ * (nothing committed at either phase) and is what the text matcher this replaced also did.
176
+ *
177
+ * What still fails CLOSED is the error not arriving: a future wrapper that drops `cause` takes
178
+ * every link below it with it, so no typed claim matches and the write is simply not retried.
179
+ * `control-write-degraded-cohort-member.integration.ts` turns that into a red assertion on a live
180
+ * aggregate; NOTE: on Optimystic 1.20.0 none of its cases produced an aggregate at all (2026-10-28:
181
+ * the injected reset failed the write's read typed, and a pend's shortfall arrives on its own), so
182
+ * that guard can pass without ever seeing one.
183
+ *
184
+ * NOTE: accepted tradeoff — a REJECTION raised while promises are still being collected reaches
185
+ * this repo wrapped in this same aggregate, and this matcher claims it on the phase alone,
186
+ * whatever the cause inside says. That re-presents such a rejection up to two more times inside
187
+ * the 10 s budget. Kept deliberately, and re-decided on 2026-09-17 against the current upstream
188
+ * behaviour rather than inherited:
189
+ *
190
+ * - Contention is no longer a rejection at all. "Another write holds this block right now"
191
+ * (`pending conflict`) is now a `held` verdict that counts toward neither approvals nor
192
+ * rejections (`validatePendOperations`,
193
+ * `../optimystic/packages/db-p2p/src/cluster/cluster-repo.ts`), so the rejection this tradeoff
194
+ * was originally written about does not arrive any more. It reaches this funnel as
195
+ * `SyncRetryExhaustedError` instead, which {@link reportsPossiblyStoredWrite} declines by type
196
+ * — upstream documents resubmitting after it as unsafe (the attempt that spent the budget may
197
+ * have left its log entry standing), and its collection sync has already spent ten retries on
198
+ * the race. The torn-write rule beside it: a `TornActionError` is re-presented only when
199
+ * `final` is true; any other torn write is declined.
200
+ * - What remains rejectable at the promise phase is stale revision, membership-not-admitted, an
201
+ * expired transaction, and a configured validator's refusal (`ClusterMember.evaluatePromise`).
202
+ * A block whose revision a member cannot establish is approved, not refused: the member logs
203
+ * `validation-block-unavailable` and votes on (`judgeStaleRevisions`). Stale revision is worth
204
+ * a retry: this loop re-runs the WHOLE write body, reads included
205
+ * (`ControlDatabase.withWriteLock`'s contract), so attempt 2 presents a pend against the
206
+ * revision that made attempt 1 stale. A blanket "decline any chain reporting a validator
207
+ * rejection" rule would remove that retry to save two wasted attempts on the others.
208
+ *
209
+ * Revisit if a re-presentation ever becomes expensive relative to what it buys — a rejection class
210
+ * that costs a full cohort round-trip to re-present, or a write body whose reads are no longer
211
+ * cheap — or when upstream offers a typed refusal surface to classify the rejection itself on.
212
+ * Contention is no longer the reason to revisit.
213
+ *
214
+ * An aggregate whose per-peer details came out EMPTY (possible when `formatBatchStatuses` has no
215
+ * batches to format) is claimed like any other: `phase` is on the error whether or not a batch
216
+ * formatted, and `get`/`pend` is itself the proof that nothing committed.
217
+ *
218
+ * Exported for the READ classifier (`control-read-retry.ts`), which reuses it verbatim, `pend`
219
+ * included: a control read presents no transaction, so it cannot produce a `pend` aggregate at
220
+ * all — claiming that phase there is unreachable rather than unsafe, and one shared predicate is
221
+ * one thing to keep correct instead of two.
222
+ */
223
+ export function isUncommittedTransactorAggregate(links: readonly Error[]): boolean {
224
+ return links.some(link => link instanceof PeersIncompleteError
225
+ && (link.phase === 'get' || link.phase === 'pend'));
226
+ }
227
+
228
+ /**
229
+ * Does any link of the failure's `cause` chain report a COMMIT-phase transactor aggregate — i.e.
230
+ * an outcome nobody can call committed or not?
231
+ *
232
+ * Vetoes the whole chain rather than the one link carrying the phase, and vetoes it regardless of
233
+ * which claim would otherwise have taken it: an indeterminate commit anywhere in the chain costs a
234
+ * retry we could have had instead of risking a re-run over a write that landed.
235
+ *
236
+ * Fails CLOSED in the only direction that matters: this veto and every TYPED claim the write
237
+ * classifier makes rest on the same `instanceof`, so a chain this cannot see (a wrapper that
238
+ * dropped `cause`, a second loaded copy of `@optimystic/db-core`) is a chain no typed claim can
239
+ * see either, and nothing is retried for the veto to have to stop.
240
+ *
241
+ * NOTE: that symmetry holds for every claim matched by type, which is all of them in the default
242
+ * and lost-update policies. Schema init adds one matched by TEXT
243
+ * ({@link isSelfCoordinationGraceRefusal}), and a commit aggregate raised OVER that refusal embeds
244
+ * it as the aggregate's own `; root: …` tail — so a chain that kept the text and lost the typed
245
+ * link would be claimed with this veto blind, where the text veto this replaced declined it. Fine
246
+ * today: every wrapper between the transactor and `applyControlSchema` passes the inner error as
247
+ * `cause` (Quereus' DDL, module-create and failed-apply wrappers all do). Revisit if one stops, or
248
+ * if the default policy ever grows a text matcher of its own — either way the veto then needs a
249
+ * text arm beside the typed one.
250
+ */
251
+ function reportsIndeterminateCommit(links: readonly Error[]): boolean {
252
+ return links.some(link => link instanceof PeersIncompleteError && link.phase === 'commit');
253
+ }
254
+
255
+ /**
256
+ * Does any link of the `cause` chain say some of this write may be stored, or may still be?
257
+ * Such a failure is never re-presented — a re-run could store the write twice.
258
+ *
259
+ * - `SyncRetryExhaustedError` (and its `SyncRevisionStalledError` subclass): upstream documents
260
+ * resubmitting as unsafe, because the attempt that spent the budget may have left its log
261
+ * entry standing.
262
+ * - `TornActionError` without `final: true`: the write's log entry is stored and nobody could
263
+ * establish that the rest can never land — it may be saved already, or land later.
264
+ * - `CoordinatorPartialCommitError` / `PartialCommitError`: another collection or tree of the
265
+ * same transaction is already durable, and re-running the whole body would apply it twice.
266
+ *
267
+ * Every one of these embeds text from elsewhere in its message (a responder's refusal, the
268
+ * underlying failure), and upstream may chain that failure on `cause` besides — so this veto runs
269
+ * before any claim.
270
+ *
271
+ * Matched by TYPE: each survives the bridge's and Quereus' rewraps on `cause`. An error built by a
272
+ * second loaded copy of `@optimystic/db-core` (or of the plugin, for `PartialCommitError`) fails
273
+ * `instanceof`, and then this veto does not fire — but neither does any claim against that same
274
+ * copy, so nothing is retried for it to have to stop. The asymmetry with
275
+ * {@link isFinalTornWrite} is deliberate: there, a missed `instanceof` means no retry, which is the
276
+ * safe side. No text fallback parses `TornActionError`'s closing sentence, since upstream says its
277
+ * wording is for log lines only.
278
+ *
279
+ * NOTE: the plugin is registered through its `/plugin` entry (`control-database.ts`) but
280
+ * `PartialCommitError` is imported from its root entry; the two are one class only because the
281
+ * plugin's build emits both entries over one shared chunk. If upstream ever bundles the entries
282
+ * separately, this `instanceof` stops matching with every spec still green — import the class from
283
+ * the entry the plugin is registered through.
284
+ */
285
+ function reportsPossiblyStoredWrite(links: readonly Error[]): boolean {
286
+ return links.some(link =>
287
+ link instanceof SyncRetryExhaustedError
288
+ || (link instanceof TornActionError && link.final !== true)
289
+ || link instanceof CoordinatorPartialCommitError
290
+ || link instanceof PartialCommitError);
291
+ }
292
+
293
+ /**
294
+ * A torn write the library marks FINAL: not saved, unable to land, its pending records confirmed
295
+ * cancelled — so submitting it again stores it once.
296
+ *
297
+ * Worth re-presenting, not merely safe to: upstream raises it mostly when a rival holds the
298
+ * revision this write's log entry claimed, which is contention, and the loop re-runs the write
299
+ * body's reads, so the next attempt builds on the rival's revision — the same argument that keeps
300
+ * stale-revision rejections retried (the accepted-tradeoff `NOTE:` on
301
+ * {@link isUncommittedTransactorAggregate}).
302
+ *
303
+ * NOTE: `CoordinatorStaleLossError` (db-core; "nothing durably committed, safe to re-drive") is not
304
+ * claimed, so it falls to the text matchers; it escapes only after the coordinator's own retry budget
305
+ * ran out. Seen abandoning a control write on 2026-09-18 (`control-delete-while-alone-convergence`,
306
+ * under load): a node's own storage refused its own pend as a `stale conflict` for the ~14 s the
307
+ * coordinator spent re-driving, then gave up. Still not claimed here — the failing attempt already
308
+ * ran past {@link CONTROL_WRITE_RETRY_BUDGET_MS}, so a retry from this loop would never get to run,
309
+ * and the refusal came from the node's OWN storage disagreeing with its own revision view, which does
310
+ * not change while the node is alone; re-driving the same write body again would hit the same
311
+ * refusal. The cause (a commit torn by a sibling that stopped mid-commit, leaving the node with a
312
+ * revision view its own storage disputes) is `tickets/blocked/forked-control-collection-sync-livelocks.md`
313
+ * → "Second trigger".
314
+ */
315
+ function isFinalTornWrite(link: Error): boolean {
316
+ return link instanceof TornActionError && link.final === true;
317
+ }
318
+
319
+ /**
320
+ * A LOST UPDATE: the optimystic bridge refusing a commit because another writer changed or
321
+ * removed a row this statement read (`TransactionBridge.mapCommitRefusal` over a
322
+ * `TreeEntryChangedError`, `quereus-plugin-optimystic/src/optimystic-adapter/txn-bridge.ts`).
323
+ * Claimed by TYPE for {@link LOST_UPDATE_RETRY_POLICY} only.
324
+ *
325
+ * Why it is a proven non-commit: the refusal is raised inside the action's atomic handler, so
326
+ * none of that action's entries land. A refusal after a sibling tree or collection of the same
327
+ * transaction already synced is not delivered bare — the per-tree sweep wraps it in
328
+ * `PartialCommitError`, the coordinator path in `CoordinatorPartialCommitError` — and
329
+ * {@link reportsPossiblyStoredWrite} vetoes both by type before this predicate runs. A bare chain
330
+ * carrying this class therefore means nothing of the write is durable.
331
+ *
332
+ * Why it is not in the default list: the rejection is of the write's READ SET, not of its
333
+ * signature, so re-presenting the same statement is only right when the body re-reads the row and
334
+ * decides again over what it finds. That is a property of each opted-in body (see the policy's
335
+ * `NOTE:`), not of control writes in general.
336
+ *
337
+ * Not matched by text: `ConcurrentModificationError` is exported from both the plugin's root and
338
+ * `/plugin` entries over one shared chunk, as `PartialCommitError` is, so the one `instanceof`
339
+ * covers both (the `NOTE:` on {@link reportsPossiblyStoredWrite} applies to it too). A second
340
+ * loaded copy of the plugin would fail the `instanceof` and the lost update would then simply not
341
+ * be retried — the safe side.
342
+ */
343
+ function isLostUpdate(link: Error): boolean {
344
+ return link instanceof ConcurrentModificationError;
345
+ }
346
+
347
+ /**
348
+ * Optimystic refusing to let a node elect ITSELF coordinator because its last connection dropped
349
+ * less than the guard's grace period ago (`Libp2pKeyPeerNetwork.shouldAllowSelfCoordination` →
350
+ * `findCoordinator`, `db-p2p/src/libp2p-key-network.ts`).
351
+ *
352
+ * Matched ONLY with the `grace-period-not-elapsed` reason. The same sentence is raised with three
353
+ * other reasons and none of them is worth a retry: `disabled` is static configuration, and
354
+ * `partition-detected` / `suspicious-shrinkage` describe a network condition that will not resolve
355
+ * inside a few seconds of backoff. The grace-period one WILL — it clears as soon as the node holds
356
+ * one connection again, which a cold-starting node dialling its bootstrap peers is actively
357
+ * working on.
358
+ *
359
+ * NOTE: matched by TEXT, not by type. `FindCoordinatorError` (`code: 'SELF_COORDINATION_BLOCKED'`)
360
+ * is exported from `@optimystic/db-p2p`, and when this matcher was written the error OBJECT did not
361
+ * survive the trip: `OptimysticVirtualTable.initialize` rethrew as `new Error(message)` with no
362
+ * `cause`. It now rethrows through `rewrapAsQueryError`, which keeps `cause`
363
+ * (`quereus-plugin-optimystic/src/optimystic-module.ts`); whether every Quereus wrapper above it on
364
+ * the schema-init path keeps it too has not been checked, and the text still arrives either way.
365
+ * This matcher — the module's only one — fails CLOSED: a rewording upstream stops the retry
366
+ * engaging, it never makes it unsafe.
367
+ */
368
+ const SELF_COORDINATION_GRACE_REFUSAL =
369
+ /Self-coordination blocked: grace-period-not-elapsed\. No coordinator available for key\./;
370
+
371
+ /** Self-coordination refused because the node's last connection dropped moments ago. */
372
+ function isSelfCoordinationGraceRefusal(message: string): boolean {
373
+ return SELF_COORDINATION_GRACE_REFUSAL.test(message);
374
+ }
375
+
376
+ /**
377
+ * The error messages the DEFAULT write policy claims: none. Every failure it re-presents is now
378
+ * claimed by TYPE in {@link matchesRetriableFailure} — the transactor's get/pend aggregate
379
+ * ({@link isUncommittedTransactorAggregate}), a block read the cohort could not answer
380
+ * ({@link reportsUnreachableCohort}), an unanswered super-majority shortfall
381
+ * ({@link reportsUnansweredShortfall}) and a final torn write ({@link isFinalTornWrite}) — and so
382
+ * are both vetoes.
383
+ *
384
+ * Kept empty rather than deleted for two reasons: it is what {@link RETRIABLE_SCHEMA_INIT_MATCHERS}
385
+ * spreads, so the "widened, not replaced" relation between the two policies stays expressed in
386
+ * code; and a future text matcher has one obvious home. The only text matcher left in this module
387
+ * is the schema-init self-coordination refusal, which comes from `@optimystic/db-p2p`, not from the
388
+ * transactor.
389
+ *
390
+ * Deliberately NOT matched, here or anywhere: every constraint / authorization failure
391
+ * (`CHECK constraint failed:`, `UNIQUE constraint failed:`) — those reach the same funnel
392
+ * and must be retried zero times: the cohort REFUSED the write, so re-presenting it
393
+ * re-presents a spent signature and can never commit.
394
+ */
395
+ const RETRIABLE_CONTROL_WRITE_MATCHERS: readonly ((message: string) => boolean)[] = [];
396
+
397
+ /**
398
+ * The (currently empty) default list PLUS the self-coordination grace refusal — the classifier for
399
+ * schema init ONLY ({@link SCHEMA_INIT_RETRY_POLICY}), deliberately not folded into the list above.
400
+ *
401
+ * Why this class is safe HERE and not everywhere: a write refused at coordinator SELECTION never
402
+ * reached a peer, so re-presenting it is a proven non-commit. But `findCoordinator` is also
403
+ * reached from `NetworkTransactor.commitBlock` during PHASE 2 (`resolveCoordinator`,
404
+ * `db-core/src/transactor/network-transactor.ts`), and `commit()` commits the header block before
405
+ * the rest — so a general control write refused there can be refused AFTER something already
406
+ * committed. Worse, it is thrown from the batch assembly OUTSIDE the `try` that composes the
407
+ * commit-phase aggregate (`batchesForPayload`, `db-core/src/transactor/network-transactor.ts`), so
408
+ * it normally arrives with no aggregate around it at all and
409
+ * {@link reportsIndeterminateCommit} has nothing to veto on — and re-running an insert body over a
410
+ * write that landed is exactly the `UNIQUE constraint failed: CadrePeer.PeerId` failure that veto
411
+ * exists to prevent. (The one path where the veto does fire is the per-block retry's
412
+ * re-resolution inside `processBatches`, where such a throw becomes the commit aggregate's root
413
+ * cause.)
414
+ *
415
+ * Schema init does not have that problem: `apply schema` is a diff rather than a replay, and a
416
+ * failed apply is taken back whole — Quereus unwinds every step it ran and verifies the catalog
417
+ * against a pre-apply fingerprint — so a re-run emits exactly the DDL the live catalog is missing.
418
+ * The full argument, including the plugin-side dependency that unwind carries, is at the
419
+ * `applyControlSchema` call site in `control-database.ts`.
420
+ *
421
+ * RETRIED DELIBERATELY, not by oversight: the failures Quereus cannot take back. When the unwind
422
+ * does not complete — an undo statement threw, the post-unwind catalog did not match the pre-apply
423
+ * fingerprint, that catalog could not be re-collected to check, or a step the differ marks
424
+ * irreversible because it discards data (dropping a table or a column, narrowing a column's type —
425
+ * of which only dropping a column reaches a `CadreControl` apply, as the catalog-only migration
426
+ * step `refuseIncompatibleControlStore` in `control-schema-version.ts` lets through; it discards
427
+ * nothing there, since rows keep the field) poisoned the journal before it
428
+ * ran, leaving nothing unwound — Quereus keeps the failing step's own message, APPENDS the reason the
429
+ * schema could not be restored, and carries the original as `cause`. So a transient cause
430
+ * underneath still matches here, and neither veto ({@link reportsPossiblyStoredWrite},
431
+ * {@link reportsIndeterminateCommit}) looks for that reason text. Retrying over a partially migrated
432
+ * schema is safe for the same reason the ordinary re-run is: the plugin commits whatever its write
433
+ * batch holds, so storage and the catalog are left in step either way, and the next apply diffs
434
+ * against what is really there. Vetoing it instead would turn a healable transient outage into a
435
+ * dead start.
436
+ */
437
+ const RETRIABLE_SCHEMA_INIT_MATCHERS: readonly ((message: string) => boolean)[] = [
438
+ ...RETRIABLE_CONTROL_WRITE_MATCHERS,
439
+ isSelfCoordinationGraceRefusal,
440
+ ];
441
+
442
+ /**
443
+ * Did this control write fail because the cluster cohort did not ANSWER — i.e. is
444
+ * re-presenting the SAME signed write a moment later the right response?
445
+ *
446
+ * Classifies entirely by TYPE, over the `cause` chain — by the time a failure reaches
447
+ * `ControlDatabase` it is wrapped in a `QuereusError` (the real chain is `QuereusError` → `Error`
448
+ * → `Error`), so every claim and veto must work at any depth. Anything that is not an `Error` is
449
+ * never retried.
450
+ *
451
+ * Two vetoes run over the whole chain before any claim: {@link reportsPossiblyStoredWrite}
452
+ * (a spent sync budget, a non-final torn write, a partial commit) and
453
+ * {@link reportsIndeterminateCommit} (a commit-phase transactor aggregate). A chain either veto
454
+ * flags, at any level, is never retried on the strength of some other level looking transient.
455
+ * Four failures are claimed as retriable: the transactor's get/pend aggregate
456
+ * ({@link isUncommittedTransactorAggregate}, shared with the read classifier), a block read the
457
+ * cohort could not answer ({@link reportsUnreachableCohort}, also shared with it), an unanswered
458
+ * super-majority shortfall ({@link reportsUnansweredShortfall}, shared with the edge node's
459
+ * `retryAfterRestart`) and a final torn write ({@link isFinalTornWrite}).
460
+ *
461
+ * The RETRIABLE failures need a real multi-node cluster to produce, so the unit cases build the
462
+ * upstream classes directly; the degraded-cohort scenario
463
+ * (`control-write-degraded-cohort-member.integration.ts`) asserts this classifier against the
464
+ * super-majority shortfall from a real silent member, and absorbs a real stream reset end to end
465
+ * (on Optimystic 1.20.0 the reset fails the write's read as an unanswered block, claimed by type).
466
+ */
467
+ export function isRetriableControlWriteFailure(error: unknown): boolean {
468
+ return matchesRetriableFailure(error, RETRIABLE_CONTROL_WRITE_MATCHERS);
469
+ }
470
+
471
+ /**
472
+ * {@link isRetriableControlWriteFailure} widened by exactly one class — the self-coordination
473
+ * grace refusal ({@link RETRIABLE_SCHEMA_INIT_MATCHERS}) — for `ControlDatabase.applyControlSchema`.
474
+ *
475
+ * Opt-in per call site, via {@link SCHEMA_INIT_RETRY_POLICY}. Every other control write keeps the
476
+ * default classifier untouched.
477
+ */
478
+ export function isRetriableSchemaInitFailure(error: unknown): boolean {
479
+ return matchesRetriableFailure(error, RETRIABLE_SCHEMA_INIT_MATCHERS);
480
+ }
481
+
482
+ /**
483
+ * {@link isRetriableControlWriteFailure} widened by exactly one class — a lost update
484
+ * ({@link isLostUpdate}), claimed by type — for the `CadrePeer` writers that re-read the row inside
485
+ * their locked body. Opt-in per call site, via {@link LOST_UPDATE_RETRY_POLICY}; both vetoes still
486
+ * run first, so a lost update carried inside a partial commit, a spent sync budget or a non-final
487
+ * torn write stays declined.
488
+ */
489
+ export function isRetriableLostUpdateFailure(error: unknown): boolean {
490
+ return matchesRetriableFailure(error, RETRIABLE_CONTROL_WRITE_MATCHERS, isLostUpdate);
491
+ }
492
+
493
+ /**
494
+ * Shared body of the three classifiers: walk the `cause` chain, let
495
+ * {@link reportsPossiblyStoredWrite} and then {@link reportsIndeterminateCommit} veto it, then claim
496
+ * a get/pend transactor aggregate ({@link isUncommittedTransactorAggregate}), a block read the
497
+ * cohort could not answer ({@link reportsUnreachableCohort}), an unanswered
498
+ * super-majority shortfall ({@link reportsUnansweredShortfall}), a final torn write
499
+ * ({@link isFinalTornWrite}) or any link `claimsLink` names, then ask `matchers`. The vetoes run
500
+ * BEFORE any claim for every policy — a chain reporting a possibly-stored write or a commit-phase
501
+ * batch is never retried, however transient some other level looks, and a final torn write or a
502
+ * lost update carried by a partial commit is still declined because a sibling collection landed.
503
+ * `claimsLink` is the one typed claim a policy may add; it sits here beside the shared typed claims
504
+ * so the vetoes stay in one place above all of them.
505
+ *
506
+ * The three shared typed claims are predicates over the WHOLE chain and the policy's own is per
507
+ * link, which is why the one `some` below carries only the latter. The shortfall claim being shared
508
+ * with the edge node is what keeps the two write policies from drifting on it; where a shortfall
509
+ * leaves the write is still decided here, by the commit-phase veto above.
510
+ */
511
+ function matchesRetriableFailure(
512
+ error: unknown,
513
+ matchers: readonly ((message: string) => boolean)[],
514
+ claimsLink?: (link: Error) => boolean
515
+ ): boolean {
516
+ if (!(error instanceof Error)) {
517
+ return false;
518
+ }
519
+ const links = causeChain(error);
520
+ if (reportsPossiblyStoredWrite(links) || reportsIndeterminateCommit(links)) {
521
+ return false;
522
+ }
523
+ // NOTE: an unanswered read can fail AFTER this write's log entry is stored: the refresh between
524
+ // commit attempts reads the collection's log ends, and finishing the write's own entry
525
+ // (`Collection.completeOwnEntry`) asks `getStatus` when no attempt is retained at the entry's
526
+ // revision (a forked lineage — both commit paths retain the failed attempt before refreshing).
527
+ // Either throw escapes the refresh loop unwrapped. Claimed anyway, because the get/pend
528
+ // aggregate those same reads raise is already claimed beside it, so this adds no new case: the
529
+ // re-run is a new transaction whose body re-reads the blocks, so it diffs to nothing or fails on
530
+ // `UNIQUE` where the earlier write landed, and writes it once where it did not. A refresh that
531
+ // already saved a sibling collection arrives as `CoordinatorPartialCommitError`, which the veto
532
+ // above declines.
533
+ if (isUncommittedTransactorAggregate(links) || reportsUnreachableCohort(links)
534
+ || reportsUnansweredShortfall(links)
535
+ || links.some(link => isFinalTornWrite(link) || claimsLink?.(link) === true)) {
536
+ return true;
537
+ }
538
+ return chainMessages(error).some(message => matchers.some(matches => matches(message)));
539
+ }
540
+
541
+ /**
542
+ * Policy and pacing overrides for {@link retryControlWrite}. Production callers pass nothing
543
+ * (or a named policy such as {@link SCHEMA_INIT_RETRY_POLICY}); specs inject a recorded
544
+ * `sleep`, a shorter delay list, or a fake clock so no test ever waits out a real backoff.
545
+ *
546
+ * Every field defaults to the shipped control-write policy ({@link CONTROL_WRITE_ATTEMPTS},
547
+ * {@link CONTROL_WRITE_RETRY_DELAYS_MS}, {@link isRetriableControlWriteFailure}), so an
548
+ * omitted field is byte-identical to the behaviour before per-call-site policies existed.
549
+ * The field shapes and semantics live on the shared {@link ControlRetryOptions}.
550
+ */
551
+ export type ControlWriteRetryOptions = ControlRetryOptions;
552
+
553
+ /**
554
+ * The schema-init policy: `ControlDatabase.applyControlSchema`'s distributed DDL, which
555
+ * additionally absorbs optimystic's self-coordination grace refusal and gets more attempts over a
556
+ * longer backoff to do it (see {@link SCHEMA_INIT_ATTEMPTS} and
557
+ * {@link SCHEMA_INIT_RETRY_DELAYS_MS}). Still bounded by the shared
558
+ * {@link CONTROL_WRITE_RETRY_BUDGET_MS}.
559
+ *
560
+ * NOTE: exactly one call site opts in today, and the re-run safety this policy assumes is that
561
+ * site's, not a general property — `apply schema` is a diff, and a failed apply is unwound whole
562
+ * and verified against the pre-apply catalog (full argument at the `applyControlSchema` call site
563
+ * in `control-database.ts`). A second opt-in must re-derive that argument for its own write body
564
+ * first; if this policy ever grows a third consumer, rename it for what the callers share rather
565
+ * than widening it by default. {@link LOST_UPDATE_RETRY_POLICY} is a separate policy for a
566
+ * separate class, not a second consumer of this one.
567
+ */
568
+ export const SCHEMA_INIT_RETRY_POLICY: Readonly<ControlWriteRetryOptions> = {
569
+ attempts: SCHEMA_INIT_ATTEMPTS,
570
+ delaysMs: SCHEMA_INIT_RETRY_DELAYS_MS,
571
+ isRetriable: isRetriableSchemaInitFailure,
572
+ };
573
+
574
+ /**
575
+ * The lost-update policy: the default classifier plus a lost update claimed by type
576
+ * ({@link isRetriableLostUpdateFailure}), over the default attempts, backoff and budget. A re-run
577
+ * here is a RE-DECISION, not a re-presentation: the body reads the row again under the lock and
578
+ * signs over what it finds, so the write that lost to a rival is replaced by one made over the
579
+ * rival's result. The budget bounds it as it bounds every write — a losing attempt whose read
580
+ * phase waited out one per-peer read deadline (~7.5 s measured in the degraded-cohort scenario's
581
+ * trio boot) gets exactly one retry, which is the ceiling to expect; one that waited out two
582
+ * (14.7 s, measured once in 18 of that scenario's boots, on the member that cannot reach one
583
+ * sibling) gets none and is abandoned on the budget, and the lost publish is then the reconcile
584
+ * pass's or the heartbeat's to redo, as every abandoned self-publish is.
585
+ *
586
+ * NOTE: the re-run safety this policy assumes is each opted-in body's, not a general property. A
587
+ * body may opt in only when its read of the row, its decision and its signature ALL run inside
588
+ * the locked body, so that the re-run presents a write made over the row as it now stands rather
589
+ * than the first attempt's signed record (which the rival may have stamped past, or which may
590
+ * overwrite what the rival wrote). Three `CadrePeer` writers opt in, through
591
+ * `ControlDatabase.mutateCadrePeer`'s policy parameter or `lockedWithRetry` directly:
592
+ * `updateSelfPeerRecord` (re-reads and re-signs the node's own record), `reauthorizeCadrePeer`
593
+ * (re-reads the stamp and decides again whether the row is still the owner's to re-touch) and
594
+ * the two removals `deleteCadrePeer` / `removeMachine` (stamp read and signature already inside
595
+ * the body, and a self-publish never changes the stamp the `'remove'` digest binds). A new opt-in
596
+ * must re-derive that argument for its own body first.
597
+ */
598
+ export const LOST_UPDATE_RETRY_POLICY: Readonly<ControlWriteRetryOptions> = {
599
+ isRetriable: isRetriableLostUpdateFailure,
600
+ };
601
+
602
+ /**
603
+ * Run `attempt` up to {@link CONTROL_WRITE_ATTEMPTS} times (or `options.attempts`), retrying only
604
+ * failures the policy's classifier — {@link isRetriableControlWriteFailure} by default —
605
+ * calls transient, and only while {@link CONTROL_WRITE_RETRY_BUDGET_MS} has not elapsed.
606
+ *
607
+ * `attempt` must be atomic and re-runnable: a failed cluster write rolls back (nothing is
608
+ * half-applied), and re-running the body re-runs its reads too — `ControlDatabase`'s
609
+ * locked write bodies all satisfy this (see the contract on
610
+ * `ControlDatabase.withWriteLock`). The backoff sleeps happen with NO lock held; the caller
611
+ * takes and releases its lock inside `attempt`.
612
+ *
613
+ * On exhaustion (attempts or budget) the LAST error is rethrown unchanged — never wrapped,
614
+ * so the exact messages downstream code and the degraded-cohort-member scenario assert on
615
+ * survive. A non-retriable failure propagates from the attempt that raised it.
616
+ *
617
+ * Either way — declined or exhausted — an `options.onAbandon` observer is notified exactly
618
+ * once before the rethrow (a `ControlRetryAbandonment`). Only WRITES pass one: an abandoned
619
+ * read throws to a caller that is awaiting it, so nothing is lost silently there
620
+ * (`control-read-retry.ts` says so at its own seam), while an abandoned write may have no
621
+ * caller at all — a background self-record republish is `void`-ed with a `debug` catch, so
622
+ * its failure reaches nobody unless something is listening here.
623
+ * `ControlDatabase.setControlWriteAbandonedListener` is the only thing that passes one in
624
+ * production; `retryControlWrite` itself neither supplies nor requires an observer.
625
+ */
626
+ export function retryControlWrite<T>(
627
+ attempt: () => Promise<T>,
628
+ options: ControlWriteRetryOptions = {}
629
+ ): Promise<T> {
630
+ return retryControlOperation(attempt, {
631
+ attempts: CONTROL_WRITE_ATTEMPTS,
632
+ delaysMs: CONTROL_WRITE_RETRY_DELAYS_MS,
633
+ budgetMs: CONTROL_WRITE_RETRY_BUDGET_MS,
634
+ isRetriable: isRetriableControlWriteFailure,
635
+ // The default prefix, named anyway: the degraded-cohort scenario asserts on
636
+ // `Control write [<label>] …` lines byte-for-byte.
637
+ logPrefix: 'Control write',
638
+ }, options);
639
+ }