@serfab/cadre-core 0.13.0 → 1.1.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 (131) hide show
  1. package/README.md +20 -6
  2. package/dist/bootstrap-peer-store-file.js +2 -2
  3. package/dist/bootstrap-peer-store.d.ts +32 -12
  4. package/dist/bootstrap-peer-store.js +41 -15
  5. package/dist/bootstrap-peer-store.js.map +1 -1
  6. package/dist/cadre-node.d.ts +558 -80
  7. package/dist/cadre-node.js +1060 -170
  8. package/dist/cadre-node.js.map +1 -1
  9. package/dist/control-authorization.d.ts +2 -2
  10. package/dist/control-authorization.js +1 -0
  11. package/dist/control-authorization.js.map +1 -1
  12. package/dist/control-cohort.d.ts +13 -26
  13. package/dist/control-cohort.js +0 -26
  14. package/dist/control-cohort.js.map +1 -1
  15. package/dist/control-database.d.ts +299 -44
  16. package/dist/control-database.js +469 -69
  17. package/dist/control-database.js.map +1 -1
  18. package/dist/control-read-retry.d.ts +40 -11
  19. package/dist/control-read-retry.js +48 -15
  20. package/dist/control-read-retry.js.map +1 -1
  21. package/dist/control-retry.d.ts +58 -3
  22. package/dist/control-retry.js +58 -3
  23. package/dist/control-retry.js.map +1 -1
  24. package/dist/control-schema.d.ts +1 -1
  25. package/dist/control-schema.js +103 -19
  26. package/dist/control-schema.js.map +1 -1
  27. package/dist/control-write-retry.d.ts +80 -11
  28. package/dist/control-write-retry.js +176 -29
  29. package/dist/control-write-retry.js.map +1 -1
  30. package/dist/enrolled-machine-store.js +2 -2
  31. package/dist/index.d.ts +14 -7
  32. package/dist/index.js +33 -6
  33. package/dist/index.js.map +1 -1
  34. package/dist/node-local-snapshot.d.ts +15 -7
  35. package/dist/node-local-snapshot.js +23 -8
  36. package/dist/node-local-snapshot.js.map +1 -1
  37. package/dist/peer-dial.d.ts +143 -0
  38. package/dist/peer-dial.js +176 -0
  39. package/dist/peer-dial.js.map +1 -0
  40. package/dist/relay-addrs.d.ts +90 -52
  41. package/dist/relay-addrs.js +91 -59
  42. package/dist/relay-addrs.js.map +1 -1
  43. package/dist/relay-reservation.d.ts +71 -3
  44. package/dist/relay-reservation.js +116 -8
  45. package/dist/relay-reservation.js.map +1 -1
  46. package/dist/seed-bootstrap.d.ts +30 -1
  47. package/dist/seed-bootstrap.js +62 -17
  48. package/dist/seed-bootstrap.js.map +1 -1
  49. package/dist/storage-scope.d.ts +62 -0
  50. package/dist/storage-scope.js +75 -0
  51. package/dist/storage-scope.js.map +1 -0
  52. package/dist/strand-database.d.ts +34 -16
  53. package/dist/strand-database.js +38 -24
  54. package/dist/strand-database.js.map +1 -1
  55. package/dist/strand-first-sync-gate.d.ts +152 -0
  56. package/dist/strand-first-sync-gate.js +208 -0
  57. package/dist/strand-first-sync-gate.js.map +1 -0
  58. package/dist/strand-formation-manager.d.ts +87 -5
  59. package/dist/strand-formation-manager.js +109 -5
  60. package/dist/strand-formation-manager.js.map +1 -1
  61. package/dist/strand-formation-protocol.d.ts +21 -1
  62. package/dist/strand-formation-protocol.js +30 -0
  63. package/dist/strand-formation-protocol.js.map +1 -1
  64. package/dist/strand-instance-manager.d.ts +243 -6
  65. package/dist/strand-instance-manager.js +470 -37
  66. package/dist/strand-instance-manager.js.map +1 -1
  67. package/dist/strand-member-key.d.ts +20 -12
  68. package/dist/strand-member-key.js +20 -12
  69. package/dist/strand-member-key.js.map +1 -1
  70. package/dist/strand-member-registry.js +3 -0
  71. package/dist/strand-member-registry.js.map +1 -1
  72. package/dist/strand-membership-reconciler.d.ts +361 -0
  73. package/dist/strand-membership-reconciler.js +548 -0
  74. package/dist/strand-membership-reconciler.js.map +1 -0
  75. package/dist/strand-membership-writer.d.ts +131 -11
  76. package/dist/strand-membership-writer.js +396 -134
  77. package/dist/strand-membership-writer.js.map +1 -1
  78. package/dist/strand-network-config.d.ts +46 -14
  79. package/dist/strand-network-config.js +79 -23
  80. package/dist/strand-network-config.js.map +1 -1
  81. package/dist/strand-solicitation.d.ts +10 -1
  82. package/dist/strand-solicitation.js +5 -0
  83. package/dist/strand-solicitation.js.map +1 -1
  84. package/dist/strand-wake-protocol.d.ts +11 -7
  85. package/dist/strand-wake-protocol.js +20 -52
  86. package/dist/strand-wake-protocol.js.map +1 -1
  87. package/dist/strand-watcher.js +6 -0
  88. package/dist/strand-watcher.js.map +1 -1
  89. package/dist/timed-step.d.ts +12 -0
  90. package/dist/timed-step.js +28 -0
  91. package/dist/timed-step.js.map +1 -0
  92. package/dist/timeout-scheduler.d.ts +19 -0
  93. package/dist/timeout-scheduler.js +22 -0
  94. package/dist/timeout-scheduler.js.map +1 -0
  95. package/dist/types.d.ts +262 -30
  96. package/dist/types.js.map +1 -1
  97. package/package.json +8 -8
  98. package/src/bootstrap-peer-store-file.ts +2 -2
  99. package/src/bootstrap-peer-store.ts +69 -27
  100. package/src/cadre-node.ts +7301 -6353
  101. package/src/control-authorization.ts +2 -1
  102. package/src/control-cohort.ts +122 -130
  103. package/src/control-database.ts +537 -69
  104. package/src/control-read-retry.ts +202 -167
  105. package/src/control-retry.ts +297 -190
  106. package/src/control-schema.ts +103 -19
  107. package/src/control-write-retry.ts +533 -383
  108. package/src/enrolled-machine-store.ts +2 -2
  109. package/src/index.ts +83 -6
  110. package/src/node-local-snapshot.ts +25 -8
  111. package/src/peer-dial.ts +215 -0
  112. package/src/relay-addrs.ts +458 -436
  113. package/src/relay-reservation.ts +951 -828
  114. package/src/seed-bootstrap.ts +76 -18
  115. package/src/storage-scope.ts +78 -0
  116. package/src/strand-database.ts +50 -27
  117. package/src/strand-first-sync-gate.ts +258 -0
  118. package/src/strand-formation-manager.ts +140 -5
  119. package/src/strand-formation-protocol.ts +43 -1
  120. package/src/strand-instance-manager.ts +577 -37
  121. package/src/strand-member-key.ts +20 -12
  122. package/src/strand-member-registry.ts +3 -0
  123. package/src/strand-membership-reconciler.ts +680 -0
  124. package/src/strand-membership-writer.ts +527 -189
  125. package/src/strand-network-config.ts +102 -24
  126. package/src/strand-solicitation.ts +16 -1
  127. package/src/strand-wake-protocol.ts +21 -66
  128. package/src/strand-watcher.ts +6 -0
  129. package/src/timed-step.ts +28 -0
  130. package/src/timeout-scheduler.ts +28 -0
  131. package/src/types.ts +1789 -1554
