@optimystic/db-core 1.4.0 → 1.5.1

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 (157) hide show
  1. package/README.md +336 -336
  2. package/dist/src/collection/collection.d.ts +44 -4
  3. package/dist/src/collection/collection.d.ts.map +1 -1
  4. package/dist/src/collection/collection.js +95 -14
  5. package/dist/src/collection/collection.js.map +1 -1
  6. package/dist/src/collections/tree/struct.d.ts +9 -4
  7. package/dist/src/collections/tree/struct.d.ts.map +1 -1
  8. package/dist/src/collections/tree/struct.js +9 -4
  9. package/dist/src/collections/tree/struct.js.map +1 -1
  10. package/dist/src/log/log.d.ts +41 -8
  11. package/dist/src/log/log.d.ts.map +1 -1
  12. package/dist/src/log/log.js +15 -10
  13. package/dist/src/log/log.js.map +1 -1
  14. package/dist/src/testing/test-transactor.d.ts +36 -0
  15. package/dist/src/testing/test-transactor.d.ts.map +1 -1
  16. package/dist/src/testing/test-transactor.js +49 -0
  17. package/dist/src/testing/test-transactor.js.map +1 -1
  18. package/dist/src/transaction/coordinator.d.ts.map +1 -1
  19. package/dist/src/transaction/coordinator.js +26 -9
  20. package/dist/src/transaction/coordinator.js.map +1 -1
  21. package/package.json +1 -1
  22. package/src/blocks/block-store.ts +31 -31
  23. package/src/blocks/block-types.ts +11 -11
  24. package/src/blocks/index.ts +5 -5
  25. package/src/blocks/structs.ts +17 -17
  26. package/src/btree/btree.ts +872 -872
  27. package/src/btree/independent-trunk.ts +53 -53
  28. package/src/btree/index.ts +5 -5
  29. package/src/btree/key-range.ts +15 -15
  30. package/src/btree/keyset.ts +6 -6
  31. package/src/btree/nodes.ts +25 -25
  32. package/src/btree/path.ts +37 -37
  33. package/src/btree/tree-block.ts +11 -11
  34. package/src/btree/trunk.ts +14 -14
  35. package/src/chain/chain-nodes.ts +26 -26
  36. package/src/chain/chain.ts +349 -349
  37. package/src/chain/index.ts +3 -3
  38. package/src/cluster/i-cluster.ts +6 -6
  39. package/src/cluster/index.ts +3 -3
  40. package/src/cohort-topic/addressing.ts +120 -120
  41. package/src/cohort-topic/antidos/bootstrap-evidence.ts +106 -106
  42. package/src/cohort-topic/antidos/index.ts +5 -5
  43. package/src/cohort-topic/antidos/rate-limiter.ts +210 -210
  44. package/src/cohort-topic/antidos/replay-guard.ts +146 -146
  45. package/src/cohort-topic/antidos/topic-budget.ts +160 -160
  46. package/src/cohort-topic/antiflood/index.ts +2 -2
  47. package/src/cohort-topic/antiflood/invariants.ts +108 -108
  48. package/src/cohort-topic/antiflood/jitter.ts +117 -117
  49. package/src/cohort-topic/coldstart.ts +237 -237
  50. package/src/cohort-topic/dmax.ts +88 -88
  51. package/src/cohort-topic/gossip/bus.ts +254 -254
  52. package/src/cohort-topic/gossip/index.ts +3 -3
  53. package/src/cohort-topic/gossip/records.ts +45 -45
  54. package/src/cohort-topic/gossip/view.ts +91 -91
  55. package/src/cohort-topic/index.ts +20 -20
  56. package/src/cohort-topic/load/barometer.ts +134 -134
  57. package/src/cohort-topic/load/index.ts +1 -1
  58. package/src/cohort-topic/member-engine.ts +430 -430
  59. package/src/cohort-topic/membership/index.ts +3 -3
  60. package/src/cohort-topic/membership/publisher.ts +163 -163
  61. package/src/cohort-topic/membership/source.ts +41 -41
  62. package/src/cohort-topic/ports.ts +157 -157
  63. package/src/cohort-topic/promotion.ts +477 -477
  64. package/src/cohort-topic/registration/bytes.ts +37 -37
  65. package/src/cohort-topic/registration/handoff.ts +154 -154
  66. package/src/cohort-topic/registration/index.ts +6 -6
  67. package/src/cohort-topic/registration/renewal.ts +495 -495
  68. package/src/cohort-topic/registration/sharding.ts +61 -61
  69. package/src/cohort-topic/registration/store.ts +81 -81
  70. package/src/cohort-topic/registration/types.ts +91 -91
  71. package/src/cohort-topic/ring-hash.ts +50 -50
  72. package/src/cohort-topic/service.ts +416 -416
  73. package/src/cohort-topic/sig/index.ts +2 -2
  74. package/src/cohort-topic/sig/payloads.ts +59 -59
  75. package/src/cohort-topic/sig/threshold.ts +64 -64
  76. package/src/cohort-topic/tiers.ts +74 -74
  77. package/src/cohort-topic/traffic.ts +233 -233
  78. package/src/cohort-topic/walk.ts +326 -326
  79. package/src/cohort-topic/willingness.ts +237 -237
  80. package/src/cohort-topic/wire/index.ts +18 -18
  81. package/src/cohort-topic/wire/payloads.ts +126 -126
  82. package/src/collection/action.ts +48 -48
  83. package/src/collection/collection-type-registry.ts +37 -37
  84. package/src/collection/collection.ts +2203 -2118
  85. package/src/collection/index.ts +4 -4
  86. package/src/collections/diary/index.ts +2 -2
  87. package/src/collections/diary/struct.ts +3 -3
  88. package/src/collections/index.ts +2 -2
  89. package/src/collections/tree/collection-trunk.ts +25 -25
  90. package/src/collections/tree/index.ts +2 -2
  91. package/src/collections/tree/readme.md +55 -55
  92. package/src/collections/tree/struct.ts +9 -4
  93. package/src/log/index.ts +2 -2
  94. package/src/log/log.ts +304 -268
  95. package/src/log/struct.ts +165 -165
  96. package/src/matchmaking/capability-filter.ts +45 -45
  97. package/src/matchmaking/config.ts +98 -98
  98. package/src/matchmaking/index.ts +21 -21
  99. package/src/matchmaking/multi-cohort-seeker.ts +234 -234
  100. package/src/matchmaking/provider.ts +123 -123
  101. package/src/matchmaking/query-eval.ts +105 -105
  102. package/src/matchmaking/seeker-walk.ts +127 -127
  103. package/src/matchmaking/seeker.ts +86 -86
  104. package/src/matchmaking/topic-anchor.ts +90 -90
  105. package/src/matchmaking/voting-quorum.ts +394 -394
  106. package/src/network/i-peer-network.ts +25 -25
  107. package/src/network/repo-protocol.ts +13 -13
  108. package/src/network/types.ts +37 -37
  109. package/src/reactivity/backfill.ts +220 -220
  110. package/src/reactivity/backpressure.ts +191 -191
  111. package/src/reactivity/checkpoint.ts +308 -308
  112. package/src/reactivity/config.ts +172 -172
  113. package/src/reactivity/dedupe.ts +132 -132
  114. package/src/reactivity/forwarder.ts +87 -87
  115. package/src/reactivity/index.ts +34 -34
  116. package/src/reactivity/notification.ts +123 -123
  117. package/src/reactivity/policy.ts +79 -79
  118. package/src/reactivity/push-state.ts +310 -310
  119. package/src/reactivity/recover.ts +153 -153
  120. package/src/reactivity/replay-buffer.ts +141 -141
  121. package/src/reactivity/resume.ts +549 -549
  122. package/src/reactivity/rotation.ts +415 -415
  123. package/src/reactivity/subscriber.ts +132 -132
  124. package/src/reactivity/subscription.ts +66 -66
  125. package/src/reactivity/topic-anchor.ts +71 -71
  126. package/src/reactivity/verify.ts +73 -73
  127. package/src/reactivity/wire-validate.ts +13 -13
  128. package/src/testing/async-wait.ts +65 -65
  129. package/src/testing/index.ts +2 -2
  130. package/src/testing/test-transactor.ts +62 -0
  131. package/src/transaction/actions-engine.ts +68 -68
  132. package/src/transaction/coordinator.ts +28 -11
  133. package/src/transaction/index.ts +52 -52
  134. package/src/transaction/operations-hash.ts +196 -196
  135. package/src/transaction/read-dependency-collector.ts +78 -78
  136. package/src/transaction/session.ts +238 -238
  137. package/src/transaction/transaction.ts +442 -442
  138. package/src/transaction/validator.ts +197 -197
  139. package/src/transactor/block-floors.ts +126 -126
  140. package/src/transactor/index.ts +6 -6
  141. package/src/transactor/network-transactor.ts +1545 -1545
  142. package/src/transform/atomic-proxy.ts +92 -92
  143. package/src/transform/cache-source.ts +370 -370
  144. package/src/transform/helpers.ts +164 -164
  145. package/src/transform/index.ts +7 -7
  146. package/src/transform/struct.ts +21 -21
  147. package/src/utility/actor.ts +62 -62
  148. package/src/utility/backoff.ts +95 -95
  149. package/src/utility/batch-coordinator.ts +191 -191
  150. package/src/utility/ensured.ts +32 -32
  151. package/src/utility/groupby.ts +18 -18
  152. package/src/utility/hash-string.ts +14 -14
  153. package/src/utility/is-record-empty.ts +5 -5
  154. package/src/utility/latches.ts +42 -42
  155. package/src/utility/lru-map.ts +60 -60
  156. package/src/utility/nameof.ts +7 -7
  157. package/src/utility/pending.ts +43 -43
