@optimystic/db-core 1.19.0 → 1.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/dist/src/cluster/structs.d.ts +41 -8
  2. package/dist/src/cluster/structs.d.ts.map +1 -1
  3. package/dist/src/cluster/structs.js +18 -7
  4. package/dist/src/cluster/structs.js.map +1 -1
  5. package/dist/src/collection/action.d.ts +29 -0
  6. package/dist/src/collection/action.d.ts.map +1 -1
  7. package/dist/src/collection/action.js +6 -0
  8. package/dist/src/collection/action.js.map +1 -1
  9. package/dist/src/collection/collection.d.ts +533 -120
  10. package/dist/src/collection/collection.d.ts.map +1 -1
  11. package/dist/src/collection/collection.js +974 -500
  12. package/dist/src/collection/collection.js.map +1 -1
  13. package/dist/src/collection/head-commit.d.ts +110 -0
  14. package/dist/src/collection/head-commit.d.ts.map +1 -0
  15. package/dist/src/collection/head-commit.js +65 -0
  16. package/dist/src/collection/head-commit.js.map +1 -0
  17. package/dist/src/collection/index.d.ts +2 -0
  18. package/dist/src/collection/index.d.ts.map +1 -1
  19. package/dist/src/collection/index.js +2 -0
  20. package/dist/src/collection/index.js.map +1 -1
  21. package/dist/src/collection/segments.d.ts +77 -0
  22. package/dist/src/collection/segments.d.ts.map +1 -0
  23. package/dist/src/collection/segments.js +110 -0
  24. package/dist/src/collection/segments.js.map +1 -0
  25. package/dist/src/collection/struct.d.ts +156 -1
  26. package/dist/src/collection/struct.d.ts.map +1 -1
  27. package/dist/src/collection/struct.js +70 -0
  28. package/dist/src/collection/struct.js.map +1 -1
  29. package/dist/src/collection/write-attempts.d.ts +245 -0
  30. package/dist/src/collection/write-attempts.d.ts.map +1 -0
  31. package/dist/src/collection/write-attempts.js +439 -0
  32. package/dist/src/collection/write-attempts.js.map +1 -0
  33. package/dist/src/collections/tree/struct.d.ts +100 -17
  34. package/dist/src/collections/tree/struct.d.ts.map +1 -1
  35. package/dist/src/collections/tree/struct.js +38 -7
  36. package/dist/src/collections/tree/struct.js.map +1 -1
  37. package/dist/src/collections/tree/tree.d.ts +17 -5
  38. package/dist/src/collections/tree/tree.d.ts.map +1 -1
  39. package/dist/src/collections/tree/tree.js +112 -26
  40. package/dist/src/collections/tree/tree.js.map +1 -1
  41. package/dist/src/index.d.ts +2 -0
  42. package/dist/src/index.d.ts.map +1 -1
  43. package/dist/src/index.js +2 -0
  44. package/dist/src/index.js.map +1 -1
  45. package/dist/src/network/i-repo.d.ts +3 -0
  46. package/dist/src/network/i-repo.d.ts.map +1 -1
  47. package/dist/src/network/index.d.ts +3 -0
  48. package/dist/src/network/index.d.ts.map +1 -1
  49. package/dist/src/network/index.js +3 -0
  50. package/dist/src/network/index.js.map +1 -1
  51. package/dist/src/network/promise-shortfall-error.d.ts +40 -0
  52. package/dist/src/network/promise-shortfall-error.d.ts.map +1 -0
  53. package/dist/src/network/promise-shortfall-error.js +67 -0
  54. package/dist/src/network/promise-shortfall-error.js.map +1 -0
  55. package/dist/src/network/refuse-solo.d.ts +8 -0
  56. package/dist/src/network/refuse-solo.d.ts.map +1 -0
  57. package/dist/src/network/refuse-solo.js +8 -0
  58. package/dist/src/network/refuse-solo.js.map +1 -0
  59. package/dist/src/network/stale-failure.d.ts +20 -3
  60. package/dist/src/network/stale-failure.d.ts.map +1 -1
  61. package/dist/src/network/stale-failure.js +24 -3
  62. package/dist/src/network/stale-failure.js.map +1 -1
  63. package/dist/src/network/struct.d.ts +148 -2
  64. package/dist/src/network/struct.d.ts.map +1 -1
  65. package/dist/src/network/struct.js.map +1 -1
  66. package/dist/src/network/validity-rejected-error.d.ts +28 -0
  67. package/dist/src/network/validity-rejected-error.d.ts.map +1 -0
  68. package/dist/src/network/validity-rejected-error.js +51 -0
  69. package/dist/src/network/validity-rejected-error.js.map +1 -0
  70. package/dist/src/offline/entry.d.ts +72 -0
  71. package/dist/src/offline/entry.d.ts.map +1 -0
  72. package/dist/src/offline/entry.js +73 -0
  73. package/dist/src/offline/entry.js.map +1 -0
  74. package/dist/src/offline/index.d.ts +5 -0
  75. package/dist/src/offline/index.d.ts.map +1 -0
  76. package/dist/src/offline/index.js +5 -0
  77. package/dist/src/offline/index.js.map +1 -0
  78. package/dist/src/offline/journal.d.ts +61 -0
  79. package/dist/src/offline/journal.d.ts.map +1 -0
  80. package/dist/src/offline/journal.js +2 -0
  81. package/dist/src/offline/journal.js.map +1 -0
  82. package/dist/src/offline/queue.d.ts +484 -0
  83. package/dist/src/offline/queue.d.ts.map +1 -0
  84. package/dist/src/offline/queue.js +1236 -0
  85. package/dist/src/offline/queue.js.map +1 -0
  86. package/dist/src/offline/reachability.d.ts +25 -0
  87. package/dist/src/offline/reachability.d.ts.map +1 -0
  88. package/dist/src/offline/reachability.js +13 -0
  89. package/dist/src/offline/reachability.js.map +1 -0
  90. package/dist/src/offline/status.d.ts +148 -0
  91. package/dist/src/offline/status.d.ts.map +1 -0
  92. package/dist/src/offline/status.js +63 -0
  93. package/dist/src/offline/status.js.map +1 -0
  94. package/dist/src/offline/wake.d.ts +30 -0
  95. package/dist/src/offline/wake.d.ts.map +1 -0
  96. package/dist/src/offline/wake.js +68 -0
  97. package/dist/src/offline/wake.js.map +1 -0
  98. package/dist/src/testing/test-transactor.d.ts +29 -0
  99. package/dist/src/testing/test-transactor.d.ts.map +1 -1
  100. package/dist/src/testing/test-transactor.js +50 -0
  101. package/dist/src/testing/test-transactor.js.map +1 -1
  102. package/dist/src/transaction/commit-failure-class.d.ts +103 -0
  103. package/dist/src/transaction/commit-failure-class.d.ts.map +1 -0
  104. package/dist/src/transaction/commit-failure-class.js +96 -0
  105. package/dist/src/transaction/commit-failure-class.js.map +1 -0
  106. package/dist/src/transaction/coordinator.d.ts +165 -41
  107. package/dist/src/transaction/coordinator.d.ts.map +1 -1
  108. package/dist/src/transaction/coordinator.js +605 -300
  109. package/dist/src/transaction/coordinator.js.map +1 -1
  110. package/dist/src/transaction/entry-commit.d.ts +139 -0
  111. package/dist/src/transaction/entry-commit.d.ts.map +1 -0
  112. package/dist/src/transaction/entry-commit.js +199 -0
  113. package/dist/src/transaction/entry-commit.js.map +1 -0
  114. package/dist/src/transaction/index.d.ts +4 -1
  115. package/dist/src/transaction/index.d.ts.map +1 -1
  116. package/dist/src/transaction/index.js +1 -0
  117. package/dist/src/transaction/index.js.map +1 -1
  118. package/dist/src/transaction/transaction.d.ts +20 -0
  119. package/dist/src/transaction/transaction.d.ts.map +1 -1
  120. package/dist/src/transaction/validator.d.ts +7 -0
  121. package/dist/src/transaction/validator.d.ts.map +1 -1
  122. package/dist/src/transaction/validator.js +21 -12
  123. package/dist/src/transaction/validator.js.map +1 -1
  124. package/dist/src/transactor/network-transactor.d.ts +1 -0
  125. package/dist/src/transactor/network-transactor.d.ts.map +1 -1
  126. package/dist/src/transactor/network-transactor.js +61 -28
  127. package/dist/src/transactor/network-transactor.js.map +1 -1
  128. package/dist/src/transactor/transactor-source.d.ts +22 -11
  129. package/dist/src/transactor/transactor-source.d.ts.map +1 -1
  130. package/dist/src/transactor/transactor-source.js +9 -13
  131. package/dist/src/transactor/transactor-source.js.map +1 -1
  132. package/dist/src/utility/visit-every.d.ts +14 -0
  133. package/dist/src/utility/visit-every.d.ts.map +1 -0
  134. package/dist/src/utility/visit-every.js +27 -0
  135. package/dist/src/utility/visit-every.js.map +1 -0
  136. package/package.json +1 -1
  137. package/src/cluster/structs.ts +42 -7
  138. package/src/collection/action.ts +34 -0
  139. package/src/collection/collection.ts +1048 -543
  140. package/src/collection/head-commit.ts +148 -0
  141. package/src/collection/index.ts +2 -0
  142. package/src/collection/segments.ts +149 -0
  143. package/src/collection/struct.ts +183 -1
  144. package/src/collection/write-attempts.ts +506 -0
  145. package/src/collections/tree/struct.ts +97 -17
  146. package/src/collections/tree/tree.ts +125 -29
  147. package/src/index.ts +2 -0
  148. package/src/network/i-repo.ts +3 -0
  149. package/src/network/index.ts +3 -0
  150. package/src/network/promise-shortfall-error.ts +69 -0
  151. package/src/network/refuse-solo.ts +7 -0
  152. package/src/network/stale-failure.ts +27 -4
  153. package/src/network/struct.ts +154 -2
  154. package/src/network/validity-rejected-error.ts +55 -0
  155. package/src/offline/entry.ts +127 -0
  156. package/src/offline/index.ts +4 -0
  157. package/src/offline/journal.ts +60 -0
  158. package/src/offline/queue.ts +1342 -0
  159. package/src/offline/reachability.ts +32 -0
  160. package/src/offline/status.ts +183 -0
  161. package/src/offline/wake.ts +67 -0
  162. package/src/testing/test-transactor.ts +53 -0
  163. package/src/transaction/commit-failure-class.ts +133 -0
  164. package/src/transaction/coordinator.ts +696 -349
  165. package/src/transaction/entry-commit.ts +285 -0
  166. package/src/transaction/index.ts +4 -0
  167. package/src/transaction/transaction.ts +21 -0
  168. package/src/transaction/validator.ts +22 -12
  169. package/src/transactor/network-transactor.ts +62 -28
  170. package/src/transactor/transactor-source.ts +29 -13
  171. package/src/utility/visit-every.ts +25 -0
@@ -1,4 +1,4 @@
1
- import type { IBlock, Action, ActionType, ActionHandler, BlockId, ITransactor, BlockStore, Transforms, ActionId, ActionLineage, BlockContentDigests, GetBlockResult } from "../index.js";
1
+ import type { IBlock, Action, ActionType, ActionHandler, BlockId, ITransactor, BlockStore, Transforms, ActionId, ActionLineage, GetBlockResult, CommitResult } from "../index.js";
2
2
  import { Log } from "../log/log.js";
3
3
  import type { LogBlock } from "../log/log.js";
4
4
  import type { ActionEntry, GetFromResult, LogEntry } from "../log/struct.js";
@@ -6,28 +6,27 @@ import { Atomic } from "../transform/atomic.js";
6
6
  import { Tracker } from "../transform/tracker.js";
7
7
  import type { BasePins } from "../transform/base-pins.js";
8
8
  import { CacheSource } from "../transform/cache-source.js";
9
- import { describeTouchedBlocks, baseRevsField } from "../transform/digest.js";
10
- import { oversizedBlock } from "../network/block-size.js";
11
- import type { BlockBaseRevs, BlockGets } from "../network/struct.js";
12
- import { copyTransforms, isTransformsEmpty } from "../transform/helpers.js";
9
+ import type { BlockGets } from "../network/struct.js";
10
+ import { copyTransforms, emptyTransforms, isTransformsEmpty } from "../transform/helpers.js";
13
11
  import { TransactorSource, answeredBlock, servedRevision } from "../transactor/transactor-source.js";
14
12
  import { BlockFloors } from "../transactor/block-floors.js";
15
13
  import type { WriteDurability } from "../network/struct.js";
16
- import { mergeDurability, withBlockRevs } from "../network/durability.js";
17
- import { highestStaleAt, isExpiryFailure } from "../network/stale-failure.js";
18
- import { TransactionExpiredError } from "../network/transaction-expired-error.js";
19
- import type { CollectionHeaderBlock, CollectionId, CommittedTail, CommittedTailAnswer, CommittedTailQuery, ICollection, SyncOptions, TornActionReason } from "./index.js";
20
- import { CollectionHeaderVanishedError, SyncRetryExhaustedError, SyncRevisionStalledError, TornActionError } from "./struct.js";
21
- import type { ActionContext } from "./action.js";
22
- import { actionIdAt } from "./action.js";
14
+ import { withBlockRevs } from "../network/durability.js";
15
+ import type { CollectionHeaderBlock, CollectionId, CommittedTail, CommittedTailAnswer, CommittedTailQuery, HeadCommitOptions, ICollection, InFlightAttempt, InFlightCycle, OpenHeadCommitOptions, SyncOptions, TornActionReason } from "./index.js";
16
+ import { ActionRefusedError, CollectionHeaderVanishedError, SealedSegmentsError, TornActionError } from "./struct.js";
17
+ import { SegmentList } from "./segments.js";
18
+ import type { EntryId, SealedSegment } from "./segments.js";
19
+ import type { ActionContext, ActionRev, AlreadyAppliedTally } from "./action.js";
20
+ import { actionIdAt, addTallies, ZeroTally } from "./action.js";
21
+ import { AttemptCycle, resumedAttempt, retainedAttempt, stageAttempt } from "./write-attempts.js";
22
+ import type { AttemptTarget, Refresh, StagedAttempt, WriteIdentity } from "./write-attempts.js";
23
+ import { driveHeadCommit } from "./head-commit.js";
24
+ import type { HeadCommitHandle } from "./head-commit.js";
23
25
  import type { ReadDependency } from "../transaction/transaction.js";
24
- import { clampPriority, SlotHoldAfterLosses } from "../transaction/transaction.js";
25
26
  import { ReadDependencyCollector } from "../transaction/read-dependency-collector.js";
26
27
  import { randomBytes } from '@noble/hashes/utils.js';
27
28
  import { toString as uint8ArrayToString } from 'uint8arrays/to-string';
28
29
  import { Latches } from "../utility/latches.js";
29
- import { jitteredBackoffMs, abortableDelay, makeAbortError } from "../utility/backoff.js";
30
- import type { JitteredBackoffConfig, RandFn } from "../utility/backoff.js";
31
30
  import { createLogger } from "../logger.js";
32
31
 
33
32
  const log = createLogger('collection');
@@ -53,26 +52,6 @@ type DivergenceSite = 'refresh' | 'attach';
53
52
  * as `forkRev=` / `heldAction=` / `readAction=`. */
54
53
  type LineageFork = { rev: number, heldAction: ActionId, readAction: ActionId };
55
54
 
56
- /** Exactly what one failed write attempt sent to the transactor — enough to send the same thing
57
- * again. Retained by {@link Collection.retainInFlightAttempt} so that a refresh which then finds
58
- * this attempt's own log entry can land the blocks the attempt left behind, at the same action id
59
- * and revision (see {@link Collection.completeOwnEntry}). */
60
- export type InFlightAttempt = {
61
- /** The revision the attempt's log entry was stamped with, and pended and committed at. */
62
- rev: number;
63
- /** Every transform the attempt pended — the log blocks included. The caller hands over a copy
64
- * it will not mutate; the collection keeps it as given. */
65
- transforms: Transforms;
66
- /** The attempt's log tail block, committed first. */
67
- tailId: BlockId;
68
- /** The per-block content declarations the attempt's commit carried, if any. */
69
- blockDigests?: BlockContentDigests;
70
- /** The per-block bases the attempt's pend carried, if any (see `PendRequest.baseRevs`). Kept
71
- * with the transforms because they describe them: a re-send of these operations must name the
72
- * same bases they were computed against. */
73
- baseRevs?: BlockBaseRevs;
74
- };
75
-
76
55
  /** What one refresh ({@link Collection.refreshInFlight}, and the refresh inside a sync) found out
77
56
  * about the write in flight on the instance's behalf. The caller hands in an empty report and the
78
57
  * refresh fills it in AS IT GOES, rather than returning it at the end, so a refresh that throws
@@ -108,50 +87,19 @@ type LogEnds = {
108
87
  type AttributedRead = { entry: GetBlockResult | undefined } | { error: unknown };
109
88
  type AttributedReads = Map<BlockId, AttributedRead>;
110
89
 
111
- /** Default base backoff (and historical fixed delay) between sync retries, in ms. */
112
- const PendingRetryDelayMs = 100;
113
- /** Default max consecutive no-progress stale-failure retries before {@link Collection.sync} gives up. */
114
- const DefaultMaxAttempts = 10;
115
- /** Default ceiling on a single exponential-backoff sleep, in ms. */
116
- const DefaultMaxBackoffMs = 5000;
117
- /** Default consecutive stalled refreshes — ones that moved this collection's revision NOWHERE
118
- * while a responder CONFIRMED a revision at or above the one being requested — before
119
- * {@link Collection.sync} gives up. Two, not one, so a single transiently-lagging read is absorbed.
120
- *
121
- * NOTE: two is a judgement call, not a measurement — nothing here counts how often a legitimate
122
- * loser reads a view that moves nowhere for two consecutive rounds. The check only strikes when the
123
- * refresh made NO progress at all, so a client merely catching up is already excluded; if a
124
- * spurious `SyncRevisionStalledError` ever shows up under real contention anyway, raise this. */
125
- const DefaultMaxStalledAttempts = 2;
126
-
127
- /**
128
- * The sleep before the refresh that follows a write's `failures`-th consecutive loss.
129
- *
130
- * The jittered backoff exists to separate a herd of writers that lost the SAME race, so they do not
131
- * re-collide on the next tick. A loss to a rival that had already committed (the refusal carried a
132
- * confirmed `staleAt`) is not a herd, and once this write has taken `SlotHoldAfterLosses` such losses
133
- * (`confirmedLosses`, counted over the whole write as a member counts its stale refusals of one
134
- * action) the members that refused it hold the next slot for it — so sleeping only spends that hold.
135
- * Both sides count the same refusals against the same constant, so the writer stops sleeping on the
136
- * loss after which a member holds, with nothing said over the wire. A loss the latest refusal did not
137
- * confirm (`latestConfirmed` false — a race against something still in flight) keeps the jitter.
138
- *
139
- * NOTE: against members that do not hold (an earlier release, `slotHoldWindowMs: 0`, or a member the
140
- * refused pends did not reach) this retries without sleeping and so spends the same attempt budget
141
- * sooner, at about twice one writer's pend rate (measured in the plan stage of
142
- * `slot-hold-for-an-aged-writer`). Accepted: the backoff bought that writer nothing either, it only
143
- * delayed the same give-up.
144
- */
145
- function retryBackoffMs(failures: number, confirmedLosses: number, latestConfirmed: boolean,
146
- config: JitteredBackoffConfig, rand?: RandFn): number {
147
- if (latestConfirmed && confirmedLosses >= SlotHoldAfterLosses) {
148
- return 0;
149
- }
150
- return jitteredBackoffMs(failures - 1, config, rand);
151
- }
90
+ /** The tracker a head commit's attempts are built from: the head segment's actions staged over the
91
+ * committed state, and the revision the attempt built from it requests (see
92
+ * {@link Collection.headTrackerFor}). */
93
+ type HeadTracker = {
94
+ rev: number;
95
+ tracker: Tracker<IBlock>;
96
+ };
152
97
 