@@ -1,167 +1,202 @@
1
- import { chainMessages, retryControlOperation } from './control-retry.js';
2
- import type { ControlRetryOptions } from './control-retry.js';
3
- import { isUncommittedTransactorAggregate } from './control-write-retry.js';
4
-
5
- /**
6
- * Bounded retry for TRANSIENT control-read failures — the classifier and policy behind
7
- * `ControlDatabase.readRows`, the single funnel every control read passes through.
8
- *
9
- * Why this exists: control WRITES have absorbed transient cluster failures since
10
- * `control-write-retry.ts` landed, but a read had no second chance — one stream reset
11
- * during a scan ended the read outright (measured: a rigged single `eval` failure killed
12
- * `queryRevokedStamps` after exactly one attempt while the same injection against `exec`
13
- * was absorbed). This module gives reads the same bounded re-presentation with a SHORTER
14
- * deadline and a NARROWER failure set, because the tightest caller deadline over a control
15
- * read is the inbound admission gate's 2 s fail-open timeout
16
- * (`ADMISSION_DECISION_TIMEOUT_MS`, `membership-connection-gater.ts`) — a read budget that
17
- * does not fit inside it with headroom spends its retries after the gate has already
18
- * admitted.
19
- *
20
- * This is deliberately NOT "the write classifier minus its commit veto" — the retriable
21
- * set differs in both directions (see {@link isRetriableControlReadFailure}). The loop
22
- * lives in `control-retry.ts`, shared with the write policy; this module owns only the
23
- * read policy. And like the write side, classification is by TEXT: optimystic's
24
- * `OptimysticVirtualTable` catches every scan-path error and rethrows
25
- * `new Error('Query failed: ' + message)` with NO `cause`
26
- * (`quereus-plugin-optimystic/src/optimystic-module.ts`), so the typed
27
- * `BlockUnavailableError` and its `reason` field are destroyed before they reach this
28
- * repo; Quereus then wraps that as `Error during query on table '<T>': …` preserving
29
- * `cause` (`quereus/src/runtime/emit/scan.ts`). Every matcher fails CLOSED — an upstream
30
- * rewording stops the retry engaging, it never makes it unsafe.
31
- */
32
-
33
- /**
34
- * Attempts allowed per control read: the first, plus two retries. Attempts are cheap here —
35
- * the observed transient failure (the transactor's read-phase aggregate off a stream still
36
- * forming) surfaces in ~25 ms — and {@link CONTROL_READ_RETRY_BUDGET_MS} is what terminates
37
- * the loop when an attempt is slow instead.
38
- */
39
- export const CONTROL_READ_ATTEMPTS = 3;
40
-
41
- /**
42
- * Backoff before read retry N, jittered ±50% and capped at the largest base by the shared
43
- * loop — so worst case 150 ms + 400 ms = 550 ms of total sleep (the second delay's
44
- * upside jitter is clipped by the cap). Much shorter than the write list because the
45
- * whole loop must fit under {@link CONTROL_READ_RETRY_BUDGET_MS}; the spec pins that
46
- * relationship rather than the number.
47
- */
48
- export const CONTROL_READ_RETRY_DELAYS_MS: readonly number[] = [100, 400];
49
-
50
- /**
51
- * Elapsed-time ceiling on the whole read-retry loop, checked after a failed attempt BEFORE
52
- * sleeping — so one slow attempt (e.g. a `cohort-unreachable` read that burned the
53
- * transactor's own deadline) terminates the loop rather than compounding.
54
- *
55
- * 1500 ms, sized against `ADMISSION_DECISION_TIMEOUT_MS` (2000 ms): the inbound admission
56
- * gate reads the control DB and is FAIL-OPEN on both throw and timeout, so a read that
57
- * outlives the gate's deadline spends its retries after the gate has already admitted an
58
- * unplaced peer. Under the deadline, a read that succeeds on its second attempt lets the
59
- * gate make the real decision instead. `control-read-retry.spec.ts` asserts the
60
- * relationship so a future edit to either constant reddens instead of silently
61
- * reintroducing the fail-open admit. NOTE: `queryCadrePeers` / `queryPeerRecord` each
62
- * issue TWO network reads (the revoked-stamp filter plus the row scan) and the budget is
63
- * per read, so a membership read can spend up to two budgets back to back — still inside
64
- * 2 s only because each stays well under it. Do not raise these numbers without
65
- * re-checking against `ADMISSION_DECISION_TIMEOUT_MS`.
66
- */
67
- export const CONTROL_READ_RETRY_BUDGET_MS = 1_500;
68
-
69
- /**
70
- * The block-unavailability reasons a repeat read can actually improve on, matched against
71
- * upstream's exact template `Block <id> is unavailable (<reason>): …`
72
- * (`BlockUnavailableError`, `db-core/src/network/struct.ts`):
73
- *
74
- * - **`peers-unreachable`** — part of the cohort answered and part could not be asked, and
75
- * OTHER coordinators are reachable, so asking one of them can still settle it. Upstream's
76
- * own definition invites the second attempt.
77
- * - **`cohort-unreachable`** — the marginal member of the set. Upstream says the answer
78
- * will not improve until this node's connectivity does — but during bring-up connectivity
79
- * DOES improve within a second (the boot-time failure shape recorded in
80
- * `tickets/blocked/control-read-over-fresh-edge-stream-resets`), and the cost of being
81
- * wrong is bounded by {@link CONTROL_READ_RETRY_BUDGET_MS}, which is the whole reason it
82
- * is safe to include.
83
- *
84
- * Deliberately NOT matched:
85
- *
86
- * - **`claimed-elsewhere`** — a cohort peer positively claims the block exists and nobody
87
- * could corroborate or acquire it. MEASURED not to clear: reissuing the same call every
88
- * second for 60 s returned the identical error every time (2026-08-20, recorded in the
89
- * fix ticket). Retrying spends the whole budget and fails anyway; the root cause is
90
- * upstream and tracked by `tickets/blocked/block-held-by-only-one-machine-is-unreadable`
91
- * — this retry must not paper over it.
92
- * - **`unmaterializable`** — records are held locally but cannot be reassembled. A local
93
- * data problem; a second read reads the same records.
94
- * - **`Block <id> may be stale`** (`BlockPossiblyStaleError`) — about currency, not
95
- * existence: a cohort claim no reachable coordinator could confirm or refute will not
96
- * resolve inside a few hundred milliseconds of backoff.
97
- * - Anything unmatched. The default is no retry.
98
- */
99
- const RETRIABLE_BLOCK_UNAVAILABLE =
100
- /Block \S+ is unavailable \((?:peers-unreachable|cohort-unreachable)\)/;
101
-
102
- /** A block-unavailable read failure whose reason a repeat read can improve on. */
103
- function isRetriableBlockUnavailable(message: string): boolean {
104
- return RETRIABLE_BLOCK_UNAVAILABLE.test(message);
105
- }
106
-
107
- /**
108
- * Pacing overrides for {@link retryControlRead} — the read twin of
109
- * `ControlWriteRetryOptions`. Every field defaults to the shipped read policy
110
- * ({@link CONTROL_READ_ATTEMPTS}, {@link CONTROL_READ_RETRY_DELAYS_MS},
111
- * {@link isRetriableControlReadFailure}); field shapes and semantics live on the shared
112
- * {@link ControlRetryOptions}.
113
- */
114
- export type ControlReadRetryOptions = ControlRetryOptions;
115
-
116
- /**
117
- * Did this control read fail in a way a repeat read can improve on?
118
- *
119
- * Two classes, both meaning "the cluster could not be ASKED properly just now":
120
- *
121
- * - the transactor's read-phase aggregate (`Some peers did not complete: …[block:…]`),
122
- * reused verbatim from the write classifier — a `get` batch formats the single-block
123
- * `[block:` token, and a read can never produce the commit-phase `[blocks:` token, so
124
- * the write side's indeterminate-commit veto has nothing to veto here (a read commits
125
- * nothing and re-running it is always safe);
126
- * - the block-unavailability reasons in {@link RETRIABLE_BLOCK_UNAVAILABLE} (and only
127
- * those — see its comment for the measured exclusions).
128
- *
129
- * Classifies by MESSAGE, walking the `cause` chain with the shared `chainMessages`,
130
- * because only text survives the trip out of optimystic (see the module comment).
131
- * Anything that is not an `Error` is never retried.
132
- */
133
- export function isRetriableControlReadFailure(error: unknown): boolean {
134
- if (!(error instanceof Error)) {
135
- return false;
136
- }
137
- return chainMessages(error).some(message =>
138
- isUncommittedTransactorAggregate(message) || isRetriableBlockUnavailable(message));
139
- }
140
-
141
- /**
142
- * Run `attempt` — a full drain of one control read — up to
143
- * {@link CONTROL_READ_ATTEMPTS} times, retrying only failures
144
- * {@link isRetriableControlReadFailure} calls transient, and only while
145
- * {@link CONTROL_READ_RETRY_BUDGET_MS} has not elapsed.
146
- *
147
- * Reads are idempotent, so `attempt` needs no atomicity contract — but it must be a
148
- * COLLECTING drain, not a live iterator: a half-consumed iterator cannot be retried
149
- * without re-yielding rows the caller already saw, which is why
150
- * `ControlDatabase.readRows` materializes before this loop ever sees a failure.
151
- *
152
- * On exhaustion the LAST error is rethrown unchanged. Log lines carry the
153
- * `Control read [<label>] …` prefix so a read's retries can be attributed among the
154
- * several reads in flight concurrently in a real party.
155
- */
156
- export function retryControlRead<T>(
157
- attempt: () => Promise<T>,
158
- options: ControlReadRetryOptions = {}
159
- ): Promise<T> {
160
- return retryControlOperation(attempt, {
161
- attempts: CONTROL_READ_ATTEMPTS,
162
- delaysMs: CONTROL_READ_RETRY_DELAYS_MS,
163
- budgetMs: CONTROL_READ_RETRY_BUDGET_MS,
164
- isRetriable: isRetriableControlReadFailure,
165
- logPrefix: 'Control read',
166
- }, options);
167
- }
1
+ import { BlockUnavailableError } from '@optimystic/db-core';
2
+ import { causeChain, chainMessages, retryControlOperation } from './control-retry.js';
3
+ import type { ControlRetryOptions } from './control-retry.js';
4
+ import { isUncommittedTransactorAggregate } from './control-write-retry.js';
5
+
6
+ /**
7
+ * Bounded retry for TRANSIENT control-read failures — the classifier and policy behind
8
+ * `ControlDatabase.readRows`, the single funnel every control read passes through.
9
+ *
10
+ * Why this exists: control WRITES have absorbed transient cluster failures since
11
+ * `control-write-retry.ts` landed, but a read had no second chance — one stream reset
12
+ * during a scan ended the read outright (measured: a rigged single `eval` failure killed
13
+ * `queryRevokedStamps` after exactly one attempt while the same injection against `exec`
14
+ * was absorbed). This module gives reads the same bounded re-presentation with a SHORTER
15
+ * deadline and a NARROWER failure set, because the tightest caller deadline over a control
16
+ * read is the inbound admission gate's 2 s fail-open timeout
17
+ * (`ADMISSION_DECISION_TIMEOUT_MS`, `membership-connection-gater.ts`) — a read budget that
18
+ * does not fit inside it with headroom spends its retries after the gate has already
19
+ * admitted.
20
+ *
21
+ * This is deliberately NOT "the write classifier minus its commit veto" — the retriable
22
+ * set differs in both directions (see {@link isRetriableControlReadFailure}). The loop
23
+ * lives in `control-retry.ts`, shared with the write policy; this module owns only the
24
+ * read policy. And like the write side, the retry classifies by TEXT. That was forced when
25
+ * it was written — optimystic's scan path used to rethrow `new Error('Query failed: ' +
26
+ * message)` with no `cause` — and is no longer: `OptimysticVirtualTable` now rethrows
27
+ * through `rewrapAsQueryError` (`quereus-plugin-optimystic/src/optimystic-module.ts`),
28
+ * which keeps the typed `BlockUnavailableError` on `cause`, and Quereus wraps that as
29
+ * `Error during query on table '<T>': …`, again preserving `cause`
30
+ * (`quereus/src/runtime/emit/scan.ts`). The text matchers still work because every wrap
31
+ * embeds the inner message. Every matcher fails CLOSED — an upstream rewording stops the
32
+ * retry engaging, it never makes it unsafe. {@link isCohortUnreachableRead}, which is not a
33
+ * retry classifier, matches by type.
34
+ */
35
+
36
+ /**
37
+ * Attempts allowed per control read: the first, plus two retries. Attempts are cheap here —
38
+ * the observed transient failure (the transactor's read-phase aggregate off a stream still
39
+ * forming) surfaces in ~25 ms — and {@link CONTROL_READ_RETRY_BUDGET_MS} is what terminates
40
+ * the loop when an attempt is slow instead.
41
+ */
42
+ export const CONTROL_READ_ATTEMPTS = 3;
43
+
44
+ /**
45
+ * Backoff before read retry N, jittered ±50% and capped at the largest base by the shared
46
+ * loop — so worst case 150 ms + 400 ms = 550 ms of total sleep (the second delay's
47
+ * upside jitter is clipped by the cap). Much shorter than the write list because the
48
+ * whole loop must fit under {@link CONTROL_READ_RETRY_BUDGET_MS}; the spec pins that
49
+ * relationship rather than the number.
50
+ */
51
+ export const CONTROL_READ_RETRY_DELAYS_MS: readonly number[] = [100, 400];
52
+
53
+ /**
54
+ * Elapsed-time ceiling on the whole read-retry loop, checked after a failed attempt BEFORE
55
+ * sleeping — so one slow attempt (e.g. a `cohort-unreachable` read that burned the
56
+ * transactor's own deadline) terminates the loop rather than compounding.
57
+ *
58
+ * 1500 ms, sized against `ADMISSION_DECISION_TIMEOUT_MS` (2000 ms): the inbound admission
59
+ * gate reads the control DB and is FAIL-OPEN on both throw and timeout, so a read that
60
+ * outlives the gate's deadline spends its retries after the gate has already admitted an
61
+ * unplaced peer. Under the deadline, a read that succeeds on its second attempt lets the
62
+ * gate make the real decision instead. `control-read-retry.spec.ts` asserts the
63
+ * relationship so a future edit to either constant reddens instead of silently
64
+ * reintroducing the fail-open admit. NOTE: `queryCadrePeers` / `queryPeerRecord` each
65
+ * issue TWO network reads (the revoked-stamp filter plus the row scan) and the budget is
66
+ * per read, so a membership read can spend up to two budgets back to back — still inside
67
+ * 2 s only because each stays well under it. Do not raise these numbers without
68
+ * re-checking against `ADMISSION_DECISION_TIMEOUT_MS`.
69
+ */
70
+ export const CONTROL_READ_RETRY_BUDGET_MS = 1_500;
71
+
72
+ /**
73
+ * The block-unavailability reasons a repeat read can actually improve on, matched against
74
+ * upstream's exact template `Block <id> is unavailable (<reason>): …`
75
+ * (`BlockUnavailableError`, `db-core/src/network/struct.ts`):
76
+ *
77
+ * - **`peers-unreachable`** — part of the cohort answered and part could not be asked, and
78
+ * OTHER coordinators are reachable, so asking one of them can still settle it. Upstream's
79
+ * own definition invites the second attempt.
80
+ * - **`cohort-unreachable`** — the marginal member of the set. Upstream says the answer
81
+ * will not improve until this node's connectivity does — but during bring-up connectivity
82
+ * DOES improve within a second (the boot-time failure shape recorded in
83
+ * `tickets/blocked/control-read-over-fresh-edge-stream-resets`), and the cost of being
84
+ * wrong is bounded by {@link CONTROL_READ_RETRY_BUDGET_MS}, which is the whole reason it
85
+ * is safe to include.
86
+ *
87
+ * Deliberately NOT matched:
88
+ *
89
+ * - **`claimed-elsewhere`** — a cohort peer positively claims the block exists and nobody
90
+ * could corroborate or acquire it. MEASURED not to clear: reissuing the same call every
91
+ * second for 60 s returned the identical error every time (2026-08-20, recorded in the
92
+ * fix ticket). Retrying spends the whole budget and fails anyway. The measured cause (a
93
+ * block only one machine held) was fixed upstream by the solo-commit proof in
94
+ * `@optimystic/db-p2p` 0.28.0 (`tickets/complete/block-held-by-only-one-machine-is-unreadable`),
95
+ * so a `claimed-elsewhere` that surfaces now is a new defect — this retry must not hide it.
96
+ * - **`unmaterializable`** — records are held locally but cannot be reassembled. A local
97
+ * data problem; a second read reads the same records.
98
+ * - **`Block <id> may be stale`** (`BlockPossiblyStaleError`) — about currency, not
99
+ * existence: a cohort claim no reachable coordinator could confirm or refute will not
100
+ * resolve inside a few hundred milliseconds of backoff.
101
+ * - Anything unmatched. The default is no retry.
102
+ */
103
+ const RETRIABLE_BLOCK_UNAVAILABLE =
104
+ /Block \S+ is unavailable \((?:peers-unreachable|cohort-unreachable)\)/;
105
+
106
+ /** A block-unavailable read failure whose reason a repeat read can improve on. */
107
+ function isRetriableBlockUnavailable(message: string): boolean {
108
+ return RETRIABLE_BLOCK_UNAVAILABLE.test(message);
109
+ }
110
+
111
+ /**
112
+ * Pacing overrides for {@link retryControlRead} — the read twin of
113
+ * `ControlWriteRetryOptions`. Every field defaults to the shipped read policy
114
+ * ({@link CONTROL_READ_ATTEMPTS}, {@link CONTROL_READ_RETRY_DELAYS_MS},
115
+ * {@link isRetriableControlReadFailure}); field shapes and semantics live on the shared
116
+ * {@link ControlRetryOptions}.
117
+ */
118
+ export type ControlReadRetryOptions = ControlRetryOptions;
119
+
120
+ /**
121
+ * Did this control read fail in a way a repeat read can improve on?
122
+ *
123
+ * Two classes, both meaning "the cluster could not be ASKED properly just now":
124
+ *
125
+ * - the transactor's read-phase aggregate (`Some peers did not complete: …[block:…]`),
126
+ * reused verbatim from the write classifier — a `get` batch formats the single-block
127
+ * `[block:` token, and a read can never produce the commit-phase `[blocks:` token, so
128
+ * the write side's indeterminate-commit veto has nothing to veto here (a read commits
129
+ * nothing and re-running it is always safe);
130
+ * - the block-unavailability reasons in {@link RETRIABLE_BLOCK_UNAVAILABLE} (and only
131
+ * those — see its comment for the measured exclusions).
132
+ *
133
+ * Classifies by MESSAGE, walking the `cause` chain with the shared `chainMessages` (why
134
+ * text, in the module comment). Anything that is not an `Error` is never retried.
135
+ */
136
+ export function isRetriableControlReadFailure(error: unknown): boolean {
137
+ if (!(error instanceof Error)) {
138
+ return false;
139
+ }
140
+ return chainMessages(error).some(message =>
141
+ isUncommittedTransactorAggregate(message) || isRetriableBlockUnavailable(message));
142
+ }
143
+
144
+ /**
145
+ * Did this control read fail because no cohort member other than the answering node could
146
+ * be asked about a block nobody here holds — a `BlockUnavailableError` with reason
147
+ * `cohort-unreachable` anywhere on the `cause` chain?
148
+ *
149
+ * Not a retry classifier. It answers "is there a better answer to wait for?", and is used
150
+ * by exactly one reader, `ControlDatabase.queryRevokedStamps`, to read an isolated node's
151
+ * never-received `Revocation` block as "no revocations known" (the reasoning is in the NOTE
152
+ * there). Upstream names this the one reason a caller may treat permissively
153
+ * (`db-core/src/transactor/network-transactor.ts`). The other reasons do NOT match:
154
+ * `peers-unreachable` means part of the cohort answered, and `claimed-elsewhere` /
155
+ * `unmaterializable` mean the block is known to exist, so an empty answer could hide a
156
+ * real revocation.
157
+ *
158
+ * Matched by TYPE, since the typed error survives upstream's rewraps (module comment).
159
+ * Fails CLOSED: a non-`Error`, a text-only copy of the message, and an error built by a
160
+ * second loaded copy of `@optimystic/db-core` (which `instanceof` cannot recognise) all
161
+ * answer false, and the reader throws as it did before this existed.
162
+ */
163
+ export function isCohortUnreachableRead(error: unknown): boolean {
164
+ return causeChain(error).some(link =>
165
+ link instanceof BlockUnavailableError && link.reason === 'cohort-unreachable');
166
+ }
167
+
168
+ /**
169
+ * Run `attempt` — a full drain of one control read — up to
170
+ * {@link CONTROL_READ_ATTEMPTS} times, retrying only failures
171
+ * {@link isRetriableControlReadFailure} calls transient, and only while
172
+ * {@link CONTROL_READ_RETRY_BUDGET_MS} has not elapsed.
173
+ *
174
+ * Reads are idempotent, so `attempt` needs no atomicity contract — but it must be a
175
+ * COLLECTING drain, not a live iterator: a half-consumed iterator cannot be retried
176
+ * without re-yielding rows the caller already saw, which is why
177
+ * `ControlDatabase.readRows` materializes before this loop ever sees a failure.
178
+ *
179
+ * On exhaustion the LAST error is rethrown unchanged. Log lines carry the
180
+ * `Control read [<label>] …` prefix so a read's retries can be attributed among the
181
+ * several reads in flight concurrently in a real party.
182
+ *
183
+ * No reader passes an `onAbandon` observer, deliberately, though the shared options type
184
+ * offers one ({@link ControlRetryOptions.onAbandon}) and the loop would honour it. That hook
185
+ * exists because an abandoned WRITE can have no caller at all — the background self-record
186
+ * republish is `void`-ed with a `debug`-only catch, so giving up on it is invisible. Every
187
+ * control read is awaited by the caller that issued it, so an abandoned read surfaces as that
188
+ * caller's rejection; there is nothing here to lose silently. A fire-and-forget read would be
189
+ * the reason to start passing one.
190
+ */
191
+ export function retryControlRead<T>(
192
+ attempt: () => Promise<T>,
193
+ options: ControlReadRetryOptions = {}
194
+ ): Promise<T> {
195
+ return retryControlOperation(attempt, {
196
+ attempts: CONTROL_READ_ATTEMPTS,
197
+ delaysMs: CONTROL_READ_RETRY_DELAYS_MS,
198
+ budgetMs: CONTROL_READ_RETRY_BUDGET_MS,
199
+ isRetriable: isRetriableControlReadFailure,
200
+ logPrefix: 'Control read',
201
+ }, options);
202
+ }