@@ -1,1545 +1,1545 @@
1
- import { peerIdFromString } from "../network/types.js";
2
- import type { PeerId } from "../network/types.js";
3
- import { highestStaleAt, isConflictFailure } from "../network/stale-failure.js";
4
- import { BlockUnavailableError, BlockPossiblyStaleError } from "../network/struct.js";
5
- import { mergeDurability, withTornBlocks } from "../network/durability.js";
6
- import { judgeCohortLineage, type CohortLineage, type MemberLineage } from "../network/lineage.js";
7
- import type { ActionTransforms, ActionBlocks, ActionLineage, BlockActionStatus, ITransactor, PendSuccess, CommitSuccess, StaleFailure, IKeyNetwork, BlockId, GetBlockResults, PendResult, CommitResult, PendRequest, IRepo, BlockGets, Transforms, CommitRequest, ActionId, RepoCommitRequest, ClusterNomineesResult, CollectionId, IBlock, GetBlockResult, CoordinatorIntent, BlockUnavailableReason, BlockContentDigests, BlockBaseRevs, WriteDurability } from "../index.js";
8
- import type { IBlockChangeNotifier, CollectionChangeListener } from "./change-notifier.js";
9
- import { transformForBlockId, concatTransforms, concatTransform, transformsFromTransform, blockIdsForTransforms } from "../transform/helpers.js";
10
- import { Tracker } from "../transform/tracker.js";
11
- import { blockDigestsField, baseRevsField } from "../transform/digest.js";
12
- import { CacheSource } from "../transform/cache-source.js";
13
- import { TransactorSource, servedRevision } from "./transactor-source.js";
14
- import { Log } from "../log/log.js";
15
- import { groupBy } from "../utility/groupby.js";
16
- import { routingKeyForBlock } from "../network/routing-key.js";
17
- import { isRecordEmpty } from "../utility/is-record-empty.js";
18
- import { type CoordinatorBatch, makeBatchesByPeer, incompleteBatches, everyBatch, allBatches, mergeBlocks, processBatches, createBatchesForPayload } from "../utility/batch-coordinator.js";
19
- import { abortableDelay, jitteredBackoffMs } from "../utility/backoff.js";
20
- import { createLogger, verbose } from "../logger.js";
21
-
22
- const log = createLogger('network-transactor');
23
-
24
- type NetworkTransactorInit = {
25
- timeoutMs: number;
26
- abortOrCancelTimeoutMs: number;
27
- keyNetwork: IKeyNetwork;
28
- getRepo: (peerId: PeerId) => IRepo;
29
- /**
30
- * Per-peer dial deadline in ms applied to each downstream repo call.
31
- * `timeoutMs` is the overall transaction budget; `dialTimeoutMs` caps how
32
- * long a single peer can hold that budget hostage during its dial. When a
33
- * peer is unreachable, the dial fails fast and the batch-retry loop can
34
- * re-pick a different coordinator within the remaining overall budget.
35
- * Omit to fall back to a sensible default (3s); set 0 / negative to disable.
36
- */
37
- dialTimeoutMs?: number;
38
- /**
39
- * Optional local change-notifier (e.g. the hosting node's StorageRepo) used to
40
- * satisfy {@link IBlockChangeNotifier}. When supplied, `onCollectionChange`
41
- * delegates to it so consumers can feature-detect change notifications on the
42
- * transactor they already hold rather than reaching into node internals. When
43
- * absent, `onCollectionChange` is a logged no-op.
44
- */
45
- localChangeNotifier?: IBlockChangeNotifier;
46
- /**
47
- * The peer id of the node this transactor runs on, when `getRepo` hands that id the node's own
48
- * co-located repo rather than a network client — the same "co-located node" idea as
49
- * `localChangeNotifier`. It only breaks ties when a pend's blocks are grouped onto coordinators:
50
- * among cohort members covering equally many blocks, this node wins, so a write it is responsible
51
- * for is coordinated without a network hop. It never wins over a member covering more blocks
52
- * (fewer batches come first), and it never makes this node a coordinator for a block whose cohort
53
- * does not include it. Omit when nothing is co-located; ties then go to the member seen first,
54
- * which is the nearest.
55
- */
56
- localPeerId?: PeerId;
57
- }
58
-
59
- /**
60
- * Default per-peer dial deadline. Chosen as a compromise between:
61
- * - long enough for a typical libp2p dial+TLS handshake on a wired LAN
62
- * (sub-second) plus reasonable WAN latency, including circuit-relay hops;
63
- * - short enough that an unreachable cluster member burns ~1/10th of a
64
- * typical 30s transaction budget before the retry loop moves on.
65
- */
66
- const DEFAULT_DIAL_TIMEOUT_MS = 3000;
67
-
68
- export class NetworkTransactor implements ITransactor, IBlockChangeNotifier {
69
- private readonly keyNetwork: IKeyNetwork;
70
- private readonly timeoutMs: number;
71
- private readonly abortOrCancelTimeoutMs: number;
72
- private readonly dialTimeoutMs: number | undefined;
73
- private readonly getRepo: (peerId: PeerId) => IRepo;
74
- private readonly localChangeNotifier: IBlockChangeNotifier | undefined;
75
- /** `NetworkTransactorInit.localPeerId` as a string, the form cohort peer ids arrive in. */
76
- private readonly localPeerId: string | undefined;
77
-
78
- /**
79
- * Per-transaction coordinator cache: `actionId → (blockId → resolved coordinator)`.
80
- * {@link pend} populates it from its final (retry-adjusted) batch assignment; commit
81
- * reads it via {@link resolveCoordinator} before falling back to a live
82
- * `findCoordinator`, so a block's coordinator is resolved once per transaction across
83
- * the pend→commit window instead of once at pend and again at commit.
84
- *
85
- * Keyed by `actionId`, which is unique per transaction, so an entry is only ever read
86
- * by commits of the SAME transaction — the ones that immediately follow its pend. Once
87
- * those finish, nothing reads the entry again (a later transaction has a fresh
88
- * actionId), so it carries no cross-transaction staleness even if it lingers. The TTL
89
- * and size cap in {@link txnCoordinatorsFor} are therefore only a memory backstop that
90
- * reclaims entries from transactions that pend but never commit — NOT a staleness
91
- * bound. This is why keying by actionId gives the same "thrown away when the
92
- * transaction ends" safety as threading a Map through the call, without touching the
93
- * ITransactor contract.
94
- */
95
- private readonly txnCoordinatorCache = new Map<ActionId, { coordinators: Map<BlockId, PeerId>; expires: number }>();
96
- private static readonly MAX_TXN_COORDINATOR_CACHE_ENTRIES = 1000;
97
-
98
- constructor(
99
- init: NetworkTransactorInit,
100
- ) {
101
- this.keyNetwork = init.keyNetwork;
102
- this.timeoutMs = init.timeoutMs;
103
- this.abortOrCancelTimeoutMs = init.abortOrCancelTimeoutMs;
104
- // A user explicitly passing 0 or negative means "do not bound dials separately".
105
- // Undefined falls back to the library default.
106
- this.dialTimeoutMs = init.dialTimeoutMs === undefined
107
- ? DEFAULT_DIAL_TIMEOUT_MS
108
- : (init.dialTimeoutMs > 0 ? init.dialTimeoutMs : undefined);
109
- this.getRepo = init.getRepo;
110
- this.localChangeNotifier = init.localChangeNotifier;
111
- this.localPeerId = init.localPeerId?.toString();
112
- }
113
-
114
- /**
115
- * Subscribe to commits landing on the local node for `collectionId`, delegating
116
- * to the `localChangeNotifier` supplied at construction. When no notifier was
117
- * supplied this is a no-op (returns an inert unsubscribe) — a NetworkTransactor
118
- * with no co-located storage cannot observe commits locally.
119
- */
120
- onCollectionChange(collectionId: CollectionId, listener: CollectionChangeListener): () => void {
121
- if (!this.localChangeNotifier) {
122
- log('onCollectionChange: no localChangeNotifier configured; subscription is a no-op for collection=%s', collectionId);
123
- return () => { };
124
- }
125
- return this.localChangeNotifier.onCollectionChange(collectionId, listener);
126
- }
127
-
128
- async get(blockGets: BlockGets): Promise<GetBlockResults> {
129
- // Group by block id
130
- const distinctBlockIds = Array.from(new Set(blockGets.blockIds));
131
- const t0 = Date.now();
132
- log('get blockIds=%d', distinctBlockIds.length);
133
-
134
- // `intent: 'read'` throughout this method: a read that can find no reachable
135
- // coordinator may still be answered from the local replica (degraded but reported),
136
- // where a write on the same evidence may not. See CoordinatorIntent.
137
- const batches = await this.batchesForPayload<BlockId[], GetBlockResults>(
138
- distinctBlockIds,
139
- distinctBlockIds,
140
- (gets, blockId, mergeWithGets) => [...(mergeWithGets ?? []), ...gets.filter(bid => bid === blockId)],
141
- [],
142
- undefined,
143
- 'read'
144
- );
145
-
146
- const expiration = Date.now() + this.timeoutMs;
147
-
148
- let error: Error | undefined;
149
- try {
150
- await processBatches(
151
- batches,
152
- (batch) => this.getRepo(batch.peerId).get({ blockIds: batch.payload, context: blockGets.context }, { expiration, dialTimeoutMs: this.dialTimeoutMs }),
153
- batch => batch.payload,
154
- (gets, blockId, mergeWithGets) => [...(mergeWithGets ?? []), ...gets.filter(bid => bid === blockId)],
155
- expiration,
156
- (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), { ...options, intent: 'read' })
157
- );
158
- } catch (e) {
159
- error = e as Error;
160
- }
161
-
162
- // Second-chance retry: ONLY for a genuine no-response — a batch with no valid
163
- // response, a response missing an entry for a requested block id, or an entry
164
- // flagged `unavailable`. An authoritative "absent" answer (a valid response that
165
- // carries an entry for every requested block id, even one whose entry has only
166
- // `state` and no materialized `block`) is FINAL and must not retry. A block that
167
- // genuinely does not exist yet surfaces as `{ state: {} }` (an entry that is
168
- // present and unflagged) — retrying it doubles the round-trips on the common
169
- // createOrOpen "does this block exist?" probe. Cross-member reconciliation for a
170
- // missing block has already happened one layer down: CoordinatorRepo.get detects
171
- // `isMissing` and consults cluster peers on every such read before it responds —
172
- // and when that consult FAILS, the entry now says so via `unavailable` instead of
173
- // posing as an authoritative absent. So by the time an unflagged absent reaches
174
- // here there is nothing left for a transactor-level retry to discover, while a
175
- // flagged entry earns the retry against a different peer that an absent
176
- // deliberately does not. (The coordinator never remembers an absence across reads:
177
- // one that did served a just-committed block as never created — GitHub issue #20.)
178
- // See tickets txn-perf-authoritative-notfound and repo-reports-unavailable-vs-absent.
179
- const hasValidResponse = (b: CoordinatorBatch<BlockId[], GetBlockResults>) => {
180
- return b.request?.isResponse === true && b.request.response != null;
181
- };
182
-
183
- // Content the CALLER can prove is too old, from the floor it carried on the request
184
- // (see {@link BlockGets.floors}): the caller walked a log entry saying this block changed at
185
- // that revision, so anything below it is not the view the read asked for, however current
186
- // the answering repo honestly believes its copy to be. Only a block-carrying entry can be
187
- // below a floor — an absent answer is judged by its own rules above, and treating one as
188
- // below-floor would put the one-round `createOrOpen` probe back on the retry path.
189
- // Reported here rather than left to the reader: `TransactorSource` reports
190
- // `collection:block-below-floor` from the MERGED answer, so a read the retry below repaired
191
- // is the one case that leaves no trace anywhere else — the extra round would show up in a
192
- // field log as an unexplained second consult. Costs nothing on an unfloored read, which
193
- // leaves on the first clause.
194
- const belowFloor = (bid: BlockId, entry: GetBlockResult): boolean => {
195
- const floor = blockGets.floors?.[bid];
196
- if (floor === undefined || entry.block == null || servedRevision(entry) >= floor) return false;
197
- log('get:below-floor blockId=%s served=%d floor=%d', bid, servedRevision(entry), floor);
198
- return true;
199
- };
200
-
201
- // A batch is answered when its response carries an entry for EVERY requested
202
- // block id and none of those entries carries a doubt marker or falls below the
203
- // caller's floor. An entry present with only `state` (no `block`) is an
204
- // authoritative "absent", which counts as answered — not a gap. An `unavailable`
205
- // entry is the peer saying it could not find out whether the block EXISTS; an
206
- // `unconfirmedAheadRev` entry is the peer saying it could not confirm the content
207
- // it served is CURRENT (a cohort claim sits ahead of it, unsettled); a below-floor
208
- // entry is the CALLER knowing the content is behind a revision it has already seen
209
- // the log commit. None counts as answered, so each earns the second-chance retry
210
- // against a different coordinator.
211
- const isAuthoritative = (b: CoordinatorBatch<BlockId[], GetBlockResults>) => {
212
- if (!hasValidResponse(b)) return false;
213
- const resp = b.request!.response! as GetBlockResults;
214
- return b.payload.every(bid => resp[bid] !== undefined
215
- && resp[bid]!.unavailable === undefined
216
- && resp[bid]!.unconfirmedAheadRev === undefined
217
- && !belowFloor(bid, resp[bid]!));
218
- };
219
-
220
- // Retry only genuine no-response / partial-response batches. An authoritative
221
- // absent answer is not retried.
222
- // NOTE: a 'cohort-unreachable' entry earns this retry like any other flagged entry,
223
- // and on a genuinely isolated node the retry re-picks the same node (the
224
- // findCoordinator:all-excluded path) and repeats the same futile consult. Fine
225
- // today — one extra bounded consult on an already failing read. If isolated-node
226
- // read latency ever matters, skip the retry for that reason rather than widening
227
- // isAuthoritative.
228
- // This is ONE extra round, not a loop: a below-floor answer that every reachable
229
- // coordinator repeats survives the merge below as the highest revision anyone
230
- // served, UNFLAGGED. Deliberate — a log entry is not proof its blocks landed, so a
231
- // floor no machine can meet may simply describe an abandoned write, in which case
232
- // the below-floor content is the correct content and every machine agrees on it
233
- // (see the accepted-tradeoff NOTE at `TransactorSource.mayRetain`). The reader
234
- // judges it again and returns it uncached.
235
- const retryable = Array.from(allBatches(batches)).filter(b =>
236
- !isAuthoritative(b as any)
237
- ) as CoordinatorBatch<BlockId[], GetBlockResults>[];
238
-
239
- if (retryable.length > 0 && Date.now() < expiration) {
240
- log('get:retry retryable=%d', retryable.length);
241
- // Fan out the per-batch retries concurrently. Each root batch builds its own
242
- // excluded-peer set and attaches its own `subsumedBy`, so the retry rounds are
243
- // independent per root and safe to run in parallel.
244
- const retryOutcomes = await Promise.allSettled(retryable.map(async b => {
245
- const excluded = new Set<PeerId>([b.peerId, ...((b.excludedPeers ?? []) as PeerId[])]);
246
- const retries = await createBatchesForPayload<BlockId[], GetBlockResults>(
247
- b.payload,
248
- b.payload,
249
- (gets, blockId, mergeWithGets) => [...(mergeWithGets ?? []), ...gets.filter(id => id === blockId)],
250
- Array.from(excluded),
251
- (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), { ...options, intent: 'read' })
252
- );
253
- if (retries.length > 0) {
254
- b.subsumedBy = [...(b.subsumedBy ?? []), ...retries];
255
- await processBatches(
256
- retries,
257
- (batch) => this.getRepo(batch.peerId).get({ blockIds: batch.payload, context: blockGets.context }, { expiration, dialTimeoutMs: this.dialTimeoutMs }),
258
- batch => batch.payload,
259
- (gets, blockId, mergeWithGets) => [...(mergeWithGets ?? []), ...gets.filter(id => id === blockId)],
260
- expiration,
261
- (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), { ...options, intent: 'read' })
262
- );
263
- }
264
- }));
265
- // First-error-wins: keep any pre-existing error, otherwise adopt the first
266
- // rejection across the concurrent retries (retryable order is preserved).
267
- for (const outcome of retryOutcomes) {
268
- if (outcome.status === 'rejected' && !error) {
269
- error = outcome.reason instanceof Error ? outcome.reason : new Error(String(outcome.reason));
270
- }
271
- }
272
- }
273
-
274
-
275
- // Cache the completed batches that had actual responses (not just coordinator not found)
276
- const completedBatches = Array.from(allBatches(batches, b => b.request?.isResponse as boolean && !isRecordEmpty(b.request!.response!)));
277
-
278
- // Ranking per block id: a block the answering repo could confirm is current beats
279
- // one it marked possibly-behind (`unconfirmedAheadRev`), which beats an
280
- // authoritative absent, which beats an absent marked possibly-behind (a doubted
281
- // tombstone), which beats an `unavailable` guess. Content still beats absence at
282
- // every confidence level, and one peer that positively knows outranks another
283
- // that could not find out. Without the confirmed-over-unconfirmed split, a stale
284
- // flagged block and the fresh confirmed block fetched by its own retry round tie
285
- // — and only strictly-greater rank replaces, so first-arrival (the stale one)
286
- // would win the very merge the retry exists to fix. Non-object junk ranks below
287
- // everything so any real entry replaces it.
288
- // Rank alone does not order two peers that both served content: a confirmed block ranks 6
289
- // whatever revision it is. Cohort peers were expected to agree — they share the block's
290
- // revision log, so they agree on the highest committed revision at or below a pin — but a
291
- // peer inside its read-repair window answers from its own copy without consulting anyone,
292
- // and two cohort members answered one pinned read at revisions 6 and 7. Since only a
293
- // strictly greater rank replaces, first arrival (the stale one) would win the very merge a
294
- // below-floor retry exists to fix. So equally-ranked entries that BOTH carry a block break
295
- // the tie on the newer content, measured by `servedRevision` — the same number the floor is
296
- // judged against and the same number the reader records as its read dependency, so the
297
- // merge cannot prefer one revision while the reader believes it read another. The tie-break
298
- // is deliberately inside a rank rather than across ranks: a confirmed older block still
299
- // beats an unconfirmed newer one, because "the peer could not confirm this is current" is
300
- // a statement about the ANSWER, not about the revision, and adopting the unconfirmed one
301
- // would re-open the doubt the rank split exists to resolve.
302
- // `unavailable` answers rank among THEMSELVES by how much they establish, so the merged
303
- // entry never presents a weaker doubt than some peer actually returned. This matters
304
- // because the reason travels out verbatim on `BlockUnavailableError` and callers act on
305
- // it: 'cohort-unreachable' is the one reason a caller may treat permissively (the
306
- // answering node reached nobody, so its own view is all it has), and a partitioned
307
- // coordinator answering first must not mask a well-connected one that positively
308
- // established the block EXISTS ('claimed-elsewhere', or 'unmaterializable' — records
309
- // held here). 'peers-unreachable' sits between: it establishes that some of the cohort
310
- // was reachable, without settling existence.
311
- const unavailableRank = (reason: BlockUnavailableReason): number =>
312
- reason === 'cohort-unreachable' ? 0 : reason === 'peers-unreachable' ? 1 : 2;
313
- const rankOf = (r: unknown): number => {
314
- if (!r || typeof r !== 'object') return -1;
315
- const entry = r as GetBlockResults[BlockId];
316
- if (entry.block != null) return entry.unconfirmedAheadRev === undefined ? 6 : 5;
317
- if (entry.unavailable !== undefined) return unavailableRank(entry.unavailable);
318
- return entry.unconfirmedAheadRev === undefined ? 4 : 3;
319
- };
320
- const carriesBlock = (r: unknown): r is GetBlockResult =>
321
- !!r && typeof r === 'object' && (r as GetBlockResult).block != null;
322
- /** Whether `candidate` displaces the entry already held for the same block: a strictly
323
- * better rank, or — at equal rank, both carrying content — strictly newer content.
324
- *
325
- * NOTE: `servedRevision` falls back to `state.latest` for a producer that omits
326
- * `materialized`, and on a PINNED read that fallback overstates — `state.latest` is the
327
- * newest revision the repo holds, not the revision it served. Every in-tree producer
328
- * populates `materialized` (`StorageRepo`, `TestTransactor`; `CoordinatorRepo` forwards it
329
- * verbatim), so the fallback only reaches a third-party `IRepo`, and `belowFloor` above
330
- * reads the same number, so the two stay consistent. If such a repo ever answers pinned
331
- * reads beside one that does report `materialized`, it can win this tie with a number
332
- * describing content it did not serve: cap the comparison at `blockGets.context.rev` then
333
- * (a correct answer to a pinned read is never above the pin), in both places at once.
334
- *
335
- * NOTE: `servedRevision` also reads `state`, which the type requires but a decoded wire
336
- * response could still omit. Ranking never touched it, so an entry like that used to fault
337
- * only the reader of ITS block; it now faults the whole `get`, siblings included. Left
338
- * alone because the reader called `servedRevision` on such an entry anyway — this widens
339
- * the blast radius, it does not create the fault. If a third-party `IRepo` ever makes it
340
- * real, make `servedRevision` tolerate a missing `state` rather than guarding here. */
341
- const beats = (candidate: unknown, held: unknown): boolean => {
342
- const byRank = rankOf(candidate) - rankOf(held);
343
- return byRank !== 0
344
- ? byRank > 0
345
- : carriesBlock(candidate) && carriesBlock(held) && servedRevision(candidate) > servedRevision(held);
346
- };
347
-
348
- // Create a lookup map from successful responses only
349
- const resultEntries = new Map<string, any>();
350
- for (const batch of completedBatches) {
351
- const resp = batch.request!.response! as any;
352
- for (const [bid, res] of Object.entries(resp)) {
353
- const existing = resultEntries.get(bid);
354
- if (!existing || beats(res, existing)) {
355
- resultEntries.set(bid, res);
356
- }
357
- }
358
- }
359
- // Ensure we have at least one response per requested block id
360
- const missingIds = distinctBlockIds.filter(bid => !resultEntries.has(bid));
361
- if (missingIds.length > 0) {
362
- log('get:missing blockIds=%o', missingIds);
363
- const details = this.formatBatchStatuses(batches,
364
- b => {
365
- const status = b.request == null ? 'no-response' : (b.request.isResponse ? 'response' : 'in-flight')
366
- const errMsg = b.request?.isError ? ` cause=${errorMessage(b.request.error)}` : ''
367
- return `${b.peerId.toString()}[block:${b.blockId}](${status})${errMsg}`
368
- });
369
- const rootCause = firstBatchError(batches) ?? error;
370
- const aggregate = new Error(`Some peers did not complete: ${details}${rootCause ? `; root: ${rootCause.message}` : ''}`);
371
- (aggregate as any).cause = rootCause;
372
- throw aggregate;
373
- }
374
-
375
- log('get:done blockIds=%d ms=%d', distinctBlockIds.length, Date.now() - t0);
376
- return Object.fromEntries(resultEntries) as GetBlockResults;
377
- }
378
-
379
- async getStatus(blockActions: ActionBlocks[]): Promise<BlockActionStatus[]> {
380
- // Collect all unique block IDs across all action refs
381
- const allBlockIds = [...new Set(blockActions.flatMap(ref => ref.blockIds))];
382
-
383
- if (allBlockIds.length === 0) {
384
- return blockActions.map(ref => ({ ...ref, statuses: [] }));
385
- }
386
-
387
- // Get block states from repos
388
- const blockStates = await this.get({ blockIds: allBlockIds });
389
-
390
- // A block whose repo could not determine whether it exists carries no status either:
391
- // its empty `state` would read below as `aborted`, turning "I could not find out" into
392
- // a definite verdict on someone's action. Fail loudly instead, like every other read of
393
- // an unavailable block (see BlockUnavailableError). The same goes for a state the repo
394
- // could not confirm is CURRENT (`unconfirmedAheadRev`, surviving the retry round above):
395
- // an action committed at the claimed-ahead revision would read out of the stale state as
396
- // a definite `aborted` — this read is unpinned, so the doubt always applies.
397
- for (const blockId of allBlockIds) {
398
- const entry = blockStates[blockId];
399
- if (entry?.unavailable !== undefined && entry.block == null) {
400
- throw new BlockUnavailableError(blockId, entry.unavailable);
401
- }
402
- if (entry?.unconfirmedAheadRev !== undefined) {
403
- throw new BlockPossiblyStaleError(blockId, entry.unconfirmedAheadRev);
404
- }
405
- }
406
-
407
- // Determine status for each action ref
408
- const results: BlockActionStatus[] = blockActions.map(ref => ({
409
- ...ref,
410
- statuses: ref.blockIds.map(blockId => {
411
- const result = blockStates[blockId];
412
- if (!result) {
413
- return 'aborted';
414
- }
415
- const { state } = result;
416
- if (state.pendings?.includes(ref.actionId)) {
417
- return 'pending';
418
- }
419
- if (state.latest?.actionId === ref.actionId) {
420
- return 'committed';
421
- }
422
- // Neither pending nor the latest committed. Block state alone calls this `aborted`, but a
423
- // committed action that was later durably **invalidated** also presents this way — the
424
- // compensating revision is now the block's latest, so the original action is no longer it.
425
- // The `refineInvalidatedStatuses` pass below disambiguates from the authoritative log.
426
- return 'aborted';
427
- })
428
- }));
429
-
430
- // Authoritative `committed-invalidated` from durable state: consult each affected collection's
431
- // log for an InvalidationEntry against the queried action (survives a node restart — the in-memory
432
- // dispute map is only a fast cache; the log is the source of truth). Only `aborted` slots are
433
- // ambiguous, so this is a no-op for ordinary pending/committed queries.
434
- await this.refineInvalidatedStatuses(results, blockStates);
435
- return results;
436
- }
437
-
438
- /**
439
- * Refine the otherwise-`aborted` statuses to `committed-invalidated` for any queried action that has a
440
- * durable {@link import("../log/struct.js").InvalidationEntry} against it. Reads the collection log via
441
- * {@link Log.findInvalidation} — the durable, restart-surviving source of truth (`docs/right-is-right.md`
442
- * §Durable Invalidation) — rather than the per-node, in-memory dispute map. A `pending` slot is left
443
- * untouched: a still-pending transaction whose base was invalidated will be rejected on its own
444
- * validation ("pending → will-be-rejected"), which is not the same as `committed-invalidated`.
445
- *
446
- * Best-effort and isolated: a log-open/read fault leaves the slot `aborted` (logged) rather than
447
- * failing the whole status query. The per-call caches keep one log open and one lookup per
448
- * `(collection, action)` even when many refs share a collection.
449
- */
450
- private async refineInvalidatedStatuses(results: BlockActionStatus[], blockStates: GetBlockResults): Promise<void> {
451
- const logByCollection = new Map<CollectionId, Log<unknown> | undefined>();
452
- const invalidatedByKey = new Map<string, boolean>();
453
-
454
- for (const ref of results) {
455
- if (!ref.statuses.some(status => status === 'aborted')) {
456
- continue; // no ambiguous slot — an invalidation could not change this ref's answer
457
- }
458
- const collectionId = collectionIdForRef(ref, blockStates);
459
- if (collectionId === undefined) {
460
- continue; // genuinely aborted: no fetched block to anchor a collection log on
461
- }
462
- const key = `${collectionId} ${ref.actionId}`;
463
- let invalidated = invalidatedByKey.get(key);
464
- if (invalidated === undefined) {
465
- invalidated = await this.hasDurableInvalidation(collectionId, ref.actionId, logByCollection);
466
- invalidatedByKey.set(key, invalidated);
467
- }
468
- if (!invalidated) {
469
- continue;
470
- }
471
- for (let i = 0; i < ref.statuses.length; i++) {
472
- if (ref.statuses[i] === 'aborted') {
473
- ref.statuses[i] = 'committed-invalidated';
474
- }
475
- }
476
- }
477
- }
478
-
479
- /** Whether `actionId` has a durable invalidation entry in `collectionId`'s log (opened once, cached). */
480
- private async hasDurableInvalidation(
481
- collectionId: CollectionId,
482
- actionId: ActionId,
483
- logByCollection: Map<CollectionId, Log<unknown> | undefined>,
484
- ): Promise<boolean> {
485
- try {
486
- let collectionLog = logByCollection.get(collectionId);
487
- if (!logByCollection.has(collectionId)) {
488
- const source = new TransactorSource<IBlock>(collectionId, this, undefined);
489
- const tracker = new Tracker<IBlock>(new CacheSource<IBlock>(source));
490
- collectionLog = await Log.open<unknown>(tracker, collectionId);
491
- logByCollection.set(collectionId, collectionLog);
492
- }
493
- if (!collectionLog) {
494
- return false;
495
- }
496
- return (await collectionLog.findInvalidation(actionId)) !== undefined;
497
- } catch (err) {
498
- log('getStatus: durable invalidation lookup failed collection=%s action=%s: %o', collectionId, actionId, err);
499
- return false;
500
- }
501
- }
502
-
503
- /**
504
- * See {@link ITransactor.getLineage}. Asks EVERY member of each block's cohort, directly, and
505
- * folds their answers with {@link judgeCohortLineage} — not the coordinator round {@link get}
506
- * runs, because no single member can answer for the cohort: a member that took a later revision
507
- * as a replica cannot say what it was built from, while the member it came from can.
508
- *
509
- * The per-member `get` carries no context, so it pins nothing and promotes nothing; asking is
510
- * never what makes a write land.
511
- *
512
- * NOTE: one request per cohort member per block. Reached only when a writer's own half-landed
513
- * write was refused as superseded, which is rare, so the fan-out is not batched by member. If a
514
- * write path ever calls this routinely, group the blocks a member is in the cohort of into one
515
- * request per member.
516
- */
517
- async getLineage(ref: ActionBlocks & { rev: number }): Promise<ActionLineage> {
518
- const target = { actionId: ref.actionId, rev: ref.rev };
519
- const expiration = Date.now() + this.timeoutMs;
520
- const answers = await Promise.all(ref.blockIds.map(blockId => this.cohortLineage(blockId, target, expiration)));
521
- const durabilities = answers.flatMap(answer => answer.durability === undefined ? [] : [answer.durability]);
522
- const saved = answers.length > 0 && durabilities.length === answers.length;
523
- log('getLineage actionId=%s rev=%d blocks=%o', ref.actionId, ref.rev, answers.map(answer => answer.lineage));
524
- return {
525
- blocks: answers.map(answer => answer.lineage),
526
- ...(saved ? { durability: mergeDurability(durabilities) } : {})
527
- };
528
- }
529
-
530
- /** One block's cohort answer: every member asked in parallel, a member that cannot be reached
531
- * (or whose cohort cannot be resolved at all) counted as `unknown` rather than left out. */
532
- private async cohortLineage(blockId: BlockId, target: { actionId: ActionId; rev: number }, expiration: number): Promise<CohortLineage> {
533
- let cohort: string[];
534
- try {
535
- cohort = Object.keys(await this.keyNetwork.findCluster(routingKeyForBlock(blockId)));
536
- } catch (err) {
537
- log('getLineage:cohort-unresolved blockId=%s error=%s', blockId, errorMessage(err));
538
- return { lineage: 'unknown' };
539
- }
540
- const members = await Promise.all(cohort.map(async (peerId): Promise<MemberLineage> => {
541
- try {
542
- const results = await this.getRepo(peerIdFromString(peerId)).get(
543
- { blockIds: [blockId], lineageOf: target }, { expiration, dialTimeoutMs: this.dialTimeoutMs });
544
- const entry = results?.[blockId];
545
- return { peerId, lineage: entry?.lineage ?? 'unknown', ...(entry?.state?.latest ? { latest: entry.state.latest } : {}) };
546
- } catch (err) {
547
- log('getLineage:member-silent blockId=%s peer=%s error=%s', blockId, peerId, errorMessage(err));
548
- return { peerId, lineage: 'unknown' };
549
- }
550
- }));
551
- return judgeCohortLineage(members);
552
- }
553
-
554
- private async consolidateCoordinators(
555
- blockIds: BlockId[],
556
- transforms: Transforms,
557
- transformForBlock: (payload: Transforms, blockId: BlockId, mergeWith?: Transforms) => Transforms
558
- ): Promise<CoordinatorBatch<Transforms, PendResult>[]> {
559
- // Use cluster intersections to minimize the number of coordinators.
560
- // For each block, find its full cluster, then greedily assign blocks to
561
- // peers that appear in the most clusters — reducing round trips when
562
- // blocks share cluster members.
563
-
564
- // Step 1: Get cluster peer sets for each block
565
- const blockClusterPeerIds: Map<BlockId, Set<string>> = new Map();
566
- const fallbackBlocks: BlockId[] = [];
567
-
568
- await Promise.all(blockIds.map(async bid => {
569
- try {
570
- const clusterPeers = await this.keyNetwork.findCluster(routingKeyForBlock(bid));
571
- blockClusterPeerIds.set(bid, new Set(Object.keys(clusterPeers)));
572
- } catch {
573
- fallbackBlocks.push(bid);
574
- }
575
- }));
576
-
577
- // Step 2: Build peer → blocks index (which blocks each peer can coordinate)
578
- const peerBlocks = new Map<string, BlockId[]>();
579
- for (const [blockId, peerIds] of blockClusterPeerIds) {
580
- for (const peerId of peerIds) {
581
- const blocks = peerBlocks.get(peerId) ?? [];
582
- blocks.push(blockId);
583
- peerBlocks.set(peerId, blocks);
584
- }
585
- }
586
-
587
- // Step 3: Greedy set cover — assign blocks to peers covering the most uncovered blocks
588
- const uncovered = new Set(blockClusterPeerIds.keys());
589
- const assignments = new Map<string, BlockId[]>(); // peerIdStr → assigned blockIds
590
-
591
- while (uncovered.size > 0) {
592
- const best = bestCoveringPeer(peerBlocks, uncovered, this.localPeerId);
593
- if (!best) break;
594
- assignments.set(best.peerId, best.covered);
595
- for (const bid of best.covered) uncovered.delete(bid);
596
- }
597
-
598
- // Step 4: Any remaining uncovered blocks fall back to findCoordinator
599
- for (const bid of uncovered) fallbackBlocks.push(bid);
600
-
601
- const fallbackCoordinators = await Promise.all(
602
- fallbackBlocks.map(async bid => ({
603
- blockId: bid,
604
- coordinator: await this.keyNetwork.findCoordinator(routingKeyForBlock(bid), { excludedPeers: [] })
605
- }))
606
- );
607
- for (const { blockId, coordinator } of fallbackCoordinators) {
608
- const key = coordinator.toString();
609
- const existing = assignments.get(key) ?? [];
610
- existing.push(blockId);
611
- assignments.set(key, existing);
612
- }
613
-
614
- // Step 5: Convert assignments to batches
615
- const batches: CoordinatorBatch<Transforms, PendResult>[] = [];
616
- for (const [peerIdStr, consolidatedBlocks] of assignments) {
617
- const peerId = peerIdFromString(peerIdStr);
618
-
619
- let batchTransforms: Transforms = { inserts: {}, updates: {}, deletes: [] };
620
- for (const bid of consolidatedBlocks) {
621
- const blockTransforms = transformForBlock(transforms, bid, batchTransforms);
622
- batchTransforms = blockTransforms;
623
- }
624
-
625
- batches.push({
626
- peerId,
627
- payload: batchTransforms,
628
- blockId: consolidatedBlocks[0]!,
629
- coordinatingBlockIds: consolidatedBlocks,
630
- excludedPeers: []
631
- });
632
- }
633
-
634
- return batches;
635
- }
636
-
637
- async pend(blockAction: PendRequest): Promise<PendResult> {
638
- const t0 = Date.now();
639
- const transformForBlock = (payload: Transforms, blockId: BlockId, mergeWithPayload: Transforms | undefined): Transforms => {
640
- const filteredTransform = transformForBlockId(payload, blockId);
641
- return mergeWithPayload
642
- ? concatTransform(mergeWithPayload, blockId, filteredTransform)
643
- : transformsFromTransform(filteredTransform, blockId);
644
- };
645
- const blockIds = blockIdsForTransforms(blockAction.transforms);
646
- const batches = await this.consolidateCoordinators(blockIds, blockAction.transforms, transformForBlock);
647
- log('pend actionId=%s blockIds=%d batches=%d', blockAction.actionId, blockIds.length, batches.length);
648
- if (verbose) {
649
- const batchSummary = batches.map(b => ({
650
- peer: b.peerId.toString().substring(0, 12),
651
- blocks: b.coordinatingBlockIds ?? [b.blockId],
652
- inserts: Object.keys(b.payload.inserts ?? {}).length,
653
- updates: Object.keys(b.payload.updates ?? {}).length,
654
- deletes: b.payload.deletes?.length ?? 0
655
- }));
656
- log('pend:batches actionId=%s detail=%o', blockAction.actionId, batchSummary);
657
- }
658
- const expiration = Date.now() + this.timeoutMs;
659
-
660
- let error: Error | undefined;
661
- try {
662
- // Process all batches, noting all outstanding peers
663
- await processBatches(
664
- batches,
665
- (batch) => this.getRepo(batch.peerId).pend(
666
- pendRequestForBatch(blockAction, batch.payload),
667
- {
668
- expiration,
669
- dialTimeoutMs: this.dialTimeoutMs,
670
- coordinatingBlockIds: batch.coordinatingBlockIds
671
- }
672
- ),
673
- batch => blockIdsForTransforms(batch.payload),
674
- transformForBlock,
675
- expiration,
676
- (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), options)
677
- );
678
- // Cache resolved coordinators for follow-up commit to hit the same peers
679
- try {
680
- for (const b of Array.from(allBatches(batches))) {
681
- this.keyNetwork.recordCoordinator?.(routingKeyForBlock(b.blockId), b.peerId);
682
- }
683
- } catch (e) { log('WARN: Failed to record coordinator hint %o', e); }
684
- } catch (e) {
685
- error = e as Error;
686
- }
687
-
688
- if (!everyBatch(batches, b => b.request?.isResponse as boolean && b.request!.response!.success)) {
689
- const details = this.formatBatchStatuses(batches,
690
- b => {
691
- const status = b.request == null ? 'no-response' : (b.request.isResponse ? 'non-success' : 'in-flight')
692
- const errMsg = b.request?.isError ? ` cause=${errorMessage(b.request.error)}` : ''
693
- return `${b.peerId.toString()}[block:${b.blockId}](${status})${errMsg}`
694
- });
695
- // Prefer the first-attempt per-batch error over any outer `error` so the root cause
696
- // surfaced in the aggregate message is the actual coordinator failure, not any
697
- // downstream "no coordinator available" thrown by retry lookup.
698
- const rootCause = firstBatchError(batches) ?? error;
699
- const aggregate = new Error(`Some peers did not complete: ${details}${rootCause ? `; root: ${rootCause.message}` : ''}`);
700
- (aggregate as any).cause = rootCause;
701
- (aggregate as AggregateError).errors = rootCause ? [rootCause] : [];
702
- error = aggregate;
703
- }
704
-
705
- if (error) { // If any failures, discharge every pending record this pend left behind
706
- log('pend:cancel actionId=%s', blockAction.actionId);
707
- // AWAITED, not fired off as a background microtask. Returning before the cancel lands means
708
- // a caller that retries immediately meets its own still-standing pending record and burns a
709
- // whole attempt out of its retry budget on it (measured: the attempt after a lost pend reply
710
- // was rejected by its own record, and only the one after that landed).
711
- // The tradeoff, stated: a losing pend now pays a cancel round-trip before it returns its
712
- // StaleFailure, where before it returned at once and cleaned up behind itself. That is the
713
- // right trade — the old shape spent one of the CALLER's retries instead of one round-trip.
714
- // The catch matters now that `cancelBatch` is checked and throwable: a cancel that could not
715
- // discharge must be reported, but must not replace the pend verdict below (the StaleFailure
716
- // the caller reads via `isConflictFailure` to decide to rebase, or the original error).
717
- try {
718
- await this.cancelBatch(batches, { blockIds, actionId: blockAction.actionId });
719
- } catch (cancelError) {
720
- log('WARN: cancel after pend failure did not discharge: %o', cancelError);
721
- }
722
- const stale = Array.from(allBatches(batches, b => b.request?.isResponse as boolean && !b.request!.response!.success));
723
- if (stale.length > 0) { // Any active stale failures should preempt reporting connection or other potential transient errors (we have information)
724
- log('pend:stale actionId=%s staleCount=%d', blockAction.actionId, stale.length);
725
- // Carry the first available reject reason through: `SyncRetryExhaustedError.lastReason`
726
- // and the multi-collection writer's failure message both read it, and it is the only
727
- // diagnostic that survives an exhausted retry budget.
728
- const reason = stale.map(b => (b.request!.response! as StaleFailure).reason).find(r => r !== undefined);
729
- // This response is REBUILT from the per-batch ones rather than forwarded, so
730
- // retryability has to be carried explicitly or it is lost: a batch whose failure was
731
- // a confirmed lost race can arrive with neither `missing` nor `pending` (see
732
- // CoordinatorRepo.classifyStaleRejection), and the aggregate would then look like a
733
- // hard rejection to `isConflictFailure`. Any conflicting batch makes the aggregate a
734
- // conflict — the pend failed as a whole, and a re-read/rebase can clear it.
735
- // NOTE: `some`, not `every`, so a pend whose batches mix a lost race with a genuine hard
736
- // rejection is reported retryable and burns its (bounded, backed-off) retry budget before
737
- // failing. Deliberate: an unclassified reason-only response from an older peer is
738
- // indistinguishable from a hard rejection here, and `every` would refuse to retry a real
739
- // race whenever one batch came from such a peer. Revisit if every producer sets `conflict`
740
- // (then `every` is both safe and tighter), or if mixed-outcome pends show up as wasted
741
- // retry latency in practice.
742
- const conflict = stale.some(b => isConflictFailure(b.request!.response! as StaleFailure));
743
- // Deliberately NOT first-wins like `reason` above — `highestStaleAt` takes the largest
744
- // confirmed revision, which is the binding constraint on the client's next request.
745
- // Its doc comment carries the rule and the one-pend-one-collection assumption it rests on.
746
- const staleAt = highestStaleAt(stale.map(b => (b.request!.response! as StaleFailure).staleAt));
747
- return {
748
- success: false,
749
- conflict,
750
- ...(reason === undefined ? {} : { reason }),
751
- ...(staleAt === undefined ? {} : { staleAt }),
752
- missing: distinctBlockActionTransforms(stale.flatMap(b => (b.request!.response! as StaleFailure).missing).filter((x): x is ActionTransforms => x !== undefined)),
753
- };
754
- }
755
- throw error; // No stale failures, report the original error
756
- }
757
-
758
- // Collect replies back into result structure
759
- const completed = Array.from(allBatches(batches, b => b.request?.isResponse as boolean && b.request!.response!.success));
760
-
761
- // Seed the per-transaction coordinator cache from the final (retry-adjusted) batch
762
- // assignment so the follow-up commit reuses pend's resolution without a fresh
763
- // findCoordinator round or a hop through the optional recordCoordinator hint. We read
764
- // blockIdsForTransforms(b.payload) rather than the anchor b.blockId so EVERY block a
765
- // consolidated batch coordinates is recorded — and against the peer that actually
766
- // pended it, since a block re-homed by a retry lands in the retry batch's payload.
767
- // NOTE: this cache assumes cluster membership is stable for the transaction's
768
- // lifetime — the coordinator resolved here is reused verbatim at commit. Transactions
769
- // are short, so that holds today. If a future change lets clusters churn *within* a
770
- // single transaction (e.g. very long-running commits), a cached coordinator could
771
- // point at a peer no longer in the cohort; commit self-heals (a failed cached peer is
772
- // excluded and re-resolved live by processBatches), at the cost of one wasted round-trip.
773
- const txnCoordinators = this.txnCoordinatorsFor(blockAction.actionId);
774
- for (const b of completed) {
775
- for (const bid of blockIdsForTransforms(b.payload)) {
776
- txnCoordinators.set(bid, b.peerId);
777
- }
778
- }
779
-
780
- log('pend:done actionId=%s ms=%d batches=%d', blockAction.actionId, Date.now() - t0, batches.length);
781
- return {
782
- success: true,
783
- pending: completed.flatMap(b => (b.request!.response! as PendSuccess).pending),
784
- blockIds: blockIdsForTransforms(blockAction.transforms),
785
- // The weakest coordinator's answer is the action's answer (`mergeDurability`). A pend has
786
- // no torn case: a batch that did not succeed fails the whole pend above.
787
- // NOTE: a pend naming NO blocks now throws here (`mergeDurability` refuses an empty input rather
788
- // than fabricate a class), where it used to answer success. No caller produces one today —
789
- // `Collection.sync` skips an empty change set, and the multi-collection coordinator pends only
790
- // collections that appended a log entry. If one ever appears, decide what an empty write's
791
- // durability means at that caller; do not make the merge invent one.
792
- durability: mergeDurability(completed.map(b => (b.request!.response! as PendSuccess).durability))
793
- };
794
- }
795
-
796
- /**
797
- * Discharges every pending record `actionRef` left behind, and THROWS if it could not.
798
- *
799
- * Cancel is the only removal path a client controls (see docs/repository.md, "a pending record's
800
- * lifetime is bounded by its writer"), so a cancel that silently did nothing wedges the block
801
- * against every later writer. `processBatches` never rethrows — it records each batch's outcome
802
- * and swallows the rejection — so a cancel in which every peer's RPC failed used to return
803
- * normally, and each of this method's callers read "returned" as "discharged". It now checks
804
- * completeness and rides out a transient fault, exactly as {@link pend} and {@link commitBlocks}
805
- * already do for their own rounds. See {@link dischargeCancel} for the loop and its bounds.
806
- */
807
- async cancel(actionRef: ActionBlocks): Promise<void> {
808
- log('cancel actionId=%s blockIds=%d', actionRef.actionId, actionRef.blockIds.length);
809
- await this.dischargeCancel(actionRef);
810
- }
811
-
812
- async queryClusterNominees(blockId: BlockId): Promise<ClusterNomineesResult> {
813
- const routingKey = routingKeyForBlock(blockId);
814
- const clusterPeers = await this.keyNetwork.findCluster(routingKey);
815
- const nominees = Object.keys(clusterPeers).map(idStr => peerIdFromString(idStr));
816
- return { nominees };
817
- }
818
-
819
- /**
820
- * Commits the action: its log tail, then every other block it touched (the header included, when
821
- * the action touches it).
822
- *
823
- * `request.tailId` is threaded into every per-block commit so the coordinator carries it into the
824
- * consensus commit op → each committing node's StorageRepo.commit stamps it onto the emitted
825
- * CollectionChangeEvent (the reactivity topic anchor). Without this the per-block RepoCommitRequest
826
- * drops the collection tail and reactivity origination is gated off (undefined tail → non-member).
827
- * `request.blockDigests` (when present) is the FULL per-block declaration map for the action; it is
828
- * narrowed to each request's own blocks at send time ({@link sendCommit}) so each cohort only signs
829
- * for the blocks it is actually driving.
830
- *
831
- * **One round when one coordinator covers every block** ({@link commitInOneRound}) — always the
832
- * case in small groups, where `consolidateCoordinators` collapses the pend onto one peer. Otherwise,
833
- * or when that round throws, **two**: the tail, then the rest ({@link commitTailThenSweep}).
834
- *
835
- * Either way the guarantee `Collection.bootstrapContext` rests on holds: no member commits a
836
- * non-tail block of the action without its tail. In one round it holds because every member's
837
- * `StorageRepo.commit` applies the tail first and stops at the first failure; in two, because the
838
- * sweep starts only once the tail round was acknowledged.
839
- */
840
- async commit(request: CommitRequest): Promise<CommitResult> {
841
- const t0 = Date.now();
842
- log('commit actionId=%s rev=%d blockIds=%d', request.actionId, request.rev, request.blockIds.length);
843
- const remainingBlocks = Array.from(new Set(request.blockIds)).filter(bid => bid !== request.tailId);
844
- // An action touching only its tail has nothing to combine: its single round IS the tail round,
845
- // with the tail round's retries.
846
- if (remainingBlocks.length > 0) {
847
- const result = await this.commitInOneRound(request, remainingBlocks);
848
- if (result) {
849
- log('commit:done actionId=%s ms=%d path=one-round success=%s', request.actionId, Date.now() - t0, result.success);
850
- return result;
851
- }
852
- }
853
- const result = await this.commitTailThenSweep(request, remainingBlocks);
854
- log('commit:done actionId=%s ms=%d path=tail-then-sweep torn=%d', request.actionId, Date.now() - t0,
855
- result.success ? result.durability.torn?.length ?? 0 : 0);
856
- return result;
857
- }
858
-
859
- /**
860
- * Sends the whole action — tail first, then `remainingBlocks` in order — to one coordinator as ONE
861
- * commit, when one coordinator covers every block. Returns `undefined` when the round does not
862
- * apply (the blocks need more than one coordinator, or their coordinators could not be looked up)
863
- * or when it THREW; the caller then runs {@link commitTailThenSweep} for the same request.
864
- *
865
- * Tail first on the wire because `CoordinatorRepo.commit` runs consensus on `blockIds[0]`'s cohort:
866
- * the combined record runs on the tail's cohort, as the tail round would. The other blocks then
867
- * commit on the tail's cohort rather than on their own — the same approximation a multi-block
868
- * sweep batch already makes (backlog `debt-sender-side-coordinating-block-binding-is-unchecked`),
869
- * and identical whenever the cohorts coincide.
870
- *
871
- * A RETURNED refusal (a confirmed conflict, or `commit-not-durable`) is returned as a refused tail
872
- * is: the caller cancels and the writer's retry takes over. A refusal can still leave the tail AND
873
- * the other blocks on a minority of the cohort — a strictly more complete state than a refused
874
- * tail round leaves, and one `Collection.completeOwnEntry` already finishes.
875
- *
876
- * A THROW is not retried here. `processBatches`' retry re-batches the failed blocks onto possibly
877
- * different coordinators, in parallel, which could land a non-tail block on one cohort before the
878
- * tail lands on another. The two-step fallback re-sends everything instead, and whatever the thrown
879
- * round did land is this action's own revision, so re-committing it is an idempotent no-op
880
- * (`isOwnRevision` in `StorageRepo.commit`). The fallback starts from the same cached coordinator,
881
- * so a dead one costs one more dial before its retries move on, and a round that hangs to its
882
- * deadline costs one more `timeoutMs` before the fallback starts.
883
- */
884
- private async commitInOneRound(request: CommitRequest, remainingBlocks: BlockId[]): Promise<CommitResult | undefined> {
885
- const blockIds = [request.tailId, ...remainingBlocks];
886
- const coordinator = await this.soleCommitCoordinator(blockIds, request.actionId);
887
- if (!coordinator) {
888
- return undefined;
889
- }
890
- let result: CommitResult;
891
- try {
892
- result = await this.sendCommit(coordinator, blockIds, request, Date.now() + this.timeoutMs);
893
- } catch (e) {
894
- log('WARN: one-round commit threw; committing the tail, then the rest: actionId=%s peer=%s error=%s',
895
- request.actionId, coordinator.toString(), errorMessage(e));
896
- return undefined;
897
- }
898
- return result.success
899
- ? { success: true, durability: mergeDurability([result.durability]) }
900
- : refusalFrom([result]);
901
- }
902
-
903
- /**
904
- * The one coordinator covering every block in `blockIds` — resolved as {@link commitBlocks}
905
- * resolves them, preferring what the pend already resolved — or `undefined` when they need more
906
- * than one, or a lookup failed (logged; the two-step path then repeats the lookups and reports
907
- * whatever they report).
908
- */
909
- private async soleCommitCoordinator(blockIds: BlockId[], actionId: ActionId): Promise<PeerId | undefined> {
910
- let batches: CoordinatorBatch<BlockId[], CommitResult>[];
911
- try {
912
- batches = await this.batchesForPayload<BlockId[], CommitResult>(blockIds, blockIds, mergeBlocks, [], actionId);
913
- } catch (e) {
914
- log('commit:one-round-unplanned actionId=%s error=%s', actionId, errorMessage(e));
915
- return undefined;
916
- }
917
- if (batches.length !== 1) {
918
- log('commit:one-round-inapplicable actionId=%s coordinators=%d', actionId, batches.length);
919
- return undefined;
920
- }
921
- return batches[0]!.peerId;
922
- }
923
-
924
- /**
925
- * Commits the tail, and — once the tail round was acknowledged — every block in `remainingBlocks`.
926
- * The path for an action whose blocks need more than one coordinator, for an action touching only
927
- * its tail, and for a {@link commitInOneRound} that threw.
928
- */
929
- private async commitTailThenSweep(request: CommitRequest, remainingBlocks: BlockId[]): Promise<CommitResult> {
930
- const tailResult = await this.commitBlock(request.tailId, request.actionId, request.rev, request.tailId, request.blockDigests);
931
- if (!tailResult.success) {
932
- // NOTE: a refused tail is NOT an absent tail. The coordinator's durability gate answers
933
- // `commit-not-durable` whenever fewer than a majority hold the revision — even though
934
- // some members stored it — and this return means the sweep below never runs, so every
935
- // other block of the action is left uncommitted while the log entry may already be
936
- // readable. This layer cannot tell "tail absent" from "tail present on a minority", so it
937
- // does not sweep anyway (that would commit data blocks under a tail that may never reach
938
- // a majority). The writer closes the gap instead: its retry keeps the SAME action id,
939
- // and if its refresh finds this action's own log entry it re-sends this attempt — same
940
- // transforms, same revision — to land what was left behind before treating the write as
941
- // saved (`Collection.completeOwnEntry`). A write is saved only when every block its log
942
- // entry names holds its revision; the entry alone proves nothing but the tail.
943
- return tailResult;
944
- }
945
- // Every coordinator that confirmed part of this action reports who holds its part; the
946
- // action-level answer is the WEAKEST of them (`mergeDurability`), so a caller reading only the
947
- // scalar fields reads the binding constraint. The blocks a torn sweep abandons are on nobody,
948
- // and `torn` names them: they never heal by replication, only by re-driving the action.
949
- const cohortReports: WriteDurability[] = [tailResult.durability];
950
- let torn: BlockId[] = [];
951
-
952
- // Sweep every non-tail block (the header, when the action touches it, lands here too — after
953
- // the tail, like any other touched block). The tail is the only exclusion needed.
954
- //
955
- // The tail-then-sweep order IS load-bearing; do not reorder it to put the contested blocks
956
- // first. Across two rounds it is the only thing keeping a member from committing a non-tail
957
- // block of this action without the tail, which `Collection.bootstrapContext` relies on (see
958
- // {@link commit}): that bootstrap is what makes pending non-tail blocks visible to a chain
959
- // walk. Sweeping before the tail would also let a committed header point at a never-committed
960
- // tail: a dangling pointer, strictly worse than an orphaned block.
961
- if (remainingBlocks.length > 0) {
962
- const { batches, error } = await this.commitBlocks({ blockIds: remainingBlocks, actionId: request.actionId, rev: request.rev, tailId: request.tailId, blockDigests: request.blockDigests });
963
- cohortReports.push(...confirmedDurabilities(batches));
964
- if (error) {
965
- // Split by the failure's NATURE, exactly as commitBlock does for the tail: a RETURNED
966
- // `success:false` from a cohort coordinator is a confirmed optimistic-concurrency loss
967
- // (post conversion-arms, coordinators only return non-success for confirmed conflicts) —
968
- // a rival holds one of these blocks' revisions, no reconciliation will ever apply OUR
969
- // transform there, and proceeding would acknowledge a torn action (tail committed, the
970
- // conflicted block permanently pointing elsewhere — the acknowledged-but-absent write).
971
- // Surface it so the caller cancels and re-drives at a fresh revision.
972
- const stale = this.staleFromBatches(batches);
973
- if (stale) {
974
- return stale;
975
- }
976
- // The tail already committed durably when this returns, as has any sweep batch that
977
- // landed before the error — a torn action.
978
- // Refusing is still right, and must NOT be softened back into a blanket tolerance:
979
- // acknowledging a torn action would report a write as durable while one of its blocks
980
- // permanently points somewhere else. The two consequences that used to make the refusal
981
- // itself harmful are now handled upstream, so the writer recovers on its own:
982
- // - its re-pend no longer meets its OWN durable revision as if a rival held it. All
983
- // three pend-tier checks carve out `latest.rev === request.rev &&
984
- // latest.actionId === request.actionId` (StorageRepo.pend, which also skips saving
985
- // a pending record for such a block; ClusterMember.validatePendOperations; and
986
- // CoordinatorRepo's stale classification). The retry no longer wedges.
987
- // - its retry recognises its own already-committed log entry instead of replaying it
988
- // (Collection.updateInternal's `inFlightActionId` arm, set by both write paths —
989
- // syncInternal and TransactionCoordinator.commitOnce — which reuse one action id
990
- // across all of a write's attempts). It no longer appends a duplicate entry.
991
- // - and before consuming that entry it FINISHES the action: the blocks this return
992
- // abandons are on nobody (the caller cancels their pending records next), so the
993
- // refresh re-sends the refused attempt verbatim at the same revision, which the
994
- // carve-outs above turn into "land exactly what is missing"
995
- // (Collection.completeOwnEntry). The entry alone never counts as saved. If a rival
996
- // has since taken a revision one of those blocks needed, the writer is told so by
997
- // name (TornActionError) rather than acknowledged.
998
- //
999
- // Transport-shaped failures (throws, no returned refusal) keep the tolerance for the
1000
- // RESULT — the tail committed durably, and reporting failure now would disown an
1001
- // acknowledged write — but NOT for the state the sweep abandoned, which
1002
- // `cancelAbandonedSweepBlocks` below repairs before this returns.
1003
- try { log('WARN: non-tail commit had errors; cancelling unconfirmed blocks, proceeding after tail commit: %s', error.message); } catch { /* ignore */ }
1004
- torn = await this.cancelAbandonedSweepBlocks(request.actionId, remainingBlocks, batches);
1005
- }
1006
- }
1007
-
1008
- // `withTornBlocks` clamps the class below `full` when the sweep abandoned anything — a cohort
1009
- // can hold every block it was asked for while the action as a whole is incomplete — and never
1010
- // raises it. `isFullyDurable` then answers false; a consumer that needs to know WHICH blocks
1011
- // reads `torn`.
1012
- return { success: true, durability: withTornBlocks(mergeDurability(cohortReports), torn) };
1013
- }
1014
-
1015
- /**
1016
- * Cancels every sweep block whose commit batch never confirmed success, so an acknowledged
1017
- * commit never walks away from a pending record. Best-effort: a failed cancel is logged, never
1018
- * thrown, because the tail is already durable and the caller has nothing left to retry.
1019
- *
1020
- * **Why cancelling is required.** A thrown sweep does not imply the sweep's commit consensus
1021
- * exists anywhere: it also covers a sweep whose cluster transaction reached NOBODY, where no
1022
- * consensus record exists, no reconciliation will ever run, and every cohort member still holds
1023
- * the pending record its pend wrote. Nothing else removes such a record (its only removers are a
1024
- * client cancel, a divergence-shaped commit refusal, and a forward write of the SAME action — see
1025
- * docs/repository.md "a pending record's lifetime is bounded by its writer"), and while it stands
1026
- * the members reject every later write to the block from any writer.
1027
- *
1028
- * **Why cancelling is safe** in all three timings:
1029
- * - the sweep's commit DID land on a member (a lost response) ⇒ that member already promoted the
1030
- * record, so the cancel is a no-op there;
1031
- * - it did not land ⇒ the cancel is exactly the repair;
1032
- * - its consensus is still in flight and lands AFTER the cancel ⇒ the member meets a missing
1033
- * pend, which `ClusterMember.applyConsensusOperation` already treats as "behind" divergence and
1034
- * cures by reconciling the block from a cohort peer.
1035
- *
1036
- * Confirmed blocks are excluded only to skip a pointless consensus round — cancelling one would
1037
- * also be a no-op — so an over-broad `confirmed` set costs latency, never correctness.
1038
- *
1039
- * Residuals: the cancel is retried and checked ({@link dischargeCancel}) but still bounded, so a
1040
- * fault outlasting its budget leaves the record wedged until a node-side backstop sweep exists (backlog:
1041
- * `debt-unpromotable-pending-records-need-a-sweep`); and this covers only the sweep's abandonment
1042
- * — `StorageRepo.commit`'s genuine-fault arm deliberately KEEPS a failed batch's pendings for a
1043
- * retry, so it is a second producer of the same durable state whenever that retry never comes.
1044
- *
1045
- * @returns the abandoned block ids — exactly the set cancelled here — so {@link commit} can name
1046
- * them as `torn` on the acknowledgement without re-deriving the set by a second rule.
1047
- */
1048
- private async cancelAbandonedSweepBlocks(actionId: ActionId, sweptBlocks: BlockId[], batches: CoordinatorBatch<BlockId[], CommitResult>[]): Promise<BlockId[]> {
1049
- // NOTE: `confirmed` is only ever non-empty when the sweep spans MORE THAN ONE batch, and it
1050
- // does so only when no single peer covers every swept block — `consolidateCoordinators`'
1051
- // greedy set cover collapses the pend onto one coordinator otherwise, and commit reuses that
1052
- // resolution. So on a mesh whose nodes are all responsible for all blocks — every in-process
1053
- // test mesh today — this filter is structurally unreachable, and
1054
- // packages/db-p2p/test/torn-commit-cancels-abandoned-blocks.spec.ts cannot cover it. Pinning
1055
- // a partial sweep needs a mesh whose responsibility sets are disjoint enough to force two
1056
- // pend batches; a new failure injection alone will not reach it. That fixture is tracked in
1057
- // backlog `debt-no-mesh-fixture-forces-two-coordinator-batches`, which collects this site and
1058
- // the two others with the same gap.
1059
- const confirmed = new Set<BlockId>();
1060
- for (const b of allBatches(batches, bb => bb.request?.isResponse === true && bb.request!.response!.success)) {
1061
- for (const bid of b.payload) confirmed.add(bid);
1062
- }
1063
- const abandoned = sweptBlocks.filter(bid => !confirmed.has(bid));
1064
- if (abandoned.length === 0) {
1065
- return abandoned;
1066
- }
1067
- try {
1068
- await this.cancel({ actionId, blockIds: abandoned });
1069
- } catch (cancelError) {
1070
- try { log('WARN: cancel of abandoned sweep blocks failed — pending records may wedge until the node-side sweep lands: %o', cancelError); } catch { /* ignore */ }
1071
- }
1072
- return abandoned;
1073
- }
1074
-
1075
- private async commitBlock(blockId: BlockId, actionId: ActionId, rev: number, tailId?: BlockId, blockDigests?: BlockContentDigests): Promise<CommitResult> {
1076
- const { batches: tailBatches, error: tailError } = await this.commitBlocks({ blockIds: [blockId], actionId, rev, tailId, blockDigests });
1077
- if (tailError) {
1078
- // commit is a pure attempt: stale → { success:false }, transient → throw. Cancellation
1079
- // is the CALLER's responsibility (coordinator cancelPhase; TransactorSource.transact),
1080
- // which owns the retry budget and the committed-vs-pending picture — self-cancelling here
1081
- // would tear down a pend a caller's retry loop is still working against, and double-cancel.
1082
- // Collect and return any active stale failures
1083
- const stale = this.staleFromBatches(tailBatches);
1084
- if (stale) {
1085
- return stale;
1086
- }
1087
- throw tailError;
1088
- }
1089
- return { success: true, durability: mergeDurability(confirmedDurabilities(tailBatches)) };
1090
- }
1091
-
1092
- /**
1093
- * The RETURNED `success:false` responses out of a set of commit batches, merged by
1094
- * {@link refusalFrom}, or `undefined` when every failure was transport-shaped (thrown, no
1095
- * response). Shared by {@link commitBlock} (the tail) and {@link commitTailThenSweep}'s non-tail
1096
- * sweep — both must distinguish a confirmed conflict (return it; the caller cancels and
1097
- * re-drives) from a transient fault (throw / tolerate).
1098
- */
1099
- private staleFromBatches(batches: CoordinatorBatch<BlockId[], CommitResult>[]): StaleFailure | undefined {
1100
- const stale = Array.from(allBatches(batches, b => b.request?.isResponse as boolean && !b.request!.response!.success));
1101
- return stale.length === 0 ? undefined : refusalFrom(stale.map(b => b.request!.response! as StaleFailure));
1102
- }
1103
-
1104
- /**
1105
- * The one place a commit request to a coordinator is built — shared by {@link commitInOneRound}
1106
- * and {@link commitBlocks}. `blockDigests` arrives as the action's FULL declaration map and is
1107
- * narrowed to `blockIds` here, at send time, never up front: each request becomes its own cluster
1108
- * record, so shipping the whole map would make one cohort sign for blocks it is not responsible
1109
- * for; and `processBatches` re-batches failed blocks onto different coordinators, so only a
1110
- * send-time subset stays correct across retries.
1111
- */
1112
- private sendCommit(peerId: PeerId, blockIds: BlockId[], { actionId, rev, tailId, blockDigests }: RepoCommitRequest, expiration: number): Promise<CommitResult> {
1113
- return this.getRepo(peerId).commit(
1114
- { actionId, blockIds, rev, tailId, ...digestsFor(blockDigests, blockIds) },
1115
- { expiration, dialTimeoutMs: this.dialTimeoutMs }
1116
- );
1117
- }
1118
-
1119
- /** Attempts to commit a set of blocks, and handles failures and errors. */
1120
- private async commitBlocks(request: RepoCommitRequest) {
1121
- const { blockIds, actionId, rev } = request;
1122
- const expiration = Date.now() + this.timeoutMs;
1123
- // Thread the transaction's actionId so both the initial batch assembly and any
1124
- // per-block retry re-resolution prefer the coordinator pend already resolved.
1125
- const batches = await this.batchesForPayload<BlockId[], CommitResult>(blockIds, blockIds, mergeBlocks, [], actionId);
1126
- log('commitBlocks actionId=%s rev=%d batches=%d', actionId, rev, batches.length);
1127
- let error: Error | undefined;
1128
- try {
1129
- await processBatches(
1130
- batches,
1131
- (batch) => this.sendCommit(batch.peerId, batch.payload, request, expiration),
1132
- batch => batch.payload,
1133
- mergeBlocks,
1134
- expiration,
1135
- async (blockId, options) => this.resolveCoordinator(blockId, options, actionId)
1136
- );
1137
- } catch (e) {
1138
- error = e as Error;
1139
- }
1140
-
1141
- if (!everyBatch(batches, b => b.request?.isResponse as boolean && b.request!.response!.success)) {
1142
- const details = this.formatBatchStatuses(batches,
1143
- b => {
1144
- const status = b.request == null ? 'no-response' : (b.request.isResponse ? 'non-success' : 'in-flight')
1145
- const resp: any = (b.request as any)?.response;
1146
- const extra = resp && resp.success === false ? (Array.isArray(resp.missing) ? ` missing=${resp.missing.length}` : ' success=false') : '';
1147
- const errMsg = b.request?.isError ? ` cause=${errorMessage(b.request.error)}` : ''
1148
- return `${b.peerId.toString()}[blocks:${b.payload instanceof Array ? (b.payload as any[]).length : 1}](${status})${extra ? ' ' + extra : ''}${errMsg}`
1149
- });
1150
- const rootCause = firstBatchError(batches) ?? error;
1151
- const aggregate = new Error(`Some peers did not complete: ${details}${rootCause ? `; root: ${rootCause.message}` : ''}`);
1152
- (aggregate as any).cause = rootCause;
1153
- error = aggregate;
1154
- }
1155
- return { batches, error };
1156
- };
1157
-
1158
- /** Creates batches for a given payload, grouped by the coordinating peer for each block id */
1159
- private async batchesForPayload<TPayload, TResponse>(
1160
- blockIds: BlockId[],
1161
- payload: TPayload,
1162
- getBlockPayload: (payload: TPayload, blockId: BlockId, mergeWithPayload: TPayload | undefined) => TPayload,
1163
- excludedPeers: PeerId[],
1164
- /** When set, prefer a coordinator this transaction already resolved at pend (see {@link resolveCoordinator}). */
1165
- actionId?: ActionId,
1166
- /** What the batches will be used for. Defaults to `'write'` — see {@link CoordinatorIntent}. */
1167
- intent: CoordinatorIntent = 'write'
1168
- ): Promise<CoordinatorBatch<TPayload, TResponse>[]> {
1169
- return createBatchesForPayload<TPayload, TResponse>(
1170
- blockIds,
1171
- payload,
1172
- getBlockPayload,
1173
- excludedPeers,
1174
- async (blockId, options) => this.resolveCoordinator(blockId, options, actionId, intent)
1175
- );
1176
- }
1177
-
1178
- /**
1179
- * Resolve the coordinator for `blockId`, preferring one this transaction already
1180
- * resolved during pend (the per-transaction cache) before falling back to a live
1181
- * `findCoordinator`. A cached coordinator that is in `excludedPeers` (already tried and
1182
- * failed during a retry) is skipped so a retry can't loop on a dead coordinator. A
1183
- * cache miss — including every call with no `actionId` (get/cancel) — never fails; it
1184
- * always falls through to live resolution.
1185
- */
1186
- private async resolveCoordinator(
1187
- blockId: BlockId,
1188
- options: { excludedPeers: PeerId[] },
1189
- actionId: ActionId | undefined,
1190
- intent: CoordinatorIntent = 'write'
1191
- ): Promise<PeerId> {
1192
- if (actionId !== undefined) {
1193
- const cached = this.txnCoordinatorCache.get(actionId)?.coordinators.get(blockId);
1194
- if (cached && !options.excludedPeers.some(p => p.toString() === cached.toString())) {
1195
- return cached;
1196
- }
1197
- }
1198
- return this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), { ...options, intent });
1199
- }
1200
-
1201
- /**
1202
- * Get (creating if absent) the per-transaction coordinator map for `actionId`,
1203
- * refreshing its expiry and lazily sweeping expired sibling entries. See
1204
- * {@link txnCoordinatorCache} for why the TTL/size cap here is a memory backstop and
1205
- * not a staleness bound.
1206
- */
1207
- private txnCoordinatorsFor(actionId: ActionId): Map<BlockId, PeerId> {
1208
- const now = Date.now();
1209
- // Reclaim entries from transactions that pended but never committed. A live entry is
1210
- // never stale (unique actionId; read only by its own transaction's commit), so
1211
- // sweeping lazily on write is safe.
1212
- for (const [aid, entry] of this.txnCoordinatorCache) {
1213
- if (entry.expires <= now) this.txnCoordinatorCache.delete(aid);
1214
- }
1215
- // Comfortably covers a normal pend→commit gap (~2 op budgets) with a fixed floor;
1216
- // an entry outliving this only loses the optimization (commit re-resolves live),
1217
- // never correctness.
1218
- const ttlMs = Math.max(this.timeoutMs * 2, 60_000);
1219
- const existing = this.txnCoordinatorCache.get(actionId);
1220
- if (existing) {
1221
- existing.expires = now + ttlMs;
1222
- return existing.coordinators;
1223
- }
1224
- const created = { coordinators: new Map<BlockId, PeerId>(), expires: now + ttlMs };
1225
- this.txnCoordinatorCache.set(actionId, created);
1226
- while (this.txnCoordinatorCache.size > NetworkTransactor.MAX_TXN_COORDINATOR_CACHE_ENTRIES) {
1227
- const oldest = this.txnCoordinatorCache.keys().next().value as ActionId | undefined;
1228
- if (oldest == null || oldest === actionId) break;
1229
- this.txnCoordinatorCache.delete(oldest);
1230
- }
1231
- return created.coordinators;
1232
- }
1233
-
1234
- /**
1235
- * Cancels a pending transaction by canceling all blocks associated with the transaction,
1236
- * including failed peers. Seeds the first round from the peers the failed operation actually
1237
- * talked to (a coordinator that answered the pend is the one most likely to be holding the
1238
- * record); every later round re-resolves live. Throws on failure to discharge — see
1239
- * {@link dischargeCancel}.
1240
- *
1241
- * The seed uses each batch's `coordinatingBlockIds` — the full set `consolidateCoordinators`
1242
- * assigned to that peer — not its anchor `blockId` alone. Anchor-only was silently lossy: when
1243
- * consolidation collapsed several blocks onto one coordinator, the non-anchor blocks got no
1244
- * cancel at all. `processBatches`' retry batches carry no `coordinatingBlockIds` and fall back to
1245
- * their anchor, so a retried multi-block batch can still under-cover the seed round;
1246
- * `dischargeCancel`'s per-block outstanding set notices and the next round resolves those live.
1247
- * That residual costs a round, never correctness, and is unreachable on a mesh where every node
1248
- * covers every block — see backlog `debt-no-mesh-fixture-forces-two-coordinator-batches`.
1249
- */
1250
- private async cancelBatch<TPayload, TResponse>(
1251
- batches: CoordinatorBatch<TPayload, TResponse>[],
1252
- actionRef: ActionBlocks,
1253
- ) {
1254
- const operationBatches = makeBatchesByPeer<BlockId[], void>(
1255
- Array.from(allBatches(batches)).flatMap(b => (b.coordinatingBlockIds ?? [b.blockId]).map(bid => [bid, b.peerId] as const)),
1256
- actionRef.blockIds,
1257
- mergeBlocks,
1258
- []
1259
- );
1260
- await this.dischargeCancel(actionRef, operationBatches);
1261
- }
1262
-
1263
- /**
1264
- * Rounds {@link dischargeCancel} will run before giving up, in addition to the
1265
- * `abortOrCancelTimeoutMs` deadline; whichever bound trips first ends the loop.
1266
- *
1267
- * NOTE: accepted tradeoff — the round cap can end the loop well before the deadline. Six rounds
1268
- * means five backoffs, whose pre-jitter values with `baseMs` 50 / `capMs` 500 are 50, 100, 200,
1269
- * 400, 500 ms, each drawn from `(0.5·exp, exp]` — so 0.63–1.25 s of waiting, plus each round's
1270
- * own RPC time (measured end to end: 1054 ms for the dead-transport arm of
1271
- * packages/db-p2p/test/reset-does-not-strand-its-own-pend.spec.ts). That clears a stream reset
1272
- * and reconnect, and against a genuinely dead transport it hands the caller a legible failure in
1273
- * about a second instead of spending its whole (typically 5 s) abort budget issuing RPCs nobody
1274
- * will answer. Raise it if faults longer than that but shorter than the abort budget turn out to
1275
- * strand records in practice.
1276
- */
1277
- private static readonly MAX_CANCEL_ROUNDS = 6;
1278
-
1279
- /**
1280
- * Runs cancel rounds until every block of `actionRef` has had a cancel ANSWERED by some peer, or
1281
- * the budget runs out — and then throws an aggregate naming the action and the blocks whose
1282
- * pending records are still standing.
1283
- *
1284
- * **Why a completeness check.** `processBatches` deliberately never rethrows, so "it returned"
1285
- * says nothing about whether any peer was reached. A block is only discharged once some batch
1286
- * carrying it got a response; anything else leaves its pending record standing, and while it
1287
- * stands `ClusterMember.validatePendOperations` votes reject on every later pend touching the
1288
- * block, from any writer. An application retry loop opens a NEW transaction and so mints a new
1289
- * action id, which is none of the three things that remove a record (client cancel,
1290
- * divergence-shaped commit refusal, forward write of the SAME action id — docs/repository.md),
1291
- * so the write collides with its own predecessor permanently.
1292
- *
1293
- * **Why a TIME-based retry on top of `processBatches`' own.** That one is a PEER retry: it
1294
- * re-homes a failed block onto an alternate coordinator immediately, with no delay. A stream
1295
- * reset is time-shaped, not peer-shaped — every peer is equally unreachable for the length of
1296
- * the fault — so only a delayed re-attempt clears it. Each round rebuilds its batches from
1297
- * scratch, so a re-resolved coordinator is picked up.
1298
- *
1299
- * **Why retrying is safe.** Cancel is idempotent, and the three-timings argument written out in
1300
- * {@link cancelAbandonedSweepBlocks} covers a cancel that races a landing commit. Extra rounds
1301
- * cost latency only. Each round narrows to the blocks still outstanding, so a partially
1302
- * successful round does not re-issue the cancels that already landed.
1303
- *
1304
- * NOTE: a fault that outlasts these bounds still strands the record, and nothing node-side
1305
- * reclaims it. That residual is the backstop tracked in backlog
1306
- * `debt-unpromotable-pending-records-need-a-sweep`.
1307
- *
1308
- * @param seedBatches Batches to use for round 0 only (see {@link cancelBatch}). Omitted → round
1309
- * 0 resolves coordinators live like every later round.
1310
- */
1311
- private async dischargeCancel(
1312
- actionRef: ActionBlocks,
1313
- seedBatches?: CoordinatorBatch<BlockId[], void>[]
1314
- ): Promise<void> {
1315
- let outstanding = Array.from(new Set(actionRef.blockIds));
1316
- if (outstanding.length === 0) {
1317
- return;
1318
- }
1319
- const deadline = Date.now() + this.abortOrCancelTimeoutMs;
1320
- let roundBatches: CoordinatorBatch<BlockId[], void>[] = [];
1321
- let lastError: Error | undefined;
1322
- for (let round = 0; ; ++round) {
1323
- roundBatches = [];
1324
- try {
1325
- // Batch construction can throw (coordinator lookup); `processBatches` cannot.
1326
- roundBatches = round === 0 && seedBatches
1327
- ? seedBatches
1328
- : await this.batchesForPayload<BlockId[], void>(outstanding, outstanding, mergeBlocks, []);
1329
- await processBatches(
1330
- roundBatches,
1331
- (batch) => this.getRepo(batch.peerId).cancel({ actionId: actionRef.actionId, blockIds: batch.payload }, { expiration: deadline, dialTimeoutMs: this.dialTimeoutMs }),
1332
- batch => batch.payload,
1333
- mergeBlocks,
1334
- deadline,
1335
- (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), options)
1336
- );
1337
- } catch (e) {
1338
- lastError = asError(e);
1339
- }
1340
-
1341
- const discharged = dischargedBlocks(roundBatches);
1342
- outstanding = outstanding.filter(bid => !discharged.has(bid));
1343
- if (outstanding.length === 0) {
1344
- if (round > 0) {
1345
- log('cancel:discharged actionId=%s rounds=%d', actionRef.actionId, round + 1);
1346
- }
1347
- return;
1348
- }
1349
-
1350
- const remainingMs = deadline - Date.now();
1351
- if (round + 1 >= NetworkTransactor.MAX_CANCEL_ROUNDS || remainingMs <= 0) {
1352
- break;
1353
- }
1354
- log('cancel:retry actionId=%s round=%d outstanding=%d', actionRef.actionId, round, outstanding.length);
1355
- await abortableDelay(Math.min(jitteredBackoffMs(round, { baseMs: 50, capMs: 500 }), remainingMs));
1356
- }
1357
-
1358
- const details = this.formatBatchStatuses(roundBatches,
1359
- b => {
1360
- const status = b.request == null ? 'no-response' : (b.request.isResponse ? 'responded' : 'in-flight');
1361
- const errMsg = b.request?.isError ? ` cause=${errorMessage(b.request.error)}` : '';
1362
- return `${b.peerId.toString()}[block:${b.blockId}](${status})${errMsg}`;
1363
- });
1364
- const rootCause = firstBatchError(roundBatches) ?? lastError;
1365
- const aggregate = new Error(`Cancel of action ${actionRef.actionId} did not discharge ${outstanding.length} block(s): ${outstanding.join(', ')}`
1366
- + (details ? `; peers: ${details}` : '')
1367
- + (rootCause ? `; root: ${rootCause.message}` : ''));
1368
- (aggregate as any).cause = rootCause;
1369
- (aggregate as AggregateError).errors = rootCause ? [rootCause] : [];
1370
- throw aggregate;
1371
- }
1372
-
1373
- /** Renders the batches worth naming in an aggregate error: the ones that never completed, or —
1374
- * when every batch completed and the aggregate is about a non-success RESPONSE rather than a
1375
- * transport fault — all of them. */
1376
- private formatBatchStatuses<TPayload, TResponse>(
1377
- batches: CoordinatorBatch<TPayload, TResponse>[],
1378
- formatter: (b: CoordinatorBatch<TPayload, TResponse>) => string
1379
- ): string {
1380
- const incompletes = Array.from(incompleteBatches(batches))
1381
- let details = incompletes.map(formatter).join(', ')
1382
- if (details.length === 0) {
1383
- details = Array.from(allBatches(batches)).map(formatter).join(', ')
1384
- }
1385
- return details
1386
- }
1387
- }
1388
-
1389
-
1390
- /**
1391
- * One round of `consolidateCoordinators`' greedy cover: the cohort member covering the most still-uncovered
1392
- * blocks, with the blocks it covers, or undefined when no member covers any.
1393
- *
1394
- * A tie goes to `localPeerId` when it is among the tied members, otherwise to the member seen first. Cohorts
1395
- * arrive in proximity order, so "seen first" is the nearest; without the local preference a node that is in
1396
- * a block's cohort but not nearest would send its own write over the network, and on a network no wider than
1397
- * a cohort (every node in every cohort) that would be nearly every write.
1398
- */
1399
- function bestCoveringPeer(peerBlocks: Map<string, BlockId[]>, uncovered: Set<BlockId>, localPeerId: string | undefined): { peerId: string; covered: BlockId[] } | undefined {
1400
- let best: { peerId: string; covered: BlockId[] } | undefined;
1401
- for (const [peerId, blocks] of peerBlocks) {
1402
- const covered = blocks.filter(bid => uncovered.has(bid));
1403
- if (covered.length === 0) continue;
1404
- const bestCount = best?.covered.length ?? 0;
1405
- if (covered.length > bestCount || (covered.length === bestCount && peerId === localPeerId)) {
1406
- best = { peerId, covered };
1407
- }
1408
- }
1409
- return best;
1410
- }
1411
-
1412
- /**
1413
- * The block ids some batch in the tree got an ANSWER for. A cancel batch that errored, or never
1414
- * responded, discharged nothing — its blocks' pending records are still standing. Batch payloads
1415
- * are block-id lists (built with {@link mergeBlocks}), including the retry batches
1416
- * `processBatches` re-homes, so the union across the whole tree is the discharged set.
1417
- */
1418
- function dischargedBlocks(batches: CoordinatorBatch<BlockId[], void>[]): Set<BlockId> {
1419
- const discharged = new Set<BlockId>();
1420
- for (const b of allBatches(batches, bb => bb.request?.isResponse === true)) {
1421
- for (const bid of b.payload) discharged.add(bid);
1422
- }
1423
- return discharged;
1424
- }
1425
-
1426
- /**
1427
- * The durability report off every commit batch in the tree that answered `success: true` — the
1428
- * coordinators' own answers for the blocks they drove, one per confirmed batch. Retry batches
1429
- * (`subsumedBy`) are included, so a block re-homed after a failed first attempt reports through the
1430
- * peer that actually committed it. Batches that threw or returned a refusal contribute nothing.
1431
- */
1432
- function confirmedDurabilities(batches: CoordinatorBatch<BlockId[], CommitResult>[]): WriteDurability[] {
1433
- return Array.from(allBatches(batches, b => b.request?.isResponse === true && b.request!.response!.success))
1434
- .map(b => (b.request!.response! as CommitSuccess).durability);
1435
- }
1436
-
1437
- /**
1438
- * One {@link StaleFailure} standing for every refused commit response in `responses`, rebuilt the
1439
- * same way {@link NetworkTransactor.pend}'s aggregate is: `reason` is the first one any response gave
1440
- * (the only diagnostic that survives into the coordinator's error text — a refusal whose reason is
1441
- * `commit-not-durable` must not read as "stale commit", a rival's win), `conflict` holds when any
1442
- * response was a classified conflict, and `staleAt` is the highest confirmed revision. A reason-only
1443
- * refusal (no `missing`) comes out with `missing: []` and its reason intact.
1444
- */
1445
- function refusalFrom(responses: StaleFailure[]): StaleFailure {
1446
- const staleAt = highestStaleAt(responses.map(r => r.staleAt));
1447
- const reason = responses.map(r => r.reason).find(r => r !== undefined);
1448
- return {
1449
- missing: distinctBlockActionTransforms(responses.flatMap(r => r.missing).filter((x): x is ActionTransforms => x !== undefined)),
1450
- ...(staleAt === undefined ? {} : { staleAt }),
1451
- ...(reason === undefined ? {} : { reason }),
1452
- conflict: responses.some(isConflictFailure),
1453
- success: false as const
1454
- };
1455
- }
1456
-
1457
- /** The entries of `all` whose ids appear in `batchBlockIds` — the per-batch narrowing both
1458
- * per-block declarations share ({@link digestsFor}, {@link baseRevsFor}). */
1459
- function subsetOf<T>(all: Record<BlockId, T>, batchBlockIds: BlockId[]): Record<BlockId, T> {
1460
- const subset: Record<BlockId, T> = {};
1461
- for (const id of batchBlockIds) {
1462
- const entry = all[id];
1463
- if (entry !== undefined) subset[id] = entry;
1464
- }
1465
- return subset;
1466
- }
1467
-
1468
- /** The subset of `all` whose ids appear in `batchBlockIds`, wrapped (via {@link blockDigestsField})
1469
- * so it spreads to nothing when the batch declares no digests. Called at SEND time, once per attempt,
1470
- * because `processBatches` re-batches failed blocks onto different coordinators — a subset computed
1471
- * up front would follow the wrong batch on retry. */
1472
- function digestsFor(all: BlockContentDigests | undefined, batchBlockIds: BlockId[]): { blockDigests?: BlockContentDigests } {
1473
- return all ? blockDigestsField(subsetOf(all, batchBlockIds)) : {};
1474
- }
1475
-
1476
- /** The pend-side sibling of {@link digestsFor}: the subset of `all` whose ids appear in
1477
- * `batchBlockIds`, wrapped (via {@link baseRevsField}) so it spreads to nothing when no block in the
1478
- * batch names a base. Same send-time rule, for the same reason. */
1479
- function baseRevsFor(all: BlockBaseRevs | undefined, batchBlockIds: BlockId[]): { baseRevs?: BlockBaseRevs } {
1480
- return all ? baseRevsField(subsetOf(all, batchBlockIds)) : {};
1481
- }
1482
-
1483
- /** `action` re-scoped to one coordinator batch: the batch's own transforms, and the bases for the
1484
- * blocks in it alone (see {@link PendRequest.baseRevs}). The action-wide `baseRevs` key is dropped
1485
- * BEFORE the subset is spread, so a batch none of whose blocks names a base carries no key at all
1486
- * rather than the whole action's map — and no cohort signs for a block it is not responsible for. */
1487
- function pendRequestForBatch(action: PendRequest, payload: Transforms): PendRequest {
1488
- const { baseRevs, ...rest } = action;
1489
- return { ...rest, transforms: payload, ...baseRevsFor(baseRevs, blockIdsForTransforms(payload)) };
1490
- }
1491
-
1492
- /**
1493
- * The owning collection id for an action ref, read from any fetched block's header. A
1494
- * committed-then-invalidated action still has a materialized (compensating) block whose header carries
1495
- * the collection id; a genuinely-aborted action has no fetched block, so this returns `undefined` and
1496
- * the status stays `aborted`.
1497
- */
1498
- function collectionIdForRef(ref: ActionBlocks, blockStates: GetBlockResults): CollectionId | undefined {
1499
- for (const blockId of ref.blockIds) {
1500
- const collectionId = blockStates[blockId]?.block?.header.collectionId;
1501
- if (collectionId !== undefined) {
1502
- return collectionId;
1503
- }
1504
- }
1505
- return undefined;
1506
- }
1507
-
1508
- /** Returns a readable message for an unknown error value. */
1509
- function errorMessage(err: unknown): string {
1510
- if (err instanceof Error) return err.message;
1511
- if (err == null) return 'unknown';
1512
- try { return String(err); } catch { return 'unknown'; }
1513
- }
1514
-
1515
- /**
1516
- * Returns the first batch-level error encountered across the batch tree,
1517
- * preferring root batches over retries. Used to preserve the ORIGINAL first-attempt
1518
- * failure reason when constructing aggregate errors — retry lookup failures
1519
- * (e.g., findCoordinator throwing because self is excluded on a solo node) must
1520
- * not shadow the actual root cause.
1521
- */
1522
- function firstBatchError<TPayload, TResponse>(batches: CoordinatorBatch<TPayload, TResponse>[]): Error | undefined {
1523
- // Prefer errors on root batches first
1524
- for (const root of batches) {
1525
- if (root.request?.isError) return asError(root.request.error);
1526
- }
1527
- // Fall back to errors in any retry subtree
1528
- for (const b of allBatches(batches)) {
1529
- if (b.request?.isError) return asError(b.request.error);
1530
- }
1531
- return undefined;
1532
- }
1533
-
1534
- function asError(err: unknown): Error {
1535
- return err instanceof Error ? err : new Error(errorMessage(err));
1536
- }
1537
-
1538
- /**
1539
- * Returns the block actions grouped by action id and concatenated transforms
1540
- */
1541
- export function distinctBlockActionTransforms(blockActions: ActionTransforms[]): ActionTransforms[] {
1542
- const grouped = groupBy(blockActions, ({ actionId }) => actionId);
1543
- return Object.entries(grouped).map(([actionId, actions]) =>
1544
- ({ actionId, transforms: concatTransforms(...actions.map(t => t.transforms)) } as ActionTransforms));
1545
- }
1
+ import { peerIdFromString } from "../network/types.js";
2
+ import type { PeerId } from "../network/types.js";
3
+ import { highestStaleAt, isConflictFailure } from "../network/stale-failure.js";
4
+ import { BlockUnavailableError, BlockPossiblyStaleError } from "../network/struct.js";
5
+ import { mergeDurability, withTornBlocks } from "../network/durability.js";
6
+ import { judgeCohortLineage, type CohortLineage, type MemberLineage } from "../network/lineage.js";
7
+ import type { ActionTransforms, ActionBlocks, ActionLineage, BlockActionStatus, ITransactor, PendSuccess, CommitSuccess, StaleFailure, IKeyNetwork, BlockId, GetBlockResults, PendResult, CommitResult, PendRequest, IRepo, BlockGets, Transforms, CommitRequest, ActionId, RepoCommitRequest, ClusterNomineesResult, CollectionId, IBlock, GetBlockResult, CoordinatorIntent, BlockUnavailableReason, BlockContentDigests, BlockBaseRevs, WriteDurability } from "../index.js";
8
+ import type { IBlockChangeNotifier, CollectionChangeListener } from "./change-notifier.js";
9
+ import { transformForBlockId, concatTransforms, concatTransform, transformsFromTransform, blockIdsForTransforms } from "../transform/helpers.js";
10
+ import { Tracker } from "../transform/tracker.js";
11
+ import { blockDigestsField, baseRevsField } from "../transform/digest.js";
12
+ import { CacheSource } from "../transform/cache-source.js";
13
+ import { TransactorSource, servedRevision } from "./transactor-source.js";
14
+ import { Log } from "../log/log.js";
15
+ import { groupBy } from "../utility/groupby.js";
16
+ import { routingKeyForBlock } from "../network/routing-key.js";
17
+ import { isRecordEmpty } from "../utility/is-record-empty.js";
18
+ import { type CoordinatorBatch, makeBatchesByPeer, incompleteBatches, everyBatch, allBatches, mergeBlocks, processBatches, createBatchesForPayload } from "../utility/batch-coordinator.js";
19
+ import { abortableDelay, jitteredBackoffMs } from "../utility/backoff.js";
20
+ import { createLogger, verbose } from "../logger.js";
21
+
22
+ const log = createLogger('network-transactor');
23
+
24
+ type NetworkTransactorInit = {
25
+ timeoutMs: number;
26
+ abortOrCancelTimeoutMs: number;
27
+ keyNetwork: IKeyNetwork;
28
+ getRepo: (peerId: PeerId) => IRepo;
29
+ /**
30
+ * Per-peer dial deadline in ms applied to each downstream repo call.
31
+ * `timeoutMs` is the overall transaction budget; `dialTimeoutMs` caps how
32
+ * long a single peer can hold that budget hostage during its dial. When a
33
+ * peer is unreachable, the dial fails fast and the batch-retry loop can
34
+ * re-pick a different coordinator within the remaining overall budget.
35
+ * Omit to fall back to a sensible default (3s); set 0 / negative to disable.
36
+ */
37
+ dialTimeoutMs?: number;
38
+ /**
39
+ * Optional local change-notifier (e.g. the hosting node's StorageRepo) used to
40
+ * satisfy {@link IBlockChangeNotifier}. When supplied, `onCollectionChange`
41
+ * delegates to it so consumers can feature-detect change notifications on the
42
+ * transactor they already hold rather than reaching into node internals. When
43
+ * absent, `onCollectionChange` is a logged no-op.
44
+ */
45
+ localChangeNotifier?: IBlockChangeNotifier;
46
+ /**
47
+ * The peer id of the node this transactor runs on, when `getRepo` hands that id the node's own
48
+ * co-located repo rather than a network client — the same "co-located node" idea as
49
+ * `localChangeNotifier`. It only breaks ties when a pend's blocks are grouped onto coordinators:
50
+ * among cohort members covering equally many blocks, this node wins, so a write it is responsible
51
+ * for is coordinated without a network hop. It never wins over a member covering more blocks
52
+ * (fewer batches come first), and it never makes this node a coordinator for a block whose cohort
53
+ * does not include it. Omit when nothing is co-located; ties then go to the member seen first,
54
+ * which is the nearest.
55
+ */
56
+ localPeerId?: PeerId;
57
+ }
58
+
59
+ /**
60
+ * Default per-peer dial deadline. Chosen as a compromise between:
61
+ * - long enough for a typical libp2p dial+TLS handshake on a wired LAN
62
+ * (sub-second) plus reasonable WAN latency, including circuit-relay hops;
63
+ * - short enough that an unreachable cluster member burns ~1/10th of a
64
+ * typical 30s transaction budget before the retry loop moves on.
65
+ */
66
+ const DEFAULT_DIAL_TIMEOUT_MS = 3000;
67
+
68
+ export class NetworkTransactor implements ITransactor, IBlockChangeNotifier {
69
+ private readonly keyNetwork: IKeyNetwork;
70
+ private readonly timeoutMs: number;
71
+ private readonly abortOrCancelTimeoutMs: number;
72
+ private readonly dialTimeoutMs: number | undefined;
73
+ private readonly getRepo: (peerId: PeerId) => IRepo;
74
+ private readonly localChangeNotifier: IBlockChangeNotifier | undefined;
75
+ /** `NetworkTransactorInit.localPeerId` as a string, the form cohort peer ids arrive in. */
76
+ private readonly localPeerId: string | undefined;
77
+
78
+ /**
79
+ * Per-transaction coordinator cache: `actionId → (blockId → resolved coordinator)`.
80
+ * {@link pend} populates it from its final (retry-adjusted) batch assignment; commit
81
+ * reads it via {@link resolveCoordinator} before falling back to a live
82
+ * `findCoordinator`, so a block's coordinator is resolved once per transaction across
83
+ * the pend→commit window instead of once at pend and again at commit.
84
+ *
85
+ * Keyed by `actionId`, which is unique per transaction, so an entry is only ever read
86
+ * by commits of the SAME transaction — the ones that immediately follow its pend. Once
87
+ * those finish, nothing reads the entry again (a later transaction has a fresh
88
+ * actionId), so it carries no cross-transaction staleness even if it lingers. The TTL
89
+ * and size cap in {@link txnCoordinatorsFor} are therefore only a memory backstop that
90
+ * reclaims entries from transactions that pend but never commit — NOT a staleness
91
+ * bound. This is why keying by actionId gives the same "thrown away when the
92
+ * transaction ends" safety as threading a Map through the call, without touching the
93
+ * ITransactor contract.
94
+ */
95
+ private readonly txnCoordinatorCache = new Map<ActionId, { coordinators: Map<BlockId, PeerId>; expires: number }>();
96
+ private static readonly MAX_TXN_COORDINATOR_CACHE_ENTRIES = 1000;
97
+
98
+ constructor(
99
+ init: NetworkTransactorInit,
100
+ ) {
101
+ this.keyNetwork = init.keyNetwork;
102
+ this.timeoutMs = init.timeoutMs;
103
+ this.abortOrCancelTimeoutMs = init.abortOrCancelTimeoutMs;
104
+ // A user explicitly passing 0 or negative means "do not bound dials separately".
105
+ // Undefined falls back to the library default.
106
+ this.dialTimeoutMs = init.dialTimeoutMs === undefined
107
+ ? DEFAULT_DIAL_TIMEOUT_MS
108
+ : (init.dialTimeoutMs > 0 ? init.dialTimeoutMs : undefined);
109
+ this.getRepo = init.getRepo;
110
+ this.localChangeNotifier = init.localChangeNotifier;
111
+ this.localPeerId = init.localPeerId?.toString();
112
+ }
113
+
114
+ /**
115
+ * Subscribe to commits landing on the local node for `collectionId`, delegating
116
+ * to the `localChangeNotifier` supplied at construction. When no notifier was
117
+ * supplied this is a no-op (returns an inert unsubscribe) — a NetworkTransactor
118
+ * with no co-located storage cannot observe commits locally.
119
+ */
120
+ onCollectionChange(collectionId: CollectionId, listener: CollectionChangeListener): () => void {
121
+ if (!this.localChangeNotifier) {
122
+ log('onCollectionChange: no localChangeNotifier configured; subscription is a no-op for collection=%s', collectionId);
123
+ return () => { };
124
+ }
125
+ return this.localChangeNotifier.onCollectionChange(collectionId, listener);
126
+ }
127
+
128
+ async get(blockGets: BlockGets): Promise<GetBlockResults> {
129
+ // Group by block id
130
+ const distinctBlockIds = Array.from(new Set(blockGets.blockIds));
131
+ const t0 = Date.now();
132
+ log('get blockIds=%d', distinctBlockIds.length);
133
+
134
+ // `intent: 'read'` throughout this method: a read that can find no reachable
135
+ // coordinator may still be answered from the local replica (degraded but reported),
136
+ // where a write on the same evidence may not. See CoordinatorIntent.
137
+ const batches = await this.batchesForPayload<BlockId[], GetBlockResults>(
138
+ distinctBlockIds,
139
+ distinctBlockIds,
140
+ (gets, blockId, mergeWithGets) => [...(mergeWithGets ?? []), ...gets.filter(bid => bid === blockId)],
141
+ [],
142
+ undefined,
143
+ 'read'
144
+ );
145
+
146
+ const expiration = Date.now() + this.timeoutMs;
147
+
148
+ let error: Error | undefined;
149
+ try {
150
+ await processBatches(
151
+ batches,
152
+ (batch) => this.getRepo(batch.peerId).get({ blockIds: batch.payload, context: blockGets.context }, { expiration, dialTimeoutMs: this.dialTimeoutMs }),
153
+ batch => batch.payload,
154
+ (gets, blockId, mergeWithGets) => [...(mergeWithGets ?? []), ...gets.filter(bid => bid === blockId)],
155
+ expiration,
156
+ (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), { ...options, intent: 'read' })
157
+ );
158
+ } catch (e) {
159
+ error = e as Error;
160
+ }
161
+
162
+ // Second-chance retry: ONLY for a genuine no-response — a batch with no valid
163
+ // response, a response missing an entry for a requested block id, or an entry
164
+ // flagged `unavailable`. An authoritative "absent" answer (a valid response that
165
+ // carries an entry for every requested block id, even one whose entry has only
166
+ // `state` and no materialized `block`) is FINAL and must not retry. A block that
167
+ // genuinely does not exist yet surfaces as `{ state: {} }` (an entry that is
168
+ // present and unflagged) — retrying it doubles the round-trips on the common
169
+ // createOrOpen "does this block exist?" probe. Cross-member reconciliation for a
170
+ // missing block has already happened one layer down: CoordinatorRepo.get detects
171
+ // `isMissing` and consults cluster peers on every such read before it responds —
172
+ // and when that consult FAILS, the entry now says so via `unavailable` instead of
173
+ // posing as an authoritative absent. So by the time an unflagged absent reaches
174
+ // here there is nothing left for a transactor-level retry to discover, while a
175
+ // flagged entry earns the retry against a different peer that an absent
176
+ // deliberately does not. (The coordinator never remembers an absence across reads:
177
+ // one that did served a just-committed block as never created — GitHub issue #20.)
178
+ // See tickets txn-perf-authoritative-notfound and repo-reports-unavailable-vs-absent.
179
+ const hasValidResponse = (b: CoordinatorBatch<BlockId[], GetBlockResults>) => {
180
+ return b.request?.isResponse === true && b.request.response != null;
181
+ };
182
+
183
+ // Content the CALLER can prove is too old, from the floor it carried on the request
184
+ // (see {@link BlockGets.floors}): the caller walked a log entry saying this block changed at
185
+ // that revision, so anything below it is not the view the read asked for, however current
186
+ // the answering repo honestly believes its copy to be. Only a block-carrying entry can be
187
+ // below a floor — an absent answer is judged by its own rules above, and treating one as
188
+ // below-floor would put the one-round `createOrOpen` probe back on the retry path.
189
+ // Reported here rather than left to the reader: `TransactorSource` reports
190
+ // `collection:block-below-floor` from the MERGED answer, so a read the retry below repaired
191
+ // is the one case that leaves no trace anywhere else — the extra round would show up in a
192
+ // field log as an unexplained second consult. Costs nothing on an unfloored read, which
193
+ // leaves on the first clause.
194
+ const belowFloor = (bid: BlockId, entry: GetBlockResult): boolean => {
195
+ const floor = blockGets.floors?.[bid];
196
+ if (floor === undefined || entry.block == null || servedRevision(entry) >= floor) return false;
197
+ log('get:below-floor blockId=%s served=%d floor=%d', bid, servedRevision(entry), floor);
198
+ return true;
199
+ };
200
+
201
+ // A batch is answered when its response carries an entry for EVERY requested
202
+ // block id and none of those entries carries a doubt marker or falls below the
203
+ // caller's floor. An entry present with only `state` (no `block`) is an
204
+ // authoritative "absent", which counts as answered — not a gap. An `unavailable`
205
+ // entry is the peer saying it could not find out whether the block EXISTS; an
206
+ // `unconfirmedAheadRev` entry is the peer saying it could not confirm the content
207
+ // it served is CURRENT (a cohort claim sits ahead of it, unsettled); a below-floor
208
+ // entry is the CALLER knowing the content is behind a revision it has already seen
209
+ // the log commit. None counts as answered, so each earns the second-chance retry
210
+ // against a different coordinator.
211
+ const isAuthoritative = (b: CoordinatorBatch<BlockId[], GetBlockResults>) => {
212
+ if (!hasValidResponse(b)) return false;
213
+ const resp = b.request!.response! as GetBlockResults;
214
+ return b.payload.every(bid => resp[bid] !== undefined
215
+ && resp[bid]!.unavailable === undefined
216
+ && resp[bid]!.unconfirmedAheadRev === undefined
217
+ && !belowFloor(bid, resp[bid]!));
218
+ };
219
+
220
+ // Retry only genuine no-response / partial-response batches. An authoritative
221
+ // absent answer is not retried.
222
+ // NOTE: a 'cohort-unreachable' entry earns this retry like any other flagged entry,
223
+ // and on a genuinely isolated node the retry re-picks the same node (the
224
+ // findCoordinator:all-excluded path) and repeats the same futile consult. Fine
225
+ // today — one extra bounded consult on an already failing read. If isolated-node
226
+ // read latency ever matters, skip the retry for that reason rather than widening
227
+ // isAuthoritative.
228
+ // This is ONE extra round, not a loop: a below-floor answer that every reachable
229
+ // coordinator repeats survives the merge below as the highest revision anyone
230
+ // served, UNFLAGGED. Deliberate — a log entry is not proof its blocks landed, so a
231
+ // floor no machine can meet may simply describe an abandoned write, in which case
232
+ // the below-floor content is the correct content and every machine agrees on it
233
+ // (see the accepted-tradeoff NOTE at `TransactorSource.mayRetain`). The reader
234
+ // judges it again and returns it uncached.
235
+ const retryable = Array.from(allBatches(batches)).filter(b =>
236
+ !isAuthoritative(b as any)
237
+ ) as CoordinatorBatch<BlockId[], GetBlockResults>[];
238
+
239
+ if (retryable.length > 0 && Date.now() < expiration) {
240
+ log('get:retry retryable=%d', retryable.length);
241
+ // Fan out the per-batch retries concurrently. Each root batch builds its own
242
+ // excluded-peer set and attaches its own `subsumedBy`, so the retry rounds are
243
+ // independent per root and safe to run in parallel.
244
+ const retryOutcomes = await Promise.allSettled(retryable.map(async b => {
245
+ const excluded = new Set<PeerId>([b.peerId, ...((b.excludedPeers ?? []) as PeerId[])]);
246
+ const retries = await createBatchesForPayload<BlockId[], GetBlockResults>(
247
+ b.payload,
248
+ b.payload,
249
+ (gets, blockId, mergeWithGets) => [...(mergeWithGets ?? []), ...gets.filter(id => id === blockId)],
250
+ Array.from(excluded),
251
+ (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), { ...options, intent: 'read' })
252
+ );
253
+ if (retries.length > 0) {
254
+ b.subsumedBy = [...(b.subsumedBy ?? []), ...retries];
255
+ await processBatches(
256
+ retries,
257
+ (batch) => this.getRepo(batch.peerId).get({ blockIds: batch.payload, context: blockGets.context }, { expiration, dialTimeoutMs: this.dialTimeoutMs }),
258
+ batch => batch.payload,
259
+ (gets, blockId, mergeWithGets) => [...(mergeWithGets ?? []), ...gets.filter(id => id === blockId)],
260
+ expiration,
261
+ (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), { ...options, intent: 'read' })
262
+ );
263
+ }
264
+ }));
265
+ // First-error-wins: keep any pre-existing error, otherwise adopt the first
266
+ // rejection across the concurrent retries (retryable order is preserved).
267
+ for (const outcome of retryOutcomes) {
268
+ if (outcome.status === 'rejected' && !error) {
269
+ error = outcome.reason instanceof Error ? outcome.reason : new Error(String(outcome.reason));
270
+ }
271
+ }
272
+ }
273
+
274
+
275
+ // Cache the completed batches that had actual responses (not just coordinator not found)
276
+ const completedBatches = Array.from(allBatches(batches, b => b.request?.isResponse as boolean && !isRecordEmpty(b.request!.response!)));
277
+
278
+ // Ranking per block id: a block the answering repo could confirm is current beats
279
+ // one it marked possibly-behind (`unconfirmedAheadRev`), which beats an
280
+ // authoritative absent, which beats an absent marked possibly-behind (a doubted
281
+ // tombstone), which beats an `unavailable` guess. Content still beats absence at
282
+ // every confidence level, and one peer that positively knows outranks another
283
+ // that could not find out. Without the confirmed-over-unconfirmed split, a stale
284
+ // flagged block and the fresh confirmed block fetched by its own retry round tie
285
+ // — and only strictly-greater rank replaces, so first-arrival (the stale one)
286
+ // would win the very merge the retry exists to fix. Non-object junk ranks below
287
+ // everything so any real entry replaces it.
288
+ // Rank alone does not order two peers that both served content: a confirmed block ranks 6
289
+ // whatever revision it is. Cohort peers were expected to agree — they share the block's
290
+ // revision log, so they agree on the highest committed revision at or below a pin — but a
291
+ // peer inside its read-repair window answers from its own copy without consulting anyone,
292
+ // and two cohort members answered one pinned read at revisions 6 and 7. Since only a
293
+ // strictly greater rank replaces, first arrival (the stale one) would win the very merge a
294
+ // below-floor retry exists to fix. So equally-ranked entries that BOTH carry a block break
295
+ // the tie on the newer content, measured by `servedRevision` — the same number the floor is
296
+ // judged against and the same number the reader records as its read dependency, so the
297
+ // merge cannot prefer one revision while the reader believes it read another. The tie-break
298
+ // is deliberately inside a rank rather than across ranks: a confirmed older block still
299
+ // beats an unconfirmed newer one, because "the peer could not confirm this is current" is
300
+ // a statement about the ANSWER, not about the revision, and adopting the unconfirmed one
301
+ // would re-open the doubt the rank split exists to resolve.
302
+ // `unavailable` answers rank among THEMSELVES by how much they establish, so the merged
303
+ // entry never presents a weaker doubt than some peer actually returned. This matters
304
+ // because the reason travels out verbatim on `BlockUnavailableError` and callers act on
305
+ // it: 'cohort-unreachable' is the one reason a caller may treat permissively (the
306
+ // answering node reached nobody, so its own view is all it has), and a partitioned
307
+ // coordinator answering first must not mask a well-connected one that positively
308
+ // established the block EXISTS ('claimed-elsewhere', or 'unmaterializable' — records
309
+ // held here). 'peers-unreachable' sits between: it establishes that some of the cohort
310
+ // was reachable, without settling existence.
311
+ const unavailableRank = (reason: BlockUnavailableReason): number =>
312
+ reason === 'cohort-unreachable' ? 0 : reason === 'peers-unreachable' ? 1 : 2;
313
+ const rankOf = (r: unknown): number => {
314
+ if (!r || typeof r !== 'object') return -1;
315
+ const entry = r as GetBlockResults[BlockId];
316
+ if (entry.block != null) return entry.unconfirmedAheadRev === undefined ? 6 : 5;
317
+ if (entry.unavailable !== undefined) return unavailableRank(entry.unavailable);
318
+ return entry.unconfirmedAheadRev === undefined ? 4 : 3;
319
+ };
320
+ const carriesBlock = (r: unknown): r is GetBlockResult =>
321
+ !!r && typeof r === 'object' && (r as GetBlockResult).block != null;
322
+ /** Whether `candidate` displaces the entry already held for the same block: a strictly
323
+ * better rank, or — at equal rank, both carrying content — strictly newer content.
324
+ *
325
+ * NOTE: `servedRevision` falls back to `state.latest` for a producer that omits
326
+ * `materialized`, and on a PINNED read that fallback overstates — `state.latest` is the
327
+ * newest revision the repo holds, not the revision it served. Every in-tree producer
328
+ * populates `materialized` (`StorageRepo`, `TestTransactor`; `CoordinatorRepo` forwards it
329
+ * verbatim), so the fallback only reaches a third-party `IRepo`, and `belowFloor` above
330
+ * reads the same number, so the two stay consistent. If such a repo ever answers pinned
331
+ * reads beside one that does report `materialized`, it can win this tie with a number
332
+ * describing content it did not serve: cap the comparison at `blockGets.context.rev` then
333
+ * (a correct answer to a pinned read is never above the pin), in both places at once.
334
+ *
335
+ * NOTE: `servedRevision` also reads `state`, which the type requires but a decoded wire
336
+ * response could still omit. Ranking never touched it, so an entry like that used to fault
337
+ * only the reader of ITS block; it now faults the whole `get`, siblings included. Left
338
+ * alone because the reader called `servedRevision` on such an entry anyway — this widens
339
+ * the blast radius, it does not create the fault. If a third-party `IRepo` ever makes it
340
+ * real, make `servedRevision` tolerate a missing `state` rather than guarding here. */
341
+ const beats = (candidate: unknown, held: unknown): boolean => {
342
+ const byRank = rankOf(candidate) - rankOf(held);
343
+ return byRank !== 0
344
+ ? byRank > 0
345
+ : carriesBlock(candidate) && carriesBlock(held) && servedRevision(candidate) > servedRevision(held);
346
+ };
347
+
348
+ // Create a lookup map from successful responses only
349
+ const resultEntries = new Map<string, any>();
350
+ for (const batch of completedBatches) {
351
+ const resp = batch.request!.response! as any;
352
+ for (const [bid, res] of Object.entries(resp)) {
353
+ const existing = resultEntries.get(bid);
354
+ if (!existing || beats(res, existing)) {
355
+ resultEntries.set(bid, res);
356
+ }
357
+ }
358
+ }
359
+ // Ensure we have at least one response per requested block id
360
+ const missingIds = distinctBlockIds.filter(bid => !resultEntries.has(bid));
361
+ if (missingIds.length > 0) {
362
+ log('get:missing blockIds=%o', missingIds);
363
+ const details = this.formatBatchStatuses(batches,
364
+ b => {
365
+ const status = b.request == null ? 'no-response' : (b.request.isResponse ? 'response' : 'in-flight')
366
+ const errMsg = b.request?.isError ? ` cause=${errorMessage(b.request.error)}` : ''
367
+ return `${b.peerId.toString()}[block:${b.blockId}](${status})${errMsg}`
368
+ });
369
+ const rootCause = firstBatchError(batches) ?? error;
370
+ const aggregate = new Error(`Some peers did not complete: ${details}${rootCause ? `; root: ${rootCause.message}` : ''}`);
371
+ (aggregate as any).cause = rootCause;
372
+ throw aggregate;
373
+ }
374
+
375
+ log('get:done blockIds=%d ms=%d', distinctBlockIds.length, Date.now() - t0);
376
+ return Object.fromEntries(resultEntries) as GetBlockResults;
377
+ }
378
+
379
+ async getStatus(blockActions: ActionBlocks[]): Promise<BlockActionStatus[]> {
380
+ // Collect all unique block IDs across all action refs
381
+ const allBlockIds = [...new Set(blockActions.flatMap(ref => ref.blockIds))];
382
+
383
+ if (allBlockIds.length === 0) {
384
+ return blockActions.map(ref => ({ ...ref, statuses: [] }));
385
+ }
386
+
387
+ // Get block states from repos
388
+ const blockStates = await this.get({ blockIds: allBlockIds });
389
+
390
+ // A block whose repo could not determine whether it exists carries no status either:
391
+ // its empty `state` would read below as `aborted`, turning "I could not find out" into
392
+ // a definite verdict on someone's action. Fail loudly instead, like every other read of
393
+ // an unavailable block (see BlockUnavailableError). The same goes for a state the repo
394
+ // could not confirm is CURRENT (`unconfirmedAheadRev`, surviving the retry round above):
395
+ // an action committed at the claimed-ahead revision would read out of the stale state as
396
+ // a definite `aborted` — this read is unpinned, so the doubt always applies.
397
+ for (const blockId of allBlockIds) {
398
+ const entry = blockStates[blockId];
399
+ if (entry?.unavailable !== undefined && entry.block == null) {
400
+ throw new BlockUnavailableError(blockId, entry.unavailable);
401
+ }
402
+ if (entry?.unconfirmedAheadRev !== undefined) {
403
+ throw new BlockPossiblyStaleError(blockId, entry.unconfirmedAheadRev);
404
+ }
405
+ }
406
+
407
+ // Determine status for each action ref
408
+ const results: BlockActionStatus[] = blockActions.map(ref => ({
409
+ ...ref,
410
+ statuses: ref.blockIds.map(blockId => {
411
+ const result = blockStates[blockId];
412
+ if (!result) {
413
+ return 'aborted';
414
+ }
415
+ const { state } = result;
416
+ if (state.pendings?.includes(ref.actionId)) {
417
+ return 'pending';
418
+ }
419
+ if (state.latest?.actionId === ref.actionId) {
420
+ return 'committed';
421
+ }
422
+ // Neither pending nor the latest committed. Block state alone calls this `aborted`, but a
423
+ // committed action that was later durably **invalidated** also presents this way — the
424
+ // compensating revision is now the block's latest, so the original action is no longer it.
425
+ // The `refineInvalidatedStatuses` pass below disambiguates from the authoritative log.
426
+ return 'aborted';
427
+ })
428
+ }));
429
+
430
+ // Authoritative `committed-invalidated` from durable state: consult each affected collection's
431
+ // log for an InvalidationEntry against the queried action (survives a node restart — the in-memory
432
+ // dispute map is only a fast cache; the log is the source of truth). Only `aborted` slots are
433
+ // ambiguous, so this is a no-op for ordinary pending/committed queries.
434
+ await this.refineInvalidatedStatuses(results, blockStates);
435
+ return results;
436
+ }
437
+
438
+ /**
439
+ * Refine the otherwise-`aborted` statuses to `committed-invalidated` for any queried action that has a
440
+ * durable {@link import("../log/struct.js").InvalidationEntry} against it. Reads the collection log via
441
+ * {@link Log.findInvalidation} — the durable, restart-surviving source of truth (`docs/right-is-right.md`
442
+ * §Durable Invalidation) — rather than the per-node, in-memory dispute map. A `pending` slot is left
443
+ * untouched: a still-pending transaction whose base was invalidated will be rejected on its own
444
+ * validation ("pending → will-be-rejected"), which is not the same as `committed-invalidated`.
445
+ *
446
+ * Best-effort and isolated: a log-open/read fault leaves the slot `aborted` (logged) rather than
447
+ * failing the whole status query. The per-call caches keep one log open and one lookup per
448
+ * `(collection, action)` even when many refs share a collection.
449
+ */
450
+ private async refineInvalidatedStatuses(results: BlockActionStatus[], blockStates: GetBlockResults): Promise<void> {
451
+ const logByCollection = new Map<CollectionId, Log<unknown> | undefined>();
452
+ const invalidatedByKey = new Map<string, boolean>();
453
+
454
+ for (const ref of results) {
455
+ if (!ref.statuses.some(status => status === 'aborted')) {
456
+ continue; // no ambiguous slot — an invalidation could not change this ref's answer
457
+ }
458
+ const collectionId = collectionIdForRef(ref, blockStates);
459
+ if (collectionId === undefined) {
460
+ continue; // genuinely aborted: no fetched block to anchor a collection log on
461
+ }
462
+ const key = `${collectionId} ${ref.actionId}`;
463
+ let invalidated = invalidatedByKey.get(key);
464
+ if (invalidated === undefined) {
465
+ invalidated = await this.hasDurableInvalidation(collectionId, ref.actionId, logByCollection);
466
+ invalidatedByKey.set(key, invalidated);
467
+ }
468
+ if (!invalidated) {
469
+ continue;
470
+ }
471
+ for (let i = 0; i < ref.statuses.length; i++) {
472
+ if (ref.statuses[i] === 'aborted') {
473
+ ref.statuses[i] = 'committed-invalidated';
474
+ }
475
+ }
476
+ }
477
+ }
478
+
479
+ /** Whether `actionId` has a durable invalidation entry in `collectionId`'s log (opened once, cached). */
480
+ private async hasDurableInvalidation(
481
+ collectionId: CollectionId,
482
+ actionId: ActionId,
483
+ logByCollection: Map<CollectionId, Log<unknown> | undefined>,
484
+ ): Promise<boolean> {
485
+ try {
486
+ let collectionLog = logByCollection.get(collectionId);
487
+ if (!logByCollection.has(collectionId)) {
488
+ const source = new TransactorSource<IBlock>(collectionId, this, undefined);
489
+ const tracker = new Tracker<IBlock>(new CacheSource<IBlock>(source));
490
+ collectionLog = await Log.open<unknown>(tracker, collectionId);
491
+ logByCollection.set(collectionId, collectionLog);
492
+ }
493
+ if (!collectionLog) {
494
+ return false;
495
+ }
496
+ return (await collectionLog.findInvalidation(actionId)) !== undefined;
497
+ } catch (err) {
498
+ log('getStatus: durable invalidation lookup failed collection=%s action=%s: %o', collectionId, actionId, err);
499
+ return false;
500
+ }
501
+ }
502
+
503
+ /**
504
+ * See {@link ITransactor.getLineage}. Asks EVERY member of each block's cohort, directly, and
505
+ * folds their answers with {@link judgeCohortLineage} — not the coordinator round {@link get}
506
+ * runs, because no single member can answer for the cohort: a member that took a later revision
507
+ * as a replica cannot say what it was built from, while the member it came from can.
508
+ *
509
+ * The per-member `get` carries no context, so it pins nothing and promotes nothing; asking is
510
+ * never what makes a write land.
511
+ *
512
+ * NOTE: one request per cohort member per block. Reached only when a writer's own half-landed
513
+ * write was refused as superseded, which is rare, so the fan-out is not batched by member. If a
514
+ * write path ever calls this routinely, group the blocks a member is in the cohort of into one
515
+ * request per member.
516
+ */
517
+ async getLineage(ref: ActionBlocks & { rev: number }): Promise<ActionLineage> {
518
+ const target = { actionId: ref.actionId, rev: ref.rev };
519
+ const expiration = Date.now() + this.timeoutMs;
520
+ const answers = await Promise.all(ref.blockIds.map(blockId => this.cohortLineage(blockId, target, expiration)));
521
+ const durabilities = answers.flatMap(answer => answer.durability === undefined ? [] : [answer.durability]);
522
+ const saved = answers.length > 0 && durabilities.length === answers.length;
523
+ log('getLineage actionId=%s rev=%d blocks=%o', ref.actionId, ref.rev, answers.map(answer => answer.lineage));
524
+ return {
525
+ blocks: answers.map(answer => answer.lineage),
526
+ ...(saved ? { durability: mergeDurability(durabilities) } : {})
527
+ };
528
+ }
529
+
530
+ /** One block's cohort answer: every member asked in parallel, a member that cannot be reached
531
+ * (or whose cohort cannot be resolved at all) counted as `unknown` rather than left out. */
532
+ private async cohortLineage(blockId: BlockId, target: { actionId: ActionId; rev: number }, expiration: number): Promise<CohortLineage> {
533
+ let cohort: string[];
534
+ try {
535
+ cohort = Object.keys(await this.keyNetwork.findCluster(routingKeyForBlock(blockId)));
536
+ } catch (err) {
537
+ log('getLineage:cohort-unresolved blockId=%s error=%s', blockId, errorMessage(err));
538
+ return { lineage: 'unknown' };
539
+ }
540
+ const members = await Promise.all(cohort.map(async (peerId): Promise<MemberLineage> => {
541
+ try {
542
+ const results = await this.getRepo(peerIdFromString(peerId)).get(
543
+ { blockIds: [blockId], lineageOf: target }, { expiration, dialTimeoutMs: this.dialTimeoutMs });
544
+ const entry = results?.[blockId];
545
+ return { peerId, lineage: entry?.lineage ?? 'unknown', ...(entry?.state?.latest ? { latest: entry.state.latest } : {}) };
546
+ } catch (err) {
547
+ log('getLineage:member-silent blockId=%s peer=%s error=%s', blockId, peerId, errorMessage(err));
548
+ return { peerId, lineage: 'unknown' };
549
+ }
550
+ }));
551
+ return judgeCohortLineage(members);
552
+ }
553
+
554
+ private async consolidateCoordinators(
555
+ blockIds: BlockId[],
556
+ transforms: Transforms,
557
+ transformForBlock: (payload: Transforms, blockId: BlockId, mergeWith?: Transforms) => Transforms
558
+ ): Promise<CoordinatorBatch<Transforms, PendResult>[]> {
559
+ // Use cluster intersections to minimize the number of coordinators.
560
+ // For each block, find its full cluster, then greedily assign blocks to
561
+ // peers that appear in the most clusters — reducing round trips when
562
+ // blocks share cluster members.
563
+
564
+ // Step 1: Get cluster peer sets for each block
565
+ const blockClusterPeerIds: Map<BlockId, Set<string>> = new Map();
566
+ const fallbackBlocks: BlockId[] = [];
567
+
568
+ await Promise.all(blockIds.map(async bid => {
569
+ try {
570
+ const clusterPeers = await this.keyNetwork.findCluster(routingKeyForBlock(bid));
571
+ blockClusterPeerIds.set(bid, new Set(Object.keys(clusterPeers)));
572
+ } catch {
573
+ fallbackBlocks.push(bid);
574
+ }
575
+ }));
576
+
577
+ // Step 2: Build peer → blocks index (which blocks each peer can coordinate)
578
+ const peerBlocks = new Map<string, BlockId[]>();
579
+ for (const [blockId, peerIds] of blockClusterPeerIds) {
580
+ for (const peerId of peerIds) {
581
+ const blocks = peerBlocks.get(peerId) ?? [];
582
+ blocks.push(blockId);
583
+ peerBlocks.set(peerId, blocks);
584
+ }
585
+ }
586
+
587
+ // Step 3: Greedy set cover — assign blocks to peers covering the most uncovered blocks
588
+ const uncovered = new Set(blockClusterPeerIds.keys());
589
+ const assignments = new Map<string, BlockId[]>(); // peerIdStr → assigned blockIds
590
+
591
+ while (uncovered.size > 0) {
592
+ const best = bestCoveringPeer(peerBlocks, uncovered, this.localPeerId);
593
+ if (!best) break;
594
+ assignments.set(best.peerId, best.covered);
595
+ for (const bid of best.covered) uncovered.delete(bid);
596
+ }
597
+
598
+ // Step 4: Any remaining uncovered blocks fall back to findCoordinator
599
+ for (const bid of uncovered) fallbackBlocks.push(bid);
600
+
601
+ const fallbackCoordinators = await Promise.all(
602
+ fallbackBlocks.map(async bid => ({
603
+ blockId: bid,
604
+ coordinator: await this.keyNetwork.findCoordinator(routingKeyForBlock(bid), { excludedPeers: [] })
605
+ }))
606
+ );
607
+ for (const { blockId, coordinator } of fallbackCoordinators) {
608
+ const key = coordinator.toString();
609
+ const existing = assignments.get(key) ?? [];
610
+ existing.push(blockId);
611
+ assignments.set(key, existing);
612
+ }
613
+
614
+ // Step 5: Convert assignments to batches
615
+ const batches: CoordinatorBatch<Transforms, PendResult>[] = [];
616
+ for (const [peerIdStr, consolidatedBlocks] of assignments) {
617
+ const peerId = peerIdFromString(peerIdStr);
618
+
619
+ let batchTransforms: Transforms = { inserts: {}, updates: {}, deletes: [] };
620
+ for (const bid of consolidatedBlocks) {
621
+ const blockTransforms = transformForBlock(transforms, bid, batchTransforms);
622
+ batchTransforms = blockTransforms;
623
+ }
624
+
625
+ batches.push({
626
+ peerId,
627
+ payload: batchTransforms,
628
+ blockId: consolidatedBlocks[0]!,
629
+ coordinatingBlockIds: consolidatedBlocks,
630
+ excludedPeers: []
631
+ });
632
+ }
633
+
634
+ return batches;
635
+ }
636
+
637
+ async pend(blockAction: PendRequest): Promise<PendResult> {
638
+ const t0 = Date.now();
639
+ const transformForBlock = (payload: Transforms, blockId: BlockId, mergeWithPayload: Transforms | undefined): Transforms => {
640
+ const filteredTransform = transformForBlockId(payload, blockId);
641
+ return mergeWithPayload
642
+ ? concatTransform(mergeWithPayload, blockId, filteredTransform)
643
+ : transformsFromTransform(filteredTransform, blockId);
644
+ };
645
+ const blockIds = blockIdsForTransforms(blockAction.transforms);
646
+ const batches = await this.consolidateCoordinators(blockIds, blockAction.transforms, transformForBlock);
647
+ log('pend actionId=%s blockIds=%d batches=%d', blockAction.actionId, blockIds.length, batches.length);
648
+ if (verbose) {
649
+ const batchSummary = batches.map(b => ({
650
+ peer: b.peerId.toString().substring(0, 12),
651
+ blocks: b.coordinatingBlockIds ?? [b.blockId],
652
+ inserts: Object.keys(b.payload.inserts ?? {}).length,
653
+ updates: Object.keys(b.payload.updates ?? {}).length,
654
+ deletes: b.payload.deletes?.length ?? 0
655
+ }));
656
+ log('pend:batches actionId=%s detail=%o', blockAction.actionId, batchSummary);
657
+ }
658
+ const expiration = Date.now() + this.timeoutMs;
659
+
660
+ let error: Error | undefined;
661
+ try {
662
+ // Process all batches, noting all outstanding peers
663
+ await processBatches(
664
+ batches,
665
+ (batch) => this.getRepo(batch.peerId).pend(
666
+ pendRequestForBatch(blockAction, batch.payload),
667
+ {
668
+ expiration,
669
+ dialTimeoutMs: this.dialTimeoutMs,
670
+ coordinatingBlockIds: batch.coordinatingBlockIds
671
+ }
672
+ ),
673
+ batch => blockIdsForTransforms(batch.payload),
674
+ transformForBlock,
675
+ expiration,
676
+ (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), options)
677
+ );
678
+ // Cache resolved coordinators for follow-up commit to hit the same peers
679
+ try {
680
+ for (const b of Array.from(allBatches(batches))) {
681
+ this.keyNetwork.recordCoordinator?.(routingKeyForBlock(b.blockId), b.peerId);
682
+ }
683
+ } catch (e) { log('WARN: Failed to record coordinator hint %o', e); }
684
+ } catch (e) {
685
+ error = e as Error;
686
+ }
687
+
688
+ if (!everyBatch(batches, b => b.request?.isResponse as boolean && b.request!.response!.success)) {
689
+ const details = this.formatBatchStatuses(batches,
690
+ b => {
691
+ const status = b.request == null ? 'no-response' : (b.request.isResponse ? 'non-success' : 'in-flight')
692
+ const errMsg = b.request?.isError ? ` cause=${errorMessage(b.request.error)}` : ''
693
+ return `${b.peerId.toString()}[block:${b.blockId}](${status})${errMsg}`
694
+ });
695
+ // Prefer the first-attempt per-batch error over any outer `error` so the root cause
696
+ // surfaced in the aggregate message is the actual coordinator failure, not any
697
+ // downstream "no coordinator available" thrown by retry lookup.
698
+ const rootCause = firstBatchError(batches) ?? error;
699
+ const aggregate = new Error(`Some peers did not complete: ${details}${rootCause ? `; root: ${rootCause.message}` : ''}`);
700
+ (aggregate as any).cause = rootCause;
701
+ (aggregate as AggregateError).errors = rootCause ? [rootCause] : [];
702
+ error = aggregate;
703
+ }
704
+
705
+ if (error) { // If any failures, discharge every pending record this pend left behind
706
+ log('pend:cancel actionId=%s', blockAction.actionId);
707
+ // AWAITED, not fired off as a background microtask. Returning before the cancel lands means
708
+ // a caller that retries immediately meets its own still-standing pending record and burns a
709
+ // whole attempt out of its retry budget on it (measured: the attempt after a lost pend reply
710
+ // was rejected by its own record, and only the one after that landed).
711
+ // The tradeoff, stated: a losing pend now pays a cancel round-trip before it returns its
712
+ // StaleFailure, where before it returned at once and cleaned up behind itself. That is the
713
+ // right trade — the old shape spent one of the CALLER's retries instead of one round-trip.
714
+ // The catch matters now that `cancelBatch` is checked and throwable: a cancel that could not
715
+ // discharge must be reported, but must not replace the pend verdict below (the StaleFailure
716
+ // the caller reads via `isConflictFailure` to decide to rebase, or the original error).
717
+ try {
718
+ await this.cancelBatch(batches, { blockIds, actionId: blockAction.actionId });
719
+ } catch (cancelError) {
720
+ log('WARN: cancel after pend failure did not discharge: %o', cancelError);
721
+ }
722
+ const stale = Array.from(allBatches(batches, b => b.request?.isResponse as boolean && !b.request!.response!.success));
723
+ if (stale.length > 0) { // Any active stale failures should preempt reporting connection or other potential transient errors (we have information)
724
+ log('pend:stale actionId=%s staleCount=%d', blockAction.actionId, stale.length);
725
+ // Carry the first available reject reason through: `SyncRetryExhaustedError.lastReason`
726
+ // and the multi-collection writer's failure message both read it, and it is the only
727
+ // diagnostic that survives an exhausted retry budget.
728
+ const reason = stale.map(b => (b.request!.response! as StaleFailure).reason).find(r => r !== undefined);
729
+ // This response is REBUILT from the per-batch ones rather than forwarded, so
730
+ // retryability has to be carried explicitly or it is lost: a batch whose failure was
731
+ // a confirmed lost race can arrive with neither `missing` nor `pending` (see
732
+ // CoordinatorRepo.classifyStaleRejection), and the aggregate would then look like a
733
+ // hard rejection to `isConflictFailure`. Any conflicting batch makes the aggregate a
734
+ // conflict — the pend failed as a whole, and a re-read/rebase can clear it.
735
+ // NOTE: `some`, not `every`, so a pend whose batches mix a lost race with a genuine hard
736
+ // rejection is reported retryable and burns its (bounded, backed-off) retry budget before
737
+ // failing. Deliberate: an unclassified reason-only response from an older peer is
738
+ // indistinguishable from a hard rejection here, and `every` would refuse to retry a real
739
+ // race whenever one batch came from such a peer. Revisit if every producer sets `conflict`
740
+ // (then `every` is both safe and tighter), or if mixed-outcome pends show up as wasted
741
+ // retry latency in practice.
742
+ const conflict = stale.some(b => isConflictFailure(b.request!.response! as StaleFailure));
743
+ // Deliberately NOT first-wins like `reason` above — `highestStaleAt` takes the largest
744
+ // confirmed revision, which is the binding constraint on the client's next request.
745
+ // Its doc comment carries the rule and the one-pend-one-collection assumption it rests on.
746
+ const staleAt = highestStaleAt(stale.map(b => (b.request!.response! as StaleFailure).staleAt));
747
+ return {
748
+ success: false,
749
+ conflict,
750
+ ...(reason === undefined ? {} : { reason }),
751
+ ...(staleAt === undefined ? {} : { staleAt }),
752
+ missing: distinctBlockActionTransforms(stale.flatMap(b => (b.request!.response! as StaleFailure).missing).filter((x): x is ActionTransforms => x !== undefined)),
753
+ };
754
+ }
755
+ throw error; // No stale failures, report the original error
756
+ }
757
+
758
+ // Collect replies back into result structure
759
+ const completed = Array.from(allBatches(batches, b => b.request?.isResponse as boolean && b.request!.response!.success));
760
+
761
+ // Seed the per-transaction coordinator cache from the final (retry-adjusted) batch
762
+ // assignment so the follow-up commit reuses pend's resolution without a fresh
763
+ // findCoordinator round or a hop through the optional recordCoordinator hint. We read
764
+ // blockIdsForTransforms(b.payload) rather than the anchor b.blockId so EVERY block a
765
+ // consolidated batch coordinates is recorded — and against the peer that actually
766
+ // pended it, since a block re-homed by a retry lands in the retry batch's payload.
767
+ // NOTE: this cache assumes cluster membership is stable for the transaction's
768
+ // lifetime — the coordinator resolved here is reused verbatim at commit. Transactions
769
+ // are short, so that holds today. If a future change lets clusters churn *within* a
770
+ // single transaction (e.g. very long-running commits), a cached coordinator could
771
+ // point at a peer no longer in the cohort; commit self-heals (a failed cached peer is
772
+ // excluded and re-resolved live by processBatches), at the cost of one wasted round-trip.
773
+ const txnCoordinators = this.txnCoordinatorsFor(blockAction.actionId);
774
+ for (const b of completed) {
775
+ for (const bid of blockIdsForTransforms(b.payload)) {
776
+ txnCoordinators.set(bid, b.peerId);
777
+ }
778
+ }
779
+
780
+ log('pend:done actionId=%s ms=%d batches=%d', blockAction.actionId, Date.now() - t0, batches.length);
781
+ return {
782
+ success: true,
783
+ pending: completed.flatMap(b => (b.request!.response! as PendSuccess).pending),
784
+ blockIds: blockIdsForTransforms(blockAction.transforms),
785
+ // The weakest coordinator's answer is the action's answer (`mergeDurability`). A pend has
786
+ // no torn case: a batch that did not succeed fails the whole pend above.
787
+ // NOTE: a pend naming NO blocks now throws here (`mergeDurability` refuses an empty input rather
788
+ // than fabricate a class), where it used to answer success. No caller produces one today —
789
+ // `Collection.sync` skips an empty change set, and the multi-collection coordinator pends only
790
+ // collections that appended a log entry. If one ever appears, decide what an empty write's
791
+ // durability means at that caller; do not make the merge invent one.
792
+ durability: mergeDurability(completed.map(b => (b.request!.response! as PendSuccess).durability))
793
+ };
794
+ }
795
+
796
+ /**
797
+ * Discharges every pending record `actionRef` left behind, and THROWS if it could not.
798
+ *
799
+ * Cancel is the only removal path a client controls (see docs/repository.md, "a pending record's
800
+ * lifetime is bounded by its writer"), so a cancel that silently did nothing wedges the block
801
+ * against every later writer. `processBatches` never rethrows — it records each batch's outcome
802
+ * and swallows the rejection — so a cancel in which every peer's RPC failed used to return
803
+ * normally, and each of this method's callers read "returned" as "discharged". It now checks
804
+ * completeness and rides out a transient fault, exactly as {@link pend} and {@link commitBlocks}
805
+ * already do for their own rounds. See {@link dischargeCancel} for the loop and its bounds.
806
+ */
807
+ async cancel(actionRef: ActionBlocks): Promise<void> {
808
+ log('cancel actionId=%s blockIds=%d', actionRef.actionId, actionRef.blockIds.length);
809
+ await this.dischargeCancel(actionRef);
810
+ }
811
+
812
+ async queryClusterNominees(blockId: BlockId): Promise<ClusterNomineesResult> {
813
+ const routingKey = routingKeyForBlock(blockId);
814
+ const clusterPeers = await this.keyNetwork.findCluster(routingKey);
815
+ const nominees = Object.keys(clusterPeers).map(idStr => peerIdFromString(idStr));
816
+ return { nominees };
817
+ }
818
+
819
+ /**
820
+ * Commits the action: its log tail, then every other block it touched (the header included, when
821
+ * the action touches it).
822
+ *
823
+ * `request.tailId` is threaded into every per-block commit so the coordinator carries it into the
824
+ * consensus commit op → each committing node's StorageRepo.commit stamps it onto the emitted
825
+ * CollectionChangeEvent (the reactivity topic anchor). Without this the per-block RepoCommitRequest
826
+ * drops the collection tail and reactivity origination is gated off (undefined tail → non-member).
827
+ * `request.blockDigests` (when present) is the FULL per-block declaration map for the action; it is
828
+ * narrowed to each request's own blocks at send time ({@link sendCommit}) so each cohort only signs
829
+ * for the blocks it is actually driving.
830
+ *
831
+ * **One round when one coordinator covers every block** ({@link commitInOneRound}) — always the
832
+ * case in small groups, where `consolidateCoordinators` collapses the pend onto one peer. Otherwise,
833
+ * or when that round throws, **two**: the tail, then the rest ({@link commitTailThenSweep}).
834
+ *
835
+ * Either way the guarantee `Collection.bootstrapContext` rests on holds: no member commits a
836
+ * non-tail block of the action without its tail. In one round it holds because every member's
837
+ * `StorageRepo.commit` applies the tail first and stops at the first failure; in two, because the
838
+ * sweep starts only once the tail round was acknowledged.
839
+ */
840
+ async commit(request: CommitRequest): Promise<CommitResult> {
841
+ const t0 = Date.now();
842
+ log('commit actionId=%s rev=%d blockIds=%d', request.actionId, request.rev, request.blockIds.length);
843
+ const remainingBlocks = Array.from(new Set(request.blockIds)).filter(bid => bid !== request.tailId);
844
+ // An action touching only its tail has nothing to combine: its single round IS the tail round,
845
+ // with the tail round's retries.
846
+ if (remainingBlocks.length > 0) {
847
+ const result = await this.commitInOneRound(request, remainingBlocks);
848
+ if (result) {
849
+ log('commit:done actionId=%s ms=%d path=one-round success=%s', request.actionId, Date.now() - t0, result.success);
850
+ return result;
851
+ }
852
+ }
853
+ const result = await this.commitTailThenSweep(request, remainingBlocks);
854
+ log('commit:done actionId=%s ms=%d path=tail-then-sweep torn=%d', request.actionId, Date.now() - t0,
855
+ result.success ? result.durability.torn?.length ?? 0 : 0);
856
+ return result;
857
+ }
858
+
859
+ /**
860
+ * Sends the whole action — tail first, then `remainingBlocks` in order — to one coordinator as ONE
861
+ * commit, when one coordinator covers every block. Returns `undefined` when the round does not
862
+ * apply (the blocks need more than one coordinator, or their coordinators could not be looked up)
863
+ * or when it THREW; the caller then runs {@link commitTailThenSweep} for the same request.
864
+ *
865
+ * Tail first on the wire because `CoordinatorRepo.commit` runs consensus on `blockIds[0]`'s cohort:
866
+ * the combined record runs on the tail's cohort, as the tail round would. The other blocks then
867
+ * commit on the tail's cohort rather than on their own — the same approximation a multi-block
868
+ * sweep batch already makes (backlog `debt-sender-side-coordinating-block-binding-is-unchecked`),
869
+ * and identical whenever the cohorts coincide.
870
+ *
871
+ * A RETURNED refusal (a confirmed conflict, or `commit-not-durable`) is returned as a refused tail
872
+ * is: the caller cancels and the writer's retry takes over. A refusal can still leave the tail AND
873
+ * the other blocks on a minority of the cohort — a strictly more complete state than a refused
874
+ * tail round leaves, and one `Collection.completeOwnEntry` already finishes.
875
+ *
876
+ * A THROW is not retried here. `processBatches`' retry re-batches the failed blocks onto possibly
877
+ * different coordinators, in parallel, which could land a non-tail block on one cohort before the
878
+ * tail lands on another. The two-step fallback re-sends everything instead, and whatever the thrown
879
+ * round did land is this action's own revision, so re-committing it is an idempotent no-op
880
+ * (`isOwnRevision` in `StorageRepo.commit`). The fallback starts from the same cached coordinator,
881
+ * so a dead one costs one more dial before its retries move on, and a round that hangs to its
882
+ * deadline costs one more `timeoutMs` before the fallback starts.
883
+ */
884
+ private async commitInOneRound(request: CommitRequest, remainingBlocks: BlockId[]): Promise<CommitResult | undefined> {
885
+ const blockIds = [request.tailId, ...remainingBlocks];
886
+ const coordinator = await this.soleCommitCoordinator(blockIds, request.actionId);
887
+ if (!coordinator) {
888
+ return undefined;
889
+ }
890
+ let result: CommitResult;
891
+ try {
892
+ result = await this.sendCommit(coordinator, blockIds, request, Date.now() + this.timeoutMs);
893
+ } catch (e) {
894
+ log('WARN: one-round commit threw; committing the tail, then the rest: actionId=%s peer=%s error=%s',
895
+ request.actionId, coordinator.toString(), errorMessage(e));
896
+ return undefined;
897
+ }
898
+ return result.success
899
+ ? { success: true, durability: mergeDurability([result.durability]) }
900
+ : refusalFrom([result]);
901
+ }
902
+
903
+ /**
904
+ * The one coordinator covering every block in `blockIds` — resolved as {@link commitBlocks}
905
+ * resolves them, preferring what the pend already resolved — or `undefined` when they need more
906
+ * than one, or a lookup failed (logged; the two-step path then repeats the lookups and reports
907
+ * whatever they report).
908
+ */
909
+ private async soleCommitCoordinator(blockIds: BlockId[], actionId: ActionId): Promise<PeerId | undefined> {
910
+ let batches: CoordinatorBatch<BlockId[], CommitResult>[];
911
+ try {
912
+ batches = await this.batchesForPayload<BlockId[], CommitResult>(blockIds, blockIds, mergeBlocks, [], actionId);
913
+ } catch (e) {
914
+ log('commit:one-round-unplanned actionId=%s error=%s', actionId, errorMessage(e));
915
+ return undefined;
916
+ }
917
+ if (batches.length !== 1) {
918
+ log('commit:one-round-inapplicable actionId=%s coordinators=%d', actionId, batches.length);
919
+ return undefined;
920
+ }
921
+ return batches[0]!.peerId;
922
+ }
923
+
924
+ /**
925
+ * Commits the tail, and — once the tail round was acknowledged — every block in `remainingBlocks`.
926
+ * The path for an action whose blocks need more than one coordinator, for an action touching only
927
+ * its tail, and for a {@link commitInOneRound} that threw.
928
+ */
929
+ private async commitTailThenSweep(request: CommitRequest, remainingBlocks: BlockId[]): Promise<CommitResult> {
930
+ const tailResult = await this.commitBlock(request.tailId, request.actionId, request.rev, request.tailId, request.blockDigests);
931
+ if (!tailResult.success) {
932
+ // NOTE: a refused tail is NOT an absent tail. The coordinator's durability gate answers
933
+ // `commit-not-durable` whenever fewer than a majority hold the revision — even though
934
+ // some members stored it — and this return means the sweep below never runs, so every
935
+ // other block of the action is left uncommitted while the log entry may already be
936
+ // readable. This layer cannot tell "tail absent" from "tail present on a minority", so it
937
+ // does not sweep anyway (that would commit data blocks under a tail that may never reach
938
+ // a majority). The writer closes the gap instead: its retry keeps the SAME action id,
939
+ // and if its refresh finds this action's own log entry it re-sends this attempt — same
940
+ // transforms, same revision — to land what was left behind before treating the write as
941
+ // saved (`Collection.completeOwnEntry`). A write is saved only when every block its log
942
+ // entry names holds its revision; the entry alone proves nothing but the tail.
943
+ return tailResult;
944
+ }
945
+ // Every coordinator that confirmed part of this action reports who holds its part; the
946
+ // action-level answer is the WEAKEST of them (`mergeDurability`), so a caller reading only the
947
+ // scalar fields reads the binding constraint. The blocks a torn sweep abandons are on nobody,
948
+ // and `torn` names them: they never heal by replication, only by re-driving the action.
949
+ const cohortReports: WriteDurability[] = [tailResult.durability];
950
+ let torn: BlockId[] = [];
951
+
952
+ // Sweep every non-tail block (the header, when the action touches it, lands here too — after
953
+ // the tail, like any other touched block). The tail is the only exclusion needed.
954
+ //
955
+ // The tail-then-sweep order IS load-bearing; do not reorder it to put the contested blocks
956
+ // first. Across two rounds it is the only thing keeping a member from committing a non-tail
957
+ // block of this action without the tail, which `Collection.bootstrapContext` relies on (see
958
+ // {@link commit}): that bootstrap is what makes pending non-tail blocks visible to a chain
959
+ // walk. Sweeping before the tail would also let a committed header point at a never-committed
960
+ // tail: a dangling pointer, strictly worse than an orphaned block.
961
+ if (remainingBlocks.length > 0) {
962
+ const { batches, error } = await this.commitBlocks({ blockIds: remainingBlocks, actionId: request.actionId, rev: request.rev, tailId: request.tailId, blockDigests: request.blockDigests });
963
+ cohortReports.push(...confirmedDurabilities(batches));
964
+ if (error) {
965
+ // Split by the failure's NATURE, exactly as commitBlock does for the tail: a RETURNED
966
+ // `success:false` from a cohort coordinator is a confirmed optimistic-concurrency loss
967
+ // (post conversion-arms, coordinators only return non-success for confirmed conflicts) —
968
+ // a rival holds one of these blocks' revisions, no reconciliation will ever apply OUR
969
+ // transform there, and proceeding would acknowledge a torn action (tail committed, the
970
+ // conflicted block permanently pointing elsewhere — the acknowledged-but-absent write).
971
+ // Surface it so the caller cancels and re-drives at a fresh revision.
972
+ const stale = this.staleFromBatches(batches);
973
+ if (stale) {
974
+ return stale;
975
+ }
976
+ // The tail already committed durably when this returns, as has any sweep batch that
977
+ // landed before the error — a torn action.
978
+ // Refusing is still right, and must NOT be softened back into a blanket tolerance:
979
+ // acknowledging a torn action would report a write as durable while one of its blocks
980
+ // permanently points somewhere else. The two consequences that used to make the refusal
981
+ // itself harmful are now handled upstream, so the writer recovers on its own:
982
+ // - its re-pend no longer meets its OWN durable revision as if a rival held it. All
983
+ // three pend-tier checks carve out `latest.rev === request.rev &&
984
+ // latest.actionId === request.actionId` (StorageRepo.pend, which also skips saving
985
+ // a pending record for such a block; ClusterMember.validatePendOperations; and
986
+ // CoordinatorRepo's stale classification). The retry no longer wedges.
987
+ // - its retry recognises its own already-committed log entry instead of replaying it
988
+ // (Collection.updateInternal's `inFlightActionId` arm, set by both write paths —
989
+ // syncInternal and TransactionCoordinator.commitOnce — which reuse one action id
990
+ // across all of a write's attempts). It no longer appends a duplicate entry.
991
+ // - and before consuming that entry it FINISHES the action: the blocks this return
992
+ // abandons are on nobody (the caller cancels their pending records next), so the
993
+ // refresh re-sends the refused attempt verbatim at the same revision, which the
994
+ // carve-outs above turn into "land exactly what is missing"
995
+ // (Collection.completeOwnEntry). The entry alone never counts as saved. If a rival
996
+ // has since taken a revision one of those blocks needed, the writer is told so by
997
+ // name (TornActionError) rather than acknowledged.
998
+ //
999
+ // Transport-shaped failures (throws, no returned refusal) keep the tolerance for the
1000
+ // RESULT — the tail committed durably, and reporting failure now would disown an
1001
+ // acknowledged write — but NOT for the state the sweep abandoned, which
1002
+ // `cancelAbandonedSweepBlocks` below repairs before this returns.
1003
+ try { log('WARN: non-tail commit had errors; cancelling unconfirmed blocks, proceeding after tail commit: %s', error.message); } catch { /* ignore */ }
1004
+ torn = await this.cancelAbandonedSweepBlocks(request.actionId, remainingBlocks, batches);
1005
+ }
1006
+ }
1007
+
1008
+ // `withTornBlocks` clamps the class below `full` when the sweep abandoned anything — a cohort
1009
+ // can hold every block it was asked for while the action as a whole is incomplete — and never
1010
+ // raises it. `isFullyDurable` then answers false; a consumer that needs to know WHICH blocks
1011
+ // reads `torn`.
1012
+ return { success: true, durability: withTornBlocks(mergeDurability(cohortReports), torn) };
1013
+ }
1014
+
1015
+ /**
1016
+ * Cancels every sweep block whose commit batch never confirmed success, so an acknowledged
1017
+ * commit never walks away from a pending record. Best-effort: a failed cancel is logged, never
1018
+ * thrown, because the tail is already durable and the caller has nothing left to retry.
1019
+ *
1020
+ * **Why cancelling is required.** A thrown sweep does not imply the sweep's commit consensus
1021
+ * exists anywhere: it also covers a sweep whose cluster transaction reached NOBODY, where no
1022
+ * consensus record exists, no reconciliation will ever run, and every cohort member still holds
1023
+ * the pending record its pend wrote. Nothing else removes such a record (its only removers are a
1024
+ * client cancel, a divergence-shaped commit refusal, and a forward write of the SAME action — see
1025
+ * docs/repository.md "a pending record's lifetime is bounded by its writer"), and while it stands
1026
+ * the members reject every later write to the block from any writer.
1027
+ *
1028
+ * **Why cancelling is safe** in all three timings:
1029
+ * - the sweep's commit DID land on a member (a lost response) ⇒ that member already promoted the
1030
+ * record, so the cancel is a no-op there;
1031
+ * - it did not land ⇒ the cancel is exactly the repair;
1032
+ * - its consensus is still in flight and lands AFTER the cancel ⇒ the member meets a missing
1033
+ * pend, which `ClusterMember.applyConsensusOperation` already treats as "behind" divergence and
1034
+ * cures by reconciling the block from a cohort peer.
1035
+ *
1036
+ * Confirmed blocks are excluded only to skip a pointless consensus round — cancelling one would
1037
+ * also be a no-op — so an over-broad `confirmed` set costs latency, never correctness.
1038
+ *
1039
+ * Residuals: the cancel is retried and checked ({@link dischargeCancel}) but still bounded, so a
1040
+ * fault outlasting its budget leaves the record wedged until a node-side backstop sweep exists (backlog:
1041
+ * `debt-unpromotable-pending-records-need-a-sweep`); and this covers only the sweep's abandonment
1042
+ * — `StorageRepo.commit`'s genuine-fault arm deliberately KEEPS a failed batch's pendings for a
1043
+ * retry, so it is a second producer of the same durable state whenever that retry never comes.
1044
+ *
1045
+ * @returns the abandoned block ids — exactly the set cancelled here — so {@link commit} can name
1046
+ * them as `torn` on the acknowledgement without re-deriving the set by a second rule.
1047
+ */
1048
+ private async cancelAbandonedSweepBlocks(actionId: ActionId, sweptBlocks: BlockId[], batches: CoordinatorBatch<BlockId[], CommitResult>[]): Promise<BlockId[]> {
1049
+ // NOTE: `confirmed` is only ever non-empty when the sweep spans MORE THAN ONE batch, and it
1050
+ // does so only when no single peer covers every swept block — `consolidateCoordinators`'
1051
+ // greedy set cover collapses the pend onto one coordinator otherwise, and commit reuses that
1052
+ // resolution. So on a mesh whose nodes are all responsible for all blocks — every in-process
1053
+ // test mesh today — this filter is structurally unreachable, and
1054
+ // packages/db-p2p/test/torn-commit-cancels-abandoned-blocks.spec.ts cannot cover it. Pinning
1055
+ // a partial sweep needs a mesh whose responsibility sets are disjoint enough to force two
1056
+ // pend batches; a new failure injection alone will not reach it. That fixture is tracked in
1057
+ // backlog `debt-no-mesh-fixture-forces-two-coordinator-batches`, which collects this site and
1058
+ // the two others with the same gap.
1059
+ const confirmed = new Set<BlockId>();
1060
+ for (const b of allBatches(batches, bb => bb.request?.isResponse === true && bb.request!.response!.success)) {
1061
+ for (const bid of b.payload) confirmed.add(bid);
1062
+ }
1063
+ const abandoned = sweptBlocks.filter(bid => !confirmed.has(bid));
1064
+ if (abandoned.length === 0) {
1065
+ return abandoned;
1066
+ }
1067
+ try {
1068
+ await this.cancel({ actionId, blockIds: abandoned });
1069
+ } catch (cancelError) {
1070
+ try { log('WARN: cancel of abandoned sweep blocks failed — pending records may wedge until the node-side sweep lands: %o', cancelError); } catch { /* ignore */ }
1071
+ }
1072
+ return abandoned;
1073
+ }
1074
+
1075
+ private async commitBlock(blockId: BlockId, actionId: ActionId, rev: number, tailId?: BlockId, blockDigests?: BlockContentDigests): Promise<CommitResult> {
1076
+ const { batches: tailBatches, error: tailError } = await this.commitBlocks({ blockIds: [blockId], actionId, rev, tailId, blockDigests });
1077
+ if (tailError) {
1078
+ // commit is a pure attempt: stale → { success:false }, transient → throw. Cancellation
1079
+ // is the CALLER's responsibility (coordinator cancelPhase; TransactorSource.transact),
1080
+ // which owns the retry budget and the committed-vs-pending picture — self-cancelling here
1081
+ // would tear down a pend a caller's retry loop is still working against, and double-cancel.
1082
+ // Collect and return any active stale failures
1083
+ const stale = this.staleFromBatches(tailBatches);
1084
+ if (stale) {
1085
+ return stale;
1086
+ }
1087
+ throw tailError;
1088
+ }
1089
+ return { success: true, durability: mergeDurability(confirmedDurabilities(tailBatches)) };
1090
+ }
1091
+
1092
+ /**
1093
+ * The RETURNED `success:false` responses out of a set of commit batches, merged by
1094
+ * {@link refusalFrom}, or `undefined` when every failure was transport-shaped (thrown, no
1095
+ * response). Shared by {@link commitBlock} (the tail) and {@link commitTailThenSweep}'s non-tail
1096
+ * sweep — both must distinguish a confirmed conflict (return it; the caller cancels and
1097
+ * re-drives) from a transient fault (throw / tolerate).
1098
+ */
1099
+ private staleFromBatches(batches: CoordinatorBatch<BlockId[], CommitResult>[]): StaleFailure | undefined {
1100
+ const stale = Array.from(allBatches(batches, b => b.request?.isResponse as boolean && !b.request!.response!.success));
1101
+ return stale.length === 0 ? undefined : refusalFrom(stale.map(b => b.request!.response! as StaleFailure));
1102
+ }
1103
+
1104
+ /**
1105
+ * The one place a commit request to a coordinator is built — shared by {@link commitInOneRound}
1106
+ * and {@link commitBlocks}. `blockDigests` arrives as the action's FULL declaration map and is
1107
+ * narrowed to `blockIds` here, at send time, never up front: each request becomes its own cluster
1108
+ * record, so shipping the whole map would make one cohort sign for blocks it is not responsible
1109
+ * for; and `processBatches` re-batches failed blocks onto different coordinators, so only a
1110
+ * send-time subset stays correct across retries.
1111
+ */
1112
+ private sendCommit(peerId: PeerId, blockIds: BlockId[], { actionId, rev, tailId, blockDigests }: RepoCommitRequest, expiration: number): Promise<CommitResult> {
1113
+ return this.getRepo(peerId).commit(
1114
+ { actionId, blockIds, rev, tailId, ...digestsFor(blockDigests, blockIds) },
1115
+ { expiration, dialTimeoutMs: this.dialTimeoutMs }
1116
+ );
1117
+ }
1118
+
1119
+ /** Attempts to commit a set of blocks, and handles failures and errors. */
1120
+ private async commitBlocks(request: RepoCommitRequest) {
1121
+ const { blockIds, actionId, rev } = request;
1122
+ const expiration = Date.now() + this.timeoutMs;
1123
+ // Thread the transaction's actionId so both the initial batch assembly and any
1124
+ // per-block retry re-resolution prefer the coordinator pend already resolved.
1125
+ const batches = await this.batchesForPayload<BlockId[], CommitResult>(blockIds, blockIds, mergeBlocks, [], actionId);
1126
+ log('commitBlocks actionId=%s rev=%d batches=%d', actionId, rev, batches.length);
1127
+ let error: Error | undefined;
1128
+ try {
1129
+ await processBatches(
1130
+ batches,
1131
+ (batch) => this.sendCommit(batch.peerId, batch.payload, request, expiration),
1132
+ batch => batch.payload,
1133
+ mergeBlocks,
1134
+ expiration,
1135
+ async (blockId, options) => this.resolveCoordinator(blockId, options, actionId)
1136
+ );
1137
+ } catch (e) {
1138
+ error = e as Error;
1139
+ }
1140
+
1141
+ if (!everyBatch(batches, b => b.request?.isResponse as boolean && b.request!.response!.success)) {
1142
+ const details = this.formatBatchStatuses(batches,
1143
+ b => {
1144
+ const status = b.request == null ? 'no-response' : (b.request.isResponse ? 'non-success' : 'in-flight')
1145
+ const resp: any = (b.request as any)?.response;
1146
+ const extra = resp && resp.success === false ? (Array.isArray(resp.missing) ? ` missing=${resp.missing.length}` : ' success=false') : '';
1147
+ const errMsg = b.request?.isError ? ` cause=${errorMessage(b.request.error)}` : ''
1148
+ return `${b.peerId.toString()}[blocks:${b.payload instanceof Array ? (b.payload as any[]).length : 1}](${status})${extra ? ' ' + extra : ''}${errMsg}`
1149
+ });
1150
+ const rootCause = firstBatchError(batches) ?? error;
1151
+ const aggregate = new Error(`Some peers did not complete: ${details}${rootCause ? `; root: ${rootCause.message}` : ''}`);
1152
+ (aggregate as any).cause = rootCause;
1153
+ error = aggregate;
1154
+ }
1155
+ return { batches, error };
1156
+ };
1157
+
1158
+ /** Creates batches for a given payload, grouped by the coordinating peer for each block id */
1159
+ private async batchesForPayload<TPayload, TResponse>(
1160
+ blockIds: BlockId[],
1161
+ payload: TPayload,
1162
+ getBlockPayload: (payload: TPayload, blockId: BlockId, mergeWithPayload: TPayload | undefined) => TPayload,
1163
+ excludedPeers: PeerId[],
1164
+ /** When set, prefer a coordinator this transaction already resolved at pend (see {@link resolveCoordinator}). */
1165
+ actionId?: ActionId,
1166
+ /** What the batches will be used for. Defaults to `'write'` — see {@link CoordinatorIntent}. */
1167
+ intent: CoordinatorIntent = 'write'
1168
+ ): Promise<CoordinatorBatch<TPayload, TResponse>[]> {
1169
+ return createBatchesForPayload<TPayload, TResponse>(
1170
+ blockIds,
1171
+ payload,
1172
+ getBlockPayload,
1173
+ excludedPeers,
1174
+ async (blockId, options) => this.resolveCoordinator(blockId, options, actionId, intent)
1175
+ );
1176
+ }
1177
+
1178
+ /**
1179
+ * Resolve the coordinator for `blockId`, preferring one this transaction already
1180
+ * resolved during pend (the per-transaction cache) before falling back to a live
1181
+ * `findCoordinator`. A cached coordinator that is in `excludedPeers` (already tried and
1182
+ * failed during a retry) is skipped so a retry can't loop on a dead coordinator. A
1183
+ * cache miss — including every call with no `actionId` (get/cancel) — never fails; it
1184
+ * always falls through to live resolution.
1185
+ */
1186
+ private async resolveCoordinator(
1187
+ blockId: BlockId,
1188
+ options: { excludedPeers: PeerId[] },
1189
+ actionId: ActionId | undefined,
1190
+ intent: CoordinatorIntent = 'write'
1191
+ ): Promise<PeerId> {
1192
+ if (actionId !== undefined) {
1193
+ const cached = this.txnCoordinatorCache.get(actionId)?.coordinators.get(blockId);
1194
+ if (cached && !options.excludedPeers.some(p => p.toString() === cached.toString())) {
1195
+ return cached;
1196
+ }
1197
+ }
1198
+ return this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), { ...options, intent });
1199
+ }
1200
+
1201
+ /**
1202
+ * Get (creating if absent) the per-transaction coordinator map for `actionId`,
1203
+ * refreshing its expiry and lazily sweeping expired sibling entries. See
1204
+ * {@link txnCoordinatorCache} for why the TTL/size cap here is a memory backstop and
1205
+ * not a staleness bound.
1206
+ */
1207
+ private txnCoordinatorsFor(actionId: ActionId): Map<BlockId, PeerId> {
1208
+ const now = Date.now();
1209
+ // Reclaim entries from transactions that pended but never committed. A live entry is
1210
+ // never stale (unique actionId; read only by its own transaction's commit), so
1211
+ // sweeping lazily on write is safe.
1212
+ for (const [aid, entry] of this.txnCoordinatorCache) {
1213
+ if (entry.expires <= now) this.txnCoordinatorCache.delete(aid);
1214
+ }
1215
+ // Comfortably covers a normal pend→commit gap (~2 op budgets) with a fixed floor;
1216
+ // an entry outliving this only loses the optimization (commit re-resolves live),
1217
+ // never correctness.
1218
+ const ttlMs = Math.max(this.timeoutMs * 2, 60_000);
1219
+ const existing = this.txnCoordinatorCache.get(actionId);
1220
+ if (existing) {
1221
+ existing.expires = now + ttlMs;
1222
+ return existing.coordinators;
1223
+ }
1224
+ const created = { coordinators: new Map<BlockId, PeerId>(), expires: now + ttlMs };
1225
+ this.txnCoordinatorCache.set(actionId, created);
1226
+ while (this.txnCoordinatorCache.size > NetworkTransactor.MAX_TXN_COORDINATOR_CACHE_ENTRIES) {
1227
+ const oldest = this.txnCoordinatorCache.keys().next().value as ActionId | undefined;
1228
+ if (oldest == null || oldest === actionId) break;
1229
+ this.txnCoordinatorCache.delete(oldest);
1230
+ }
1231
+ return created.coordinators;
1232
+ }
1233
+
1234
+ /**
1235
+ * Cancels a pending transaction by canceling all blocks associated with the transaction,
1236
+ * including failed peers. Seeds the first round from the peers the failed operation actually
1237
+ * talked to (a coordinator that answered the pend is the one most likely to be holding the
1238
+ * record); every later round re-resolves live. Throws on failure to discharge — see
1239
+ * {@link dischargeCancel}.
1240
+ *
1241
+ * The seed uses each batch's `coordinatingBlockIds` — the full set `consolidateCoordinators`
1242
+ * assigned to that peer — not its anchor `blockId` alone. Anchor-only was silently lossy: when
1243
+ * consolidation collapsed several blocks onto one coordinator, the non-anchor blocks got no
1244
+ * cancel at all. `processBatches`' retry batches carry no `coordinatingBlockIds` and fall back to
1245
+ * their anchor, so a retried multi-block batch can still under-cover the seed round;
1246
+ * `dischargeCancel`'s per-block outstanding set notices and the next round resolves those live.
1247
+ * That residual costs a round, never correctness, and is unreachable on a mesh where every node
1248
+ * covers every block — see backlog `debt-no-mesh-fixture-forces-two-coordinator-batches`.
1249
+ */
1250
+ private async cancelBatch<TPayload, TResponse>(
1251
+ batches: CoordinatorBatch<TPayload, TResponse>[],
1252
+ actionRef: ActionBlocks,
1253
+ ) {
1254
+ const operationBatches = makeBatchesByPeer<BlockId[], void>(
1255
+ Array.from(allBatches(batches)).flatMap(b => (b.coordinatingBlockIds ?? [b.blockId]).map(bid => [bid, b.peerId] as const)),
1256
+ actionRef.blockIds,
1257
+ mergeBlocks,
1258
+ []
1259
+ );
1260
+ await this.dischargeCancel(actionRef, operationBatches);
1261
+ }
1262
+
1263
+ /**
1264
+ * Rounds {@link dischargeCancel} will run before giving up, in addition to the
1265
+ * `abortOrCancelTimeoutMs` deadline; whichever bound trips first ends the loop.
1266
+ *
1267
+ * NOTE: accepted tradeoff — the round cap can end the loop well before the deadline. Six rounds
1268
+ * means five backoffs, whose pre-jitter values with `baseMs` 50 / `capMs` 500 are 50, 100, 200,
1269
+ * 400, 500 ms, each drawn from `(0.5·exp, exp]` — so 0.63–1.25 s of waiting, plus each round's
1270
+ * own RPC time (measured end to end: 1054 ms for the dead-transport arm of
1271
+ * packages/db-p2p/test/reset-does-not-strand-its-own-pend.spec.ts). That clears a stream reset
1272
+ * and reconnect, and against a genuinely dead transport it hands the caller a legible failure in
1273
+ * about a second instead of spending its whole (typically 5 s) abort budget issuing RPCs nobody
1274
+ * will answer. Raise it if faults longer than that but shorter than the abort budget turn out to
1275
+ * strand records in practice.
1276
+ */
1277
+ private static readonly MAX_CANCEL_ROUNDS = 6;
1278
+
1279
+ /**
1280
+ * Runs cancel rounds until every block of `actionRef` has had a cancel ANSWERED by some peer, or
1281
+ * the budget runs out — and then throws an aggregate naming the action and the blocks whose
1282
+ * pending records are still standing.
1283
+ *
1284
+ * **Why a completeness check.** `processBatches` deliberately never rethrows, so "it returned"
1285
+ * says nothing about whether any peer was reached. A block is only discharged once some batch
1286
+ * carrying it got a response; anything else leaves its pending record standing, and while it
1287
+ * stands `ClusterMember.validatePendOperations` votes reject on every later pend touching the
1288
+ * block, from any writer. An application retry loop opens a NEW transaction and so mints a new
1289
+ * action id, which is none of the three things that remove a record (client cancel,
1290
+ * divergence-shaped commit refusal, forward write of the SAME action id — docs/repository.md),
1291
+ * so the write collides with its own predecessor permanently.
1292
+ *
1293
+ * **Why a TIME-based retry on top of `processBatches`' own.** That one is a PEER retry: it
1294
+ * re-homes a failed block onto an alternate coordinator immediately, with no delay. A stream
1295
+ * reset is time-shaped, not peer-shaped — every peer is equally unreachable for the length of
1296
+ * the fault — so only a delayed re-attempt clears it. Each round rebuilds its batches from
1297
+ * scratch, so a re-resolved coordinator is picked up.
1298
+ *
1299
+ * **Why retrying is safe.** Cancel is idempotent, and the three-timings argument written out in
1300
+ * {@link cancelAbandonedSweepBlocks} covers a cancel that races a landing commit. Extra rounds
1301
+ * cost latency only. Each round narrows to the blocks still outstanding, so a partially
1302
+ * successful round does not re-issue the cancels that already landed.
1303
+ *
1304
+ * NOTE: a fault that outlasts these bounds still strands the record, and nothing node-side
1305
+ * reclaims it. That residual is the backstop tracked in backlog
1306
+ * `debt-unpromotable-pending-records-need-a-sweep`.
1307
+ *
1308
+ * @param seedBatches Batches to use for round 0 only (see {@link cancelBatch}). Omitted → round
1309
+ * 0 resolves coordinators live like every later round.
1310
+ */
1311
+ private async dischargeCancel(
1312
+ actionRef: ActionBlocks,
1313
+ seedBatches?: CoordinatorBatch<BlockId[], void>[]
1314
+ ): Promise<void> {
1315
+ let outstanding = Array.from(new Set(actionRef.blockIds));
1316
+ if (outstanding.length === 0) {
1317
+ return;
1318
+ }
1319
+ const deadline = Date.now() + this.abortOrCancelTimeoutMs;
1320
+ let roundBatches: CoordinatorBatch<BlockId[], void>[] = [];
1321
+ let lastError: Error | undefined;
1322
+ for (let round = 0; ; ++round) {
1323
+ roundBatches = [];
1324
+ try {
1325
+ // Batch construction can throw (coordinator lookup); `processBatches` cannot.
1326
+ roundBatches = round === 0 && seedBatches
1327
+ ? seedBatches
1328
+ : await this.batchesForPayload<BlockId[], void>(outstanding, outstanding, mergeBlocks, []);
1329
+ await processBatches(
1330
+ roundBatches,
1331
+ (batch) => this.getRepo(batch.peerId).cancel({ actionId: actionRef.actionId, blockIds: batch.payload }, { expiration: deadline, dialTimeoutMs: this.dialTimeoutMs }),
1332
+ batch => batch.payload,
1333
+ mergeBlocks,
1334
+ deadline,
1335
+ (blockId, options) => this.keyNetwork.findCoordinator(routingKeyForBlock(blockId), options)
1336
+ );
1337
+ } catch (e) {
1338
+ lastError = asError(e);
1339
+ }
1340
+
1341
+ const discharged = dischargedBlocks(roundBatches);
1342
+ outstanding = outstanding.filter(bid => !discharged.has(bid));
1343
+ if (outstanding.length === 0) {
1344
+ if (round > 0) {
1345
+ log('cancel:discharged actionId=%s rounds=%d', actionRef.actionId, round + 1);
1346
+ }
1347
+ return;
1348
+ }
1349
+
1350
+ const remainingMs = deadline - Date.now();
1351
+ if (round + 1 >= NetworkTransactor.MAX_CANCEL_ROUNDS || remainingMs <= 0) {
1352
+ break;
1353
+ }
1354
+ log('cancel:retry actionId=%s round=%d outstanding=%d', actionRef.actionId, round, outstanding.length);
1355
+ await abortableDelay(Math.min(jitteredBackoffMs(round, { baseMs: 50, capMs: 500 }), remainingMs));
1356
+ }
1357
+
1358
+ const details = this.formatBatchStatuses(roundBatches,
1359
+ b => {
1360
+ const status = b.request == null ? 'no-response' : (b.request.isResponse ? 'responded' : 'in-flight');
1361
+ const errMsg = b.request?.isError ? ` cause=${errorMessage(b.request.error)}` : '';
1362
+ return `${b.peerId.toString()}[block:${b.blockId}](${status})${errMsg}`;
1363
+ });
1364
+ const rootCause = firstBatchError(roundBatches) ?? lastError;
1365
+ const aggregate = new Error(`Cancel of action ${actionRef.actionId} did not discharge ${outstanding.length} block(s): ${outstanding.join(', ')}`
1366
+ + (details ? `; peers: ${details}` : '')
1367
+ + (rootCause ? `; root: ${rootCause.message}` : ''));
1368
+ (aggregate as any).cause = rootCause;
1369
+ (aggregate as AggregateError).errors = rootCause ? [rootCause] : [];
1370
+ throw aggregate;
1371
+ }
1372
+
1373
+ /** Renders the batches worth naming in an aggregate error: the ones that never completed, or —
1374
+ * when every batch completed and the aggregate is about a non-success RESPONSE rather than a
1375
+ * transport fault — all of them. */
1376
+ private formatBatchStatuses<TPayload, TResponse>(
1377
+ batches: CoordinatorBatch<TPayload, TResponse>[],
1378
+ formatter: (b: CoordinatorBatch<TPayload, TResponse>) => string
1379
+ ): string {
1380
+ const incompletes = Array.from(incompleteBatches(batches))
1381
+ let details = incompletes.map(formatter).join(', ')
1382
+ if (details.length === 0) {
1383
+ details = Array.from(allBatches(batches)).map(formatter).join(', ')
1384
+ }
1385
+ return details
1386
+ }
1387
+ }
1388
+
1389
+
1390
+ /**
1391
+ * One round of `consolidateCoordinators`' greedy cover: the cohort member covering the most still-uncovered
1392
+ * blocks, with the blocks it covers, or undefined when no member covers any.
1393
+ *
1394
+ * A tie goes to `localPeerId` when it is among the tied members, otherwise to the member seen first. Cohorts
1395
+ * arrive in proximity order, so "seen first" is the nearest; without the local preference a node that is in
1396
+ * a block's cohort but not nearest would send its own write over the network, and on a network no wider than
1397
+ * a cohort (every node in every cohort) that would be nearly every write.
1398
+ */
1399
+ function bestCoveringPeer(peerBlocks: Map<string, BlockId[]>, uncovered: Set<BlockId>, localPeerId: string | undefined): { peerId: string; covered: BlockId[] } | undefined {
1400
+ let best: { peerId: string; covered: BlockId[] } | undefined;
1401
+ for (const [peerId, blocks] of peerBlocks) {
1402
+ const covered = blocks.filter(bid => uncovered.has(bid));
1403
+ if (covered.length === 0) continue;
1404
+ const bestCount = best?.covered.length ?? 0;
1405
+ if (covered.length > bestCount || (covered.length === bestCount && peerId === localPeerId)) {
1406
+ best = { peerId, covered };
1407
+ }
1408
+ }
1409
+ return best;
1410
+ }
1411
+
1412
+ /**
1413
+ * The block ids some batch in the tree got an ANSWER for. A cancel batch that errored, or never
1414
+ * responded, discharged nothing — its blocks' pending records are still standing. Batch payloads
1415
+ * are block-id lists (built with {@link mergeBlocks}), including the retry batches
1416
+ * `processBatches` re-homes, so the union across the whole tree is the discharged set.
1417
+ */
1418
+ function dischargedBlocks(batches: CoordinatorBatch<BlockId[], void>[]): Set<BlockId> {
1419
+ const discharged = new Set<BlockId>();
1420
+ for (const b of allBatches(batches, bb => bb.request?.isResponse === true)) {
1421
+ for (const bid of b.payload) discharged.add(bid);
1422
+ }
1423
+ return discharged;
1424
+ }
1425
+
1426
+ /**
1427
+ * The durability report off every commit batch in the tree that answered `success: true` — the
1428
+ * coordinators' own answers for the blocks they drove, one per confirmed batch. Retry batches
1429
+ * (`subsumedBy`) are included, so a block re-homed after a failed first attempt reports through the
1430
+ * peer that actually committed it. Batches that threw or returned a refusal contribute nothing.
1431
+ */
1432
+ function confirmedDurabilities(batches: CoordinatorBatch<BlockId[], CommitResult>[]): WriteDurability[] {
1433
+ return Array.from(allBatches(batches, b => b.request?.isResponse === true && b.request!.response!.success))
1434
+ .map(b => (b.request!.response! as CommitSuccess).durability);
1435
+ }
1436
+
1437
+ /**
1438
+ * One {@link StaleFailure} standing for every refused commit response in `responses`, rebuilt the
1439
+ * same way {@link NetworkTransactor.pend}'s aggregate is: `reason` is the first one any response gave
1440
+ * (the only diagnostic that survives into the coordinator's error text — a refusal whose reason is
1441
+ * `commit-not-durable` must not read as "stale commit", a rival's win), `conflict` holds when any
1442
+ * response was a classified conflict, and `staleAt` is the highest confirmed revision. A reason-only
1443
+ * refusal (no `missing`) comes out with `missing: []` and its reason intact.
1444
+ */
1445
+ function refusalFrom(responses: StaleFailure[]): StaleFailure {
1446
+ const staleAt = highestStaleAt(responses.map(r => r.staleAt));
1447
+ const reason = responses.map(r => r.reason).find(r => r !== undefined);
1448
+ return {
1449
+ missing: distinctBlockActionTransforms(responses.flatMap(r => r.missing).filter((x): x is ActionTransforms => x !== undefined)),
1450
+ ...(staleAt === undefined ? {} : { staleAt }),
1451
+ ...(reason === undefined ? {} : { reason }),
1452
+ conflict: responses.some(isConflictFailure),
1453
+ success: false as const
1454
+ };
1455
+ }
1456
+
1457
+ /** The entries of `all` whose ids appear in `batchBlockIds` — the per-batch narrowing both
1458
+ * per-block declarations share ({@link digestsFor}, {@link baseRevsFor}). */
1459
+ function subsetOf<T>(all: Record<BlockId, T>, batchBlockIds: BlockId[]): Record<BlockId, T> {
1460
+ const subset: Record<BlockId, T> = {};
1461
+ for (const id of batchBlockIds) {
1462
+ const entry = all[id];
1463
+ if (entry !== undefined) subset[id] = entry;
1464
+ }
1465
+ return subset;
1466
+ }
1467
+
1468
+ /** The subset of `all` whose ids appear in `batchBlockIds`, wrapped (via {@link blockDigestsField})
1469
+ * so it spreads to nothing when the batch declares no digests. Called at SEND time, once per attempt,
1470
+ * because `processBatches` re-batches failed blocks onto different coordinators — a subset computed
1471
+ * up front would follow the wrong batch on retry. */
1472
+ function digestsFor(all: BlockContentDigests | undefined, batchBlockIds: BlockId[]): { blockDigests?: BlockContentDigests } {
1473
+ return all ? blockDigestsField(subsetOf(all, batchBlockIds)) : {};
1474
+ }
1475
+
1476
+ /** The pend-side sibling of {@link digestsFor}: the subset of `all` whose ids appear in
1477
+ * `batchBlockIds`, wrapped (via {@link baseRevsField}) so it spreads to nothing when no block in the
1478
+ * batch names a base. Same send-time rule, for the same reason. */
1479
+ function baseRevsFor(all: BlockBaseRevs | undefined, batchBlockIds: BlockId[]): { baseRevs?: BlockBaseRevs } {
1480
+ return all ? baseRevsField(subsetOf(all, batchBlockIds)) : {};
1481
+ }
1482
+
1483
+ /** `action` re-scoped to one coordinator batch: the batch's own transforms, and the bases for the
1484
+ * blocks in it alone (see {@link PendRequest.baseRevs}). The action-wide `baseRevs` key is dropped
1485
+ * BEFORE the subset is spread, so a batch none of whose blocks names a base carries no key at all
1486
+ * rather than the whole action's map — and no cohort signs for a block it is not responsible for. */
1487
+ function pendRequestForBatch(action: PendRequest, payload: Transforms): PendRequest {
1488
+ const { baseRevs, ...rest } = action;
1489
+ return { ...rest, transforms: payload, ...baseRevsFor(baseRevs, blockIdsForTransforms(payload)) };
1490
+ }
1491
+
1492
+ /**
1493
+ * The owning collection id for an action ref, read from any fetched block's header. A
1494
+ * committed-then-invalidated action still has a materialized (compensating) block whose header carries
1495
+ * the collection id; a genuinely-aborted action has no fetched block, so this returns `undefined` and
1496
+ * the status stays `aborted`.
1497
+ */
1498
+ function collectionIdForRef(ref: ActionBlocks, blockStates: GetBlockResults): CollectionId | undefined {
1499
+ for (const blockId of ref.blockIds) {
1500
+ const collectionId = blockStates[blockId]?.block?.header.collectionId;
1501
+ if (collectionId !== undefined) {
1502
+ return collectionId;
1503
+ }
1504
+ }
1505
+ return undefined;
1506
+ }
1507
+
1508
+ /** Returns a readable message for an unknown error value. */
1509
+ function errorMessage(err: unknown): string {
1510
+ if (err instanceof Error) return err.message;
1511
+ if (err == null) return 'unknown';
1512
+ try { return String(err); } catch { return 'unknown'; }
1513
+ }
1514
+
1515
+ /**
1516
+ * Returns the first batch-level error encountered across the batch tree,
1517
+ * preferring root batches over retries. Used to preserve the ORIGINAL first-attempt
1518
+ * failure reason when constructing aggregate errors — retry lookup failures
1519
+ * (e.g., findCoordinator throwing because self is excluded on a solo node) must
1520
+ * not shadow the actual root cause.
1521
+ */
1522
+ function firstBatchError<TPayload, TResponse>(batches: CoordinatorBatch<TPayload, TResponse>[]): Error | undefined {
1523
+ // Prefer errors on root batches first
1524
+ for (const root of batches) {
1525
+ if (root.request?.isError) return asError(root.request.error);
1526
+ }
1527
+ // Fall back to errors in any retry subtree
1528
+ for (const b of allBatches(batches)) {
1529
+ if (b.request?.isError) return asError(b.request.error);
1530
+ }
1531
+ return undefined;
1532
+ }
1533
+
1534
+ function asError(err: unknown): Error {
1535
+ return err instanceof Error ? err : new Error(errorMessage(err));
1536
+ }
1537
+
1538
+ /**
1539
+ * Returns the block actions grouped by action id and concatenated transforms
1540
+ */
1541
+ export function distinctBlockActionTransforms(blockActions: ActionTransforms[]): ActionTransforms[] {
1542
+ const grouped = groupBy(blockActions, ({ actionId }) => actionId);
1543
+ return Object.entries(grouped).map(([actionId, actions]) =>
1544
+ ({ actionId, transforms: concatTransforms(...actions.map(t => t.transforms)) } as ActionTransforms));
1545
+ }