153
98
  export type CollectionInitOptions<TAction> = {
154
- modules: Record<ActionType, ActionHandler<TAction>>;
99
+ /** One handler per action type. A handler may answer what the action accepted as already applied
100
+ * ({@link AlreadyAppliedTally}); one that answers nothing counts as the zero tally, so a collection
101
+ * type with no such notion returns nothing. */
102
+ modules: Record<ActionType, ActionHandler<TAction, AlreadyAppliedTally | void>>;
155
103
  createHeaderBlock: (id: BlockId, store: BlockStore<IBlock>) => IBlock;
156
104
  /** Called for each local action that is potentially in conflict with a remote action.
157
105
  * @param action - The local action to check
@@ -160,7 +108,15 @@ export type CollectionInitOptions<TAction> = {
160
108
  * action (return a new instance to apply instead of the original — it is re-staged via
161
109
  * the conflict replay), or undefined to discard this action
162
110
  */
163
- filterConflict?: (action: Action<TAction>, potential: Action<TAction>[]) => Action<TAction> | undefined
111
+ filterConflict?: (action: Action<TAction>, potential: Action<TAction>[]) => Action<TAction> | undefined;
112
+ /** Called once per refusal of a SEALED segment discovered by a replay (see
113
+ * {@link Collection.replayActions}): the segment's entry id and the handler's refusal. Called
114
+ * synchronously from inside the replay, under the collection latch, so it MUST NOT call a
115
+ * latched method of this collection ({@link Collection.update}, {@link Collection.dropSealed},
116
+ * {@link Collection.sync}, …) synchronously — the latch is non-reentrant and that would
117
+ * deadlock. The queue schedules its reaction instead. A throw out of the callback is caught and
118
+ * logged (`collection:refusal-callback-threw`), never allowed to abort the replay. */
119
+ onSealedRefused?: (entryId: EntryId, error: ActionRefusedError) => void;
164
120
  }
165
121
 
166
122
  /** Options for building a committed read view (see {@link Collection.createReadTracker}
@@ -195,8 +151,17 @@ export interface CollectionSnapshot<TAction> {
195
151
  * were not built on. Absent on a snapshot built by hand; such a restore keeps whatever pins
196
152
  * the tracker holds for the restored ids. */
197
153
  pins?: BasePins;
198
- /** Pending actions queued at snapshot time. */
154
+ /** The OPEN segment's actions at snapshot time (see {@link SegmentList}). Sealed segments are
155
+ * not captured as actions — their effects are in `transforms`, which is what a committed read
156
+ * view built from this snapshot must include — and a restore never puts one back: whether it
157
+ * reinstates `transforms` verbatim or rebuilds the tracker from the sealed segments as they are
158
+ * then is decided by {@link sealedVersion} (see {@link Collection.restorePending}). */
199
159
  pending: Action<TAction>[];
160
+ /** {@link SegmentList.version} at capture: a restore that finds the sealed list changed since —
161
+ * a segment sealed, dropped or refused while the snapshot was outstanding — replays rather than
162
+ * reinstating `transforms`, which would put a dropped segment's effects back. Absent on a
163
+ * snapshot built by hand, which reads as "unchanged". */
164
+ sealedVersion?: number;
200
165
  /** The committed boundary (action context) the staged state sat on when captured.
201
166
  * `undefined` for a collection with no committed revision yet (an invented
202
167
  * collection whose header/root still live in the tracker). A read view built
@@ -207,9 +172,23 @@ export interface CollectionSnapshot<TAction> {
207
172
  }
208
173
 
209
174
  export class Collection<TAction> implements ICollection<TAction> {
210
- private pending: Action<TAction>[] = [];
175
+ /** The staged actions: sealed segments, one per queued entry, ahead of the open segment the
176
+ * current transaction stages into (see {@link SegmentList}). While nothing is sealed this is
177
+ * exactly the one pending list it replaced, and every path behaves as it did then. */
178
+ private readonly segments = new SegmentList<TAction>();
211
179
  private readonly latchId: string;
212
180
 
181
+ /** The transforms an INVENTED collection starts from — its header, its empty log block and (for
182
+ * a tree) its empty root, as {@link createOrOpen}'s create branch staged them. A replay resets
183
+ * the tracker to a copy of this, rather than to empty, for as long as no committed revision has
184
+ * been adopted: those blocks are then nowhere but the tracker, and resetting to empty would drop
185
+ * them and leave the collection unreadable (the hazard {@link mustReplay} and
186
+ * {@link snapshotPending} describe). Never cleared — it is read only while
187
+ * `source.actionContext` is undefined, and once a context is adopted the blocks are in storage
188
+ * and the empty reset is the right one. `undefined` for a collection opened over a committed
189
+ * header, which never replays from a baseline. */
190
+ private inventedBaseline?: Transforms;
191
+
213
192
  /** The action id of a write currently in flight ON THIS INSTANCE'S BEHALF, or `undefined`
214
193
  * outside a write. Read by {@link updateInternal}: if the committed log now carries an entry
215
194
  * under this id, that action's LOG TAIL landed despite the failure answer that sent us back here
@@ -259,7 +238,11 @@ export class Collection<TAction> implements ICollection<TAction> {
259
238
  * Only the latest attempt is kept. An own entry can only be visible at the revision of an
260
239
  * attempt whose tail landed, and a later attempt at a DIFFERENT revision is only made after a
261
240
  * refresh adopted somebody else's entry at the earlier one — which is proof the earlier tail did
262
- * not land. {@link completeOwnEntry} still checks the revision and refuses on a mismatch. */
241
+ * not land. {@link completeOwnEntry} still checks the revision and refuses on a mismatch.
242
+ *
243
+ * A head commit may be opened with one already in hand ({@link openHeadCommit}'s `resume`): the
244
+ * attempt an earlier cycle under the same action id recorded through `HeadCommitOptions.recordAttempt`
245
+ * before sending it, which the cycle's opening refresh can then finish from. */
263
246
  private inFlightAttempt?: InFlightAttempt;
264
247
 
265
248
  /** The log data-block ids the append of the action marked in {@link inFlightActionId} has
@@ -268,6 +251,32 @@ export class Collection<TAction> implements ICollection<TAction> {
268
251
  * {@link beginInFlightAction} and its disposer. */
269
252
  private mintedLogBlockIds?: { rev: number; ids: BlockId[] };
270
253
 
254
+ /** What the cycle marked in {@link inFlightActionId} asked of every send it makes
255
+ * ({@link InFlightCycle}) — read by {@link send} and by the re-send {@link completeOwnEntry} makes
256
+ * to finish a torn attempt, so neither needs it threaded through. Set by
257
+ * {@link beginInFlightAction} and cleared by its disposer. */
258
+ private inFlightCycle: InFlightCycle = {};
259
+
260
+ /** The head commit running on this instance ({@link openHeadCommit}), for the whole cycle — set and
261
+ * cleared beside {@link inFlightActionId}: the sealed segment it is committing, and the hook told
262
+ * what that segment accepted as already applied when it is dropped as committed
263
+ * ({@link HeadCommitOptions.onCommittedHead}). Read by {@link consumeOwnEntry}: the entry a head
264
+ * commit's own refresh finds under the in-flight action id records the HEAD segment's actions, not
265
+ * the open segment's, so consuming it removes that segment — and reports it through the hook, as
266
+ * the handle's `fold` does. */
267
+ private headCommit?: { readonly entryId: EntryId; readonly onCommitted?: (applied: AlreadyAppliedTally) => void };
268
+
269
+ /** Set only while a head commit has RELEASED the collection latch for its one network round trip
270
+ * ({@link HeadCommitHandle.release}), and cleared the moment it is retaken, so anything that runs under the
271
+ * latch in that window can tell. Two things must: a refresh ({@link updateInternal}) that walks
272
+ * into the in-flight entry returns without adopting it, since it can neither finish it as the
273
+ * write's own (nothing failed, nothing is retained) nor replay it as a stranger's (that would
274
+ * re-stage the head over state that already contains it); and {@link dropSealed} refuses to drop
275
+ * the segment the commit is carrying. A second {@link commitHead} meets it as its `in-flight`
276
+ * precondition. Gated on THIS field, not on {@link inFlightActionId}: the head commit's own
277
+ * refreshes run with it cleared and must take the own-entry path. */
278
+ private headInFlight?: { entryId: EntryId; actionId: ActionId };
279
+
271
280
  /** The log tail block id the most recent header read named. A refresh asks for this block in the
272
281
  * same request as the header ({@link readLogEnds}): the tail id only changes when the tail block
273
282
  * fills, so an idle refresh is one request rather than two. A stale value costs one extra request
@@ -277,7 +286,7 @@ export class Collection<TAction> implements ICollection<TAction> {
277
286
  protected constructor(
278
287
  public readonly id: CollectionId,
279
288
  public readonly transactor: ITransactor,
280
- private readonly handlers: Record<ActionType, ActionHandler<TAction>>,
289
+ private readonly handlers: Record<ActionType, ActionHandler<TAction, AlreadyAppliedTally | void>>,
281
290
  private readonly source: TransactorSource<IBlock>,
282
291
  /** Cache of unmodified blocks from the source */
283
292
  private readonly sourceCache: CacheSource<IBlock>,
@@ -288,6 +297,8 @@ export class Collection<TAction> implements ICollection<TAction> {
288
297
  * {@link BlockFloors}). */
289
298
  private readonly floors: BlockFloors,
290
299
  private readonly filterConflict?: (action: Action<TAction>, potential: Action<TAction>[]) => Action<TAction> | undefined,
300
+ /** See {@link CollectionInitOptions.onSealedRefused}. */
301
+ private readonly onSealedRefused?: (entryId: EntryId, error: ActionRefusedError) => void,
291
302
  /** Short random tag naming THIS instance (see {@link newInstanceTag}). Open paths generate
292
303
  * it BEFORE construction (so pre-construction diagnostics such as attachToLog can carry it);
293
304
  * the default covers direct construction in tests. */
@@ -338,7 +349,7 @@ export class Collection<TAction> implements ICollection<TAction> {
338
349
  return undefined;
339
350
  }
340
351
  await Collection.attachToLog<TAction>(source, sourceCache, tracker, floors, id, instanceTag, ends);
341
- const collection = new Collection(id, transactor, init.modules, source, sourceCache, tracker, floors, init.filterConflict, instanceTag);
352
+ const collection = new Collection(id, transactor, init.modules, source, sourceCache, tracker, floors, init.filterConflict, init.onSealedRefused, instanceTag);
342
353
  collection.logTailId = ends.header.tailId;
343
354
  return collection;
344
355
  }
