@optimystic/db-core 1.22.0 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +8 -4
  2. package/dist/src/collection/action.d.ts +7 -4
  3. package/dist/src/collection/action.d.ts.map +1 -1
  4. package/dist/src/collection/action.js +13 -5
  5. package/dist/src/collection/action.js.map +1 -1
  6. package/dist/src/collection/collection.d.ts +134 -46
  7. package/dist/src/collection/collection.d.ts.map +1 -1
  8. package/dist/src/collection/collection.js +207 -70
  9. package/dist/src/collection/collection.js.map +1 -1
  10. package/dist/src/collection/struct.d.ts +38 -8
  11. package/dist/src/collection/struct.d.ts.map +1 -1
  12. package/dist/src/collection/struct.js.map +1 -1
  13. package/dist/src/collection/write-attempts.d.ts +138 -34
  14. package/dist/src/collection/write-attempts.d.ts.map +1 -1
  15. package/dist/src/collection/write-attempts.js +168 -101
  16. package/dist/src/collection/write-attempts.js.map +1 -1
  17. package/dist/src/collections/diary/diary.d.ts.map +1 -1
  18. package/dist/src/collections/diary/diary.js +5 -1
  19. package/dist/src/collections/diary/diary.js.map +1 -1
  20. package/dist/src/collections/tree/tree.d.ts +15 -9
  21. package/dist/src/collections/tree/tree.d.ts.map +1 -1
  22. package/dist/src/collections/tree/tree.js +6 -4
  23. package/dist/src/collections/tree/tree.js.map +1 -1
  24. package/dist/src/hlc/clock-store.d.ts +63 -0
  25. package/dist/src/hlc/clock-store.d.ts.map +1 -0
  26. package/dist/src/hlc/clock-store.js +49 -0
  27. package/dist/src/hlc/clock-store.js.map +1 -0
  28. package/dist/src/hlc/clock.d.ts +64 -0
  29. package/dist/src/hlc/clock.d.ts.map +1 -0
  30. package/dist/src/hlc/clock.js +171 -0
  31. package/dist/src/hlc/clock.js.map +1 -0
  32. package/dist/src/hlc/hlc.d.ts +38 -0
  33. package/dist/src/hlc/hlc.d.ts.map +1 -0
  34. package/dist/src/hlc/hlc.js +41 -0
  35. package/dist/src/hlc/hlc.js.map +1 -0
  36. package/dist/src/hlc/index.d.ts +5 -0
  37. package/dist/src/hlc/index.d.ts.map +1 -0
  38. package/dist/src/hlc/index.js +5 -0
  39. package/dist/src/hlc/index.js.map +1 -0
  40. package/dist/src/hlc/skew.d.ts +35 -0
  41. package/dist/src/hlc/skew.d.ts.map +1 -0
  42. package/dist/src/hlc/skew.js +35 -0
  43. package/dist/src/hlc/skew.js.map +1 -0
  44. package/dist/src/index.d.ts +2 -0
  45. package/dist/src/index.d.ts.map +1 -1
  46. package/dist/src/index.js +2 -0
  47. package/dist/src/index.js.map +1 -1
  48. package/dist/src/lane/index.d.ts +2 -0
  49. package/dist/src/lane/index.d.ts.map +1 -0
  50. package/dist/src/lane/index.js +2 -0
  51. package/dist/src/lane/index.js.map +1 -0
  52. package/dist/src/lane/lane.d.ts +46 -0
  53. package/dist/src/lane/lane.d.ts.map +1 -0
  54. package/dist/src/lane/lane.js +26 -0
  55. package/dist/src/lane/lane.js.map +1 -0
  56. package/dist/src/log/log.d.ts +50 -22
  57. package/dist/src/log/log.d.ts.map +1 -1
  58. package/dist/src/log/log.js +21 -13
  59. package/dist/src/log/log.js.map +1 -1
  60. package/dist/src/log/struct.d.ts +61 -1
  61. package/dist/src/log/struct.d.ts.map +1 -1
  62. package/dist/src/log/struct.js +24 -0
  63. package/dist/src/log/struct.js.map +1 -1
  64. package/dist/src/network/i-repo.d.ts +10 -0
  65. package/dist/src/network/i-repo.d.ts.map +1 -1
  66. package/dist/src/network/stale-failure.d.ts +20 -7
  67. package/dist/src/network/stale-failure.d.ts.map +1 -1
  68. package/dist/src/network/stale-failure.js +29 -7
  69. package/dist/src/network/stale-failure.js.map +1 -1
  70. package/dist/src/network/struct.d.ts +35 -0
  71. package/dist/src/network/struct.d.ts.map +1 -1
  72. package/dist/src/network/struct.js.map +1 -1
  73. package/dist/src/offline/entry.d.ts +14 -0
  74. package/dist/src/offline/entry.d.ts.map +1 -1
  75. package/dist/src/offline/entry.js +2 -0
  76. package/dist/src/offline/entry.js.map +1 -1
  77. package/dist/src/offline/journal.d.ts +10 -0
  78. package/dist/src/offline/journal.d.ts.map +1 -1
  79. package/dist/src/offline/queue.d.ts +10 -0
  80. package/dist/src/offline/queue.d.ts.map +1 -1
  81. package/dist/src/offline/queue.js +29 -3
  82. package/dist/src/offline/queue.js.map +1 -1
  83. package/dist/src/offline/status.d.ts +7 -0
  84. package/dist/src/offline/status.d.ts.map +1 -1
  85. package/dist/src/offline/status.js.map +1 -1
  86. package/dist/src/testing/test-transactor.d.ts +9 -1
  87. package/dist/src/testing/test-transactor.d.ts.map +1 -1
  88. package/dist/src/testing/test-transactor.js +6 -1
  89. package/dist/src/testing/test-transactor.js.map +1 -1
  90. package/dist/src/transaction/actions-engine.d.ts +3 -0
  91. package/dist/src/transaction/actions-engine.d.ts.map +1 -1
  92. package/dist/src/transaction/actions-engine.js +3 -0
  93. package/dist/src/transaction/actions-engine.js.map +1 -1
  94. package/dist/src/transaction/coordinator.d.ts +10 -5
  95. package/dist/src/transaction/coordinator.d.ts.map +1 -1
  96. package/dist/src/transaction/coordinator.js +197 -48
  97. package/dist/src/transaction/coordinator.js.map +1 -1
  98. package/dist/src/transaction/entry-commit.d.ts +45 -10
  99. package/dist/src/transaction/entry-commit.d.ts.map +1 -1
  100. package/dist/src/transaction/entry-commit.js +20 -7
  101. package/dist/src/transaction/entry-commit.js.map +1 -1
  102. package/dist/src/transaction/errors.d.ts +69 -1
  103. package/dist/src/transaction/errors.d.ts.map +1 -1
  104. package/dist/src/transaction/errors.js +70 -1
  105. package/dist/src/transaction/errors.js.map +1 -1
  106. package/dist/src/transaction/index.d.ts +1 -1
  107. package/dist/src/transaction/index.d.ts.map +1 -1
  108. package/dist/src/transaction/index.js +1 -1
  109. package/dist/src/transaction/index.js.map +1 -1
  110. package/dist/src/transaction/session.d.ts.map +1 -1
  111. package/dist/src/transaction/session.js +18 -5
  112. package/dist/src/transaction/session.js.map +1 -1
  113. package/dist/src/transaction/transaction.d.ts +74 -15
  114. package/dist/src/transaction/transaction.d.ts.map +1 -1
  115. package/dist/src/transaction/transaction.js +35 -15
  116. package/dist/src/transaction/transaction.js.map +1 -1
  117. package/dist/src/transaction/validator.d.ts +25 -4
  118. package/dist/src/transaction/validator.d.ts.map +1 -1
  119. package/dist/src/transaction/validator.js +45 -5
  120. package/dist/src/transaction/validator.js.map +1 -1
  121. package/dist/src/transactor/block-floors.d.ts +12 -1
  122. package/dist/src/transactor/block-floors.d.ts.map +1 -1
  123. package/dist/src/transactor/block-floors.js +14 -1
  124. package/dist/src/transactor/block-floors.js.map +1 -1
  125. package/dist/src/transactor/network-transactor.d.ts +8 -0
  126. package/dist/src/transactor/network-transactor.d.ts.map +1 -1
  127. package/dist/src/transactor/network-transactor.js +8 -4
  128. package/dist/src/transactor/network-transactor.js.map +1 -1
  129. package/dist/src/transactor/transactor-source.d.ts +11 -0
  130. package/dist/src/transactor/transactor-source.d.ts.map +1 -1
  131. package/dist/src/transactor/transactor-source.js +5 -1
  132. package/dist/src/transactor/transactor-source.js.map +1 -1
  133. package/dist/src/transactor/transactor.d.ts +8 -0
  134. package/dist/src/transactor/transactor.d.ts.map +1 -1
  135. package/dist/src/transform/cache-source.d.ts +7 -0
  136. package/dist/src/transform/cache-source.d.ts.map +1 -1
  137. package/dist/src/transform/cache-source.js +14 -18
  138. package/dist/src/transform/cache-source.js.map +1 -1
  139. package/package.json +1 -1
  140. package/src/collection/action.ts +13 -5
  141. package/src/collection/collection.ts +250 -76
  142. package/src/collection/struct.ts +38 -8
  143. package/src/collection/write-attempts.ts +213 -109
  144. package/src/collections/diary/diary.ts +5 -1
  145. package/src/collections/tree/tree.ts +18 -11
  146. package/src/hlc/clock-store.ts +68 -0
  147. package/src/hlc/clock.ts +196 -0
  148. package/src/hlc/hlc.ts +56 -0
  149. package/src/hlc/index.ts +4 -0
  150. package/src/hlc/skew.ts +55 -0
  151. package/src/index.ts +2 -0
  152. package/src/lane/index.ts +1 -0
  153. package/src/lane/lane.ts +54 -0
  154. package/src/log/log.ts +341 -310
  155. package/src/log/struct.ts +62 -1
  156. package/src/network/i-repo.ts +11 -1
  157. package/src/network/stale-failure.ts +31 -7
  158. package/src/network/struct.ts +805 -770
  159. package/src/offline/entry.ts +16 -0
  160. package/src/offline/journal.ts +10 -0
  161. package/src/offline/queue.ts +38 -4
  162. package/src/offline/status.ts +7 -0
  163. package/src/testing/test-transactor.ts +1065 -1053
  164. package/src/transaction/actions-engine.ts +3 -0
  165. package/src/transaction/coordinator.ts +229 -54
  166. package/src/transaction/entry-commit.ts +56 -14
  167. package/src/transaction/errors.ts +60 -0
  168. package/src/transaction/index.ts +1 -1
  169. package/src/transaction/session.ts +18 -5
  170. package/src/transaction/transaction.ts +90 -17
  171. package/src/transaction/validator.ts +46 -5
  172. package/src/transactor/block-floors.ts +15 -1
  173. package/src/transactor/network-transactor.ts +15 -4
  174. package/src/transactor/transactor-source.ts +15 -1
  175. package/src/transactor/transactor.ts +9 -0
  176. package/src/transform/cache-source.ts +15 -17