@@ -354,6 +365,7 @@ export class Collection<TAction> implements ICollection<TAction> {
354
365
  const instanceTag = Collection.newInstanceTag();
355
366
  const { source, sourceCache, tracker, floors, ends } = await Collection.probeHeader(transactor, id, instanceTag);
356
367
 
368
+ let inventedBaseline: Transforms | undefined;
357
369
  if (ends) { // Collection already exists
358
370
  await Collection.attachToLog<TAction>(source, sourceCache, tracker, floors, id, instanceTag, ends);
359
371
  } else { // Collection does not exist
@@ -362,10 +374,15 @@ export class Collection<TAction> implements ICollection<TAction> {
362
374
  tracker.insert(headerBlock);
363
375
  source.actionContext = undefined;
364
376
  await Log.open<Action<TAction>>(tracker, id);
377
+ // Everything staged so far — the header (with the tail id Log.open wrote into it), the
378
+ // empty log block, and whatever createHeaderBlock staged beside the header — is what a
379
+ // replay has to put back while this collection has no committed revision.
380
+ inventedBaseline = copyTransforms(tracker.transforms);
365
381
  }
366
382
 
367
- const collection = new Collection(id, transactor, init.modules, source, sourceCache, tracker, floors, init.filterConflict, instanceTag);
383
+ const collection = new Collection(id, transactor, init.modules, source, sourceCache, tracker, floors, init.filterConflict, init.onSealedRefused, instanceTag);
368
384
  collection.logTailId = ends?.header.tailId;
385
+ collection.inventedBaseline = inventedBaseline;
369
386
  return collection;
370
387
  }
371
388
 
@@ -397,10 +414,12 @@ export class Collection<TAction> implements ICollection<TAction> {
397
414
  * a poll of many collections whose logs stayed on their blocks is one request, however many it
398
415
  * names; the per-block judgement is {@link readLogEnds}'s, through the same helpers.
399
416
  *
400
- * A request that throws is not every collection's failure: `NetworkTransactor.get` fails as a
401
- * whole when any block in it gets no answer, so {@link readAttributed} then reads each block
402
- * alone and only the collections whose blocks failed report an error. That fallback costs what
403
- * reading each collection separately costs, and only when a request fails. */
417
+ * A block no coordinator answered comes back flagged and fails only its own collection, through
418
+ * the per-block judgement. A request that throws as a whole — `NetworkTransactor.get` does when a
419
+ * coordinator's answer leaves a block out — is not every collection's failure either:
420
+ * {@link readAttributed} then reads each block alone and only the collections whose blocks failed
421
+ * report an error. That fallback costs what reading each collection separately costs, and only
422
+ * when a request fails. */
404
423
  static async readCommittedTails(transactor: ITransactor, queries: ReadonlyArray<CommittedTailQuery>): Promise<Map<CollectionId, CommittedTailAnswer>> {
405
424
  const knownTails = new Map(queries.map(query => [query.id, query.knownTailId]));
406
425
  const ends = await Collection.readAttributed(transactor,
@@ -464,7 +483,8 @@ export class Collection<TAction> implements ICollection<TAction> {
464
483
  return { source, sourceCache, tracker, floors, ends };
465
484
  }
466
485
 
467
- /** A new handle's floors: none yet (opening walks no entries), wired to report every below-floor
486
+ /** A new handle's floors: none yet (an open raises them from its log tail,
487
+ * {@link floorTailEntries}), wired to report every below-floor
468
488
  * answer any of the handle's read sources receives. The line is the only trace such an answer
469
489
  * leaves — the read itself succeeds (see the accepted-tradeoff NOTE at
470
490
  * `TransactorSource.mayRetain`) — so repeated lines for one block with `servedRev` short of
@@ -496,6 +516,7 @@ export class Collection<TAction> implements ICollection<TAction> {
496
516
  // Bootstrap ActionContext from the committed tail before walking the chain.
497
517
  // This allows the transactor to serve pending non-tail blocks during Log.open.
498
518
  Collection.bootstrapContext(source, ends.tail);
519
+ Collection.floorTailEntries(floors, ends);
499
520
  // The walk starts from the header and the tail, which the probe just read: keep them, so the
500
521
  // walk reads neither again. Its first read of each through the cache then records the read
501
522
  // dependency the probe's own read of the header used to.
@@ -511,6 +532,31 @@ export class Collection<TAction> implements ICollection<TAction> {
511
532
  Collection.advanceContext(source, id, instanceTag, 'attach', await collectionLog.getActionContext());
512
533
  }
513
534
 
535
+ /** Floor every block an action entry in the opened log's tail block names, at that entry's
536
+ * revision — what a refresh's walk does for the entries it walks ({@link raiseFloors}), for the
537
+ * entries an open has read but does not walk.
538
+ *
539
+ * An open adopts the revision the tail names, then reads each block it needs for the first time.
540
+ * When the answering repo's copy of such a block is older than an entry the tail holds — a node
541
+ * whose crash kept a commit's log tail but lost its other blocks within the store's durability
542
+ * window, or a coordinator that missed the commit — nothing else tells the read so, and the
543
+ * repo serves its held copy (a held block's first read after a restart is answered locally while
544
+ * the consult runs behind it). The handle then shows, say, a table row whose index entry is
545
+ * missing. With the floor, the read carries the revision the tail proves, so the repo consults
546
+ * its cohort before answering and the transactor re-asks another machine for an answer still
547
+ * below it (see {@link BlockFloors}).
548
+ *
549
+ * Only the tail block's entries: they are what the open read, and they hold the newest commits —
550
+ * the ones a durability window can tear. Invalidation entries set no floor, as on a refresh. */
551
+ private static floorTailEntries(floors: BlockFloors, ends: LogEnds): void {
552
+ const tail = ends.tail?.block as LogBlock<unknown> | undefined;
553
+ for (const entry of tail?.entries ?? []) {
554
+ if (entry.action !== undefined) {
555
+ floors.raise(entry.action.blockIds, { rev: entry.rev, actionId: entry.action.actionId });
556
+ }
557
+ }
558
+ }
559
+
514
560
  /** Adopt a freshly-read action context WITHOUT ever lowering the revision already held.
515
561
  *
516
562
  * The revision a collection last committed at is knowledge it earned; a read that found
@@ -687,21 +733,37 @@ export class Collection<TAction> implements ICollection<TAction> {
687
733
 
688
734
  private async actInternal(...actions: Action<TAction>[]) {
689
735
  await this.internalTransact(...actions);
690
- this.pending.push(...actions);
736
+ // Staging appends to the OPEN segment: a sealed segment is closed to further staging.
737
+ this.segments.open.push(...actions);
691
738
  }
692
739
 
693
- private async internalTransact(...actions: Action<TAction>[]) {
694
- const atomic = new Atomic(this.tracker);
740
+ private internalTransact(...actions: Action<TAction>[]): Promise<AlreadyAppliedTally> {
741
+ return this.stageInto(this.tracker, ...actions);
742
+ }
743
+
744
+ /** Run `actions` through their handlers over `tracker` as ONE atomic unit: a throw from any
745
+ * handler leaves none of their writes staged. The live tracker's path ({@link internalTransact})
746
+ * and a head commit's tracker ({@link buildHeadTracker}) share it.
747
+ *
748
+ * @returns the sum of what the handlers accepted as already applied ({@link AlreadyAppliedTally});
749
+ * a handler that answers nothing adds the zero tally. */
750
+ private async stageInto(tracker: Tracker<IBlock>, ...actions: Action<TAction>[]): Promise<AlreadyAppliedTally> {
751
+ const atomic = new Atomic(tracker);
752
+ let applied = ZeroTally;
695
753
 
696
754
  for (const action of actions) {
697
755
  const handler = this.handlers[action.type];
698
756
  if (!handler) {
699
757
  throw new Error(`No handler for action type ${action.type}`);
700
758
  }
701
- await handler(action, atomic);
759
+ const tally = await handler(action, atomic);
760
+ if (tally !== undefined) {
761
+ applied = addTallies(applied, tally);
762
+ }
702
763
  }
703
764
 
704
765
  atomic.commit();
766
+ return applied;
705
767
  }
706
768
 
707
769
  /** Load external changes and update our context to the latest log revision - resolve any conflicts with our pending actions. */
@@ -791,18 +853,23 @@ export class Collection<TAction> implements ICollection<TAction> {
791
853
  // finish. `getStatus` is the cheap first question; it judges a block by who holds its
792
854
  // LATEST revision, so a block this action landed and a later action has since built on
793
855
  // reads there as not committed — those are asked again, properly, by settleUnfinished.
794
- // Both write paths retain an attempt before any refresh can run, so production only
795
- // reaches this branch when the entry sits at a revision the retained attempt was not
796
- // made at — a forked lineage.
856
+ // A write's own cycle retains an attempt before any refresh can run, so from inside a cycle
857
+ // this branch is reached only when the entry sits at a revision the retained attempt was
858
+ // not made at — a forked lineage. The ordinary way here is a NEW cycle under an old id:
859
+ // the queue re-driving an entry whose earlier head commit ended in doubt without handing
860
+ // back the attempt it recorded ({@link openHeadCommit}, whose opening refresh runs with
861
+ // nothing retained unless `resume` seeds it).
797
862
  const [status] = await this.transactor.getStatus([{ actionId: entry.actionId, blockIds: entry.blockIds }]);
798
863
  if (entry.blockIds.every((_, i) => status?.statuses[i] === 'committed')) {
799
864
  // Whole, and saved: the refresh reports it as finished (see RefreshReport), so the
800
865
  // coordinator counts this participant as committed. Only WHO holds it is unknown.
801
- // NOTE: a sync whose only commit was recognised here therefore answers `undefined` —
802
- // the "nothing was written" answer — for a write that is saved, because the sync reads
803
- // the report's durability, not the finished flag. Reachable only on the forked-lineage
804
- // path above; if that path ever becomes ordinary, take the durability from
805
- // `getLineage` (as settleUnfinished does) instead of stopping at the status read.
866
+ // NOTE: a write whose only commit was recognised here therefore answers `undefined` for
867
+ // a write that is saved, because both write paths read the report's durability, not the
868
+ // finished flag. For a sync that is the "nothing was written" answer, reachable only on
869
+ // the forked-lineage path above; for a head commit it is unambiguous (a head segment is
870
+ // never empty) and is how a re-driven entry is answered. If the queue ever needs a
871
+ // durability class for a re-driven entry, take it from `getLineage` (as
872
+ // settleUnfinished does) instead of stopping at the status read.
806
873
  return undefined;
807
874
  }
808
875
  return await this.settleUnfinished(entry, rev, undefined, 'transforms-not-held',
@@ -823,7 +890,11 @@ export class Collection<TAction> implements ICollection<TAction> {
823
890
  // pair is not obviously right either: a member re-executing the transaction after a sibling
824
891
  // participant has landed no longer sees the state it was staged against. Tracked as an arm
825
892
  // of tickets/backlog/feat-no-deployment-validates-transactions-at-pend.
826
- const result = await this.source.transact(attempt.transforms, entry.actionId, rev, this.id, attempt.tailId, 0, attempt.blockDigests, attempt.baseRevs);
893
+ const result = await this.source.transact(attempt.transforms, entry.actionId, rev, this.id, attempt.tailId, {
894
+ blockDigests: attempt.blockDigests,
895
+ baseRevs: attempt.baseRevs,
896
+ refuseSolo: this.inFlightCycle.refuseSolo
897
+ });
827
898
  if (result.success) {
828
899
  return result.durability;
829
900
  }
@@ -841,6 +912,13 @@ export class Collection<TAction> implements ICollection<TAction> {
841
912
  // needs the clocks to start disagreeing between a write's attempts, since an expiry on the
842
913
  // attempt itself ends the write before any refresh. If it is ever seen burning a budget,
843
914
  // settle it at once beside the confirmed rival.
915
+ // NOTE: a promise shortfall of the re-send (`isShortfallFailure`) lands in the same arm, and
916
+ // there it can genuinely clear (the silent members come back), so the write is re-sent each
917
+ // round until the budget's last round settles it — unlike a fresh attempt's shortfall, which
918
+ // ends the write at once. If a silent cohort is ever seen holding torn writes for the whole
919
+ // budget, settle it at once here too.
920
+ // A validity rejection (`isRejectedFailure`) cannot answer the re-send: it carries no
921
+ // `validation` pair (above), so no checker judges it.
844
922
  // NOTE: a confirmed rival settles at once, even with retry budget left: re-sending is
845
923
  // pointless, but the lineage question is asked only this once, so a member that is silent
846
924
  // just now makes the answer `final: false`. If unsettled outcomes ever show up often under
@@ -957,47 +1035,122 @@ export class Collection<TAction> implements ICollection<TAction> {
957
1035
  * {@link completeOwnEntry} has returned for this entry — the entry alone is not proof the write
958
1036
  * is saved.
959
1037
  *
960
- * `addActions` wrote exactly the snapshot pending list under this action id, and the entry's
961
- * actions are therefore the LEADING `entry.actions.length` items of `this.pending` — anything
962
- * staged since is behind them, because {@link actInternal} appends. Under
963
- * {@link syncInternal} nothing can even be staged mid-cycle (`act()` shares the collection
964
- * latch); under `TransactionCoordinator.commit` the mark spans a latch-free inter-attempt
965
- * window, so an `act()` there CAN grow `pending` — still only at the tail, so the slice stays
966
- * right.
967
- *
968
- * The guard below is the load-bearing part: `slice` fails SILENTLY if that correspondence ever
969
- * breaks, dropping actions that were never committed, so an entry longer than `pending` throws
970
- * instead of losing work. (See the sibling note on `syncInternal`'s post-commit replay, which
971
- * rests on the same invariant.) */
972
- private consumeOwnEntry(entry: ActionEntry<Action<TAction>>) {
973
- if (entry.actions.length > this.pending.length) {
1038
+ * A whole-collection write (`sync`) wrote exactly the snapshot of the OPEN segment under this
1039
+ * action id, and the entry's actions are therefore the LEADING `entry.actions.length` items of
1040
+ * the open segment — anything staged since is behind them, because {@link actInternal}
1041
+ * appends. Under {@link syncInternal} nothing can even be staged mid-cycle (`act()` shares the
1042
+ * collection latch); under `TransactionCoordinator.commit` the mark spans a latch-free
1043
+ * inter-attempt window, so an `act()` there CAN grow the open segment — still only at the
1044
+ * tail, so the slice stays right. No sealed segment can exist for such a write: every
1045
+ * whole-collection path refuses while one does ({@link SealedSegmentsError}).
1046
+ *
1047
+ * A head commit ({@link commitHead}, which marks {@link headCommit} for its cycle) wrote the
1048
+ * HEAD sealed segment's actions, so its entry is consumed by removing that segment — the open
1049
+ * segment, which may have grown while the commit was on the network, is untouched. The sealed
1050
+ * segments behind the head are never touched by either arm.
1051
+ *
1052
+ * The guards are the load-bearing part: `slice` fails SILENTLY if the open correspondence ever
1053
+ * breaks, dropping actions that were never committed, so an entry longer than the open segment
1054
+ * throws instead of losing work, and an entry whose action count is not the head's throws rather
1055
+ * than removing a segment the entry does not record. (See the sibling note on `syncInternal`'s
1056
+ * post-commit replay, which rests on the same invariant.)
1057
+ *
1058
+ * @returns whether the staged set changed — always true here: even for a zero-action entry the
1059
+ * tracker still holds this action's staged transforms, and only the replay at the end of
1060
+ * `updateInternal` — which resets the tracker and re-stages just what remains — drops them.
1061
+ * That reset is what turns `hasUnsyncedChanges()` false so the sync loop exits reporting the
1062
+ * success the writer is owed (the action IS durable). */
1063
+ private consumeOwnEntry(entry: ActionEntry<Action<TAction>>): boolean {
1064
+ if (this.headCommit !== undefined) {
1065
+ this.consumeHead(entry, this.headCommit.entryId);
1066
+ } else {
1067
+ this.segments.open = this.consumedFromOpen(entry);
1068
+ }
1069
+ return true;
1070
+ }
1071
+
1072
+ /** Remove the head segment `entryId` because `entry`, its own committed log entry, made it
1073
+ * durable — the head arm of {@link consumeOwnEntry}. Bumps the segment version, so an outstanding
1074
+ * snapshot restores by replay rather than putting the committed segment back, and reports the
1075
+ * dropped segment's tally through the cycle's hook ({@link reportCommittedHead}), as the handle's
1076
+ * `fold` does for an attempt that committed. */
1077
+ private consumeHead(entry: ActionEntry<Action<TAction>>, entryId: EntryId): void {
1078
+ const head = this.segments.head();
1079
+ if (head === undefined || head.entryId !== entryId) {
1080
+ throw new Error(
1081
+ `Collection ${this.id}: own committed entry for action ${entry.actionId} records head segment `
1082
+ + `${entryId}, but the head is ${head?.entryId ?? 'nothing'}`);
1083
+ }
1084
+ if (entry.actions.length !== head.actions.length) {
1085
+ throw new Error(
1086
+ `Collection ${this.id}: own committed entry for action ${entry.actionId} holds `
1087
+ + `${entry.actions.length} actions but head segment ${entryId} holds ${head.actions.length}; `
1088
+ + `consuming it would drop actions that were never committed`);
1089
+ }
1090
+ this.reportCommittedHead(this.segments.drop(entryId));
1091
+ }
1092
+
1093
+ /** Hand the tally recorded on `segment` — the head segment just made durable and dropped — to the
1094
+ * cycle's `onCommittedHead` hook ({@link HeadCommitOptions.onCommittedHead}), under the latch, from
1095
+ * the two places that drop a head segment as committed: the handle's `fold`, and
1096
+ * {@link consumeHead}. A segment with no recorded tally is a defect, answered with the zero tally
1097
+ * and logged rather than thrown: every sealed segment is staged by {@link buildHeadTracker} before
1098
+ * its first send and by a replay when put back ({@link restoreSealed}), and the resume path that
1099
+ * re-sends a recorded attempt verbatim runs after one of those. A throw out of the hook is logged,
1100
+ * never raised — the commit is already durable. */
1101
+ private reportCommittedHead(segment: SealedSegment<TAction>): void {
1102
+ let applied = segment.applied;
1103
+ if (applied === undefined) {
1104
+ log('collection:committed-head-tally-missing id=%s tag=%s entry=%s: the head segment was committed without a recorded staging',
1105
+ this.id, this.instanceTag, segment.entryId);
1106
+ applied = ZeroTally;
1107
+ }
1108
+ const hook = this.headCommit?.onCommitted;
1109
+ if (hook === undefined) {
1110
+ return;
1111
+ }
1112
+ try {
1113
+ hook(applied);
1114
+ } catch (err) {
1115
+ log('collection:committed-head-callback-threw id=%s tag=%s entry=%s error=%s',
1116
+ this.id, this.instanceTag, segment.entryId, err instanceof Error ? err.message : String(err));
1117
+ }
1118
+ }
1119
+
1120
+ /** The open segment with the leading actions `entry` made durable dropped off it. */
1121
+ private consumedFromOpen(entry: ActionEntry<Action<TAction>>): Action<TAction>[] {
1122
+ const open = this.segments.open;
1123
+ if (entry.actions.length > open.length) {
974
1124
  throw new Error(
975
1125
  `Collection ${this.id}: own committed entry for action ${entry.actionId} holds `
976
- + `${entry.actions.length} actions but only ${this.pending.length} are pending; `
1126
+ + `${entry.actions.length} actions but only ${open.length} are pending; `
977
1127
  + `consuming it would drop actions that were never committed`);
978
1128
  }
979
- // `mutated` is unconditional, even for a zero-action entry: the tracker still holds this
980
- // action's staged transforms, and only the replay at the end of `updateInternal` — which
981
- // resets the tracker and re-stages just what remains — drops them. That reset is what turns
982
- // `hasUnsyncedChanges()` false so the sync loop exits reporting the success the writer is
983
- // owed (the action IS durable).
984
- return { after: this.pending.slice(entry.actions.length), mutated: true };
1129
+ return open.slice(entry.actions.length);
985
1130
  }
986
1131
 
987
- /** Maps each pending action to its effective form against a remote entry: the original, a
988
- * replacement, or dropped. A replacement or a discard changes the pending set; the tracker still
1132
+ /** Maps each OPEN-segment action to its effective form against a remote entry: the original, a
1133
+ * replacement, or dropped. A replacement or a discard changes the staged set; the tracker still
989
1134
  * holds the pre-filter transforms, so report it as mutated to force a replay that re-stages
990
1135
  * against the effective actions. Identity comparison per the contract: keep => same instance,
991
1136
  * replace => new instance.
1137
+ *
1138
+ * A SEALED segment's action list is the queue entry's own and is never rewritten (invariant 3
1139
+ * of docs/offline-sync.md §The segment model), so the hook is not offered them. `Tree` and
1140
+ * `Diary` install no hook, so nothing observable changes for them either way.
1141
+ *
992
1142
  * NOTE: a filterConflict hook that always allocates a fresh (but equal) instance instead of
993
1143
  * returning the same one forces a replay on every update — if that ever shows up as a hot path,
994
- * compare by value/id here instead of by reference. */
995
- private filterAgainstEntry(entry: ActionEntry<Action<TAction>>) {
996
- const before = this.pending;
1144
+ * compare by value/id here instead of by reference.
1145
+ *
1146
+ * @returns whether the open segment changed. */
1147
+ private filterAgainstEntry(entry: ActionEntry<Action<TAction>>): boolean {
1148
+ const before = this.segments.open;
997
1149
  const after = before
998
1150
  .map(p => this.doFilterConflict(p, entry.actions))
999
1151
  .filter((a): a is Action<TAction> => a !== undefined);
1000
- return { after, mutated: after.length !== before.length || after.some((a, i) => a !== before[i]) };
1152
+ this.segments.open = after;
1153
+ return after.length !== before.length || after.some((a, i) => a !== before[i]);
1001
1154
  }
1002
1155
 
1003
1156
  /** Refresh this instance against the stored log: adopt the latest committed revision, resolve
@@ -1089,6 +1242,21 @@ export class Collection<TAction> implements ICollection<TAction> {
1089
1242
  const collectionLog = await Log.open<Action<TAction>>(tracker, this.id);
1090
1243
  const latest = collectionLog ? await collectionLog.getFrom(actionContext?.rev ?? 0) : undefined;
1091
1244
 
1245
+ // A refresh that runs while this instance's own head commit is on the network — a reader's,
1246
+ // the latch being released for that round trip — and walks into that commit's entry adopts
1247
+ // NOTHING (see {@link headInFlight}): the entry is not failed, so it is not finished and consumed
1248
+ // as the write's own below, and it is not a stranger's, so it is not filtered and replayed. The
1249
+ // head commit applies its own outcome when it retakes the latch, after which the next refresh
1250
+ // finds nothing new. The reader is served the state before this collection's own write, which it
1251
+ // sees staged anyway. Entries behind it in the same walk wait with it — an own entry is always
1252
+ // the first above the held revision, since the attempt requested exactly that revision.
1253
+ const headInFlight = this.headInFlight;
1254
+ if (headInFlight !== undefined && latest?.entries.some(entry => entry.actionId === headInFlight.actionId)) {
1255
+ log('collection:refresh-deferred-to-head-commit id=%s tag=%s entry=%s action=%s',
1256
+ this.id, this.instanceTag, headInFlight.entryId, headInFlight.actionId);
1257
+ return;
1258
+ }
1259
+
1092
1260
  // This write's own entry, if its log tail landed despite the failure that sent us here.
1093
1261
  // Decided ONCE, here: the mark can be cleared latch-free while the completion below is
1094
1262
  // awaiting (see {@link inFlightActionId}), and an entry that was finished as our own must
@@ -1112,11 +1280,9 @@ export class Collection<TAction> implements ICollection<TAction> {
1112
1280
  // Process the entries and track the blocks they affect
1113
1281
  let anyConflicts = false;
1114
1282
  for (const entry of latest?.entries ?? []) {
1115
- const isOwnEntry = entry === ownEntry;
1116
- const { after, mutated } = isOwnEntry
1283
+ const mutated = entry === ownEntry
1117
1284
  ? this.consumeOwnEntry(entry)
1118
1285
  : this.filterAgainstEntry(entry);
1119
- this.pending = after;
1120
1286
  anyConflicts = anyConflicts || mutated || this.tracker.conflicts(new Set(entry.blockIds)).length > 0;
1121
1287
  }
1122
1288
 
@@ -1128,7 +1294,7 @@ export class Collection<TAction> implements ICollection<TAction> {
1128
1294
  // block; over-inclusive by design (over-invalidation just resubmits — it never wrongly retains).
1129
1295
  const invalidations = collectionLog ? await collectionLog.getInvalidationsFrom(actionContext?.rev ?? 0) : [];
1130
1296
  const revertedBlockIds = [...new Set(invalidations.flatMap(inv => inv.reverted.map(r => r.blockId)))];
1131
- if (invalidations.length > 0 && this.pending.length > 0) {
1297
+ if (invalidations.length > 0 && this.segments.replayableCount() > 0) {
1132
1298
  anyConflicts = true;
1133
1299
  }
1134
1300
 
@@ -1136,15 +1302,17 @@ export class Collection<TAction> implements ICollection<TAction> {
1136
1302
 
1137
1303
  Collection.reportShortfall(this.id, this.instanceTag, tailRev, actionContext?.rev, this.source.actionContext?.rev);
1138
1304
 
1139
- // Re-stage the pending actions against the adopted revision. The affected
1305
+ // Re-stage the staged actions against the adopted revision. The affected
1140
1306
  // blocks were already dropped from sourceCache above (per log entry / per invalidation),
1141
1307
  // so the replay's reads re-materialize from the transactor.
1142
- // NOTE: a throw out of replayActions leaves the tracker holding only the transforms
1143
- // replayed so far while `pending` still lists them all; the caller's error handling is
1144
- // expected to abort/reset the collection rather than keep staging. The coordinator's partial
1145
- // report after a refresh-saved sibling does not (backlog: debt-a-failed-refresh-can-leave-a-
1146
- // collection-half-restaged). If replay ever gains a
1147
- // routinely-throwing read path, rebuild into a scratch tracker and swap on success.
1308
+ // NOTE: a throw out of replayActions — a refusal of the OPEN segment, or any non-refusal
1309
+ // error — leaves the tracker holding only the transforms replayed so far while the open
1310
+ // segment still lists all of its actions; the caller's error handling is expected to
1311
+ // abort/reset the collection rather than keep staging. The coordinator's partial report
1312
+ // after a refresh-saved sibling does not (backlog: debt-a-failed-refresh-can-leave-a-
1313
+ // collection-half-restaged). A SEALED segment is not left half-replayed: it is staged
1314
+ // atomically, and a refusal of one is recorded and skipped rather than thrown. If replay ever
1315
+ // gains a routinely-throwing read path, rebuild into a scratch tracker and swap on success.
1148
1316
  if (this.mustReplay(anyConflicts, actionContext)) {
1149
1317
  await this.replayActions();
1150
1318
  }
@@ -1363,8 +1531,8 @@ export class Collection<TAction> implements ICollection<TAction> {
1363
1531
  });
1364
1532
  }
1365
1533
 
1366
- /** Whether {@link updateInternal} must re-stage `pending` after adopting `latest`, given the
1367
- * context it held BEFORE the refresh.
1534
+ /** Whether {@link updateInternal} must re-stage the staged actions after adopting `latest`,
1535
+ * given the context it held BEFORE the refresh.
1368
1536
  *
1369
1537
  * The answer is deliberately NOT just "a conflict was found". A conflict is detected by an
1370
1538
  * incoming log entry naming a block this tracker already holds a transform for — so an action
@@ -1379,16 +1547,17 @@ export class Collection<TAction> implements ICollection<TAction> {
1379
1547
  * The advance test rests on {@link advanceContext} being monotonic (it refuses to lower), which
1380
1548
  * is what makes "the adopted rev differs from the held one" mean "it went up".
1381
1549
  *
1382
- * The second conjunct is `pending.length` and deliberately NOT {@link hasUnsyncedChanges},
1383
- * which also counts tracker transforms. A collection {@link createOrOpen} just INVENTED holds
1384
- * its staged header/root in the tracker with NO pending action naming them, and
1385
- * {@link replayActions} resets the tracker before re-staging — so counting transforms here
1386
- * would drop those blocks and leave a brand-new collection unreadable (the same hazard
1387
- * {@link snapshotPending} documents). Nothing to re-stage means nothing to replay.
1388
- *
1389
- * NOTE: this makes a refresh that adopts a newer revision O(pending) rather than free, so a
1390
- * read taken mid-transaction while a rival keeps committing re-stages every action staged so
1391
- * far, on each such read. Measured as no change to the storage-op budgets
1550
+ * The second conjunct counts the REPLAYABLE actions — every non-refused sealed segment's plus
1551
+ * the open segment's, since a refresh that adopts a newer revision must re-stage the sealed
1552
+ * segments too — and deliberately NOT {@link hasUnsyncedChanges}, which also counts tracker
1553
+ * transforms. A collection {@link createOrOpen} just INVENTED holds its staged header/root in
1554
+ * the tracker with NO staged action naming them; {@link replayActions} now restores them from
1555
+ * {@link inventedBaseline}, but nothing to re-stage still means nothing to replay, and a replay
1556
+ * over no actions would be a wasted tracker rebuild.
1557
+ *
1558
+ * NOTE: this makes a refresh that adopts a newer revision O(staged actions) rather than free,
1559
+ * so a read taken mid-transaction while a rival keeps committing re-stages every action staged
1560
+ * so far, on each such read. Measured as no change to the storage-op budgets
1392
1561
  * (`index-backfill-cost.spec.ts`, `cold-apply-cost.spec.ts`), because the replay's reads are
1393
1562
  * served from `sourceCache`. If a long transaction's reads ever show up as slow, narrow the
1394
1563
  * replay to the actions whose reads the adopted entries actually invalidated — NOT back to
@@ -1398,7 +1567,8 @@ export class Collection<TAction> implements ICollection<TAction> {
1398
1567
  return true;
1399
1568
  }
1400
1569
  const adoptedRev = this.source.actionContext?.rev;
1401
- if (adoptedRev !== undefined && adoptedRev !== priorContext?.rev && this.pending.length > 0) {
1570
+ const replayable = this.segments.replayableCount();
1571
+ if (adoptedRev !== undefined && adoptedRev !== priorContext?.rev && replayable > 0) {
1402
1572
  return true;
1403
1573
  }
1404
1574
  // Third reason: a staged block's base has MOVED — the read cache no longer describes it at
@@ -1406,22 +1576,19 @@ export class Collection<TAction> implements ICollection<TAction> {
1406
1576
  // that adopted nothing and found no conflict can still be standing over such a block: a
1407
1577
  // concurrent read served content the cache then kept at a newer revision, say. Re-staging
1408
1578
  // is the only repair; declaring the pinned revision on the pend would merely get it refused.
1409
- return this.pending.length > 0 && this.logMovedBases(this.tracker.movedBases()) > 0;
1579
+ return replayable > 0 && this.logMovedBases(this.tracker.movedBases()) > 0;
1410
1580
  }
1411
1581
 
1412
1582
  /** Re-judge every staged update's pinned base against the read cache and re-stage the pending
1413
1583
  * queue if any has moved. Runs immediately before each pend attempt — {@link syncAttempts} and
1414
- * the coordinator's commit span both call it — because that is the last moment before the
1415
- * base the pend declares is put on the wire, and nothing between a refused attempt and the
1416
- * re-pend reads the block again (the refresh may have moved nothing and so replayed nothing).
1584
+ * the coordinator's commit span both call it, and {@link headTrackerFor} re-judges a head
1585
+ * commit's tracker the same way — because that is the last moment before the base the pend
1586
+ * declares is put on the wire, and nothing between a refused attempt and the re-pend reads the
1587
+ * block again (the refresh may have moved nothing and so replayed nothing).
1417
1588
  *
1418
- * Two steps. First, one read for each pinned block the cache does NOT retain — content handed
1419
- * through unkept (a below-floor answer, which the cache re-asks for on every read anyway): the
1420
- * pin names the revision last served, storage may have caught up since without the log moving,
1421
- * and only a read can tell. An evicted-but-kept base needs no read: its content met every floor
1422
- * the handle knows, so storage cannot have moved it without a log entry the next refresh will
1423
- * walk (and the pend would be refused as stale on revision alone). Then, one cache probe per
1424
- * pinned block ({@link Tracker.movedBases}) and a replay if any moved.
1589
+ * Two steps. First, one read for each pinned block the cache does NOT retain
1590
+ * ({@link rereadUnretainedBases}). Then, one cache probe per pinned block
1591
+ * ({@link Tracker.movedBases}) and a replay if any moved.
1425
1592
  *
1426
1593
  * Latch-free by contract, like {@link snapshotPending}: the caller holds this instance's latch
1427
1594
  * ({@link replayActions} is always run under it).
@@ -1433,18 +1600,30 @@ export class Collection<TAction> implements ICollection<TAction> {
1433
1600
  *
1434
1601
  * @returns whether the pending queue was re-staged. */
1435
1602
  async restageIfBasesMoved(): Promise<boolean> {
1436
- for (const id of this.tracker.unretainedBases()) {
1437
- // `navigation` never upgrades the purpose the original read recorded (value-wins), and
1438
- // the revision recorded is the one returned, which the replay below re-records anyway.
1439
- await this.sourceCache.tryGet(id, 'navigation');
1440
- }
1441
- if (this.pending.length === 0 || this.logMovedBases(this.tracker.movedBases()) === 0) {
1603
+ await this.rereadUnretainedBases(this.tracker);
1604
+ // Every replayable action counts, sealed segments included: a moved base under a sealed
1605
+ // segment's operations is re-staged the same way.
1606
+ if (this.segments.replayableCount() === 0 || this.logMovedBases(this.tracker.movedBases()) === 0) {
1442
1607
  return false;
1443
1608
  }
1444
1609
  await this.replayActions();
1445
1610
  return true;
1446
1611
  }
1447
1612
 
1613
+ /** One read for each of `tracker`'s pinned blocks the cache does NOT retain — content handed
1614
+ * through unkept (a below-floor answer, which the cache re-asks for on every read anyway): the
1615
+ * pin names the revision last served, storage may have caught up since without the log moving,
1616
+ * and only a read can tell. An evicted-but-kept base needs no read: its content met every floor
1617
+ * the handle knows, so storage cannot have moved it without a log entry the next refresh will
1618
+ * walk (and the pend would be refused as stale on revision alone). */
1619
+ private async rereadUnretainedBases(tracker: Tracker<IBlock>): Promise<void> {
1620
+ for (const id of tracker.unretainedBases()) {
1621
+ // `navigation` never upgrades the purpose the original read recorded (value-wins), and
1622
+ // the revision recorded is the one returned, which a replay re-records anyway.
1623
+ await this.sourceCache.tryGet(id, 'navigation');
1624
+ }
1625
+ }
1626
+
1448
1627
  /** Report each moved base, naming the revision the operations were computed against and the
1449
1628
  * one the cache describes now, and return how many there were. */
1450
1629
  private logMovedBases(moved: readonly BlockId[]): number {
@@ -1476,7 +1655,8 @@ export class Collection<TAction> implements ICollection<TAction> {
1476
1655
  return {
1477
1656
  transforms: copyTransforms(this.tracker.transforms),
1478
1657
  pins: this.tracker.pins.copy(),
1479
- pending: [...this.pending],
1658
+ pending: [...this.segments.open],
1659
+ sealedVersion: this.segments.version,
1480
1660
  context: structuredClone(this.source.actionContext),
1481
1661
  };
1482
1662
  }
@@ -1485,40 +1665,80 @@ export class Collection<TAction> implements ICollection<TAction> {
1485
1665
  * mutations staged since. Reads through the collection then observe exactly the
1486
1666
  * snapshot state again; storage is untouched because nothing was ever synced.
1487
1667
  *
1488
- * A snapshot is only restorable VERBATIM onto the committed boundary it was captured
1489
- * on. If this collection has since ADOPTED a newer committed revision — a rival's
1490
- * commit folded in by a refresh while the snapshot's transaction was in flight, e.g.
1491
- * the conflict replay that refused a guarded insert (TreeKeyTakenError) — the
1492
- * snapshot's transforms describe block state at the OLD boundary, and reinstalling
1493
- * them would shadow committed blocks with stale structure. The observed case: an
1494
- * INVENTED collection's pre-commit header/root transforms restored over the rival's
1495
- * now-committed collection make every later read descend an empty tree, silently
1496
- * hiding the committed rows. When the snapshot's pending queue is empty (the
1497
- * transaction-rollback shape: the capture predates the transaction's first stage),
1498
- * the correct restore target IS the committed state — reset the tracker empty and
1499
- * let reads flow through to the adopted revision.
1500
- *
1501
- * NOTE: a snapshot that carries PENDING actions across a moved boundary (a
1502
- * mid-transaction savepoint captured before a mid-transaction refresh adopted a
1503
- * rival's commit) still restores verbatim below — rebasing it would require an async
1504
- * replay this synchronous method cannot run. That shape predates this guard and
1505
- * keeps its old behaviour; if it is ever observed producing stale reads, the rebase
1506
- * belongs in an async caller that can replay the pending queue (see replayActions).
1668
+ * The snapshot describes the OPEN segment only (docs/offline-sync.md §Rollback and savepoints
1669
+ * only touch the open segment): its `pending` is the open segment's actions, while its
1670
+ * `transforms` are the whole tracker at capture, the sealed segments' effects included. Which
1671
+ * arm a restore takes is decided from three facts — whether the sealed list has changed since
1672
+ * the capture ({@link CollectionSnapshot.sealedVersion} against {@link SegmentList.version}),
1673
+ * whether the committed boundary has moved (this collection has since ADOPTED a newer
1674
+ * revision), and whether any segment is sealed now:
1675
+ *
1676
+ * - **Verbatim**, when the sealed list is unchanged and the boundary has not moved: the tracker
1677
+ * is reset to a copy of the captured transforms, the captured pins are restored, and the open
1678
+ * segment is set to the captured actions. This keeps an INVENTED collection's header, log
1679
+ * block and root, which live in the tracker until the first sync and would be lost by a
1680
+ * reset. It is the arm every restore took before segments existed, so while nothing is ever
1681
+ * sealed nothing behaves differently.
1682
+ * - **Replay**, when the sealed list has changed — a segment sealed, dropped or refused while
1683
+ * the snapshot was outstanding — or when the boundary has moved while a segment is sealed:
1684
+ * the open segment is set to the captured actions and the tracker is rebuilt by
1685
+ * {@link replayActions}, the sealed segments as they are NOW (refused ones skipped, a newly
1686
+ * refused one recorded and reported) and then the restored open actions. Reinstating the
1687
+ * captured transforms would put a dropped segment's effects back — the drain removes the
1688
+ * head segment after committing it, and the next head commit would commit it a second time
1689
+ * — and a reset would drop the sealed segments' effects.
1690
+ * - A moved boundary with NOTHING sealed keeps the two arms it had before segments. An empty
1691
+ * captured open segment (the transaction-rollback shape: the capture predates the
1692
+ * transaction's first stage) resets the tracker empty, because the captured transforms
1693
+ * describe block state at the OLD boundary and reinstalling them would shadow committed
1694
+ * blocks with stale structure — the observed case being an INVENTED collection's pre-commit
1695
+ * header/root restored over a rival's now-committed collection, after the conflict replay
1696
+ * that refused a guarded insert (TreeKeyTakenError), making every later read descend an
1697
+ * empty tree. A non-empty one restores verbatim (the NOTE below).
1698
+ *
1699
+ * The staged-base rule (docs/internals.md §Staged Edits Keep Their Base: an update names the
1700
+ * base it was computed against, and a rollback never pairs operations with the bases of some
1701
+ * later re-stage) is met differently by the two arms. The verbatim arm restores the captured
1702
+ * pins beside the captured operations. The replay arm restores none: its reset clears the pin
1703
+ * store, and every re-staged update pins its base from the read cache as it is now, which IS
1704
+ * the base the re-staged operations were computed against.
1705
+ *
1706
+ * A refusal of the OPEN segment inside the replay arm propagates, as it would out of a
1707
+ * refresh's replay: the caller rolling back is told that its transaction's own actions no
1708
+ * longer apply at the boundary the collection is now at. Rare — it needs a sealed change, or a
1709
+ * sealed segment across a moved boundary, AND a rival between capture and restore — and the
1710
+ * honest answer; the tracker is then as {@link updateInternal}'s note on a throw out of
1711
+ * `replayActions` describes.
1712
+ *
1713
+ * Latch-free by contract, like {@link snapshotPending}: every caller holds this instance's
1714
+ * latch or runs on the single call path that excludes a concurrent stage (the coordinator's
1715
+ * `rollback` and the bridge's savepoint rollback document that assumption).
1716
+ *
1717
+ * NOTE: a snapshot that carries PENDING actions across a moved boundary with nothing sealed (a
1718
+ * mid-transaction savepoint captured before a mid-transaction refresh adopted a rival's commit)
1719
+ * still restores verbatim. That shape predates the moved-boundary guard and keeps its old
1720
+ * behaviour; if it is ever observed producing stale reads, route it through the replay arm too.
1507
1721
  * The WRITE side of that shape is closed here: the snapshot's base pins are restored with
1508
1722
  * its transforms, so the restored operations name the bases they were computed on, and the
1509
1723
  * pre-pend re-validation (restageIfBasesMoved) finds those bases moved and re-stages. */
1510
- restorePending(snapshot: CollectionSnapshot<TAction>): void {
1724
+ async restorePending(snapshot: CollectionSnapshot<TAction>): Promise<void> {
1725
+ const sealedChanged = snapshot.sealedVersion !== undefined && snapshot.sealedVersion !== this.segments.version;
1511
1726
  const capturedRev = snapshot.context?.rev;
1512
1727
  const currentRev = this.source.actionContext?.rev;
1513
1728
  const boundaryMoved = currentRev !== undefined && (capturedRev === undefined || currentRev > capturedRev);
1729
+ if (sealedChanged || (boundaryMoved && this.segments.hasSealed())) {
1730
+ this.segments.open = [...snapshot.pending];
1731
+ await this.replayActions();
1732
+ return;
1733
+ }
1514
1734
  if (boundaryMoved && snapshot.pending.length === 0) {
1515
1735
  this.tracker.reset();
1516
- this.pending = [];
1736
+ this.segments.open = [];
1517
1737
  return;
1518
1738
  }
1519
1739
  this.tracker.reset(copyTransforms(snapshot.transforms));
1520
1740
  if (snapshot.pins) this.tracker.pins.replaceWith(snapshot.pins);
1521
- this.pending = [...snapshot.pending];
1741
+ this.segments.open = [...snapshot.pending];
1522
1742
  }
1523
1743
 
1524
1744
  /** A read-only {@link Tracker} pinned to this collection's committed state AS OF the
@@ -1583,35 +1803,213 @@ export class Collection<TAction> implements ICollection<TAction> {
1583
1803
  return new Tracker(pinnedCache, copyTransforms(transforms));
1584
1804
  }
1585
1805
 
1586
- /** The staged (not-yet-synced) actions queued by {@link act}.
1806
+ /** The OPEN segment: the staged (not-yet-synced) actions queued by {@link act} that no
1807
+ * {@link sealPending} has closed off.
1587
1808
  *
1588
1809
  * Exposed so a {@link TransactionCoordinator} can append them to the log at
1589
1810
  * commit time — mirroring what {@link sync} does internally — when the actions
1590
1811
  * were staged directly into this collection (e.g. through a Tree's stage())
1591
- * rather than applied via the coordinator's own action path. */
1812
+ * rather than applied via the coordinator's own action path.
1813
+ *
1814
+ * @throws SealedSegmentsError while any segment is sealed: the coordinator's only use is a
1815
+ * whole-collection append, which would merge the sealed segments' effects (they are in the
1816
+ * tracker) into one entry under one action id. The throw lands in `commitOnceLatched`'s
1817
+ * existing catch, which restores every participant. */
1592
1818
  getPendingActions(): Action<TAction>[] {
1593
- return this.pending;
1819
+ this.assertNoSealedSegments();
1820
+ return this.segments.open;
1594
1821
  }
1595
1822
 
1596
- /** Drop the staged actions after they have been committed through a
1597
- * coordinator. Counterpart to {@link getPendingActions}; {@link sync} clears
1598
- * its own pending inline, so this is only needed when commit was orchestrated
1599
- * externally. */
1823
+ /** Drop the OPEN segment after it has been committed through a coordinator. Counterpart to
1824
+ * {@link getPendingActions}, which cannot have returned anything while a segment was sealed,
1825
+ * so only the open segment is ever cleared here; {@link sync} clears its own inline, so this
1826
+ * is only needed when commit was orchestrated externally. */
1600
1827
  clearPendingActions(): void {
1601
- this.pending = [];
1828
+ this.segments.open = [];
1602
1829
  }
1603
1830
 
1604
- /** Whether {@link sync} has anything to push: staged actions, or tracker transforms
1605
- * that were never committed (an INVENTED collection's header/root blocks live there
1606
- * until its first sync, with no pending action to name them).
1831
+ /** Whether {@link sync} has anything to push: staged actions in the open segment, or tracker
1832
+ * transforms that were never committed — an INVENTED collection's header/root blocks, which
1833
+ * live there until its first sync with no staged action to name them, and the effects of
1834
+ * every sealed segment.
1607
1835
  *
1608
1836
  * This is the exact predicate {@link syncInternal} loops on, so `false` means a sync
1609
1837
  * would commit nothing. Exposed so a caller that would otherwise flush
1610
1838
  * unconditionally can skip the round trip — note that {@link Tree.sync} routes
1611
1839
  * through {@link updateAndSync}, so an unnecessary flush still pays a full,
1612
- * cache-bypassing {@link update} before discovering it has nothing to do. */
1840
+ * cache-bypassing {@link update} before discovering it has nothing to do.
1841
+ *
1842
+ * `true` does not promise that {@link sync} can push it: while any segment is sealed, `sync`
1843
+ * refuses with {@link SealedSegmentsError} rather than committing the sealed effects as one
1844
+ * entry, so a caller that loops on this over a sealed collection gets that typed error, never
1845
+ * a silent no-op. Check {@link sealedEntries} first, or commit the head segment.
1846
+ *
1847
+ * Nor does `false` promise that nothing is sealed. A sealed segment leaves no tracker transform
1848
+ * when every one of its actions is refused, or wrote nothing (a blind delete of a key nobody
1849
+ * holds), so over an otherwise empty tracker this reads `false` while {@link sealedEntries} is
1850
+ * non-empty. The queue drives off {@link sealedEntries}, never off this predicate. */
1613
1851
  hasUnsyncedChanges(): boolean {
1614
- return this.pending.length > 0 || !isTransformsEmpty(this.tracker.transforms);
1852
+ return this.segments.open.length > 0 || !isTransformsEmpty(this.tracker.transforms);
1853
+ }
1854
+
1855
+ /** Close the open segment into a sealed segment owned by `entryId` (see {@link SegmentList}).
1856
+ * Returns `false` and changes nothing when the open segment is empty: an invented collection's
1857
+ * header transforms are not an action and are not sealed, so an entry that staged nothing here
1858
+ * owns no segment here. Throws when `entryId` is already sealed in this collection.
1859
+ *
1860
+ * Synchronous and latch-free by contract, like {@link snapshotPending}: the caller brackets it
1861
+ * (no concurrent act or sync is in flight). */
1862
+ sealPending(entryId: EntryId): boolean {
1863
+ return this.segments.seal(entryId);
1864
+ }
1865
+
1866
+ /** The entry ids of the sealed segments, oldest first — refused ones included, until dropped. */
1867
+ sealedEntries(): EntryId[] {
1868
+ return this.segments.entryIds();
1869
+ }
1870
+
1871
+ /** The log tail block id the most recent header read named ({@link logTailId}), for a caller that
1872
+ * resolves this collection's cohorts from routing keys without a read — the offline queue's
1873
+ * reachability gate (docs/offline-sync.md §When to submit). `undefined` before the first header
1874
+ * read of an invented collection; possibly stale by one roll-over, which costs that caller nothing
1875
+ * worse than asking about a block the collection has moved on from. */
1876
+ knownLogTailId(): BlockId | undefined {
1877
+ return this.logTailId;
1878
+ }
1879
+
1880
+ /** The refusal recorded for `entryId`'s segment by a replay that excluded it (see
1881
+ * {@link replayActions}), or `undefined` when the segment is not refused — or not sealed here. */
1882
+ sealedRefusal(entryId: EntryId): ActionRefusedError | undefined {
1883
+ return this.segments.find(entryId)?.refused;
1884
+ }
1885
+
1886
+ /** The sealed segment `entryId` owns here: its actions, the array the segment holds (never
1887
+ * mutated by a caller; the offline journal serialises it), or `undefined` when the entry is not
1888
+ * sealed here. Synchronous and latch-free, like {@link sealedEntries}. */
1889
+ sealedActions(entryId: EntryId): readonly Action<TAction>[] | undefined {
1890
+ return this.segments.find(entryId)?.actions;
1891
+ }
1892
+
1893
+ /** The OPEN segment's actions — what the current transaction has staged since the last seal — as
1894
+ * the array the segment holds (never mutated by a caller). Unlike {@link getPendingActions} it
1895
+ * answers while segments are sealed, for a reader that judges the open transaction beside the
1896
+ * queued ones (the Quereus plugin's `CommitOutlook()`). Synchronous and latch-free, like
1897
+ * {@link sealedActions}. */
1898
+ openActions(): readonly Action<TAction>[] {
1899
+ return this.segments.open;
1900
+ }
1901
+
1902
+ /** The exact inverse of {@link sealPending}, list-only and latch-free by the same contract: move
1903
+ * the segment's actions back into the open segment, for an enqueue whose journal write failed
1904
+ * after sealing (`OfflineQueue.enqueue`, which unseals every collection it sealed, in reverse
1905
+ * order, and rethrows). Requires the segment to be the NEWEST sealed one and the open segment to
1906
+ * be empty — both true at that one call site, which has just sealed and staged nothing since —
1907
+ * and throws otherwise (`SegmentList.unseal`). The tracker is untouched: its transforms are
1908
+ * already what they were before the seal. The segment version moves, so a snapshot taken before
1909
+ * the transaction restores by replay ({@link restorePending}), which ends with the transaction's
1910
+ * actions gone once the caller rolls it back. */
1911
+ unseal(entryId: EntryId): void {
1912
+ this.segments.unseal(entryId);
1913
+ }
1914
+
1915
+ /** Whether this collection's committed context names `attempt.actionId` at `attempt.rev`: the
1916
+ * write that attempt sent is committed here, and this handle has adopted it. This is how a restore
1917
+ * after a restart recognises, before re-staging a journaled segment, that the segment's network
1918
+ * commit landed and the crash came after it (docs/offline-sync.md §Restore after a restart):
1919
+ * re-staging such a segment would run its own guards against its own committed rows (`absent`
1920
+ * refuses on a present key) and fail the entry with `constraint`, the opposite of the truth.
1921
+ * `false` for an invented collection, which has no context. Synchronous and latch-free.
1922
+ *
1923
+ * NOTE: `actionIdAt` reaches back only to the most recent checkpoint, and no checkpoint is written
1924
+ * today (backlog `debt-the-collection-log-never-writes-a-checkpoint`); if that changes, read the
1925
+ * log's entry at `attempt.rev` instead, since a committed attempt behind a checkpoint would
1926
+ * otherwise answer `false` and be re-staged against itself. */
1927
+ holdsCommitted(attempt: ActionRev): boolean {
1928
+ const context = this.source.actionContext;
1929
+ return context !== undefined && context.rev >= attempt.rev && actionIdAt(context, attempt.rev) === attempt.actionId;
1930
+ }
1931
+
1932
+ /**
1933
+ * Put a sealed segment back, holding `actions` under `entryId`, at `position` in the sealed list —
1934
+ * ahead of the segment `before` names, or last — and rebuild the tracker by replaying every
1935
+ * replayable segment in order ({@link replayActions}), for the offline queue's restore after a
1936
+ * restart (`OfflineQueue.restore`; docs/offline-sync.md §Restore after a restart). A record
1937
+ * restored late belongs ahead of entries queued since, in the queue and in each collection's
1938
+ * sealed list alike, or the head commit's "head is first" rule and the queue's order disagree;
1939
+ * hence insertion rather than appending, at the cost of the one replay every insertion costs.
1940
+ *
1941
+ * The replay records and reports each refusal it meets as a refresh's would — EXCEPT this
1942
+ * segment's own, which is recorded on the segment and RETURNED rather than reported through
1943
+ * `onSealedRefused`: the queue registers the entry and hears the result from its own `stage`
1944
+ * callback, since the collection cannot report it to a queue that does not yet list the entry. A
1945
+ * later segment the replay newly refuses (this segment inserts the key it also inserts, say) is
1946
+ * reported through `onSealedRefused` as any replay's would be.
1947
+ *
1948
+ * Takes the collection latch, like {@link dropSealed}. Throws before anything changes when the
1949
+ * open segment is non-empty (a transaction is open, and its actions were staged over state without
1950
+ * this segment; the only caller refuses to restore mid-transaction), when a head commit is in
1951
+ * flight ({@link SealedSegmentsError}, `in-flight`), when `entryId` is already sealed here, or when
1952
+ * `before` names no segment here. A replay error that is not a refusal (a block the replay could
1953
+ * not read, say) propagates with the segment REMOVED again: the caller's restore rolls back and
1954
+ * may try this entry again later, which would otherwise meet its own segment as "already sealed".
1955
+ * The tracker is then half re-staged, the state a refresh's replay that throws leaves too (backlog
1956
+ * `debt-a-failed-refresh-can-leave-a-collection-half-restaged`); the next replay rebuilds it.
1957
+ *
1958
+ * @returns this segment's own refusal, when the replay refused it; `undefined` when it staged. */
1959
+ async restoreSealed(entryId: EntryId, actions: readonly Action<TAction>[], position: { before: EntryId } | 'last'): Promise<ActionRefusedError | undefined> {
1960
+ const release = await Latches.acquire(this.latchId);
1961
+ try {
1962
+ if (this.segments.open.length > 0) {
1963
+ throw new Error(`Collection ${this.id}: cannot restore sealed segment ${entryId} while a transaction has `
1964
+ + `${this.segments.open.length} action(s) staged in the open segment`);
1965
+ }
1966
+ if (this.headInFlight !== undefined) {
1967
+ throw new SealedSegmentsError(this.id, this.segments.entryIds(), 'in-flight', this.headInFlight.entryId);
1968
+ }
1969
+ this.segments.insert(entryId, actions, position === 'last' ? undefined : position.before);
1970
+ try {
1971
+ await this.replayActions(entryId);
1972
+ } catch (err) {
1973
+ this.segments.drop(entryId);
1974
+ throw err;
1975
+ }
1976
+ return this.segments.find(entryId)?.refused;
1977
+ } finally {
1978
+ release();
1979
+ }
1980
+ }
1981
+
1982
+ /** Remove the sealed segment owned by `entryId`, wherever it sits, and rebuild the tracker by
1983
+ * replaying what remains ({@link replayActions}). A later segment whose guard now refuses — one
1984
+ * that updated a row the dropped segment inserted, say — is recorded and reported through
1985
+ * `onSealedRefused` during that replay; cascading the removal through the queue's other
1986
+ * collections is the queue's job (docs/offline-sync.md §Removing an entry). Throws for an id
1987
+ * that is not sealed here, before anything changes, and {@link SealedSegmentsError} (`in-flight`)
1988
+ * for the segment a {@link commitHead} on this instance is carrying to the network — the only
1989
+ * segment that cannot be dropped while it waits, since the outcome being applied names it.
1990
+ * Another segment can be: the replay here rebuilds the live tracker, which the head commit's own
1991
+ * tracker does not depend on.
1992
+ *
1993
+ * Takes the collection latch, like {@link update}. */
1994
+ async dropSealed(entryId: EntryId): Promise<void> {
1995
+ const release = await Latches.acquire(this.latchId);
1996
+ try {
1997
+ if (this.headInFlight?.entryId === entryId) {
1998
+ throw new SealedSegmentsError(this.id, this.segments.entryIds(), 'in-flight', entryId);
1999
+ }
2000
+ this.segments.drop(entryId);
2001
+ await this.replayActions();
2002
+ } finally {
2003
+ release();
2004
+ }
2005
+ }
2006
+
2007
+ /** The refusal every whole-collection commit path makes while a segment is sealed (see
2008
+ * {@link SealedSegmentsError}). */
2009
+ private assertNoSealedSegments(): void {
2010
+ if (this.segments.hasSealed()) {
2011
+ throw new SealedSegmentsError(this.id, this.segments.entryIds());
2012
+ }
1615
2013
  }
1616
2014
 
1617
2015
  /** The committed revision this collection currently READS at, or `undefined` for an
@@ -1764,8 +2162,11 @@ export class Collection<TAction> implements ICollection<TAction> {
1764
2162
  * path, which is the same assumption the participant selection in
1765
2163
  * `TransactionCoordinator.commitOnce` and its `rollback` already rest on. If a second writer is
1766
2164
  * ever allowed to drive the SAME instance concurrently, this must become a per-attempt token (a
1767
- * mark object compared by identity, refusing to replace a live one) rather than a bare id. */
1768
- beginInFlightAction(actionId: ActionId): () => void {
2165
+ * mark object compared by identity, refusing to replace a live one) rather than a bare id.
2166
+ *
2167
+ * `cycle` is what every send of the cycle carries ({@link InFlightCycle}); a re-mark replaces it,
2168
+ * which is harmless because every caller re-marks with what it marked. */
2169
+ beginInFlightAction(actionId: ActionId, cycle: InFlightCycle = {}): () => void {
1769
2170
  if (this.inFlightActionId !== actionId) {
1770
2171
  // A different action's failed attempt cannot finish this one. Re-marking the SAME id (a
1771
2172
  // coordinator re-marks on every attempt) keeps what the previous attempt retained — that
@@ -1775,11 +2176,13 @@ export class Collection<TAction> implements ICollection<TAction> {
1775
2176
  this.mintedLogBlockIds = undefined;
1776
2177
  }
1777
2178
  this.inFlightActionId = actionId;
2179
+ this.inFlightCycle = cycle;
1778
2180
  return () => {
1779
2181
  if (this.inFlightActionId === actionId) {
1780
2182
  this.inFlightActionId = undefined;
1781
2183
  this.inFlightAttempt = undefined;
1782
2184
  this.mintedLogBlockIds = undefined;
2185
+ this.inFlightCycle = {};
1783
2186
  }
1784
2187
  };
1785
2188
  }
@@ -1791,12 +2194,12 @@ export class Collection<TAction> implements ICollection<TAction> {
1791
2194
  * a path that does not still never reports a half-landed write as saved (the refresh then
1792
2195
  * refuses with a `transforms-not-held` {@link TornActionError}), but it cannot recover from one.
1793
2196
  *
1794
- * A no-op unless `actionId` is the action currently marked, so a late call from an attempt whose
1795
- * cycle has already ended cannot plant transforms under somebody else's mark. Latch-free and
2197
+ * A no-op unless the attempt's action is the one currently marked, so a late call from an attempt
2198
+ * whose cycle has already ended cannot plant transforms under somebody else's mark. Latch-free and
1796
2199
  * synchronous, like the mark itself: `TransactionCoordinator` calls it from inside its commit
1797
2200
  * span, where it already holds this instance's latch. */
1798
- retainInFlightAttempt(actionId: ActionId, attempt: InFlightAttempt): void {
1799
- if (this.inFlightActionId === actionId) {
2201
+ retainInFlightAttempt(attempt: InFlightAttempt): void {
2202
+ if (this.inFlightActionId === attempt.actionId) {
1800
2203
  this.inFlightAttempt = attempt;
1801
2204
  }
1802
2205
  }
@@ -1869,131 +2272,52 @@ export class Collection<TAction> implements ICollection<TAction> {
1869
2272
  }
1870
2273
  }
1871
2274
 
2275
+ /** The refresh a write's attempt cycle runs between attempts ({@link AttemptCycle.refreshUntilSettled}):
2276
+ * {@link updateInternal}, under the latch the write already holds and with its action marked in
2277
+ * flight, so the refresh recognises the write's own log entry. */
2278
+ private readonly refreshBetweenAttempts: Refresh = (report, lastChance, tailFloor) =>
2279
+ this.updateInternal(report, lastChance, tailFloor);
2280
+
1872
2281
  /** Mints the one action id this sync reuses across all of its retry attempts, and owns it for
1873
2282
  * the WHOLE cycle — including the inter-attempt refresh, which is the only thing that reads it
1874
2283
  * (see {@link inFlightActionId}). `sync()`/`updateAndSync()` hold the collection latch across
1875
2284
  * all of this, so the mark's lifetime is contained inside the latched span here; the disposer
1876
2285
  * runs on every exit, including a throw out of retry exhaustion or an abort. */
1877
2286
  private async syncInternal(options?: SyncOptions): Promise<WriteDurability | undefined> {
1878
- const bytes = randomBytes(16);
1879
- const actionId = uint8ArrayToString(bytes, 'base64url');
1880
- // One timestamp for the WRITE, minted here beside the action id and for the same reason: an
1881
- // attempt that takes its own would make the retry's log block differ from the one the
1882
- // attempt it repeats may already have stored under this `(action id, revision)`.
1883
- const timestamp = Date.now();
1884
-
1885
- const endInFlight = this.beginInFlightAction(actionId);
2287
+ // Before an action id is minted: a sync commits the whole tracker as one entry, and over
2288
+ // sealed segments that entry would carry several queue entries' effects.
2289
+ this.assertNoSealedSegments();
2290
+ const identity: WriteIdentity = {
2291
+ actionId: uint8ArrayToString(randomBytes(16), 'base64url'),
2292
+ // One timestamp for the WRITE, minted here beside the action id and for the same reason: an
2293
+ // attempt that takes its own would make the retry's log block differ from the one the
2294
+ // attempt it repeats may already have stored under this `(action id, revision)`.
2295
+ timestamp: Date.now(),
2296
+ };
2297
+
2298
+ const endInFlight = this.beginInFlightAction(identity.actionId, { refuseSolo: options?.refuseSoloCommit });
1886
2299
  try {
1887
- return await this.syncAttempts(actionId, timestamp, options);
2300
+ return await this.syncAttempts(identity, options);
1888
2301
  } finally {
1889
2302
  endInFlight();
1890
2303
  }
1891
2304
  }
1892
2305
 
1893
- /** The retry loop behind {@link syncInternal}, run with `actionId` already marked in flight.
2306
+ /** The retry loop behind {@link syncInternal}, run with the action already marked in flight: the
2307
+ * attempt machinery of {@link AttemptCycle} and {@link stageAttempt}, aimed at the open segment
2308
+ * over the live tracker. {@link commitHead} drives the same machinery at the head segment.
1894
2309
  *
1895
- * @param timestamp the WRITE's time, stamped on the log entry every attempt appends — see
1896
- * {@link syncInternal}, which mints it.
1897
2310
  * @returns the durability of what this sync committed, or `undefined` when the loop never ran a
1898
2311
  * commit (nothing staged). See {@link sync}. */
1899
- private async syncAttempts(actionId: ActionId, timestamp: number, options?: SyncOptions): Promise<WriteDurability | undefined> {
1900
- const maxAttempts = options?.maxAttempts ?? DefaultMaxAttempts;
1901
- const baseBackoffMs = options?.baseBackoffMs ?? PendingRetryDelayMs;
1902
- const maxBackoffMs = options?.maxBackoffMs ?? DefaultMaxBackoffMs;
1903
- const maxStalledAttempts = options?.maxStalledAttempts ?? DefaultMaxStalledAttempts;
1904
- const deadlineMs = options?.deadlineMs;
1905
- const signal = options?.signal;
1906
- const startedAt = Date.now();
1907
-
1908
- // Count of consecutive stale failures that made no forward progress. Reset to 0 on every
1909
- // successful transact, so the cap bounds only a persistently-failing sync — a legitimate
1910
- // large multi-batch sync (which iterates many times committing progress) never trips it.
1911
- let consecutiveFailures = 0;
1912
- let lastReason: string | undefined;
1913
- // Highest confirmed revision any responder has reported holding, accumulated with the
1914
- // codebase's single rule for picking among several candidates. Reported on the error, and
1915
- // the evidence the stall check below reasons from.
1916
- let lastStaleAt: { blockId: BlockId; rev: number } | undefined;
1917
- // Whether the failure most recently handled carried its OWN staleAt. A strike needs the
1918
- // responder to have re-confirmed the number this round, not merely an older observation
1919
- // left standing in `lastStaleAt`.
1920
- let lastFailureConfirmedStaleAt = false;
1921
- // Refused attempts of this write that carried their own staleAt. Never reset: a member counts
1922
- // its stale refusals per action for the action's whole life, and this is the writer's view of
1923
- // that count (see retryBackoffMs).
1924
- let confirmedLosses = 0;
1925
- // Consecutive refreshes that moved `getNextRev()` nowhere at all while a confirmed revision
1926
- // stood at or above it.
1927
- let consecutiveStalls = 0;
1928
- // The revision the PREVIOUS iteration would have requested, so the stall check can tell a
1929
- // refresh that moved nowhere from one that is still climbing toward the confirmed number.
1930
- let previousRequestedRev: number | undefined;
1931
- // Who holds what this sync has committed so far. Stays `undefined` while nothing has been
1932
- // committed, which is also the answer when the loop never runs at all — a sync with nothing
1933
- // staged writes nothing, and there is no durability to fabricate for it. Failed attempts never
1934
- // contribute: a refused attempt left nothing behind, so the answer is the committing attempt's.
1935
- let durability: WriteDurability | undefined;
1936
-
2312
+ private async syncAttempts(identity: WriteIdentity, options?: SyncOptions): Promise<WriteDurability | undefined> {
2313
+ const cycle = new AttemptCycle(this.id, this.instanceTag, options);
1937
2314
  while (this.hasUnsyncedChanges()) {
1938
- if (signal?.aborted) {
1939
- throw makeAbortError(signal);
1940
- }
1941
- // Progress-agnostic ceiling: give up if the wall-clock deadline passed. Deliberately
1942
- // ahead of the stall check: the deadline is the documented outer bound, so a sync that
1943
- // is both past it and stalled reports the deadline.
1944
- if (deadlineMs !== undefined && Date.now() - startedAt >= deadlineMs) {
1945
- throw new SyncRetryExhaustedError(this.id, consecutiveFailures, lastReason ?? 'deadline exceeded', lastStaleAt);
1946
- }
1947
-
1948
- // Can the attempt about to run possibly differ from the one that just failed? Only when
1949
- // BOTH of these hold is the answer provably no:
1950
- //
1951
- // - The revision it would request is at or below one a responder CONFIRMED is taken. A
1952
- // producer sets `staleAt` only after reading that revision as durably held by someone
1953
- // else out of its own storage, revisions are one per-collection counter that every
1954
- // commit touches, and a confirmed revision never becomes un-taken (invalidation takes
1955
- // a NEW slot). So the request is already lost before it is sent.
1956
- // - The refresh in between moved the collection nowhere. `advanceContext` never lowers
1957
- // the held revision, so "nowhere" is exactly `requestedRev` unchanged since the last
1958
- // iteration. A refresh that moved forward WITHOUT clearing the confirmed number is a
1959
- // collection still climbing (it read a replica that lags the holder — the same
1960
- // partial catch-up `reportShortfall` exists to report), and its next attempt is a
1961
- // genuinely different request that may yet win.
1962
- //
1963
- // This is NOT a second answer to "is this failure retryable?" — `isConflictFailure`
1964
- // remains the sole rule for that, untouched. It only ever stops a loop that rule had
1965
- // already decided to continue.
1966
- const requestedRev = this.getNextRev();
1967
- const refreshMoved = previousRequestedRev !== undefined && requestedRev > previousRequestedRev;
1968
- previousRequestedRev = requestedRev;
1969
- if (lastStaleAt !== undefined) {
1970
- if (requestedRev > lastStaleAt.rev || refreshMoved) {
1971
- // Either the refresh adopted a revision above the confirmed one — ordinary
1972
- // contention, where the rival's commit is exactly what we just read — or it made
1973
- // partial forward progress. Both mean the next attempt differs. Not a stall.
1974
- consecutiveStalls = 0;
1975
- } else if (lastFailureConfirmedStaleAt) {
1976
- consecutiveStalls++;
1977
- if (log.enabled) {
1978
- log('collection:sync-stalled id=%s tag=%s heldRev=%s requestedRev=%d staleBlock=%s staleRev=%d strike=%d of=%d',
1979
- this.id, this.instanceTag, this.source.actionContext?.rev ?? 'none', requestedRev,
1980
- lastStaleAt.blockId, lastStaleAt.rev, consecutiveStalls, maxStalledAttempts);
1981
- }
1982
- // Two strikes, not one: a legitimate loser can transiently read a view that has
1983
- // not yet caught up with the rival's commit, which looks identical for one round.
1984
- if (consecutiveStalls >= maxStalledAttempts) {
1985
- throw new SyncRevisionStalledError(this.id, consecutiveFailures, lastStaleAt,
1986
- requestedRev, this.source.actionContext?.rev, lastReason);
1987
- }
1988
- }
1989
- // Else: the responder told us nothing new this round. No strike, and no reset either
1990
- // — the budget stays bounded by maxAttempts.
1991
- }
2315
+ cycle.beforeAttempt(this.getNextRev(), this.source.actionContext?.rev);
1992
2316
 
1993
2317
  // A pending action is never pended over a base that has moved under it — before EVERY
1994
2318
  // attempt, first and retries alike (see restageIfBasesMoved for why the retry needs it).
1995
- // NOTE: this is the one way the byte-identity the append below relies on can be broken at
1996
- // an UNCHANGED revision — a replay re-runs the action handlers, which mint fresh ids for
2319
+ // NOTE: this is the one way the byte-identity the append relies on can be broken at an
2320
+ // UNCHANGED revision — a replay re-runs the action handlers, which mint fresh ids for
1997
2321
  // whatever blocks they insert, so the retry sends different content under this write's
1998
2322
  // `(action id, revision)`. It needs a base to move without this collection adopting a
1999
2323
  // newer revision, which takes a block re-read that catches up while the log does not
@@ -2003,219 +2327,63 @@ export class Collection<TAction> implements ICollection<TAction> {
2003
2327
  // abandon the action id and re-drive as a NEW write rather than to suppress the replay.
2004
2328
  await this.restageIfBasesMoved();
2005
2329
 
2006
- // Snapshot the pending actions so that any new actions aren't assumed to be part of this action
2007
- const pending = [...this.pending];
2008
-
2009
- // Create a snapshot tracker for the action, so that we can ditch the log changes if we have to retry the action.
2010
- // It SHARES the live tracker's pin store: the snapshot inherits transforms by copy and never
2011
- // stages the data-block updates itself, so without the shared pins the digest pass below
2012
- // could only describe bases still resident in the read cache.
2013
- // NOTE: an attempt that ends in a stale failure is abandoned WITHOUT reset(), so the log
2014
- // tail/header bases its append pinned stay in the shared store until the live tracker's
2015
- // next reset. Bounded and harmless — a few log blocks per attempt, capped by maxAttempts,
2016
- // each re-validated against the source generation before any use — but if this loop ever
2017
- // grows a per-attempt footprint beyond the log blocks, reset the abandoned tracker on the
2018
- // stale-failure branch instead of letting the residue ride to the end of the sync.
2019
- const snapshot = copyTransforms(this.tracker.transforms);
2020
- const tracker = new Tracker(this.sourceCache, snapshot, this.tracker.pins);
2021
-
2022
- // Add the action to the log (in local tracking space). The append is a fixed function of
2023
- // this write and the revision it is requesting: the timestamp was minted once for the
2024
- // whole write (syncInternal) and any data block the append has to mint takes the id an
2025
- // earlier attempt at this revision already minted (logAppendBlockIds).
2026
- const newRev = this.getNextRev();
2027
- const collectionLog = await Log.open<Action<TAction>>(tracker, this.id,
2028
- { newDataBlockId: this.logAppendBlockIds(tracker, actionId, newRev) });
2029
- if (!collectionLog) {
2030
- throw new Error(`Log not found for collection ${this.id}`);
2031
- }
2032
- const addResult = await collectionLog.addActions(pending, actionId, newRev,
2033
- () => tracker.transformedBlockIds(), { timestamp });
2034
-
2035
- // Declare what each touched block will contain once committed, computed from this snapshot
2036
- // tracker (which layers over `this.sourceCache`, so the peek/getCachedRevision probes are
2037
- // live). Purely local — an id whose base is not already cached is simply omitted and falls
2038
- // back to corroboration on the member side. Computed AFTER the log append so the log tail
2039
- // and header transforms this attempt just staged are digested too.
2040
- // NOTE: recomputed from scratch on every retry attempt (the snapshot tracker is rebuilt each
2041
- // iteration), so a sync that loses N races pays N full hashing passes over its touched
2042
- // blocks. Unmeasured and cheap relative to the round trips it is retrying; if a
2043
- // high-contention sync ever shows digest hashing in a profile, memoize per (id, staged ops).
2044
- const touched = await describeTouchedBlocks(tracker, tracker.transformedBlockIds());
2045
- // No block may be left larger than one message can carry. Refused here, before anything is
2046
- // sent, as the transaction limit is at the pend, and judged apart from the declaration, which
2047
- // never throws: only the blocks it could materialize are measured (see describeTouchedBlocks).
2048
- // It escapes `sync` unretried — a later attempt would leave the same block — and nothing on
2049
- // this instance has been touched, since the attempt ran on the snapshot tracker.
2050
- const tooLarge = oversizedBlock(touched.bytes);
2051
- if (tooLarge) throw tooLarge;
2052
- const blockDigests = touched.digests;
2053
- // The base each update-only block's operations were computed against, for the pend (see
2054
- // `PendRequest.baseRevs`): the tracker's pinned revisions, which `restageIfBasesMoved` at the
2055
- // top of this iteration has just re-judged, so a moved base was re-staged before it is named.
2056
- const baseRevs = tracker.stagedBaseRevs(tracker.transformedBlockIds());
2057
-
2058
- // Commit the action to the transactor. Carry the aged retry priority derived from the
2059
- // consecutive-failure count so a sync that keeps losing concurrent races out-ranks fresh
2060
- // (priority-0) rivals in the cluster's resolveRace (fairness-only; capped at MaxPriority).
2061
- // First attempt has consecutiveFailures == 0, so priority 0 — the common pend is unchanged.
2062
- const attempt = await this.source.transact(tracker.transforms, actionId, newRev, this.id, addResult.tailPath.block.header.id, clampPriority(consecutiveFailures), blockDigests, baseRevs);
2330
+ // Snapshot the open segment so that any new actions aren't assumed to be part of this action
2331
+ // (no segment is sealed here — syncInternal refused if one was).
2332
+ const pending = [...this.segments.open];
2333
+ const staged = await this.buildAttempt({ actions: pending, transforms: this.tracker.transforms, pins: this.tracker.pins }, identity);
2334
+ const attempt = await this.send(staged, identity, cycle.priority());
2063
2335
  if (!attempt.success) {
2064
- if (isExpiryFailure(attempt)) {
2065
- // The next attempt's expiration comes from the same clock, so it would be refused the
2066
- // same way; stop here by name. Nothing on this instance has been touched — the attempt
2067
- // ran on a snapshot tracker — so the staged actions are still staged for a sync after
2068
- // the clock is fixed.
2069
- // NOTE: an expiry refusing a commit SWEEP (`NetworkTransactor.commitTailThenSweep`)
2070
- // arrives after the log tail was stored, and no refresh follows this throw, so that
2071
- // attempt's log entry stays behind with none of its data — the state the budget-exhausted
2072
- // exit below leaves too. Needs a sweep cohort whose clocks disagree while the tail's agree;
2073
- // tracked with the other leftover-entry exits in
2074
- // tickets/backlog/bug-a-refused-write-can-leave-its-log-entry-behind.
2075
- throw new TransactionExpiredError(attempt.expired);
2076
- }
2077
- consecutiveFailures++;
2078
- lastReason = attempt.reason ?? lastReason;
2079
- // Highest-wins, not last-wins: the next request has to clear EVERY holder, so a later
2080
- // responder reporting a LOWER number understates the binding constraint. Same rule the
2081
- // producers and the transactor's aggregation already use.
2082
- lastStaleAt = highestStaleAt([lastStaleAt, attempt.staleAt]);
2083
- lastFailureConfirmedStaleAt = attempt.staleAt !== undefined;
2084
- if (lastFailureConfirmedStaleAt) confirmedLosses++;
2085
- // Give up once the consecutive no-progress budget is exhausted, so a transactor that
2086
- // persistently rejects the sync can no longer hold the collection latch forever.
2087
- // NOTE: this also bounds the legitimate `pending`-wait case (retrying the same action
2088
- // while another commit is in flight), which used to retry indefinitely. Default 10
2089
- // attempts ≈ 21s of exponential backoff. If a high-contention workload legitimately
2090
- // needs to wait longer for a pending commit to clear, raise maxAttempts for that caller.
2091
- // NOTE: no refresh follows the LAST budgeted attempt, so if that attempt's log tail
2092
- // landed nobody finds out: the caller gets plain exhaustion over a log that holds an
2093
- // entry for this write. The write is still never reported saved, which is the rule; what
2094
- // is lost is the more specific name (TornActionError). The leftover entry itself is
2095
- // tracked in tickets/backlog/bug-a-refused-write-can-leave-its-log-entry-behind.
2096
- if (consecutiveFailures >= maxAttempts) {
2097
- throw new SyncRetryExhaustedError(this.id, consecutiveFailures, lastReason, lastStaleAt);
2098
- }
2099
- // Keep exactly what this attempt sent. A refused commit is not proof nothing landed:
2100
- // the log tail is committed first and can be stored while the answer is still a
2101
- // failure, and `transact` has just cancelled every block that did not land. If the
2102
- // refresh below finds this attempt's own entry, these are the transforms that finish
2103
- // the action (see completeOwnEntry). The snapshot tracker is abandoned after this
2104
- // iteration, so its transforms are handed over as-is, uncopied.
2105
- this.retainInFlightAttempt(actionId, {
2106
- rev: newRev,
2107
- transforms: tracker.transforms,
2108
- tailId: addResult.tailPath.block.header.id,
2109
- ...(blockDigests === undefined ? {} : { blockDigests }),
2110
- ...baseRevsField(baseRevs),
2111
- });
2112
- // Refresh, and keep refreshing while it reports that this write's own half-landed
2113
- // action could not be finished YET. It must not fall through to a new attempt in that
2114
- // state: this action's log entry is already durable, and as soon as a refresh adopts a
2115
- // newer revision a new attempt appends a SECOND entry under the same action id — the
2116
- // duplicate consumeOwnEntry exists to prevent. (At an unchanged revision the rebuild
2117
- // is byte-identical — see logAppendBlockIds — so what is at stake is the second entry,
2118
- // not two versions of one tail block.) Each round is a failure against the same
2119
- // no-progress budget as a refused attempt.
2120
- // Whether the failure just handled was a loss to a rival already durably committed. Only
2121
- // the attempt's own refusal can say so; a refresh refused for a cause that can clear
2122
- // (below) is a race against something still in flight, and clears it.
2123
- let latestConfirmed = lastFailureConfirmedStaleAt;
2124
- for (;;) {
2125
- // Back off before every retry (any stale failure — reason/missing/pending), growing
2126
- // exponentially from the base delay up to the cap, with proportional random jitter so a
2127
- // herd of clients that lost the same race does not re-collide on the next tick (see
2128
- // utility/backoff.ts) — except once this write has lost to committed rivals often enough
2129
- // that a member holds the next slot for it (see retryBackoffMs). The abortable sleep lets
2130
- // an aborted sync reject promptly instead of finishing the sleep.
2131
- // NOTE: the `missing`/`reason` conflict paths now pay this backoff too (they previously
2132
- // retried with zero delay); that is what stops the persistent-`reason` hot spin. If a
2133
- // high-contention workload ever shows this base delay as recovery latency, lower
2134
- // baseBackoffMs for that caller rather than reintroducing the zero-delay retry.
2135
- const delay = retryBackoffMs(consecutiveFailures, confirmedLosses, latestConfirmed,
2136
- { baseMs: baseBackoffMs, capMs: maxBackoffMs }, options?.rand);
2137
- await abortableDelay(delay, signal);
2138
- try {
2139
- // Fetch latest state - updateInternal() will call replayActions() if there are conflicts.
2140
- // This sync's actionId is marked in flight for the whole cycle (see syncInternal), so
2141
- // the refresh recognizes a log entry written by THIS action (its log tail landed but
2142
- // the commit answered failure), FINISHES that action from the attempt retained
2143
- // above, and only then consumes the entry rather than replaying it into a duplicate.
2144
- // The round that would spend the last of the budget settles a half-landed write
2145
- // instead of asking for another round, so the error that escapes below says
2146
- // whether the write can still land. (A deadline cannot be foreseen the same
2147
- // way; a write given up on it escapes unsettled, as `final: false`.)
2148
- // The highest revision a responder confirmed is taken rides out as the floor of
2149
- // the refresh's tail read, so a machine that has not caught up to it is not the
2150
- // last one asked (see updateInternal).
2151
- const report: RefreshReport = {};
2152
- await this.updateInternal(report, consecutiveFailures + 1 >= maxAttempts, lastStaleAt?.rev);
2153
- const completed = report.ownEntryFinished?.durability;
2154
- if (completed !== undefined) {
2155
- // The refresh made this sync's write durable: that is a commit, and it is
2156
- // reported and counted exactly like one made by an attempt (see the success
2157
- // branch below for why batches fold to the weakest).
2158
- durability = durability === undefined ? completed : mergeDurability([durability, completed]);
2159
- consecutiveFailures = 0;
2160
- lastReason = undefined;
2161
- lastStaleAt = undefined;
2162
- lastFailureConfirmedStaleAt = false;
2163
- consecutiveStalls = 0;
2164
- }
2165
- break;
2166
- } catch (err) {
2167
- if (!(err instanceof TornActionError) || err.reason !== 'completion-refused') {
2168
- throw err;
2169
- }
2170
- // Refused for a cause that can clear. The error already names the write as torn,
2171
- // which is the truth if the budget ends here — so it, not a plain exhaustion,
2172
- // is what escapes: the log holds an entry for a write that was not saved.
2173
- consecutiveFailures++;
2174
- lastReason = err.detail;
2175
- latestConfirmed = false;
2176
- if (consecutiveFailures >= maxAttempts
2177
- || (deadlineMs !== undefined && Date.now() - startedAt >= deadlineMs)) {
2178
- throw err;
2179
- }
2180
- }
2181
- }
2336
+ cycle.recordRefusal(attempt);
2337
+ this.retainInFlightAttempt(retainedAttempt(staged, identity.actionId));
2338
+ await cycle.refreshUntilSettled(this.refreshBetweenAttempts);
2182
2339
  } else {
2183
- // This attempt's commit landed, so its durability is the one to report. A sync that
2184
- // commits ONCE — every sync that has a caller today — reports exactly that answer,
2185
- // untouched. A sync whose loop commits more than one batch (the `hasUnsyncedChanges`
2186
- // condition re-entering after a successful commit) folds the batches with
2187
- // `mergeDurability`, whose scalar answer is the WEAKEST of them: one batch that only
2188
- // reached the writer makes the whole sync only-on-the-writer, and reporting the last
2189
- // batch's class instead would show such a write as saved.
2190
- durability = durability === undefined ? attempt.durability : mergeDurability([durability, attempt.durability]);
2191
- // Forward progress: reset the no-progress budget.
2192
- consecutiveFailures = 0;
2193
- lastReason = undefined;
2194
- lastStaleAt = undefined;
2195
- lastFailureConfirmedStaleAt = false;
2196
- consecutiveStalls = 0;
2197
- // Clear the pending actions that were part of this action
2198
- this.pending = this.pending.slice(pending.length);
2199
- // Reset cache and replay any actions that were added during the action
2200
- const transforms = tracker.reset();
2201
- // NOTE: this replay runs BEFORE the cache fold and the context bump below — the
2202
- // inverse of the order `updateInternal` and `TransactionCoordinator.commitOnce`
2203
- // both document as required, where the newly committed state must be visible
2204
- // before anything re-reads. Dormant today: `act()` and `syncInternal` take the
2205
- // same collection latch, so `this.pending` cannot grow during the transact above
2206
- // and the slice always leaves it empty, making this replay a no-op reset. If a
2207
- // path ever stages outside that latch, move the transformCache + actionContext
2208
- // lines above this replay — otherwise the replay re-reads at the superseded
2209
- // revision over a cache that has not yet seen the commit, and re-stages onto a
2210
- // root the commit already replaced.
2340
+ cycle.recordCommit(attempt.durability);
2341
+ // Clear the open-segment actions that were part of this action
2342
+ this.segments.open = this.segments.open.slice(pending.length);
2343
+ // Fold the committed transforms into the read cache and adopt the revision BEFORE
2344
+ // replaying whatever is still staged — the order `updateInternal` and
2345
+ // `TransactionCoordinator.commitOnceLatched` require, where the newly committed state
2346
+ // must be visible before anything re-reads. It is load-bearing here for an invented
2347
+ // collection's first commit: the replay resets to the invented baseline while no
2348
+ // context is adopted, so replaying first would reinstate the header insert over the
2349
+ // now-committed header and `hasUnsyncedChanges()` would never turn false. (While
2350
+ // `act()` shares this latch nothing new is staged mid-attempt, so the replay re-stages
2351
+ // nothing; {@link commitHead} stages while its transact is in flight and relies on
2352
+ // this order.)
2353
+ this.foldOwnCommit(staged, identity.actionId);
2211
2354
  await this.replayActions();
2212
- this.sourceCache.transformCache(transforms, newRev);
2213
- this.source.actionContext = this.source.actionContext
2214
- ? { committed: [...this.source.actionContext.committed, { actionId, rev: newRev }], rev: newRev }
2215
- : { committed: [{ actionId, rev: newRev }], rev: newRev };
2216
2355
  }
2217
2356
  }
2218
- return durability;
2357
+ return cycle.durability;
2358
+ }
2359
+
2360
+ /** Build one attempt at the revision this collection would commit at next ({@link stageAttempt});
2361
+ * the ids its log append may have to mint come from {@link logAppendBlockIds}, so a retry at the
2362
+ * same revision appends the same entry. */
2363
+ private buildAttempt(target: AttemptTarget<TAction>, identity: WriteIdentity): Promise<StagedAttempt> {
2364
+ const rev = this.getNextRev();
2365
+ return stageAttempt(this.id, this.sourceCache, target, identity, rev,
2366
+ store => this.logAppendBlockIds(store, identity.actionId, rev));
2367
+ }
2368
+
2369
+ /** Send one attempt — pend, then commit — under the cycle's aged retry `priority`, carrying what
2370
+ * the cycle asked of every send ({@link inFlightCycle}). */
2371
+ private send(staged: StagedAttempt, identity: WriteIdentity, priority: number): Promise<CommitResult> {
2372
+ return this.source.transact(staged.tracker.transforms, identity.actionId, staged.rev, this.id, staged.tailId, {
2373
+ priority,
2374
+ blockDigests: staged.blockDigests,
2375
+ baseRevs: staged.baseRevs,
2376
+ refuseSolo: this.inFlightCycle.refuseSolo
2377
+ });
2378
+ }
2379
+
2380
+ /** Fold a committed attempt's transforms — the log append included — into this instance's read
2381
+ * cache and adopt the revision it committed at. Every caller does this BEFORE replaying what is
2382
+ * still staged (see the note in {@link syncAttempts}). Takes the transforms out of the attempt's
2383
+ * tracker, which is finished with. */
2384
+ private foldOwnCommit(staged: StagedAttempt, actionId: ActionId): void {
2385
+ this.sourceCache.transformCache(staged.tracker.reset(), staged.rev);
2386
+ this.recordCommitted(actionId, staged.rev);
2219
2387
  }
2220
2388
 
2221
2389
  /** Refresh from the transactor, then push. Same return contract as {@link sync}: the durability of
@@ -2230,6 +2398,287 @@ export class Collection<TAction> implements ICollection<TAction> {
2230
2398
  }
2231
2399
  }
2232
2400
 
2401
+ /** Commit exactly the head sealed segment — the oldest, `entryId` — as one log entry under the
2402
+ * action id and timestamp `options` supplies, for the offline-sync queue's drain
2403
+ * (docs/offline-sync.md §One entry, one network transaction): {@link openHeadCommit} followed by
2404
+ * the one-collection driver, `driveHeadCommit` in head-commit.ts, with the handle closed on every
2405
+ * exit. The attempt machinery is {@link syncAttempts}' ({@link AttemptCycle}, {@link stageAttempt});
2406
+ * what differs is the target — a head tracker ({@link headTrackerFor}) — and the latch, released
2407
+ * around the one network `await` ({@link HeadCommitHandle.release}). `options.recordAttempt` is
2408
+ * called with each attempt before it is sent, and `options.resume` hands back an attempt an
2409
+ * earlier cycle under the same action id recorded (see {@link HeadCommitOptions}).
2410
+ *
2411
+ * @returns what {@link sync} returns: who holds the commit, or `undefined` when the refresh
2412
+ * established that the write was already saved under `options.actionId` without re-sending.
2413
+ * @throws SealedSegmentsError before anything is done, when `entryId` is not the head segment
2414
+ * (`not-head`), carries a recorded refusal (`refused`), or a head commit is already in flight on
2415
+ * this instance (`in-flight`); the head segment's recorded refusal, an {@link ActionRefusedError},
2416
+ * when a refresh or the head tracker's staging refused it during the cycle; whatever
2417
+ * `options.recordAttempt` throws, before anything is sent; otherwise what {@link sync} throws. */
2418
+ async commitHead(entryId: EntryId, options: HeadCommitOptions): Promise<WriteDurability | undefined> {
2419
+ const handle = await this.openHeadCommit(entryId, { actionId: options.actionId, timestamp: options.timestamp }, {
2420
+ refuseSolo: options.refuseSoloCommit,
2421
+ ...(options.resume === undefined ? {} : { resume: options.resume }),
2422
+ ...(options.onCommittedHead === undefined ? {} : { onCommittedHead: options.onCommittedHead }),
2423
+ });
2424
+ try {
2425
+ return await driveHeadCommit(handle, options);
2426
+ } finally {
2427
+ handle.close();
2428
+ }
2429
+ }
2430
+
2431
+ /** Open a head commit of `entryId` under `identity` and hand back the handle a driver runs it
2432
+ * through, step by step ({@link HeadCommitHandle}): this is {@link commitHead} with the loop left
2433
+ * to the caller, for the coordinator's per-entry commit over several collections, which runs each
2434
+ * step on every collection it wrote in lock-step. Takes the collection latch, which the handle
2435
+ * holds until its `close()` except around the network round trip; checks the three
2436
+ * preconditions; marks the action in flight for the whole cycle ({@link beginInFlightAction}), as
2437
+ * a sync's is, so the refresh between attempts recognises the write's own entry; sets
2438
+ * {@link headCommit}, which tells {@link consumeOwnEntry} that such an entry records the head
2439
+ * segment; and seeds the retained attempt with `options.resume` when one is given, so that the
2440
+ * opening refresh can finish an earlier cycle's torn attempt from it ({@link completeOwnEntry}) —
2441
+ * and `stage()` re-sends it verbatim while the next attempt would request its revision
2442
+ * ({@link resumedAttempt}). The rest of `options` is the cycle's ({@link InFlightCycle}), recorded
2443
+ * with the in-flight mark, so the handle's `send()` and a refresh's re-send of a torn attempt both
2444
+ * carry it.
2445
+ *
2446
+ * **The target.** The live tracker holds every sealed segment and the open one, cumulatively, so
2447
+ * an attempt cannot run on a copy of it the way a sync's does. It runs on a HEAD TRACKER instead
2448
+ * ({@link headTrackerFor}): the head segment's actions alone, staged atomically over the
2449
+ * committed state, with pins of their own — built once per requested revision and reused across
2450
+ * attempts, since a rebuild mints fresh ids for the blocks the actions insert and would send
2451
+ * different content under one `(action id, revision)` (the rule {@link logAppendBlockIds}
2452
+ * closes). Staging runs the actions' guards against the committed state; a refusal there is the
2453
+ * segment's refusal, recorded and reported exactly as a replay's would be, and thrown out of
2454
+ * `stage()`.
2455
+ *
2456
+ * **The latch.** Held for every step EXCEPT the one `await` on the network, so `act`,
2457
+ * `sealPending`, `update` and the rest are not blocked behind a commit that can take seconds
2458
+ * (docs/offline-sync.md §The drain does not hold the collection latch across the network). While
2459
+ * it is released {@link headInFlight} is set: a refresh that walks into this commit's entry defers
2460
+ * to it, and `dropSealed` of the head refuses. A second head commit on this instance waits on the
2461
+ * latch and then meets the `in-flight` precondition.
2462
+ *
2463
+ * **The head's recorded refusal** is re-checked by `stage()` before every attempt and by
2464
+ * `refused()` after every refused send, because a refresh that adopted a rival — a reader's,
2465
+ * while the latch was released, or this cycle's own — may have replayed and refused it; each
2466
+ * throws the recorded refusal in place of another attempt. On success the driver calls `fold()`
2467
+ * (remove the head segment, bump the segment version, fold the attempt's transforms into the
2468
+ * cache and adopt its revision) and only THEN `replay()` (the remaining segments and the open
2469
+ * segment over the committed state that now holds the head) — the fold-before-replay order
2470
+ * {@link syncAttempts} takes, which anything staged while the commit was on the network relies on.
2471
+ *
2472
+ * A driver that opens handles on more than one collection opens them in sorted collection-id
2473
+ * order, the order `TransactionCoordinator.commitOnce` takes the same latches in; see the
2474
+ * interface.
2475
+ *
2476
+ * @throws Error before the latch is taken when `options.resume` was recorded under an action other than
2477
+ * `identity.actionId` — a caller defect, since the attempt would be re-sent under the wrong id;
2478
+ * SealedSegmentsError, with the latch released again, when `entryId` is not the head segment
2479
+ * (`not-head`), carries a recorded refusal (`refused`), or a head commit is already in flight on
2480
+ * this instance (`in-flight`). */
2481
+ async openHeadCommit(entryId: EntryId, identity: WriteIdentity, options: OpenHeadCommitOptions = {}): Promise<HeadCommitHandle> {
2482
+ const { resume, onCommittedHead, ...cycle } = options;
2483
+ if (resume !== undefined && resume.actionId !== identity.actionId) {
2484
+ throw new Error(`Collection ${this.id}: an attempt recorded under action ${resume.actionId} cannot resume `
2485
+ + `a head commit of ${entryId} under action ${identity.actionId}`);
2486
+ }
2487
+ const release = await Latches.acquire(this.latchId);
2488
+ try {
2489
+ this.assertHeadCommittable(entryId);
2490
+ } catch (err) {
2491
+ release();
2492
+ throw err;
2493
+ }
2494
+ const endInFlight = this.beginInFlightAction(identity.actionId, cycle);
2495
+ this.headCommit = { entryId, ...(onCommittedHead === undefined ? {} : { onCommitted: onCommittedHead }) };
2496
+ if (resume !== undefined) {
2497
+ this.retainInFlightAttempt(resume);
2498
+ }
2499
+ return this.headCommitHandle(entryId, identity, release, endInFlight, resume);
2500
+ }
2501
+
2502
+ /** The handle {@link openHeadCommit} returns: closures over this instance's private state, so
2503
+ * nothing private becomes public. `release` is the latch release of the latch the caller took;
2504
+ * `endInFlight` the disposer of the in-flight mark. The head tracker lives here, per handle, so it
2505
+ * is reused across the attempts of one cycle exactly as the in-line loop reused it. `resume` is
2506
+ * the attempt the cycle was opened with, which `stage()` re-sends verbatim while the next attempt
2507
+ * would request its revision ({@link resumedAttempt}). */
2508
+ private headCommitHandle(entryId: EntryId, identity: WriteIdentity, release: () => void, endInFlight: () => void,
2509
+ resume: InFlightAttempt | undefined): HeadCommitHandle {
2510
+ let held = true;
2511
+ let closed = false;
2512
+ let head: HeadTracker | undefined;
2513
+ const assertUsable = (step: string, needsLatch: boolean) => {
2514
+ if (closed) {
2515
+ throw new Error(`Collection ${this.id}: head commit of ${entryId} is closed; ${step}() is a defect`);
2516
+ }
2517
+ if (held !== needsLatch) {
2518
+ throw new Error(`Collection ${this.id}: head commit of ${entryId} ${held ? 'holds' : 'has released'} the latch; `
2519
+ + `${step}() is a defect here`);
2520
+ }
2521
+ };
2522
+ return {
2523
+ collectionId: this.id,
2524
+ instanceTag: this.instanceTag,
2525
+ entryId,
2526
+ refresh: (report, lastChance, tailFloor) => {
2527
+ assertUsable('refresh', true);
2528
+ return this.updateInternal(report, lastChance, tailFloor);
2529
+ },
2530
+ nextRev: () => this.getNextRev(),
2531
+ heldRev: () => this.source.actionContext?.rev,
2532
+ stage: async () => {
2533
+ assertUsable('stage', true);
2534
+ const segment = this.committableHead(entryId);
2535
+ const resumed = resumedAttempt(this.sourceCache, resume, this.getNextRev());
2536
+ if (resumed !== undefined) {
2537
+ return resumed;
2538
+ }
2539
+ head = await this.headTrackerFor(segment, head);
2540
+ return this.buildAttempt({ actions: segment.actions, transforms: head.tracker.transforms, pins: head.tracker.pins }, identity);
2541
+ },
2542
+ send: (staged, priority) => {
2543
+ assertUsable('send', false);
2544
+ return this.send(staged, identity, priority);
2545
+ },
2546
+ release: () => {
2547
+ assertUsable('release', true);
2548
+ this.headInFlight = { entryId, actionId: identity.actionId };
2549
+ held = false;
2550
+ release();
2551
+ },
2552
+ retake: async () => {
2553
+ assertUsable('retake', false);
2554
+ const retaken = await Latches.acquire(this.latchId);
2555
+ if (closed) {
2556
+ // close() ran while the latch was being acquired: it has already cleared the marks
2557
+ // latch-free, so keeping this latch would leak it for the life of the instance.
2558
+ retaken();
2559
+ throw new Error(`Collection ${this.id}: head commit of ${entryId} was closed while retake() was waiting; `
2560
+ + `a driver closes its handle only after retaking`);
2561
+ }
2562
+ release = retaken;
2563
+ held = true;
2564
+ this.headInFlight = undefined;
2565
+ },
2566
+ fold: (staged) => {
2567
+ assertUsable('fold', true);
2568
+ const dropped = this.segments.drop(this.headSegment(entryId).entryId);
2569
+ this.foldOwnCommit(staged, identity.actionId);
2570
+ this.reportCommittedHead(dropped);
2571
+ },
2572
+ replay: () => {
2573
+ assertUsable('replay', true);
2574
+ // NOTE: the remaining sealed segments and the open segment are replayed after EVERY head
2575
+ // commit, so draining a queue of n entries is quadratic in n (docs/offline-sync.md
2576
+ // §Failure modes and accepted tradeoffs). Negligible for tens of entries; if it shows up
2577
+ // for a device that queued thousands, keep per-segment trackers chained over the cache,
2578
+ // so a committed head is popped and folded instead of replayed.
2579
+ return this.replayActions();
2580
+ },
2581
+ refused: (staged) => {
2582
+ assertUsable('refused', true);
2583
+ this.committableHead(entryId);
2584
+ this.retainInFlightAttempt(retainedAttempt(staged, identity.actionId));
2585
+ },
2586
+ close: () => {
2587
+ if (closed) return;
2588
+ closed = true;
2589
+ this.headCommit = undefined;
2590
+ this.headInFlight = undefined;
2591
+ endInFlight();
2592
+ if (held) {
2593
+ held = false;
2594
+ release();
2595
+ }
2596
+ },
2597
+ };
2598
+ }
2599
+
2600
+ /** {@link commitHead}'s preconditions, each a {@link SealedSegmentsError} naming its reason. */
2601
+ private assertHeadCommittable(entryId: EntryId): void {
2602
+ const sealed = this.segments.entryIds();
2603
+ const head = this.segments.head();
2604
+ if (head === undefined || head.entryId !== entryId) {
2605
+ throw new SealedSegmentsError(this.id, sealed, 'not-head', entryId);
2606
+ }
2607
+ if (head.refused !== undefined) {
2608
+ throw new SealedSegmentsError(this.id, sealed, 'refused', entryId);
2609
+ }
2610
+ if (this.headInFlight !== undefined) {
2611
+ throw new SealedSegmentsError(this.id, sealed, 'in-flight', this.headInFlight.entryId);
2612
+ }
2613
+ }
2614
+
2615
+ /** The head segment, which a running head commit may still commit: it is `entryId` — anything
2616
+ * else is a defect ({@link headSegment}) — and it has not been refused meanwhile. A refresh that
2617
+ * adopted a rival may have replayed and refused it, and that refusal, not another attempt, is
2618
+ * then the cycle's answer. */
2619
+ private committableHead(entryId: EntryId): SealedSegment<TAction> {
2620
+ const head = this.headSegment(entryId);
2621
+ if (head.refused !== undefined) {
2622
+ throw head.refused;
2623
+ }
2624
+ return head;
2625
+ }
2626
+
2627
+ /** The head segment, asserted to be `entryId`. Nothing may remove the head while a head commit
2628
+ * of it runs — a refresh that meets it defers, `dropSealed` of it refuses — so anything else here
2629
+ * is a defect, thrown as one. */
2630
+ private headSegment(entryId: EntryId): SealedSegment<TAction> {
2631
+ const head = this.segments.head();
2632
+ if (head === undefined || head.entryId !== entryId) {
2633
+ throw new Error(`Collection ${this.id}: head segment ${entryId} was removed while its commit was running `
2634
+ + `(the head is ${head?.entryId ?? 'nothing'})`);
2635
+ }
2636
+ return head;
2637
+ }
2638
+
2639
+ /** The tracker a head attempt is built from (see {@link commitHead}): `current`, while it was
2640
+ * built for the revision the next attempt requests and no base under it has moved; otherwise a
2641
+ * fresh one ({@link buildHeadTracker}). A revision that moved is a write that is genuinely
2642
+ * different. A base that moved at the same revision is re-judged exactly as
2643
+ * {@link restageIfBasesMoved} re-judges the live queue before an attempt, and rebuilds.
2644
+ * NOTE: that rebuild is the same exception to the byte-identical retry that {@link syncAttempts}
2645
+ * records at its `restageIfBasesMoved` call — fresh ids for the blocks the actions insert under
2646
+ * an unchanged `(action id, revision)` — reached the same narrow way and refused by storage's
2647
+ * base guard on the same machines; the same answer applies if it is ever seen. */
2648
+ private async headTrackerFor(segment: SealedSegment<TAction>, current: HeadTracker | undefined): Promise<HeadTracker> {
2649
+ const rev = this.getNextRev();
2650
+ if (current?.rev === rev) {
2651
+ await this.rereadUnretainedBases(current.tracker);
2652
+ if (this.logMovedBases(current.tracker.movedBases()) === 0) {
2653
+ return current;
2654
+ }
2655
+ }
2656
+ return { rev, tracker: await this.buildHeadTracker(segment) };
2657
+ }
2658
+
2659
+ /** A tracker over this instance's read cache, with pins of its own, holding `segment`'s actions
2660
+ * staged atomically over the committed state — from the invented baseline while this collection
2661
+ * has no committed revision ({@link replayBaseline}): its header, log block and root then exist
2662
+ * nowhere else, and the head's commit has to carry them. A refusal is the segment's own,
2663
+ * recorded and reported ({@link recordSealedRefusal}) and thrown; a live replay that found it
2664
+ * first has already done the recording, and the caller never gets here. */
2665
+ private async buildHeadTracker(segment: SealedSegment<TAction>): Promise<Tracker<IBlock>> {
2666
+ const tracker = new Tracker<IBlock>(this.sourceCache, this.replayBaseline());
2667
+ try {
2668
+ segment.applied = await this.stageInto(tracker, ...segment.actions);
2669
+ } catch (err) {
2670
+ if (err instanceof ActionRefusedError) {
2671
+ // NOTE: the live tracker still holds this segment's effects from its last replay, which
2672
+ // judged the same committed state and did not refuse; a reader sees them until the next
2673
+ // replay (the queue's drop of the refused segment). Reachable only if a base re-read
2674
+ // catches up between the two stagings; if that is ever seen, replay here after recording.
2675
+ this.recordSealedRefusal(segment, err);
2676
+ }
2677
+ throw err;
2678
+ }
2679
+ return tracker;
2680
+ }
2681
+
2233
2682
  /** Stage `actions` and flush them as one call that either takes effect or leaves NOTHING behind:
2234
2683
  * when the flush throws, the actions this call staged are unstaged again before the error escapes.
2235
2684
  *
@@ -2251,6 +2700,9 @@ export class Collection<TAction> implements ICollection<TAction> {
2251
2700
  async actAndSync(actions: Action<TAction>[], options?: SyncOptions): Promise<WriteDurability | undefined> {
2252
2701
  const release = await Latches.acquire(this.latchId);
2253
2702
  try {
2703
+ // Refused before staging, so there is nothing to unstage: the sync below would refuse
2704
+ // anyway (syncInternal), and staging first would only have to be taken back.
2705
+ this.assertNoSealedSegments();
2254
2706
  const stagedBefore = copyTransforms(this.tracker.transforms);
2255
2707
  const revBefore = this.source.actionContext?.rev;
2256
2708
  await this.actInternal(...actions);
@@ -2271,18 +2723,19 @@ export class Collection<TAction> implements ICollection<TAction> {
2271
2723
  * revision from before the actions were staged.
2272
2724
  *
2273
2725
  * While the held revision has not moved, the earlier transforms are reinstated verbatim rather
2274
- * than rebuilt by replay: an INVENTED collection keeps its header and root in the tracker with
2275
- * no staged action naming them, and a replay (which resets the tracker first) would drop them —
2276
- * the hazard {@link mustReplay} and {@link snapshotPending} document. Once the revision has
2277
- * moved those transforms describe blocks at a revision this handle has left, so what remains is
2278
- * re-staged against the adopted one, exactly as a refresh would have done. */
2726
+ * than rebuilt by replay: they are exactly the state before the call, and reinstating them costs
2727
+ * no handler run (a replay would rebuild the same state from {@link inventedBaseline} and the
2728
+ * staged actions). Once the revision has moved those transforms describe blocks at a revision
2729
+ * this handle has left, so what remains is re-staged against the adopted one, exactly as a
2730
+ * refresh would have done. */
2279
2731
  private async unstage(actions: Action<TAction>[], stagedBefore: Transforms, revBefore: number | undefined): Promise<void> {
2280
2732
  // NOTE: matched by identity, which is what `filterAgainstEntry` promises for a kept action.
2281
2733
  // A `filterConflict` hook that answers a REPLACEMENT instance for one of these actions would
2282
2734
  // leave the replacement staged here. No collection installs such a hook today (`Tree` and
2283
2735
  // `Diary` install none); if one ever does, carry a per-call token on the staged actions and
2284
2736
  // match on that instead.
2285
- this.pending = this.pending.filter(staged => !actions.includes(staged));
2737
+ // The actions were staged into the OPEN segment (actAndSync refuses over sealed segments).
2738
+ this.segments.open = this.segments.open.filter(staged => !actions.includes(staged));
2286
2739
  if (this.source.actionContext?.rev === revBefore) {
2287
2740
  this.tracker.reset(stagedBefore);
2288
2741
  } else {
@@ -2304,14 +2757,70 @@ export class Collection<TAction> implements ICollection<TAction> {
2304
2757
  }
2305
2758
  }
2306
2759
 
2307
- private async replayActions() {
2308
- this.tracker.reset();
2309
- // Replay pending actions against the fresh tracker state (always called under latch)
2310
- for (const action of this.pending) {
2760
+ /** Rebuild the tracker from the staged actions over the committed state this collection now
2761
+ * reads at (always called under latch): reset to {@link replayBaseline}, then every sealed
2762
+ * segment in order, then the open segment.
2763
+ *
2764
+ * A SEALED segment is staged as ONE atomic unit — one `internalTransact` call over all of its
2765
+ * actions — so a refusal of any action in it leaves none of its writes staged, and a refusal
2766
+ * ({@link ActionRefusedError}, the only class caught) is that segment's own: recorded on it,
2767
+ * reported through `onSealedRefused`, and the replay goes on to the next segment. A segment
2768
+ * already refused is skipped and not reported again; it stays listed until dropped. The OPEN
2769
+ * segment keeps the pre-segment behaviour: one `internalTransact` per action, and a refusal
2770
+ * propagates, since it is the live transaction's own (docs/offline-sync.md §Replay with a
2771
+ * per-segment refusal). Any error that is not a refusal propagates from either.
2772
+ *
2773
+ * Each re-staged update pins its base through `Atomic.commit` → `Tracker.absorb`, the path
2774
+ * {@link act} uses, so the pend declares the bases the re-staged operations were computed on. Each
2775
+ * sealed segment that staged records what its actions accepted as already applied
2776
+ * (`SealedSegment.applied`), the tally the head commit reports when the segment is committed.
2777
+ *
2778
+ * @param unreported - a segment whose refusal is recorded but NOT reported through
2779
+ * `onSealedRefused`: the one {@link restoreSealed} is inserting, whose caller reads the recorded
2780
+ * refusal off the segment itself. */
2781
+ private async replayActions(unreported?: EntryId): Promise<void> {
2782
+ this.tracker.reset(this.replayBaseline());
2783
+ for (const segment of this.segments.replayable()) {
2784
+ try {
2785
+ segment.applied = await this.internalTransact(...segment.actions);
2786
+ } catch (err) {
2787
+ if (!(err instanceof ActionRefusedError)) {
2788
+ throw err;
2789
+ }
2790
+ this.recordSealedRefusal(segment, err, segment.entryId !== unreported);
2791
+ }
2792
+ }
2793
+ for (const action of this.segments.open) {
2311
2794
  await this.internalTransact(action);
2312
2795
  }
2313
2796
  }
2314
2797
 
2798
+ /** What a replay resets the tracker to: a copy of {@link inventedBaseline} while this collection
2799
+ * holds no committed revision (those blocks exist nowhere else), and nothing otherwise. */
2800
+ private replayBaseline(): Transforms {
2801
+ return this.source.actionContext === undefined && this.inventedBaseline !== undefined
2802
+ ? copyTransforms(this.inventedBaseline)
2803
+ : emptyTransforms();
2804
+ }
2805
+
2806
+ /** Record a replay's refusal of a sealed segment and, when `report` says so, report it once,
2807
+ * under the latch. The callback's throw is logged rather than raised: the refusal is already
2808
+ * recorded, and the rest of the replay must still run. */
2809
+ private recordSealedRefusal(segment: SealedSegment<TAction>, error: ActionRefusedError, report = true): void {
2810
+ this.segments.refuse(segment.entryId, error);
2811
+ log('collection:sealed-segment-refused id=%s tag=%s entry=%s reported=%s error=%s',
2812
+ this.id, this.instanceTag, segment.entryId, report, error.message);
2813
+ if (!report) {
2814
+ return;
2815
+ }
2816
+ try {
2817
+ this.onSealedRefused?.(segment.entryId, error);
2818
+ } catch (err) {
2819
+ log('collection:refusal-callback-threw id=%s tag=%s entry=%s error=%s',
2820
+ this.id, this.instanceTag, segment.entryId, err instanceof Error ? err.message : String(err));
2821
+ }
2822
+ }
2823
+
2315
2824
  getReadDependencies(): ReadDependency[] {
2316
2825
  return this.source.getReadDependencies();
2317
2826
  }
@@ -2337,13 +2846,9 @@ export class Collection<TAction> implements ICollection<TAction> {
2337
2846
  * than kept, because nothing proves it is current at the revision the refresh will pin to.
2338
2847
  *
2339
2848
  * Both answers pass {@link answeredBlock}'s checks as unpinned reads, header first, so a doubted
2340
- * header or tail throws exactly as it would through {@link TransactorSource.tryGet}.
2341
- *
2342
- * NOTE: a batched get fails as a whole when any block in it gets no answer
2343
- * (`NetworkTransactor.get` throws on a missing id), so an unreachable out-of-date tail fails a
2344
- * refresh that would not have needed it. Harmless today: the log has no checkpoints, so a
2345
- * refresh that finds a new tail walks back through the old one anyway. If checkpoints start
2346
- * letting that walk stop short, read the known tail in its own request instead.
2849
+ * header or tail throws exactly as it would through {@link TransactorSource.tryGet}. An
2850
+ * out-of-date tail no coordinator answered comes back flagged (`NetworkTransactor.get` flags that
2851
+ * one block rather than failing the request), and its answer is dropped unjudged.
2347
2852
  *
2348
2853
  * `tailFloor` (see {@link updateInternal}) goes on whichever request reads the tail — never on
2349
2854
  * the header, which is rewritten only when the tail rolls over or the collection changes it