@@ -1,770 +1,805 @@
1
- import type { CollectionId, BlockId, IBlock, ActionId, Transform, Transforms } from "../index.js";
2
- import type { ActionContext, ActionRev } from "../collection/action.js";
3
- import type { Transaction, ValidityRejection } from "../transaction/transaction.js";
4
- import type { DisputeResolutionProof } from "../log/struct.js";
5
- import type { PeerId } from "./types.js";
6
-
7
- export type ActionBlocks = {
8
- blockIds: BlockId[];
9
- actionId: ActionId;
10
- };
11
-
12
- export type ActionTransforms = {
13
- actionId: ActionId;
14
- rev?: number;
15
- transforms: Transforms;
16
- };
17
-
18
- export type ActionTransform = {
19
- actionId: ActionId;
20
- rev?: number;
21
- transform: Transform;
22
- };
23
-
24
- export type ActionPending = {
25
- blockId: BlockId;
26
- actionId: ActionId;
27
- transform?: Transform;
28
- };
29
-
30
- export type PendRequest = ActionTransforms & {
31
- /** What to do if there are any pending actions.
32
- * 'c' is continue normally,
33
- * 'f' is fail, returning the pending ActionIds,
34
- * 'r' is return, which fails but returns the pending ActionIds and their transforms */
35
- policy: 'c' | 'f' | 'r';
36
- /**
37
- * Present only on a validated multi-collection pend (`TransactionCoordinator.pendCollection`
38
- * under its default `pendValidation: 'transaction'`): the transaction to re-execute plus the
39
- * hash of ALL operations across all blocks it must produce. Absent on every pend that carries
40
- * bare transforms and is therefore not re-checkable — the single-collection `Collection.sync`
41
- * path, and a coordinator built with `pendValidation: 'none'` (the Quereus adapter's legacy
42
- * multi-tree commit, which has no statements to re-execute) — see
43
- * `ClusterConsensusConfig.unvalidatablePendPolicy` for what a validating receiver does with
44
- * that shape. ONE optional pair, deliberately: "transaction
45
- * without its hash" (or the reverse) was a state the old two independent optional fields
46
- * permitted and no producer ever created — and a receiver whose guard required both could be
47
- * talked out of validating by a sender that omitted one.
48
- */
49
- validation?: {
50
- /** The full transaction for replay/validation. */
51
- transaction: Transaction;
52
- /** Hash of ALL operations across all blocks the re-executed transaction must produce. */
53
- operationsHash: string;
54
- };
55
- /** For multi-collection transactions: supercluster nominees for consensus */
56
- superclusterNominees?: PeerId[];
57
- /**
58
- * Aged, advisory retry priority for a pend that carries no transaction (default 0 when absent).
59
- * A validated multi-collection pend instead carries priority on the transaction inside
60
- * {@link PendRequest.validation} ({@link Transaction.priority}); this top-level field is the
61
- * carrier for every pend without one — a `Collection.sync` pend, and an unvalidated
62
- * coordinator pend (`pendValidation: 'none'`). A cluster member reads whichever is present as the first
63
- * `resolveRace` tiebreak. FAIRNESS-ONLY: it rides inside the signed cluster `message` (so it is
64
- * integrity-protected in transit) but MUST NOT affect the operations hash, stale-read checks, or
65
- * validity — a stale pend is still rejected regardless of priority.
66
- */
67
- priority?: number;
68
- /**
69
- * Per block, the committed revision of the base the author's update operations were computed
70
- * against (`Tracker.stagedBaseRevs`). Present for a block whose transform is update-only and
71
- * whose base the author knows; never for an inserted or deleted block (base-independent), and
72
- * absent for a block the author did not read through a source that reports revisions. Omitted
73
- * entirely when empty (`baseRevsField`): the request is hashed verbatim into every cohort
74
- * signature preimage, so a pend that declares nothing must serialize exactly as it did before
75
- * the field existed. Action-wide here; the transactor narrows it to each per-coordinator batch's
76
- * own block ids at send time, exactly as it narrows {@link CommitRequest.blockDigests}.
77
- *
78
- * Storage keeps it beside the pending record (`BlockMetadata.pendingBases` in db-p2p), so every
79
- * later step that applies the record can refuse to apply it to a different version of the block
80
- * — including the read-driven promotion in `StorageRepo.get`, which has no commit message to
81
- * consult. The commit's own `blockDigests[id].baseRev` is now the fallback for a record whose
82
- * pend named no base, not the primary check.
83
- */
84
- baseRevs?: BlockBaseRevs;
85
- /**
86
- * The writer's word that this pend, together with the other pends sent with it in one request
87
- * (`IRepo.pendMany`), is the action's whole reservation — every block the action will commit is in
88
- * that one request — and that the action's commit goes as one request to the coordinator this pend
89
- * goes to. Only then may a coordinator hold back the pend record's final delivery to the other
90
- * members and send it inside the commit's first request (`ClusterCoordinator.mayDeferPendDelivery`
91
- * in db-p2p): a member that refuses any of the record's pends late refuses that one commit record,
92
- * before anything of the action is durable. A send that pends in several requests before committing
93
- * any — several collections one request each under one action id, or one collection split across
94
- * coordinators — must never carry it: one request's late refusal would surface while another
95
- * request's commit may already have landed, tearing the action.
96
- *
97
- * Set by `TransactorSource.transact`, and by `TransactionCoordinator` for a transaction of exactly
98
- * one collection or for every request of a `pendMany` (whose commit goes through `commitMany`);
99
- * `NetworkTransactor.pend` keeps it only on a request carrying the whole pend.
100
- * `Collection.completeOwnEntry` re-sends one participant of a half-landed multi-collection action
101
- * through `transact`, and carries it too: that re-send pends and commits its one collection on its
102
- * own, so its late refusal stops only its own commit, as an on-time refusal would.
103
- * Omitted rather than `false`, for the same preimage reason as {@link baseRevs}; a coordinator on
104
- * an older build ignores it, and then delivers at once as it always did.
105
- */
106
- soleReservation?: true;
107
- /**
108
- * The writer's word that this write must not be committed by a lone node that knows it is not
109
- * alone (`SyncOptions.refuseSoloCommit`). A coordinator whose cohort for the write is only itself
110
- * refuses the pend — before reserving anything — when it knows of cohort members it could not
111
- * place in the cohort, is still waiting to hear from a configured bootstrap peer, or could not
112
- * route the write to itself, answering with a {@link ShortfallFailure} whose
113
- * {@link PromiseShortfall.soloRefused} names which (`CoordinatorRepo.pendSolo` in db-p2p). A
114
- * coordinator that is genuinely alone ignores it and pends as it always did, and so does every
115
- * coordinator whose cohort has more than one member.
116
- *
117
- * Carried by every send of the write's attempt cycle, the re-send a refresh makes to finish a torn
118
- * attempt included (`Collection.completeOwnEntry`). Every per-coordinator rebuild of the request
119
- * keeps it (`pendRequestForBatch` in `NetworkTransactor`), since a batch that dropped it would
120
- * lose the protection for that coordinator's share. Omitted rather than `false`, for the same
121
- * preimage reason as {@link baseRevs}: a write that does not set it serializes exactly as before.
122
- * A coordinator on an older build ignores it and commits alone at `local`; in a group of mixed
123
- * versions the offline queue's reachability gate is then the only protection.
124
- */
125
- refuseSolo?: true;
126
- };
127
-
128
- export type BlockActionStatus = ActionBlocks & {
129
- statuses: ('pending' | 'committed' | 'checkpointed' | 'aborted' | 'committed-invalidated')[];
130
- };
131
-
132
- /** How widely a successful write is known to be held at the moment it was acknowledged. */
133
- export type DurabilityQuorum =
134
- /** Every member of the resolved cohort confirmed it holds the revision. */
135
- | 'full'
136
- /** A strict majority confirmed — the acknowledgement bar — but at least one member did not.
137
- * Also the class of a torn action whose cohort confirmed everything it was asked for
138
- * (`withTornBlocks` clamps `full` down to this; `torn` then names the blocks, and `unconfirmed`
139
- * may be empty). */
140
- | 'majority'
141
- /** The cohort resolved, and it is this node alone. Nobody else holds the revision yet. When this
142
- * node knows of other members of the cohort that it could not reach (`IKeyNetwork.absentCohortMembers`),
143
- * they are named in `unconfirmed` and counted in `cohort`: the write is owed to them. With none
144
- * named, it is a correct, complete one-machine write. */
145
- | 'local'
146
- /** The cohort did NOT resolve: the lookup threw, or named nobody, or named a single peer that
147
- * is not this node. The write is on this node's storage and the network was never consulted.
148
- * Deliberately NOT `local`: a write that lands where its cohort resolved to is in the right
149
- * place, whereas this is a write whose correct destination is unknown. */
150
- | 'unrouted';
151
-
152
- /** What the answering layer knows about who holds a successful write. Each layer refines it:
153
- * `StorageRepo` answers for itself alone, `CoordinatorRepo` answers for the cohort the write ran
154
- * on, and `NetworkTransactor` merges the per-coordinator answers into one action-level answer.
155
- * Never a policy input — read it to DISPLAY or to REPAIR, never to decide acceptance.
156
- *
157
- * The only "this write is completely saved" test is `isFullyDurable` (`network/durability.ts`);
158
- * do not compare `quorum` by hand, because a `full` cohort report can still sit on an action that
159
- * abandoned blocks (`torn`). */
160
- export type WriteDurability = {
161
- readonly quorum: DurabilityQuorum;
162
- /** Cohort members confirmed to hold the write, including this node when it holds it.
163
- * For a commit this means "reported that its storage durably holds the revision"; for a pend
164
- * it means "accepted the pending record". The two are NOT comparable — a pend confers no
165
- * storage durability (see the note in `CoordinatorRepo.pendThroughCluster`). */
166
- readonly confirmed: number;
167
- /** Size of the cohort the write ran on. Zero exactly when `quorum` is 'unrouted'. For `local`
168
- * it is one plus the known members the write ran without, so `local` does not imply 1. */
169
- readonly cohort: number;
170
- /** Cohort members that did not confirm, by peer-id string. Empty when `quorum` is 'full'.
171
- * ABSENT (not empty) when the answering layer could not name the cohort — an empty array
172
- * here means "named the cohort, nobody is missing". On a `local` write these are the members
173
- * this node knows of but could not reach when it wrote alone. */
174
- readonly unconfirmed?: readonly string[];
175
- /** The cohort the write ran on, by peer-id string. Absent where the answering layer has no
176
- * cohort view at all (a bare `StorageRepo` verdict). */
177
- readonly cohortPeerIds?: readonly string[];
178
- /** Peer-id string of the node whose under-replication ledger recorded this write's missing
179
- * copies — the one node that will fire `BlockDurabilityReachedEvent` for these blocks when they
180
- * reach full replication. Set only below `full`, and only when every non-torn block's shortfall
181
- * was recorded. Absent: no node is tracking the shortfall (nothing to push from the coordinator,
182
- * a ledger fault, no ledger, a producer that predates the field), so no full-replication event
183
- * should be expected. Per cohort answer: each `otherCohorts` entry carries its own. */
184
- readonly recordedBy?: string;
185
- /** Present only on an action-level result assembled from MORE THAN ONE distinct coordinator
186
- * answer: the other answers. Identical answers are collapsed (`mergeDurability`), so a healthy
187
- * single-cohort commit has none; one cohort answering differently for two batches appears
188
- * twice. The scalar fields above always describe the WEAKEST answer, so a consumer that reads
189
- * only them is reading the binding constraint and is never over-optimistic. */
190
- readonly otherCohorts?: readonly WriteDurability[];
191
- /** Blocks this action wrote that are NOT committed — a torn sweep abandoned and cancelled them
192
- * (`NetworkTransactor.cancelAbandonedSweepBlocks`). Action-level commit results only.
193
- * These blocks NEVER heal by replication: their transform is gone, and only the writer
194
- * re-driving the action puts them back. */
195
- readonly torn?: readonly BlockId[];
196
- /** Action-level: every block this write committed, with the revision it committed at — what a
197
- * host holds to match full-replication events (`BlockDurabilityReachedEvent`, keyed by block and
198
- * revision) back to this write. Set by the db-core layer that issued the commit
199
- * (`withBlockRevs`), never by a coordinator and never on the wire. Excludes `torn` blocks: they
200
- * hold nothing. Merging two reports keeps, per block, the HIGHER revision — a block written at r
201
- * and again at r+1 by one write is covered by an event at r+1 or later. A `Record` rather than a
202
- * `Map` so the type stays plain JSON. */
203
- readonly blockRevs?: Readonly<Record<BlockId, number>>;
204
- };
205
-
206
- export type PendSuccess = {
207
- success: true;
208
- /** List of already pending actions that were found on blocks touched by this pend */
209
- pending: ActionPending[];
210
- /** The affected blocks */
211
- blockIds: BlockId[];
212
- /** Who accepted the pending record. REQUIRED, not optional: an absent field would read as plain
213
- * success, which is exactly the ambiguity this field exists to remove (a solo write, a write
214
- * whose cohort never resolved, and a quorum write all used to answer `{ success: true }`). */
215
- durability: WriteDurability;
216
- };
217
-
218
- export type StaleFailure = {
219
- success: false;
220
- /** The reason for the failure */
221
- reason?: string;
222
- /** List of actions that have already been committed and are newer than our known revision */
223
- missing?: ActionTransforms[];
224
- /** List of actions that are pending on the blocks touched by this pend */
225
- pending?: ActionPending[];
226
- /**
227
- * Explicit retryability. True when this failure is an optimistic-concurrency loss — the
228
- * requested revision was taken, or a rival pend holds the blocks — so a re-read, rebase and
229
- * re-pend can win. Set it only when the producer genuinely classified the failure; leave it
230
- * absent otherwise, and consumers fall back to inferring from `missing`/`pending`.
231
- * Read it through `isConflictFailure` rather than testing it directly.
232
- */
233
- conflict?: boolean;
234
- /**
235
- * The block that already occupies (or is past) the requested revision, and the revision the
236
- * responder holds for it.
237
- *
238
- * CONFIRMED-ONLY: set this only when the producer read the revision out of its own storage.
239
- * A producer that merely suspects staleness — or that learned of it from another peer's
240
- * free-form reject text — must leave it absent. Absent means "no confirmed number", never
241
- * "not stale".
242
- *
243
- * DIAGNOSTIC, NOT A RETRYABILITY SIGNAL: `conflict` (read via `isConflictFailure`) remains the
244
- * single source of truth for "can a re-read and re-pend win?". Never branch retry decisions on
245
- * the presence of this field.
246
- */
247
- staleAt?: { blockId: BlockId; rev: number };
248
- /** Never set on a lost race — an expiry is its own failure shape, {@link ExpiredFailure}. */
249
- expired?: never;
250
- /** Never set on a lost race — a cohort too few of whose members answered is its own failure
251
- * shape, {@link ShortfallFailure}. */
252
- shortfall?: never;
253
- /** Never set on a lost race — a write judged invalid is its own failure shape,
254
- * {@link RejectedFailure}. */
255
- rejected?: never;
256
- };
257
-
258
- /**
259
- * Why a cohort refused a write as expired: by each refusing member's own clock, the transaction's
260
- * `expiration` had already passed when the record reached it. Plain data, so it crosses the JSON repo
261
- * protocol intact. `TransactionExpiredError` is built from it, wherever it is raised.
262
- */
263
- export type TransactionExpiry = {
264
- /** The transaction's expiration (unix ms), as the writer's transactor set it from its own clock. */
265
- expiration: number;
266
- /** Per refusing cohort member (peer-id string), the clock reading (unix ms) it signed when it
267
- * judged the record expired (`Signature.expiredAt`). Never empty. */
268
- memberClocks: Record<string, number>;
269
- /** The coordinating node's clock (unix ms) when it concluded the refusal. */
270
- coordinatorClock: number;
271
- };
272
-
273
- /**
274
- * The cohort refused the write because the transaction had already EXPIRED by the members' clocks —
275
- * a clock disagreement between the writer and the cohort, not a lost race and not a judgement of the
276
- * write. Never retryable: every retry carries an expiration set by the same clock, and is refused the
277
- * same way until a clock is corrected. A sibling of {@link StaleFailure} rather than a field on it,
278
- * because "lost to a newer revision" is exactly what this is not; the fields it can never carry are
279
- * typed `never`, so a consumer reads `reason`, `missing` or `staleAt` off either shape unnarrowed.
280
- * Tell the two apart with `isExpiryFailure`, never by reading `reason`.
281
- */
282
- export type ExpiredFailure = {
283
- success: false;
284
- /** The coordinator's description of the refusal, for a log line. Never branch on it. */
285
- reason?: string;
286
- /** Always false: an expiry is never a conflict a re-read can win. */
287
- conflict: false;
288
- expired: TransactionExpiry;
289
- missing?: never;
290
- pending?: never;
291
- staleAt?: never;
292
- shortfall?: never;
293
- rejected?: never;
294
- };
295
-
296
- /**
297
- * Why a cohort's promise round fell short with no member refusing it as a lost race or a held block,
298
- * and too few rejecting it for a rejection: too few members answered. Plain data, so it crosses the
299
- * JSON repo protocol intact. `PromiseShortfallError` is built from it, wherever it is raised.
300
- */
301
- export type PromiseShortfall = {
302
- /** Approve votes the round received. */
303
- approvals: number;
304
- /** Reject votes the round received — fewer than would make the round a rejection. */
305
- rejections: number;
306
- /** How many members the cohort the round ran on has. */
307
- peerCount: number;
308
- /** The approvals the round needed: `ceil(peerCount × superMajorityThreshold)`. */
309
- needed: number;
310
- /** Peer-id strings of the cohort members that cast no promise vote at all. */
311
- silentPeers: string[];
312
- /**
313
- * Set only when no consensus round ran: a coordinator whose cohort for the write was only itself
314
- * refused to write alone, because the write asked it to (`PendRequest.refuseSolo`). The other
315
- * fields then describe the cohort the coordinator expected rather than one it asked: one approval
316
- * (its own), no rejections, the members it knows of and could not reach as `silentPeers`, and the
317
- * bar a cohort of that size would set. Absent on a shortfall a consensus round produced, so a log
318
- * or an application can tell "refused to write alone" from "a round heard too few".
319
- */
320
- soloRefused?: SoloRefusalReason;
321
- };
322
-
323
- /**
324
- * Why a lone coordinator refused a write that asked not to be committed alone
325
- * (`PendRequest.refuseSolo`, `CommitRequest.refuseSolo`):
326
- * - `absent-members`: its cohort for the write was only itself, and it knows of cohort members it
327
- * could not place in that cohort (`IKeyNetwork.absentCohortMembers`);
328
- * - `awaiting-bootstrap`: its cohort was only itself and it is still waiting to hear from a peer it
329
- * was configured to join through (`IKeyNetwork.awaitingBootstrapContact`);
330
- * - `unrouted`: the cohort lookup failed, named nobody, or named one peer that is not this node.
331
- */
332
- export type SoloRefusalReason = 'absent-members' | 'awaiting-bootstrap' | 'unrouted';
333
-
334
- /**
335
- * The cohort refused the pend because too few of its members ANSWERED the promise round for it to
336
- * reach its bar — silence, not a judgement of the write and not a lost race. Not retryable by a write
337
- * path: every coordinator of that cohort meets the same silent members, so a re-read and re-pend fails
338
- * the same way until they come back. A sibling of {@link StaleFailure} and {@link ExpiredFailure},
339
- * with the fields it can never carry typed `never`, so a consumer reads `reason`, `missing` or
340
- * `staleAt` off any of them unnarrowed. Tell it apart with `isShortfallFailure`, never by reading
341
- * `reason`. A pend answer only: a commit that falls short is still thrown (see
342
- * `CoordinatorRepo.commit`).
343
- */
344
- export type ShortfallFailure = {
345
- success: false;
346
- /** The coordinator's description of the refusal, for a log line. Never branch on it. */
347
- reason?: string;
348
- /** Always false: silence is not a conflict a re-read can win. */
349
- conflict: false;
350
- shortfall: PromiseShortfall;
351
- missing?: never;
352
- pending?: never;
353
- staleAt?: never;
354
- expired?: never;
355
- rejected?: never;
356
- };
357
-
358
- /**
359
- * One refusal behind a {@link TransactionInvalidity}: a cohort member's validity-marked reject vote
360
- * (`Signature`'s `validity`), or the validity verdict of the coordinating node's own storage-tier check
361
- * (`StorageRepo.pend`, for a cohort of one, where no vote is cast).
362
- */
363
- export type ValidityRefusal = ValidityRejection & {
364
- /** The refusing member's peer-id string. Absent for a refusal a node's storage made without a vote. */
365
- peerId?: string;
366
- /** The refuser's description, free-form, for a log line. Never branch on it. */
367
- reason?: string;
368
- };
369
-
370
- /**
371
- * Why a write was refused as INVALID: the members that sank it judged the transaction itself wrong
372
- * (see {@link ValidityRejection} for which refusals qualify), and no refusal of any other kind sank it
373
- * beside them, bar expiry votes. Plain data, so it crosses the JSON repo protocol intact.
374
- * `ValidityRejectedError` is built from it, wherever it is raised.
375
- */
376
- export type TransactionInvalidity = {
377
- /** Every validity refusal that sank the write. Never empty. */
378
- refusals: ValidityRefusal[];
379
- };
380
-
381
- /**
382
- * The cohort refused the write because the members that sank it judged it INVALID — the transaction
383
- * failed its re-execution, its operations hash, its stamp or its client signature. Never retryable:
384
- * re-sending the same content to the same checks is refused the same way. A sibling of
385
- * {@link StaleFailure}, {@link ExpiredFailure} and {@link ShortfallFailure}, with the fields it can
386
- * never carry typed `never`, so a consumer reads `reason`, `missing` or `staleAt` off any of them
387
- * unnarrowed. Tell it apart with `isRejectedFailure`, never by reading `reason`.
388
- *
389
- * A pend answer only, and only when nothing else could explain the rejection: a reject vote with no
390
- * validity marker beside the marked ones (a stale revision, a member on an older build) leaves the
391
- * rejection unclassified, and a revision loss the coordinator's own storage confirms is returned as
392
- * the {@link StaleFailure} it is, since the writer's rebase sends different content.
393
- */
394
- export type RejectedFailure = {
395
- success: false;
396
- /** The coordinator's description of the refusal, for a log line. Never branch on it. */
397
- reason?: string;
398
- /** Always false: a verdict on the content is not a conflict a re-read can win. */
399
- conflict: false;
400
- rejected: TransactionInvalidity;
401
- missing?: never;
402
- pending?: never;
403
- staleAt?: never;
404
- expired?: never;
405
- shortfall?: never;
406
- };
407
-
408
- /** Every way a pend or a commit can be refused with an answer rather than a throw. */
409
- export type WriteFailure = StaleFailure | ExpiredFailure | ShortfallFailure | RejectedFailure;
410
-
411
- export type PendResult = PendSuccess | WriteFailure;
412
-
413
- /** What one block will materialize to at the committing revision, declared by the client that
414
- * authored the transforms. */
415
- export type BlockContentDigest = {
416
- /** base64url SHA-256 of canonicalJson(block) - see canonicalBlockHash. */
417
- digest: string;
418
- /** Committed revision of the base the digest was computed from. ABSENT when the block's
419
- * transform carries an insert, which makes the result base-independent and therefore
420
- * checkable by every member regardless of how far behind it is. */
421
- baseRev?: number;
422
- };
423
-
424
- /** Per-block content declarations riding on a commit. Optional per id: a block the client cannot
425
- * digest without a network read is simply omitted, and falls back to corroboration downstream. */
426
- export type BlockContentDigests = Record<BlockId, BlockContentDigest>;
427
-
428
- /** Per block, the committed revision its update operations were computed against — the shape
429
- * `Tracker.stagedBaseRevs` produces and {@link PendRequest.baseRevs} carries. Optional per id: an
430
- * inserted or deleted block is base-independent and never named; a block updated without a known
431
- * base is simply omitted. */
432
- export type BlockBaseRevs = Record<BlockId, number>;
433
-
434
- export type CommitRequest = ActionBlocks & {
435
- /** The header block of the collection, present only when this commit creates the collection
436
- * (the header is a fresh insert). Collection-identifying metadata, not an ordering signal —
437
- * the header commits after the tail, like any other touched block.
438
- * Consumed by dispute reporting (`dispute-service.ts`) as a fallback to name the collection. */
439
- headerId?: BlockId;
440
- /** The tail block of the log. Unconditionally the first block committed on every member, whether
441
- * it travels alone or with the action's other blocks — the ordering `Collection.bootstrapContext`
442
- * relies on. */
443
- tailId: BlockId;
444
- /** The new revision for the committed action */
445
- rev: number;
446
- /** Per-block content declarations for the committing action — see {@link BlockContentDigests}.
447
- * Rides inside the consensus message, so the generic cluster message hash folds it into every
448
- * cohort signature with no change to the hash helpers. Action-wide here; the transactor narrows
449
- * it to each per-coordinator batch's own block ids before sending (`RepoCommitRequest`). */
450
- // NOTE: accepted tradeoff — this field stays OPTIONAL even though an omitted declaration has a real
451
- // cost: `StorageRepo.persistProofIfContentMatches` retains no `BlockCommitProof` for a block that
452
- // declared no digest (`commit:proof-undeclared`), and a block with no proof is refused by any
453
- // receiver running the default `requirePushCertificate: true` (`push:reject-uncertified
454
- // reason=no-proof`). Such a block stays readable and still repairs by corroboration while two or
455
- // more holders remain, but it can never GAIN a
456
- // holder by push — so spread-on-churn and cohort-growth healing silently stop maintaining its
457
- // replication factor. Kept optional anyway because: (a) required-but-nullable is the strongest form
458
- // available and still permits `undefined`, so it does not make the bad state unrepresentable, only
459
- // typed out loud; (b) some commits legitimately declare nothing — delete-only/tombstone commits
460
- // materialize no content, and a member on a lagging base abstains; (c) measured migration cost of
461
- // required-but-nullable here and on `RepoCommitRequest` is >=194 `tsc --noEmit` errors across >=39
462
- // files (39/9 in db-core, 155/30 in db-p2p, quereus-plugin-optimystic unmeasured), nearly all fixed
463
- // by literally writing `undefined`. Revisit if undeclared commits ever become common enough to show
464
- // up as replication-factor decay.
465
- blockDigests?: BlockContentDigests;
466
- /**
467
- * {@link PendRequest.refuseSolo}, on the commit. A coordinator whose cohort for the commit is only
468
- * itself refuses it on the same rule, before minting a proof or applying anything, with a
469
- * conflict-shaped refusal (`SOLO_COMMIT_REFUSED_REASON` in db-p2p), since a commit cannot answer
470
- * with a shortfall. That is reached when the pend ran on a real cohort and the partner dropped
471
- * before the commit: the writer cancels and retries, and the retry's pend meets the pend-side
472
- * refusal. Carried through every per-coordinator rebuild of the commit (`repoCommitRequest` in
473
- * `NetworkTransactor`); omitted rather than `false` for the preimage reason
474
- * {@link blockDigests} is.
475
- */
476
- refuseSolo?: true;
477
- };
478
-
479
- /**
480
- * Originates a compensating invalidation through the same critical-cluster consensus as any
481
- * transaction: it takes a revision slot and serializes against concurrent commits. Each member
482
- * applies it deterministically — verifying {@link resolution} as an invalidation certificate, then
483
- * writing the per-block compensating revisions and appending the durable invalidation log entry.
484
- *
485
- * Carries everything a member needs to apply the reversal without trusting the originator: the
486
- * target action, the blocks it wrote, the owning collection's log, and the signed proof.
487
- */
488
- export type InvalidateRequest = {
489
- /** actionId of the committed action being reversed. */
490
- invalidatedActionId: ActionId;
491
- /** rev of the invalidated entry — pins which block revisions to roll back. */
492
- invalidatedRev: number;
493
- /** Blocks the invalidated action wrote (its commit's blockIds). */
494
- blockIds: BlockId[];
495
- /** The collection (log) the invalidated action belongs to — where the compensating entry lands. */
496
- collectionId: CollectionId;
497
- /** The invalidation certificate (challenger-wins + signed 2/3 decisive arbitrator votes). */
498
- resolution: DisputeResolutionProof;
499
- };
500
-
501
- export type CommitResult = CommitSuccess | WriteFailure;
502
-
503
- export type CommitSuccess = {
504
- success: true;
505
- /** If present, the identified collection acts as the coordinator for the multi-collection transaction */
506
- coordinatorId?: CollectionId;
507
- /** Who holds the committed revision. REQUIRED for the same reason as {@link PendSuccess.durability}:
508
- * a quorum commit, a solo commit, a commit whose cohort lookup failed, and a torn multi-block
509
- * commit all answered `{ success: true }` before this field existed, and a writer could not tell
510
- * them apart (GitHub #19). Test it through `isFullyDurable`, never by comparing `quorum`. */
511
- durability: WriteDurability;
512
- };
513
-
514
- export type BlockActionState = {
515
- /** The latest action that has been committed */
516
- latest?: ActionRev;
517
- /** If present, the specified actions are pending */
518
- pendings?: ActionId[];
519
- };
520
-
521
- export type BlockGets = {
522
- blockIds: BlockId[];
523
- context?: ActionContext; // Latest if this is omitted
524
- /** Per block, the lowest revision the ASKER can accept for it — its floor. Omit a block that
525
- * has none; omit the field entirely when no block does.
526
- *
527
- * A floor is knowledge only the asker holds: a collection that walked the log entry
528
- * "action A, committed at revision r, changed block X" knows a read of X at a context at or
529
- * above `r` must come back materialized at `r` or later, while the repo answering may honestly
530
- * believe its older copy is current. `TransactorSource.tryGet` fills this from the collection's
531
- * `BlockFloors`, and a refresh that follows a refused write puts the revision the refusal
532
- * confirmed on its read of the log tail (`Collection.readLogEnds`). `NetworkTransactor.get`
533
- * treats an answer under a block's floor as NOT answered, so it earns the same second-chance
534
- * round against a different coordinator that `unavailable` and `unconfirmedAheadRev` earn.
535
- *
536
- * On the wire, per batch: `NetworkTransactor.get` forwards to each downstream `IRepo.get` the
537
- * floors of that batch's blocks alone, and leaves the field off a batch none of whose blocks has
538
- * one. A peer that predates the field ignores it and answers as it always did, which is safe
539
- * because the reader-side check is what enforces the floor, on the merged answer, either way
540
- * (`TransactorSource` / `BlockFloorCheck`) — so an `ITransactor` that ignores the field
541
- * (`TestTransactor`, the reference peer's) stays correct too. A coordinator that does read it
542
- * (`CoordinatorRepo.get`) consults its cohort at once for a present block whose local revision
543
- * is below the floor, whatever its read-repair window says, and remembers the floor it consulted
544
- * under so a floor no machine can meet costs one consult per window; it never refuses on a floor.
545
- *
546
- * NOTE: the retry `NetworkTransactor.get` runs is per BATCH, not per block, so one below-floor
547
- * block re-asks every block that shared its coordinator. Costs nothing today — `tryGet` asks
548
- * for one block per request, and the one batched floored read is a refresh's header-and-tail
549
- * read, whose other block is the header the refresh needed from the second machine anyway —
550
- * but a read source that batches unrelated blocks would pay it. Split the retry payload down to
551
- * the failing block ids then. */
552
- floors?: Record<BlockId, number>;
553
- /** Per block, what the ASKER itself holds of it: its committed latest `(rev, actionId)`, or `null`
554
- * when it holds no committed revision. A block the asker could not read locally is left out, and
555
- * the field is left off when none could be read.
556
- *
557
- * It exists because a coordinator's cohort consult asks every other cohort member "what do you hold
558
- * for this block?", and when the asker is itself a member that question has just been answered in
559
- * its own request. A coordinator that reads the field uses the statement as that member's answer
560
- * instead of asking it over the network (`CoordinatorRepo.get`), but only where doing so loses
561
- * nothing: the statement is "nothing", or a revision at or below the coordinator's own (at an equal
562
- * revision, only under the same action). A statement ahead of the coordinator is consulted as
563
- * before, because acquiring or judging that revision needs the member's archive and commit proof,
564
- * which a stated revision carries neither of. A statement can only lower what the coordinator
565
- * concludes about being behind; it never makes it adopt anything.
566
- *
567
- * The statement names no peer. WHO is stating is the identity of the connection the request
568
- * arrived on (`MessageOptions.asker`), so a request cannot speak for another member. Filled below
569
- * the transactor, by the reader's remote-repo decorator (`stateHoldingsOnReads` in
570
- * `packages/db-p2p/src/repo/stated-holdings.ts`), and only on a read sent to another machine. A
571
- * peer that predates the field ignores it and consults as before. */
572
- askerHolds?: Record<BlockId, ActionRev | null>;
573
- /** Ask the answering repo whether each block's CURRENT content was built from this committed
574
- * action at this revision; it answers per block in {@link GetBlockResult.lineage}. On the wire,
575
- * unlike `floors`. A repo that predates the field leaves `lineage` absent, which every consumer
576
- * reads as `unknown`. Asked only by a writer deciding whether its own superseded write is saved
577
- * (`ITransactor.getLineage`); an ordinary read never sets it. */
578
- lineageOf?: ActionRev;
579
- /** The asker does not want this read to start the read-repair consult that the lazy window alone
580
- * would run BEHIND the read: a held block whose window has expired (or that the lazy mode's
581
- * `readRepairSampleRate` picked for a re-check) is answered from the answering repo's own copy and
582
- * no cohort consult is started for it. An effort hint, never a correctness one —
583
- * the doubt an earlier consult recorded still stamps `unconfirmedAheadRev`, and the window's
584
- * freshness stamp is untouched, so the next read without the flag consults as before.
585
- *
586
- * It never skips a consult whose answer the read depends on: a block missing locally (the absence
587
- * verdict), a held block whose read carries a floor above it ({@link floors}), and every consult
588
- * under `'paranoid'` read-repair still run and still block. Whole-read, so `NetworkTransactor.get`
589
- * forwards it on every batch: a remote coordinator also skips its own background consult. A peer
590
- * that predates the field ignores it and consults as before. Meant for the node's watch tick,
591
- * through `Collection.readCommittedTails`, which reads every watched tail on a timer. Distinct from
592
- * `skipClusterFetch`, the sync protocol's guard, which skips every consult and never flags. */
593
- skipWindowConsult?: true;
594
- };
595
-
596
- /**
597
- * Whether a block's current content was BUILT FROM a given committed `(actionId, rev)` — the
598
- * write's transform is part of what the block holds now, even though later actions have since
599
- * taken later revisions.
600
- *
601
- * - `contains` — it was. Holding that exact revision as the latest counts.
602
- * - `excludes` — it provably was not: another action holds that revision of the block, or the
603
- * block's history spans that revision without it. Nothing can land the write there any more.
604
- * - `behind` — the block has not reached that revision (or does not exist). The write is not
605
- * there, and could only get there through one of its own pending records.
606
- * - `unknown` — not established either way.
607
- *
608
- * One repo answers from its own records only ({@link GetBlockResult.lineage}); a transactor
609
- * answers for the block's cohort ({@link ActionLineage}).
610
- */
611
- export type BlockLineage = 'contains' | 'excludes' | 'behind' | 'unknown';
612
-
613
- /** A cohort-level answer to "is this committed write part of what these blocks hold now?" — see
614
- * `ITransactor.getLineage`. */
615
- export type ActionLineage = {
616
- /** One answer per requested block id, in request order. */
617
- blocks: BlockLineage[];
618
- /** Who holds the write, present exactly when EVERY block answered `contains`: the weakest
619
- * block's cohort report, by the same rule a commit's durability is merged. */
620
- durability?: WriteDurability;
621
- };
622
-
623
- /** Why a repo could not establish whether a block exists. Present ONLY when the repo
624
- * knows its own answer is a guess; an absent field is an authoritative answer. */
625
- export type BlockUnavailableReason =
626
- /** Records for this block exist here but it cannot be reconstructed locally — a
627
- * revision was received with no base to apply it to, or its history is truncated. */
628
- | 'unmaterializable'
629
- /** Nothing is held locally; PART of the cohort answered and part could not be asked.
630
- * A silent peer could be the sole holder, so the absence is a guess — but other
631
- * coordinators are reachable, so asking one of them can still settle it. Also the
632
- * fallback when the consult could not run at all (the cohort lookup itself failed):
633
- * a routing failure says nothing about how many cohort members were reachable. */
634
- | 'peers-unreachable'
635
- /** Nothing is held locally and NO cohort member outside the answering node could be
636
- * asked at all. Distinct from `peers-unreachable` in exactly the way that matters to
637
- * a caller: there is no better-connected coordinator to re-ask, so the answer will
638
- * not improve until that node's connectivity does. Its local view is all there is.
639
- * Also the answer of a node whose cohort view holds only itself while a peer it was
640
- * configured to join through has never been heard from
641
- * (`IKeyNetwork.awaitingBootstrapContact`): it knows of a machine outside itself and
642
- * has not reached it. */
643
- | 'cohort-unreachable'
644
- /** Nothing is held locally, but a cohort peer positively CLAIMED a revision of this
645
- * block, and the answering node could neither corroborate that claim to a quorum nor
646
- * acquire the content. The block is known to exist somewhere; reporting it absent
647
- * would be a lie regardless of whether anyone was silent. */
648
- | 'claimed-elsewhere'
649
- /** Nothing is held locally and the answering node had nobody to ask (its cohort view
650
- * was empty, or only itself), but the read carried a floor for the block
651
- * ({@link BlockGets.floors}): the asker walked a log entry committing a revision of it.
652
- * The block is known to exist, from the asker's own evidence, so "never created" would
653
- * contradict what the asker already knows. Unlike `cohort-unreachable` this is never
654
- * "the local view is all there is": another machine may hold the block, and asking one
655
- * is the remedy. */
656
- | 'named-by-log';
657
-
658
- export type GetBlockResult = {
659
- /** The retrieved block - undefined if the block was deleted */
660
- block?: IBlock;
661
- /** The latest and pending states of the repo that retrieved the block */
662
- state: BlockActionState;
663
- /** The revision the returned `block` actually IS — the `(rev, actionId)` of the highest
664
- * committed revision of THIS block at or below the caller's {@link BlockGets.context}`.rev`.
665
- * Differs from `state.latest` only for a revision-pinned read of a block that has committed
666
- * further since the pin; for an unpinned read the two agree.
667
- *
668
- * This — not `state.latest` — is what a read observed, so it is what a read dependency must
669
- * record (recording `latest` would claim the reader saw content it never read, and the
670
- * validator's stale-read check would wrongly pass), and it is the only correct label for the
671
- * content when it is passed on (a block-repair archive, a replica push). `state.latest` keeps
672
- * its own meaning: the newest revision the answering repo holds for the block.
673
- *
674
- * The revision and its action id are ONE field, deliberately: a site that must label content
675
- * it is holding needs both, and two independently-optional fields could disagree — which is
676
- * exactly the mislabel this exists to make unrepresentable (old bytes served under a newer
677
- * revision's number and action id, which a receiver keyed by action id then writes over its
678
- * own good copy; see `serveBlockArchive`).
679
- *
680
- * Optional: a producer that does not know what it materialized leaves it absent rather than
681
- * guessing, and consumers fall back to `state.latest` (read dependencies record
682
- * `state.latest?.rev ?? 0`; a labelling site refuses to label a pinned read). */
683
- materialized?: ActionRev;
684
- /** Set when this repo could not determine whether the block exists — its answer is a
685
- * guess, not an authoritative absent. Every producer that omits it (including
686
- * TestTransactor) keeps meaning "authoritative". */
687
- unavailable?: BlockUnavailableReason;
688
- /** Set when this repo served committed content it could NOT confirm is current: its
689
- * freshness consult did not converge AND a cohort peer claimed a strictly higher
690
- * revision than the one served, within the view the caller asked for (unpinned, or
691
- * pinned at or above the claim). Carries that claimed revision. The claim did not
692
- * drive a successful repair — it failed the read-repair corroboration quorum, or was
693
- * corroborated but the content could not be acquired — so it is evidence of DOUBT,
694
- * never a revision to adopt. Distinct from `unavailable`, which is about EXISTENCE:
695
- * the content here is real, it may just be behind. Absent = confirmed, so every
696
- * producer that omits it keeps its meaning. */
697
- unconfirmedAheadRev?: number;
698
- /** This repo's answer to {@link BlockGets.lineageOf}, from its OWN records only — no cohort
699
- * view. Absent when the question was not asked, or the repo predates it. */
700
- lineage?: BlockLineage;
701
- };
702
-
703
- /**
704
- * Thrown by a block read when the responsible repo could not determine whether the
705
- * block exists. Distinct from "the block is absent" (undefined) and from a transport
706
- * failure — this node's data is genuinely indeterminate and the caller must not treat
707
- * it as empty. Not a StaleFailure: `Collection.sync` does not retry it.
708
- */
709
- export class BlockUnavailableError extends Error {
710
- constructor(readonly blockId: BlockId, readonly reason: BlockUnavailableReason) {
711
- super(`Block ${blockId} is unavailable (${reason}): the repo could not determine whether it exists`);
712
- this.name = 'BlockUnavailableError';
713
- }
714
- }
715
-
716
- /**
717
- * Thrown by an unpinned ("give me latest") block read whose surviving answer carries
718
- * {@link GetBlockResult.unconfirmedAheadRev}: every reachable coordinator served content
719
- * it could not confirm is current, while a cohort peer claimed a strictly higher revision
720
- * nothing could corroborate or refute. Sibling of {@link BlockUnavailableError} — that one
721
- * is about EXISTENCE (blockless answer, could not find out), this one about CURRENCY (real
722
- * content, possibly behind). Not a StaleFailure: `Collection.sync` does not retry it.
723
- */
724
- export class BlockPossiblyStaleError extends Error {
725
- constructor(readonly blockId: BlockId, readonly claimedRev: number) {
726
- super(`Block ${blockId} may be stale: a cohort peer claimed rev ${claimedRev} that no reachable coordinator could confirm or refute`);
727
- this.name = 'BlockPossiblyStaleError';
728
- }
729
- }
730
-
731
- export type GetBlockResults = Record<BlockId, GetBlockResult>;
732
-
733
- /**
734
- * Result of validating a transaction in a PendRequest.
735
- */
736
- export type PendValidationResult = {
737
- /** Whether validation passed */
738
- valid: boolean;
739
- /** Reason for validation failure (if valid=false) */
740
- reason?: string;
741
- /** Set only on a failure that judges the transaction itself wrong; see {@link ValidityRejection}. */
742
- validity?: ValidityRejection;
743
- };
744
-
745
- /**
746
- * Hook for validating transactions in PendRequests.
747
- *
748
- * This hook is called by the storage layer when receiving a PendRequest
749
- * that carries a `validation` payload (the transaction plus its operations
750
- * hash). If validation fails — or the hook throws — the pend operation is
751
- * rejected. What a hook-configured node does with a pend carrying NO
752
- * `validation` payload is a policy decision
753
- * (`StorageRepoOptions.unvalidatablePendPolicy` in db-p2p).
754
- *
755
- * If the hook is not provided, validation is skipped (storage-only nodes).
756
- */
757
- export type PendValidationHook = (
758
- transaction: Transaction,
759
- operationsHash: string
760
- ) => Promise<PendValidationResult>;
761
-
762
- // Backward compatibility aliases (deprecated - use Action* names)
763
- /** @deprecated Use ActionBlocks instead */
764
- export type TrxBlocks = ActionBlocks;
765
- /** @deprecated Use ActionTransforms instead */
766
- export type TrxTransforms = ActionTransforms;
767
- /** @deprecated Use ActionTransform instead */
768
- export type TrxTransform = ActionTransform;
769
- /** @deprecated Use ActionPending instead */
770
- export type TrxPending = ActionPending;
1
+ import type { CollectionId, BlockId, IBlock, ActionId, Transform, Transforms } from "../index.js";
2
+ import type { ActionContext, ActionRev } from "../collection/action.js";
3
+ import type { Transaction, ValidityRejection } from "../transaction/transaction.js";
4
+ import type { DisputeResolutionProof } from "../log/struct.js";
5
+ import type { Hlc } from "../hlc/hlc.js";
6
+ import type { Lane } from "../lane/lane.js";
7
+ import type { PeerId } from "./types.js";
8
+
9
+ export type ActionBlocks = {
10
+ blockIds: BlockId[];
11
+ actionId: ActionId;
12
+ };
13
+
14
+ export type ActionTransforms = {
15
+ actionId: ActionId;
16
+ rev?: number;
17
+ transforms: Transforms;
18
+ };
19
+
20
+ export type ActionTransform = {
21
+ actionId: ActionId;
22
+ rev?: number;
23
+ transform: Transform;
24
+ };
25
+
26
+ export type ActionPending = {
27
+ blockId: BlockId;
28
+ actionId: ActionId;
29
+ transform?: Transform;
30
+ };
31
+
32
+ export type PendRequest = ActionTransforms & {
33
+ /** What to do if there are any pending actions.
34
+ * 'c' is continue normally,
35
+ * 'f' is fail, returning the pending ActionIds,
36
+ * 'r' is return, which fails but returns the pending ActionIds and their transforms */
37
+ policy: 'c' | 'f' | 'r';
38
+ /**
39
+ * Present only on a validated multi-collection pend (`TransactionCoordinator.pendCollection`
40
+ * under its default `pendValidation: 'transaction'`): the transaction to re-execute plus the
41
+ * hash of ALL operations across all blocks it must produce. Absent on every pend that carries
42
+ * bare transforms and is therefore not re-checkable — the single-collection `Collection.sync`
43
+ * path, and a coordinator built with `pendValidation: 'none'` (the Quereus adapter's legacy
44
+ * multi-tree commit, which has no statements to re-execute) — see
45
+ * `ClusterConsensusConfig.unvalidatablePendPolicy` for what a validating receiver does with
46
+ * that shape. ONE optional pair, deliberately: "transaction
47
+ * without its hash" (or the reverse) was a state the old two independent optional fields
48
+ * permitted and no producer ever created — and a receiver whose guard required both could be
49
+ * talked out of validating by a sender that omitted one.
50
+ */
51
+ validation?: {
52
+ /** The full transaction for replay/validation. */
53
+ transaction: Transaction;
54
+ /** Hash of ALL operations across all blocks the re-executed transaction must produce. */
55
+ operationsHash: string;
56
+ };
57
+ /** For multi-collection transactions: supercluster nominees for consensus */
58
+ superclusterNominees?: PeerId[];
59
+ /**
60
+ * The HLC of the write this pend carries (`LogEntry.hlc`, `Transaction.hlc`): the same value the
61
+ * log entry inside `transforms` carries, put here so a storage node observes the HLC of every
62
+ * write it stores without parsing log blocks out of transforms (docs/crdt-sync.md §Migration
63
+ * Path, Stage 1). The writer always sets it (`TransactorSource.transact`,
64
+ * `TransactionCoordinator.pendRequestFor`); optional on the wire because an older writer sends
65
+ * none, and because the re-send of a retained attempt has none at hand. Observational: a member
66
+ * reads it into its clock and never judges the pend by it. Omitted rather than `undefined`, for
67
+ * the same preimage reason as {@link baseRevs}.
68
+ */
69
+ hlc?: Hlc;
70
+ /**
71
+ * The lane of the write this pend carries (`ActionEntry.lane`, `Transaction.lane`): whether its
72
+ * conflicts with concurrent writes are the quorum's to decide (`serializable`) or may be merged
73
+ * later under the collection's declaration (`convergent`) — see `Lane` in
74
+ * `packages/db-core/src/lane/lane.ts`. The same value the log entry inside `transforms` carries,
75
+ * put here so a storage node reads it without parsing log blocks. Every writer of this build sets
76
+ * it (`TransactorSource.transact`, `TransactionCoordinator.pendRequestFor`); optional on the wire
77
+ * because an older writer sends none. A reader treats absence as "not stated", never as a lane.
78
+ * Observational: nothing judges the pend by it — a validating member checks the lane the
79
+ * transaction inside {@link validation} claims (`TransactionValidator.validate`) — and the
80
+ * coordinator's solo log lines report it. Omitted rather than `undefined`, for the same preimage
81
+ * reason as {@link baseRevs}.
82
+ */
83
+ lane?: Lane;
84
+ /**
85
+ * Aged, advisory retry priority for a pend that carries no transaction (default 0 when absent).
86
+ * A validated multi-collection pend instead carries priority on the transaction inside
87
+ * {@link PendRequest.validation} ({@link Transaction.priority}); this top-level field is the
88
+ * carrier for every pend without one — a `Collection.sync` pend, and an unvalidated
89
+ * coordinator pend (`pendValidation: 'none'`). A cluster member reads whichever is present as the first
90
+ * `resolveRace` tiebreak. FAIRNESS-ONLY: it rides inside the signed cluster `message` (so it is
91
+ * integrity-protected in transit) but MUST NOT affect the operations hash, stale-read checks, or
92
+ * validity — a stale pend is still rejected regardless of priority.
93
+ */
94
+ priority?: number;
95
+ /**
96
+ * Per block, the committed revision of the base the author's update operations were computed
97
+ * against (`Tracker.stagedBaseRevs`). Present for a block whose transform is update-only and
98
+ * whose base the author knows; never for an inserted or deleted block (base-independent), and
99
+ * absent for a block the author did not read through a source that reports revisions. Omitted
100
+ * entirely when empty (`baseRevsField`): the request is hashed verbatim into every cohort
101
+ * signature preimage, so a pend that declares nothing must serialize exactly as it did before
102
+ * the field existed. Action-wide here; the transactor narrows it to each per-coordinator batch's
103
+ * own block ids at send time, exactly as it narrows {@link CommitRequest.blockDigests}.
104
+ *
105
+ * Storage keeps it beside the pending record (`BlockMetadata.pendingBases` in db-p2p), so every
106
+ * later step that applies the record can refuse to apply it to a different version of the block
107
+ * — including the read-driven promotion in `StorageRepo.get`, which has no commit message to
108
+ * consult. The commit's own `blockDigests[id].baseRev` is now the fallback for a record whose
109
+ * pend named no base, not the primary check.
110
+ */
111
+ baseRevs?: BlockBaseRevs;
112
+ /**
113
+ * The writer's word that this pend, together with the other pends sent with it in one request
114
+ * (`IRepo.pendMany`), is the action's whole reservation — every block the action will commit is in
115
+ * that one request — and that the action's commit goes as one request to the coordinator this pend
116
+ * goes to. Only then may a coordinator hold back the pend record's final delivery to the other
117
+ * members and send it inside the commit's first request (`ClusterCoordinator.mayDeferPendDelivery`
118
+ * in db-p2p): a member that refuses any of the record's pends late refuses that one commit record,
119
+ * before anything of the action is durable. A send that pends in several requests before committing
120
+ * any — several collections one request each under one action id, or one collection split across
121
+ * coordinators — must never carry it: one request's late refusal would surface while another
122
+ * request's commit may already have landed, tearing the action.
123
+ *
124
+ * Set by `TransactorSource.transact`, and by `TransactionCoordinator` for a transaction of exactly
125
+ * one collection or for every request of a `pendMany` (whose commit goes through `commitMany`);
126
+ * `NetworkTransactor.pend` keeps it only on a request carrying the whole pend.
127
+ * `Collection.completeOwnEntry` re-sends one participant of a half-landed multi-collection action
128
+ * through `transact`, and carries it too: that re-send pends and commits its one collection on its
129
+ * own, so its late refusal stops only its own commit, as an on-time refusal would.
130
+ * Omitted rather than `false`, for the same preimage reason as {@link baseRevs}; a coordinator on
131
+ * an older build ignores it, and then delivers at once as it always did.
132
+ */
133
+ soleReservation?: true;
134
+ /**
135
+ * The writer's word that this write must not be committed by a lone node that knows it is not
136
+ * alone (`SyncOptions.refuseSoloCommit`). A coordinator whose cohort for the write is only itself
137
+ * refuses the pend — before reserving anything — when it knows of cohort members it could not
138
+ * place in the cohort, is still waiting to hear from a configured bootstrap peer, or could not
139
+ * route the write to itself, answering with a {@link ShortfallFailure} whose
140
+ * {@link PromiseShortfall.soloRefused} names which (`CoordinatorRepo.pendSolo` in db-p2p). A
141
+ * coordinator that is genuinely alone ignores it and pends as it always did, and so does every
142
+ * coordinator whose cohort has more than one member.
143
+ *
144
+ * Carried by every send of the write's attempt cycle, the re-send a refresh makes to finish a torn
145
+ * attempt included (`Collection.completeOwnEntry`). Every per-coordinator rebuild of the request
146
+ * keeps it (`pendRequestForBatch` in `NetworkTransactor`), since a batch that dropped it would
147
+ * lose the protection for that coordinator's share. Omitted rather than `false`, for the same
148
+ * preimage reason as {@link baseRevs}: a write that does not set it serializes exactly as before.
149
+ * A coordinator on an older build ignores it and commits alone at `local`; in a group of mixed
150
+ * versions the offline queue's reachability gate is then the only protection.
151
+ */
152
+ refuseSolo?: true;
153
+ };
154
+
155
+ export type BlockActionStatus = ActionBlocks & {
156
+ statuses: ('pending' | 'committed' | 'checkpointed' | 'aborted' | 'committed-invalidated')[];
157
+ };
158
+
159
+ /** How widely a successful write is known to be held at the moment it was acknowledged. */
160
+ export type DurabilityQuorum =
161
+ /** Every member of the resolved cohort confirmed it holds the revision. */
162
+ | 'full'
163
+ /** A strict majority confirmed — the acknowledgement bar — but at least one member did not.
164
+ * Also the class of a torn action whose cohort confirmed everything it was asked for
165
+ * (`withTornBlocks` clamps `full` down to this; `torn` then names the blocks, and `unconfirmed`
166
+ * may be empty). */
167
+ | 'majority'
168
+ /** The cohort resolved, and it is this node alone. Nobody else holds the revision yet. When this
169
+ * node knows of other members of the cohort that it could not reach (`IKeyNetwork.absentCohortMembers`),
170
+ * they are named in `unconfirmed` and counted in `cohort`: the write is owed to them. With none
171
+ * named, it is a correct, complete one-machine write. */
172
+ | 'local'
173
+ /** The cohort did NOT resolve: the lookup threw, or named nobody, or named a single peer that
174
+ * is not this node. The write is on this node's storage and the network was never consulted.
175
+ * Deliberately NOT `local`: a write that lands where its cohort resolved to is in the right
176
+ * place, whereas this is a write whose correct destination is unknown. */
177
+ | 'unrouted';
178
+
179
+ /** What the answering layer knows about who holds a successful write. Each layer refines it:
180
+ * `StorageRepo` answers for itself alone, `CoordinatorRepo` answers for the cohort the write ran
181
+ * on, and `NetworkTransactor` merges the per-coordinator answers into one action-level answer.
182
+ * Never a policy input — read it to DISPLAY or to REPAIR, never to decide acceptance.
183
+ *
184
+ * The only "this write is completely saved" test is `isFullyDurable` (`network/durability.ts`);
185
+ * do not compare `quorum` by hand, because a `full` cohort report can still sit on an action that
186
+ * abandoned blocks (`torn`). */
187
+ export type WriteDurability = {
188
+ readonly quorum: DurabilityQuorum;
189
+ /** Cohort members confirmed to hold the write, including this node when it holds it.
190
+ * For a commit this means "reported that its storage durably holds the revision"; for a pend
191
+ * it means "accepted the pending record". The two are NOT comparable — a pend confers no
192
+ * storage durability (see the note in `CoordinatorRepo.pendThroughCluster`). */
193
+ readonly confirmed: number;
194
+ /** Size of the cohort the write ran on. Zero exactly when `quorum` is 'unrouted'. For `local`
195
+ * it is one plus the known members the write ran without, so `local` does not imply 1. */
196
+ readonly cohort: number;
197
+ /** Cohort members that did not confirm, by peer-id string. Empty when `quorum` is 'full'.
198
+ * ABSENT (not empty) when the answering layer could not name the cohort — an empty array
199
+ * here means "named the cohort, nobody is missing". On a `local` write these are the members
200
+ * this node knows of but could not reach when it wrote alone. */
201
+ readonly unconfirmed?: readonly string[];
202
+ /** The cohort the write ran on, by peer-id string. Absent where the answering layer has no
203
+ * cohort view at all (a bare `StorageRepo` verdict). */
204
+ readonly cohortPeerIds?: readonly string[];
205
+ /** Peer-id string of the node whose under-replication ledger recorded this write's missing
206
+ * copies — the one node that will fire `BlockDurabilityReachedEvent` for these blocks when they
207
+ * reach full replication. Set only below `full`, and only when every non-torn block's shortfall
208
+ * was recorded. Absent: no node is tracking the shortfall (nothing to push from the coordinator,
209
+ * a ledger fault, no ledger, a producer that predates the field), so no full-replication event
210
+ * should be expected. Per cohort answer: each `otherCohorts` entry carries its own. */
211
+ readonly recordedBy?: string;
212
+ /** Present only on an action-level result assembled from MORE THAN ONE distinct coordinator
213
+ * answer: the other answers. Identical answers are collapsed (`mergeDurability`), so a healthy
214
+ * single-cohort commit has none; one cohort answering differently for two batches appears
215
+ * twice. The scalar fields above always describe the WEAKEST answer, so a consumer that reads
216
+ * only them is reading the binding constraint and is never over-optimistic. */
217
+ readonly otherCohorts?: readonly WriteDurability[];
218
+ /** Blocks this action wrote that are NOT committed — a torn sweep abandoned and cancelled them
219
+ * (`NetworkTransactor.cancelAbandonedSweepBlocks`). Action-level commit results only.
220
+ * These blocks NEVER heal by replication: their transform is gone, and only the writer
221
+ * re-driving the action puts them back. */
222
+ readonly torn?: readonly BlockId[];
223
+ /** Action-level: every block this write committed, with the revision it committed at — what a
224
+ * host holds to match full-replication events (`BlockDurabilityReachedEvent`, keyed by block and
225
+ * revision) back to this write. Set by the db-core layer that issued the commit
226
+ * (`withBlockRevs`), never by a coordinator and never on the wire. Excludes `torn` blocks: they
227
+ * hold nothing. Merging two reports keeps, per block, the HIGHER revision — a block written at r
228
+ * and again at r+1 by one write is covered by an event at r+1 or later. A `Record` rather than a
229
+ * `Map` so the type stays plain JSON. */
230
+ readonly blockRevs?: Readonly<Record<BlockId, number>>;
231
+ };
232
+
233
+ export type PendSuccess = {
234
+ success: true;
235
+ /** List of already pending actions that were found on blocks touched by this pend */
236
+ pending: ActionPending[];
237
+ /** The affected blocks */
238
+ blockIds: BlockId[];
239
+ /** Who accepted the pending record. REQUIRED, not optional: an absent field would read as plain
240
+ * success, which is exactly the ambiguity this field exists to remove (a solo write, a write
241
+ * whose cohort never resolved, and a quorum write all used to answer `{ success: true }`). */
242
+ durability: WriteDurability;
243
+ };
244
+
245
+ export type StaleFailure = {
246
+ success: false;
247
+ /** The reason for the failure */
248
+ reason?: string;
249
+ /** List of actions that have already been committed and are newer than our known revision */
250
+ missing?: ActionTransforms[];
251
+ /** List of actions that are pending on the blocks touched by this pend */
252
+ pending?: ActionPending[];
253
+ /**
254
+ * Explicit retryability. True when this failure is an optimistic-concurrency loss — the
255
+ * requested revision was taken, or a rival pend holds the blocks — so a re-read, rebase and
256
+ * re-pend can win. Set it only when the producer genuinely classified the failure; leave it
257
+ * absent otherwise, and consumers fall back to inferring from `missing`/`pending`.
258
+ * Read it through `isConflictFailure` rather than testing it directly.
259
+ */
260
+ conflict?: boolean;
261
+ /**
262
+ * The block that already occupies (or is past) the requested revision, and the revision the
263
+ * responder holds for it.
264
+ *
265
+ * CONFIRMED-ONLY: set this only when the producer read the revision out of its own storage.
266
+ * A producer that merely suspects staleness — or that learned of it from another peer's
267
+ * free-form reject text — must leave it absent. Absent means "no confirmed number", never
268
+ * "not stale".
269
+ *
270
+ * DIAGNOSTIC, NOT A RETRYABILITY SIGNAL: `conflict` (read via `isConflictFailure`) remains the
271
+ * single source of truth for "can a re-read and re-pend win?". Never branch retry decisions on
272
+ * the presence of this field.
273
+ */
274
+ staleAt?: { blockId: BlockId; rev: number };
275
+ /** Never set on a lost race — an expiry is its own failure shape, {@link ExpiredFailure}. */
276
+ expired?: never;
277
+ /** Never set on a lost race — a cohort too few of whose members answered is its own failure
278
+ * shape, {@link ShortfallFailure}. */
279
+ shortfall?: never;
280
+ /** Never set on a lost race — a write judged invalid is its own failure shape,
281
+ * {@link RejectedFailure}. */
282
+ rejected?: never;
283
+ };
284
+
285
+ /**
286
+ * Why a cohort refused a write as expired: by each refusing member's own clock, the transaction's
287
+ * `expiration` had already passed when the record reached it. Plain data, so it crosses the JSON repo
288
+ * protocol intact. `TransactionExpiredError` is built from it, wherever it is raised.
289
+ */
290
+ export type TransactionExpiry = {
291
+ /** The transaction's expiration (unix ms), as the writer's transactor set it from its own clock. */
292
+ expiration: number;
293
+ /** Per refusing cohort member (peer-id string), the clock reading (unix ms) it signed when it
294
+ * judged the record expired (`Signature.expiredAt`). Never empty. */
295
+ memberClocks: Record<string, number>;
296
+ /** The coordinating node's clock (unix ms) when it concluded the refusal. */
297
+ coordinatorClock: number;
298
+ };
299
+
300
+ /**
301
+ * The cohort refused the write because the transaction had already EXPIRED by the members' clocks —
302
+ * a clock disagreement between the writer and the cohort, not a lost race and not a judgement of the
303
+ * write. Never retryable: every retry carries an expiration set by the same clock, and is refused the
304
+ * same way until a clock is corrected. A sibling of {@link StaleFailure} rather than a field on it,
305
+ * because "lost to a newer revision" is exactly what this is not; the fields it can never carry are
306
+ * typed `never`, so a consumer reads `reason`, `missing` or `staleAt` off either shape unnarrowed.
307
+ * Tell the two apart with `isExpiryFailure`, never by reading `reason`.
308
+ */
309
+ export type ExpiredFailure = {
310
+ success: false;
311
+ /** The coordinator's description of the refusal, for a log line. Never branch on it. */
312
+ reason?: string;
313
+ /** Always false: an expiry is never a conflict a re-read can win. */
314
+ conflict: false;
315
+ expired: TransactionExpiry;
316
+ missing?: never;
317
+ pending?: never;
318
+ staleAt?: never;
319
+ shortfall?: never;
320
+ rejected?: never;
321
+ };
322
+
323
+ /**
324
+ * Why a cohort's promise round fell short with no member refusing it as a lost race or a held block,
325
+ * and too few rejecting it for a rejection: too few members answered. Plain data, so it crosses the
326
+ * JSON repo protocol intact. `PromiseShortfallError` is built from it, wherever it is raised.
327
+ */
328
+ export type PromiseShortfall = {
329
+ /** Approve votes the round received. */
330
+ approvals: number;
331
+ /** Reject votes the round received — fewer than would make the round a rejection. */
332
+ rejections: number;
333
+ /** How many members the cohort the round ran on has. */
334
+ peerCount: number;
335
+ /** The approvals the round needed: `ceil(peerCount × superMajorityThreshold)`. */
336
+ needed: number;
337
+ /** Peer-id strings of the cohort members that cast no promise vote at all. */
338
+ silentPeers: string[];
339
+ /**
340
+ * Set only when no consensus round ran: a coordinator whose cohort for the write was only itself
341
+ * refused to write alone, because the write asked it to (`PendRequest.refuseSolo`). The other
342
+ * fields then describe the cohort the coordinator expected rather than one it asked: one approval
343
+ * (its own), no rejections, the members it knows of and could not reach as `silentPeers`, and the
344
+ * bar a cohort of that size would set. Absent on a shortfall a consensus round produced, so a log
345
+ * or an application can tell "refused to write alone" from "a round heard too few".
346
+ */
347
+ soloRefused?: SoloRefusalReason;
348
+ };
349
+
350
+ /**
351
+ * Why a lone coordinator refused a write that asked not to be committed alone
352
+ * (`PendRequest.refuseSolo`, `CommitRequest.refuseSolo`):
353
+ * - `absent-members`: its cohort for the write was only itself, and it knows of cohort members it
354
+ * could not place in that cohort (`IKeyNetwork.absentCohortMembers`);
355
+ * - `awaiting-bootstrap`: its cohort was only itself and it is still waiting to hear from a peer it
356
+ * was configured to join through (`IKeyNetwork.awaitingBootstrapContact`);
357
+ * - `unrouted`: the cohort lookup failed, named nobody, or named one peer that is not this node.
358
+ */
359
+ export type SoloRefusalReason = 'absent-members' | 'awaiting-bootstrap' | 'unrouted';
360
+
361
+ /**
362
+ * The cohort refused the pend because too few of its members ANSWERED the promise round for it to
363
+ * reach its bar — silence, not a judgement of the write and not a lost race. Not retryable by a write
364
+ * path: every coordinator of that cohort meets the same silent members, so a re-read and re-pend fails
365
+ * the same way until they come back. A sibling of {@link StaleFailure} and {@link ExpiredFailure},
366
+ * with the fields it can never carry typed `never`, so a consumer reads `reason`, `missing` or
367
+ * `staleAt` off any of them unnarrowed. Tell it apart with `isShortfallFailure`, never by reading
368
+ * `reason`. A pend answer only: a commit that falls short is still thrown (see
369
+ * `CoordinatorRepo.commit`).
370
+ */
371
+ export type ShortfallFailure = {
372
+ success: false;
373
+ /** The coordinator's description of the refusal, for a log line. Never branch on it. */
374
+ reason?: string;
375
+ /** Always false: silence is not a conflict a re-read can win. */
376
+ conflict: false;
377
+ shortfall: PromiseShortfall;
378
+ missing?: never;
379
+ pending?: never;
380
+ staleAt?: never;
381
+ expired?: never;
382
+ rejected?: never;
383
+ };
384
+
385
+ /**
386
+ * One refusal behind a {@link TransactionInvalidity}: a cohort member's validity-marked reject vote
387
+ * (`Signature`'s `validity`), or the validity verdict of the coordinating node's own storage-tier check
388
+ * (`StorageRepo.pend`, for a cohort of one, where no vote is cast).
389
+ */
390
+ export type ValidityRefusal = ValidityRejection & {
391
+ /** The refusing member's peer-id string. Absent for a refusal a node's storage made without a vote. */
392
+ peerId?: string;
393
+ /** The refuser's description, free-form, for a log line. Never branch on it. */
394
+ reason?: string;
395
+ };
396
+
397
+ /**
398
+ * Why a write was refused as INVALID: the members that sank it judged the transaction itself wrong
399
+ * (see {@link ValidityRejection} for which refusals qualify), and no refusal of any other kind sank it
400
+ * beside them, bar expiry votes. Plain data, so it crosses the JSON repo protocol intact.
401
+ * `ValidityRejectedError` is built from it, wherever it is raised.
402
+ */
403
+ export type TransactionInvalidity = {
404
+ /** Every validity refusal that sank the write. Never empty. */
405
+ refusals: ValidityRefusal[];
406
+ };
407
+
408
+ /**
409
+ * The cohort refused the write because the members that sank it judged it INVALID — the transaction
410
+ * failed its re-execution, its operations hash, its stamp or its client signature. Never retryable:
411
+ * re-sending the same content to the same checks is refused the same way. A sibling of
412
+ * {@link StaleFailure}, {@link ExpiredFailure} and {@link ShortfallFailure}, with the fields it can
413
+ * never carry typed `never`, so a consumer reads `reason`, `missing` or `staleAt` off any of them
414
+ * unnarrowed. Tell it apart with `isRejectedFailure`, never by reading `reason`.
415
+ *
416
+ * A pend answer only, and only when nothing else could explain the rejection: a reject vote with no
417
+ * validity marker beside the marked ones (a stale revision, a member on an older build) leaves the
418
+ * rejection unclassified, and a revision loss the coordinator's own storage confirms is returned as
419
+ * the {@link StaleFailure} it is, since the writer's rebase sends different content.
420
+ */
421
+ export type RejectedFailure = {
422
+ success: false;
423
+ /** The coordinator's description of the refusal, for a log line. Never branch on it. */
424
+ reason?: string;
425
+ /** Always false: a verdict on the content is not a conflict a re-read can win. */
426
+ conflict: false;
427
+ rejected: TransactionInvalidity;
428
+ missing?: never;
429
+ pending?: never;
430
+ staleAt?: never;
431
+ expired?: never;
432
+ shortfall?: never;
433
+ };
434
+
435
+ /** Every way a pend or a commit can be refused with an answer rather than a throw. */
436
+ export type WriteFailure = StaleFailure | ExpiredFailure | ShortfallFailure | RejectedFailure;
437
+
438
+ export type PendResult = PendSuccess | WriteFailure;
439
+
440
+ /** What one block will materialize to at the committing revision, declared by the client that
441
+ * authored the transforms. */
442
+ export type BlockContentDigest = {
443
+ /** base64url SHA-256 of canonicalJson(block) - see canonicalBlockHash. */
444
+ digest: string;
445
+ /** Committed revision of the base the digest was computed from. ABSENT when the block's
446
+ * transform carries an insert, which makes the result base-independent and therefore
447
+ * checkable by every member regardless of how far behind it is. */
448
+ baseRev?: number;
449
+ };
450
+
451
+ /** Per-block content declarations riding on a commit. Optional per id: a block the client cannot
452
+ * digest without a network read is simply omitted, and falls back to corroboration downstream. */
453
+ export type BlockContentDigests = Record<BlockId, BlockContentDigest>;
454
+
455
+ /** Per block, the committed revision its update operations were computed against — the shape
456
+ * `Tracker.stagedBaseRevs` produces and {@link PendRequest.baseRevs} carries. Optional per id: an
457
+ * inserted or deleted block is base-independent and never named; a block updated without a known
458
+ * base is simply omitted. */
459
+ export type BlockBaseRevs = Record<BlockId, number>;
460
+
461
+ export type CommitRequest = ActionBlocks & {
462
+ /** The header block of the collection, present only when this commit creates the collection
463
+ * (the header is a fresh insert). Collection-identifying metadata, not an ordering signal —
464
+ * the header commits after the tail, like any other touched block.
465
+ * Consumed by dispute reporting (`dispute-service.ts`) as a fallback to name the collection. */
466
+ headerId?: BlockId;
467
+ /** The tail block of the log. Unconditionally the first block committed on every member, whether
468
+ * it travels alone or with the action's other blocks — the ordering `Collection.bootstrapContext`
469
+ * relies on. */
470
+ tailId: BlockId;
471
+ /** The new revision for the committed action */
472
+ rev: number;
473
+ /** Per-block content declarations for the committing action — see {@link BlockContentDigests}.
474
+ * Rides inside the consensus message, so the generic cluster message hash folds it into every
475
+ * cohort signature with no change to the hash helpers. Action-wide here; the transactor narrows
476
+ * it to each per-coordinator batch's own block ids before sending (`RepoCommitRequest`). */
477
+ // NOTE: accepted tradeoff — this field stays OPTIONAL even though an omitted declaration has a real
478
+ // cost: `StorageRepo.persistProofIfContentMatches` retains no `BlockCommitProof` for a block that
479
+ // declared no digest (`commit:proof-undeclared`), and a block with no proof is refused by any
480
+ // receiver running the default `requirePushCertificate: true` (`push:reject-uncertified
481
+ // reason=no-proof`). Such a block stays readable and still repairs by corroboration while two or
482
+ // more holders remain, but it can never GAIN a
483
+ // holder by push — so spread-on-churn and cohort-growth healing silently stop maintaining its
484
+ // replication factor. Kept optional anyway because: (a) required-but-nullable is the strongest form
485
+ // available and still permits `undefined`, so it does not make the bad state unrepresentable, only
486
+ // typed out loud; (b) some commits legitimately declare nothing — delete-only/tombstone commits
487
+ // materialize no content, and a member on a lagging base abstains; (c) measured migration cost of
488
+ // required-but-nullable here and on `RepoCommitRequest` is >=194 `tsc --noEmit` errors across >=39
489
+ // files (39/9 in db-core, 155/30 in db-p2p, quereus-plugin-optimystic unmeasured), nearly all fixed
490
+ // by literally writing `undefined`. Revisit if undeclared commits ever become common enough to show
491
+ // up as replication-factor decay.
492
+ blockDigests?: BlockContentDigests;
493
+ /**
494
+ * {@link PendRequest.refuseSolo}, on the commit. A coordinator whose cohort for the commit is only
495
+ * itself refuses it on the same rule, before minting a proof or applying anything, with a
496
+ * conflict-shaped refusal (`SOLO_COMMIT_REFUSED_REASON` in db-p2p), since a commit cannot answer
497
+ * with a shortfall. That is reached when the pend ran on a real cohort and the partner dropped
498
+ * before the commit: the writer cancels and retries, and the retry's pend meets the pend-side
499
+ * refusal. Carried through every per-coordinator rebuild of the commit (`repoCommitRequest` in
500
+ * `NetworkTransactor`); omitted rather than `false` for the preimage reason
501
+ * {@link blockDigests} is.
502
+ */
503
+ refuseSolo?: true;
504
+ /**
505
+ * {@link PendRequest.lane}, on the commit, so a coordinator handling the commit reads the write's
506
+ * lane with no memory of the pend. Carried through every per-coordinator rebuild of the commit
507
+ * (`repoCommitRequest` in `NetworkTransactor`); optional on the wire for an older writer, and
508
+ * absence is "not stated". Omitted rather than `undefined`, for the preimage reason
509
+ * {@link blockDigests} is.
510
+ */
511
+ lane?: Lane;
512
+ };
513
+
514
+ /**
515
+ * Originates a compensating invalidation through the same critical-cluster consensus as any
516
+ * transaction: it takes a revision slot and serializes against concurrent commits. Each member
517
+ * applies it deterministically — verifying {@link resolution} as an invalidation certificate, then
518
+ * writing the per-block compensating revisions and appending the durable invalidation log entry.
519
+ *
520
+ * Carries everything a member needs to apply the reversal without trusting the originator: the
521
+ * target action, the blocks it wrote, the owning collection's log, and the signed proof.
522
+ */
523
+ export type InvalidateRequest = {
524
+ /** actionId of the committed action being reversed. */
525
+ invalidatedActionId: ActionId;
526
+ /** rev of the invalidated entry — pins which block revisions to roll back. */
527
+ invalidatedRev: number;
528
+ /** Blocks the invalidated action wrote (its commit's blockIds). */
529
+ blockIds: BlockId[];
530
+ /** The collection (log) the invalidated action belongs to — where the compensating entry lands. */
531
+ collectionId: CollectionId;
532
+ /** The invalidation certificate (challenger-wins + signed 2/3 decisive arbitrator votes). */
533
+ resolution: DisputeResolutionProof;
534
+ };
535
+
536
+ export type CommitResult = CommitSuccess | WriteFailure;
537
+
538
+ export type CommitSuccess = {
539
+ success: true;
540
+ /** If present, the identified collection acts as the coordinator for the multi-collection transaction */
541
+ coordinatorId?: CollectionId;
542
+ /** Who holds the committed revision. REQUIRED for the same reason as {@link PendSuccess.durability}:
543
+ * a quorum commit, a solo commit, a commit whose cohort lookup failed, and a torn multi-block
544
+ * commit all answered `{ success: true }` before this field existed, and a writer could not tell
545
+ * them apart (GitHub #19). Test it through `isFullyDurable`, never by comparing `quorum`. */
546
+ durability: WriteDurability;
547
+ };
548
+
549
+ export type BlockActionState = {
550
+ /** The latest action that has been committed */
551
+ latest?: ActionRev;
552
+ /** If present, the specified actions are pending */
553
+ pendings?: ActionId[];
554
+ };
555
+
556
+ export type BlockGets = {
557
+ blockIds: BlockId[];
558
+ context?: ActionContext; // Latest if this is omitted
559
+ /** Per block, the lowest revision the ASKER can accept for it — its floor. Omit a block that
560
+ * has none; omit the field entirely when no block does.
561
+ *
562
+ * A floor is knowledge only the asker holds: a collection that walked the log entry
563
+ * "action A, committed at revision r, changed block X" knows a read of X at a context at or
564
+ * above `r` must come back materialized at `r` or later, while the repo answering may honestly
565
+ * believe its older copy is current. `TransactorSource.tryGet` fills this from the collection's
566
+ * `BlockFloors`, and a refresh that follows a refused write puts the revision the refusal
567
+ * confirmed on its read of the log tail (`Collection.readLogEnds`). `NetworkTransactor.get`
568
+ * treats an answer under a block's floor as NOT answered, so it earns the same second-chance
569
+ * round against a different coordinator that `unavailable` and `unconfirmedAheadRev` earn.
570
+ *
571
+ * On the wire, per batch: `NetworkTransactor.get` forwards to each downstream `IRepo.get` the
572
+ * floors of that batch's blocks alone, and leaves the field off a batch none of whose blocks has
573
+ * one. A peer that predates the field ignores it and answers as it always did, which is safe
574
+ * because the reader-side check is what enforces the floor, on the merged answer, either way
575
+ * (`TransactorSource` / `BlockFloorCheck`) — so an `ITransactor` that ignores the field
576
+ * (`TestTransactor`, the reference peer's) stays correct too. A coordinator that does read it
577
+ * (`CoordinatorRepo.get`) consults its cohort at once for a present block whose local revision
578
+ * is below the floor, whatever its read-repair window says, and remembers the floor it consulted
579
+ * under so a floor no machine can meet costs one consult per window; it never refuses on a floor.
580
+ *
581
+ * NOTE: the retry `NetworkTransactor.get` runs is per BATCH, not per block, so one below-floor
582
+ * block re-asks every block that shared its coordinator. Costs nothing today — `tryGet` asks
583
+ * for one block per request, and the one batched floored read is a refresh's header-and-tail
584
+ * read, whose other block is the header the refresh needed from the second machine anyway —
585
+ * but a read source that batches unrelated blocks would pay it. Split the retry payload down to
586
+ * the failing block ids then. */
587
+ floors?: Record<BlockId, number>;
588
+ /** Per block, what the ASKER itself holds of it: its committed latest `(rev, actionId)`, or `null`
589
+ * when it holds no committed revision. A block the asker could not read locally is left out, and
590
+ * the field is left off when none could be read.
591
+ *
592
+ * It exists because a coordinator's cohort consult asks every other cohort member "what do you hold
593
+ * for this block?", and when the asker is itself a member that question has just been answered in
594
+ * its own request. A coordinator that reads the field uses the statement as that member's answer
595
+ * instead of asking it over the network (`CoordinatorRepo.get`), but only where doing so loses
596
+ * nothing: the statement is "nothing", or a revision at or below the coordinator's own (at an equal
597
+ * revision, only under the same action). A statement ahead of the coordinator is consulted as
598
+ * before, because acquiring or judging that revision needs the member's archive and commit proof,
599
+ * which a stated revision carries neither of. A statement can only lower what the coordinator
600
+ * concludes about being behind; it never makes it adopt anything.
601
+ *
602
+ * The statement names no peer. WHO is stating is the identity of the connection the request
603
+ * arrived on (`MessageOptions.asker`), so a request cannot speak for another member. Filled below
604
+ * the transactor, by the reader's remote-repo decorator (`stateHoldingsOnReads` in
605
+ * `packages/db-p2p/src/repo/stated-holdings.ts`), and only on a read sent to another machine. A
606
+ * peer that predates the field ignores it and consults as before. */
607
+ askerHolds?: Record<BlockId, ActionRev | null>;
608
+ /** Ask the answering repo whether each block's CURRENT content was built from this committed
609
+ * action at this revision; it answers per block in {@link GetBlockResult.lineage}. On the wire,
610
+ * unlike `floors`. A repo that predates the field leaves `lineage` absent, which every consumer
611
+ * reads as `unknown`. Asked only by a writer deciding whether its own superseded write is saved
612
+ * (`ITransactor.getLineage`); an ordinary read never sets it. */
613
+ lineageOf?: ActionRev;
614
+ /** The asker does not want this read to start the read-repair consult that the lazy window alone
615
+ * would run BEHIND the read: a held block whose window has expired (or that the lazy mode's
616
+ * `readRepairSampleRate` picked for a re-check) is answered from the answering repo's own copy and
617
+ * no cohort consult is started for it. An effort hint, never a correctness one —
618
+ * the doubt an earlier consult recorded still stamps `unconfirmedAheadRev`, and the window's
619
+ * freshness stamp is untouched, so the next read without the flag consults as before.
620
+ *
621
+ * It never skips a consult whose answer the read depends on: a block missing locally (the absence
622
+ * verdict), a held block whose read carries a floor above it ({@link floors}), and every consult
623
+ * under `'paranoid'` read-repair still run and still block. Whole-read, so `NetworkTransactor.get`
624
+ * forwards it on every batch: a remote coordinator also skips its own background consult. A peer
625
+ * that predates the field ignores it and consults as before. Meant for the node's watch tick,
626
+ * through `Collection.readCommittedTails`, which reads every watched tail on a timer. Distinct from
627
+ * `skipClusterFetch`, the sync protocol's guard, which skips every consult and never flags. */
628
+ skipWindowConsult?: true;
629
+ };
630
+
631
+ /**
632
+ * Whether a block's current content was BUILT FROM a given committed `(actionId, rev)` — the
633
+ * write's transform is part of what the block holds now, even though later actions have since
634
+ * taken later revisions.
635
+ *
636
+ * - `contains` — it was. Holding that exact revision as the latest counts.
637
+ * - `excludes` — it provably was not: another action holds that revision of the block, or the
638
+ * block's history spans that revision without it. Nothing can land the write there any more.
639
+ * - `behind` — the block has not reached that revision (or does not exist). The write is not
640
+ * there, and could only get there through one of its own pending records.
641
+ * - `unknown` — not established either way.
642
+ *
643
+ * One repo answers from its own records only ({@link GetBlockResult.lineage}); a transactor
644
+ * answers for the block's cohort ({@link ActionLineage}).
645
+ */
646
+ export type BlockLineage = 'contains' | 'excludes' | 'behind' | 'unknown';
647
+
648
+ /** A cohort-level answer to "is this committed write part of what these blocks hold now?" — see
649
+ * `ITransactor.getLineage`. */
650
+ export type ActionLineage = {
651
+ /** One answer per requested block id, in request order. */
652
+ blocks: BlockLineage[];
653
+ /** Who holds the write, present exactly when EVERY block answered `contains`: the weakest
654
+ * block's cohort report, by the same rule a commit's durability is merged. */
655
+ durability?: WriteDurability;
656
+ };
657
+
658
+ /** Why a repo could not establish whether a block exists. Present ONLY when the repo
659
+ * knows its own answer is a guess; an absent field is an authoritative answer. */
660
+ export type BlockUnavailableReason =
661
+ /** Records for this block exist here but it cannot be reconstructed locally — a
662
+ * revision was received with no base to apply it to, or its history is truncated. */
663
+ | 'unmaterializable'
664
+ /** Nothing is held locally; PART of the cohort answered and part could not be asked.
665
+ * A silent peer could be the sole holder, so the absence is a guess — but other
666
+ * coordinators are reachable, so asking one of them can still settle it. Also the
667
+ * fallback when the consult could not run at all (the cohort lookup itself failed):
668
+ * a routing failure says nothing about how many cohort members were reachable. */
669
+ | 'peers-unreachable'
670
+ /** Nothing is held locally and NO cohort member outside the answering node could be
671
+ * asked at all. Distinct from `peers-unreachable` in exactly the way that matters to
672
+ * a caller: there is no better-connected coordinator to re-ask, so the answer will
673
+ * not improve until that node's connectivity does. Its local view is all there is.
674
+ * Also the answer of a node whose cohort view holds only itself while a peer it was
675
+ * configured to join through has never been heard from
676
+ * (`IKeyNetwork.awaitingBootstrapContact`): it knows of a machine outside itself and
677
+ * has not reached it. */
678
+ | 'cohort-unreachable'
679
+ /** Nothing is held locally, but a cohort peer positively CLAIMED a revision of this
680
+ * block, and the answering node could neither corroborate that claim to a quorum nor
681
+ * acquire the content. The block is known to exist somewhere; reporting it absent
682
+ * would be a lie regardless of whether anyone was silent. */
683
+ | 'claimed-elsewhere'
684
+ /** Nothing is held locally and the answering node had nobody to ask (its cohort view
685
+ * was empty, or only itself), but the read carried a floor for the block
686
+ * ({@link BlockGets.floors}): the asker walked a log entry committing a revision of it.
687
+ * The block is known to exist, from the asker's own evidence, so "never created" would
688
+ * contradict what the asker already knows. Unlike `cohort-unreachable` this is never
689
+ * "the local view is all there is": another machine may hold the block, and asking one
690
+ * is the remedy. */
691
+ | 'named-by-log';
692
+
693
+ export type GetBlockResult = {
694
+ /** The retrieved block - undefined if the block was deleted */
695
+ block?: IBlock;
696
+ /** The latest and pending states of the repo that retrieved the block */
697
+ state: BlockActionState;
698
+ /** The revision the returned `block` actually IS — the `(rev, actionId)` of the highest
699
+ * committed revision of THIS block at or below the caller's {@link BlockGets.context}`.rev`.
700
+ * Differs from `state.latest` only for a revision-pinned read of a block that has committed
701
+ * further since the pin; for an unpinned read the two agree.
702
+ *
703
+ * This — not `state.latest` — is what a read observed, so it is what a read dependency must
704
+ * record (recording `latest` would claim the reader saw content it never read, and the
705
+ * validator's stale-read check would wrongly pass), and it is the only correct label for the
706
+ * content when it is passed on (a block-repair archive, a replica push). `state.latest` keeps
707
+ * its own meaning: the newest revision the answering repo holds for the block.
708
+ *
709
+ * The revision and its action id are ONE field, deliberately: a site that must label content
710
+ * it is holding needs both, and two independently-optional fields could disagree — which is
711
+ * exactly the mislabel this exists to make unrepresentable (old bytes served under a newer
712
+ * revision's number and action id, which a receiver keyed by action id then writes over its
713
+ * own good copy; see `serveBlockArchive`).
714
+ *
715
+ * Optional: a producer that does not know what it materialized leaves it absent rather than
716
+ * guessing, and consumers fall back to `state.latest` (read dependencies record
717
+ * `state.latest?.rev ?? 0`; a labelling site refuses to label a pinned read). */
718
+ materialized?: ActionRev;
719
+ /** Set when this repo could not determine whether the block exists — its answer is a
720
+ * guess, not an authoritative absent. Every producer that omits it (including
721
+ * TestTransactor) keeps meaning "authoritative". */
722
+ unavailable?: BlockUnavailableReason;
723
+ /** Set when this repo served committed content it could NOT confirm is current: its
724
+ * freshness consult did not converge AND a cohort peer claimed a strictly higher
725
+ * revision than the one served, within the view the caller asked for (unpinned, or
726
+ * pinned at or above the claim). Carries that claimed revision. The claim did not
727
+ * drive a successful repair — it failed the read-repair corroboration quorum, or was
728
+ * corroborated but the content could not be acquired — so it is evidence of DOUBT,
729
+ * never a revision to adopt. Distinct from `unavailable`, which is about EXISTENCE:
730
+ * the content here is real, it may just be behind. Absent = confirmed, so every
731
+ * producer that omits it keeps its meaning. */
732
+ unconfirmedAheadRev?: number;
733
+ /** This repo's answer to {@link BlockGets.lineageOf}, from its OWN records only — no cohort
734
+ * view. Absent when the question was not asked, or the repo predates it. */
735
+ lineage?: BlockLineage;
736
+ };
737
+
738
+ /**
739
+ * Thrown by a block read when the responsible repo could not determine whether the
740
+ * block exists. Distinct from "the block is absent" (undefined) and from a transport
741
+ * failure — this node's data is genuinely indeterminate and the caller must not treat
742
+ * it as empty. Not a StaleFailure: `Collection.sync` does not retry it.
743
+ */
744
+ export class BlockUnavailableError extends Error {
745
+ constructor(readonly blockId: BlockId, readonly reason: BlockUnavailableReason) {
746
+ super(`Block ${blockId} is unavailable (${reason}): the repo could not determine whether it exists`);
747
+ this.name = 'BlockUnavailableError';
748
+ }
749
+ }
750
+
751
+ /**
752
+ * Thrown by an unpinned ("give me latest") block read whose surviving answer carries
753
+ * {@link GetBlockResult.unconfirmedAheadRev}: every reachable coordinator served content
754
+ * it could not confirm is current, while a cohort peer claimed a strictly higher revision
755
+ * nothing could corroborate or refute. Sibling of {@link BlockUnavailableError} — that one
756
+ * is about EXISTENCE (blockless answer, could not find out), this one about CURRENCY (real
757
+ * content, possibly behind). Not a StaleFailure: `Collection.sync` does not retry it.
758
+ */
759
+ export class BlockPossiblyStaleError extends Error {
760
+ constructor(readonly blockId: BlockId, readonly claimedRev: number) {
761
+ super(`Block ${blockId} may be stale: a cohort peer claimed rev ${claimedRev} that no reachable coordinator could confirm or refute`);
762
+ this.name = 'BlockPossiblyStaleError';
763
+ }
764
+ }
765
+
766
+ export type GetBlockResults = Record<BlockId, GetBlockResult>;
767
+
768
+ /**
769
+ * Result of validating a transaction in a PendRequest.
770
+ */
771
+ export type PendValidationResult = {
772
+ /** Whether validation passed */
773
+ valid: boolean;
774
+ /** Reason for validation failure (if valid=false) */
775
+ reason?: string;
776
+ /** Set only on a failure that judges the transaction itself wrong; see {@link ValidityRejection}. */
777
+ validity?: ValidityRejection;
778
+ };
779
+
780
+ /**
781
+ * Hook for validating transactions in PendRequests.
782
+ *
783
+ * This hook is called by the storage layer when receiving a PendRequest
784
+ * that carries a `validation` payload (the transaction plus its operations
785
+ * hash). If validation fails — or the hook throws — the pend operation is
786
+ * rejected. What a hook-configured node does with a pend carrying NO
787
+ * `validation` payload is a policy decision
788
+ * (`StorageRepoOptions.unvalidatablePendPolicy` in db-p2p).
789
+ *
790
+ * If the hook is not provided, validation is skipped (storage-only nodes).
791
+ */
792
+ export type PendValidationHook = (
793
+ transaction: Transaction,
794
+ operationsHash: string
795
+ ) => Promise<PendValidationResult>;
796
+
797
+ // Backward compatibility aliases (deprecated - use Action* names)
798
+ /** @deprecated Use ActionBlocks instead */
799
+ export type TrxBlocks = ActionBlocks;
800
+ /** @deprecated Use ActionTransforms instead */
801
+ export type TrxTransforms = ActionTransforms;
802
+ /** @deprecated Use ActionTransform instead */
803
+ export type TrxTransform = ActionTransform;
804
+ /** @deprecated Use ActionPending instead */
805
+ export type TrxPending = ActionPending;