@optimystic/db-p2p 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/dist/src/cluster/client.d.ts +10 -0
  2. package/dist/src/cluster/client.d.ts.map +1 -1
  3. package/dist/src/cluster/client.js +30 -1
  4. package/dist/src/cluster/client.js.map +1 -1
  5. package/dist/src/cluster/cluster-repo.d.ts +39 -14
  6. package/dist/src/cluster/cluster-repo.d.ts.map +1 -1
  7. package/dist/src/cluster/cluster-repo.js +226 -119
  8. package/dist/src/cluster/cluster-repo.js.map +1 -1
  9. package/dist/src/cluster/service.d.ts +32 -1
  10. package/dist/src/cluster/service.d.ts.map +1 -1
  11. package/dist/src/cluster/service.js +43 -2
  12. package/dist/src/cluster/service.js.map +1 -1
  13. package/dist/src/cohort-topic/stream-util.d.ts +22 -6
  14. package/dist/src/cohort-topic/stream-util.d.ts.map +1 -1
  15. package/dist/src/cohort-topic/stream-util.js +56 -10
  16. package/dist/src/cohort-topic/stream-util.js.map +1 -1
  17. package/dist/src/dispute/dispute-service.d.ts.map +1 -1
  18. package/dist/src/dispute/dispute-service.js +9 -3
  19. package/dist/src/dispute/dispute-service.js.map +1 -1
  20. package/dist/src/index.d.ts +3 -0
  21. package/dist/src/index.d.ts.map +1 -1
  22. package/dist/src/index.js +3 -0
  23. package/dist/src/index.js.map +1 -1
  24. package/dist/src/libp2p-key-network.d.ts +88 -2
  25. package/dist/src/libp2p-key-network.d.ts.map +1 -1
  26. package/dist/src/libp2p-key-network.js +134 -28
  27. package/dist/src/libp2p-key-network.js.map +1 -1
  28. package/dist/src/libp2p-node-base.d.ts.map +1 -1
  29. package/dist/src/libp2p-node-base.js +25 -1
  30. package/dist/src/libp2p-node-base.js.map +1 -1
  31. package/dist/src/logger.d.ts +17 -1
  32. package/dist/src/logger.d.ts.map +1 -1
  33. package/dist/src/logger.js +19 -2
  34. package/dist/src/logger.js.map +1 -1
  35. package/dist/src/owned-block-seed.d.ts +6 -3
  36. package/dist/src/owned-block-seed.d.ts.map +1 -1
  37. package/dist/src/owned-block-seed.js +16 -3
  38. package/dist/src/owned-block-seed.js.map +1 -1
  39. package/dist/src/peer-address-book.d.ts +72 -0
  40. package/dist/src/peer-address-book.d.ts.map +1 -0
  41. package/dist/src/peer-address-book.js +123 -0
  42. package/dist/src/peer-address-book.js.map +1 -0
  43. package/dist/src/repo/client.d.ts.map +1 -1
  44. package/dist/src/repo/client.js +11 -2
  45. package/dist/src/repo/client.js.map +1 -1
  46. package/dist/src/repo/cluster-coordinator.d.ts +30 -0
  47. package/dist/src/repo/cluster-coordinator.d.ts.map +1 -1
  48. package/dist/src/repo/cluster-coordinator.js +95 -3
  49. package/dist/src/repo/cluster-coordinator.js.map +1 -1
  50. package/dist/src/repo/coordinator-repo.d.ts +62 -9
  51. package/dist/src/repo/coordinator-repo.d.ts.map +1 -1
  52. package/dist/src/repo/coordinator-repo.js +242 -73
  53. package/dist/src/repo/coordinator-repo.js.map +1 -1
  54. package/dist/src/rn.d.ts +3 -0
  55. package/dist/src/rn.d.ts.map +1 -1
  56. package/dist/src/rn.js +3 -0
  57. package/dist/src/rn.js.map +1 -1
  58. package/dist/src/storage/cached-raw-storage.d.ts +83 -0
  59. package/dist/src/storage/cached-raw-storage.d.ts.map +1 -0
  60. package/dist/src/storage/cached-raw-storage.js +152 -0
  61. package/dist/src/storage/cached-raw-storage.js.map +1 -0
  62. package/dist/src/storage/cached-store-driver.d.ts +186 -0
  63. package/dist/src/storage/cached-store-driver.d.ts.map +1 -0
  64. package/dist/src/storage/cached-store-driver.js +775 -0
  65. package/dist/src/storage/cached-store-driver.js.map +1 -0
  66. package/dist/src/storage/i-raw-storage.d.ts +12 -5
  67. package/dist/src/storage/i-raw-storage.d.ts.map +1 -1
  68. package/dist/src/storage/shared-cache-pool.d.ts +234 -0
  69. package/dist/src/storage/shared-cache-pool.d.ts.map +1 -0
  70. package/dist/src/storage/shared-cache-pool.js +354 -0
  71. package/dist/src/storage/shared-cache-pool.js.map +1 -0
  72. package/dist/src/testing/raw-storage-conformance.d.ts +2 -1
  73. package/dist/src/testing/raw-storage-conformance.d.ts.map +1 -1
  74. package/dist/src/testing/raw-storage-conformance.js +35 -2
  75. package/dist/src/testing/raw-storage-conformance.js.map +1 -1
  76. package/package.json +3 -3
  77. package/readme.md +668 -668
  78. package/src/cluster/block-transfer.ts +424 -424
  79. package/src/cluster/client.ts +119 -88
  80. package/src/cluster/cluster-error.ts +64 -64
  81. package/src/cluster/cluster-policy.ts +203 -203
  82. package/src/cluster/cluster-repo.ts +242 -122
  83. package/src/cluster/cluster-size-coupling.ts +45 -45
  84. package/src/cluster/commit-cert.ts +139 -139
  85. package/src/cluster/i-transaction-state-store.ts +43 -43
  86. package/src/cluster/memory-transaction-state-store.ts +56 -56
  87. package/src/cluster/peer-key-binding.ts +37 -37
  88. package/src/cluster/persistent-transaction-state-store.ts +92 -92
  89. package/src/cluster/quorum-restore.ts +223 -223
  90. package/src/cluster/reconcile-block.ts +203 -203
  91. package/src/cluster/service.ts +293 -241
  92. package/src/cluster/supermajority-coupling.ts +37 -37
  93. package/src/cohort-topic/bootstrap-evidence-builder.ts +122 -122
  94. package/src/cohort-topic/bootstrap-evidence-verifiers.ts +132 -132
  95. package/src/cohort-topic/bootstrap-parent-reference.ts +159 -159
  96. package/src/cohort-topic/change-bridge.ts +109 -109
  97. package/src/cohort-topic/cohort-gossip-driver.ts +231 -231
  98. package/src/cohort-topic/cohort-gossip-transport.ts +84 -84
  99. package/src/cohort-topic/fret-trust-anchor.ts +153 -153
  100. package/src/cohort-topic/host.ts +2901 -2901
  101. package/src/cohort-topic/index.ts +13 -13
  102. package/src/cohort-topic/membership-publish-sink.ts +20 -20
  103. package/src/cohort-topic/membership-source.ts +68 -68
  104. package/src/cohort-topic/peer-codec.ts +31 -31
  105. package/src/cohort-topic/peer-sig.ts +86 -86
  106. package/src/cohort-topic/protocols.ts +71 -71
  107. package/src/cohort-topic/reactivity-membership-gate.ts +77 -77
  108. package/src/cohort-topic/size-estimator.ts +16 -16
  109. package/src/cohort-topic/stream-util.ts +135 -87
  110. package/src/cohort-topic/threshold-crypto.ts +239 -239
  111. package/src/cohort-topic/topic-router.ts +77 -77
  112. package/src/dispute/arbitrator-selection.ts +138 -138
  113. package/src/dispute/cascade.ts +524 -524
  114. package/src/dispute/dispute-service.ts +11 -5
  115. package/src/dispute/invalidation.ts +625 -625
  116. package/src/inbound-authorization.ts +190 -190
  117. package/src/index.ts +52 -49
  118. package/src/libp2p-key-network.ts +1120 -990
  119. package/src/libp2p-node-base.ts +1675 -1651
  120. package/src/libp2p-node-rn.ts +30 -30
  121. package/src/libp2p-node.ts +36 -36
  122. package/src/logger.ts +19 -2
  123. package/src/matchmaking/aggregate-counts.ts +104 -104
  124. package/src/matchmaking/index.ts +20 -20
  125. package/src/matchmaking/module.ts +363 -363
  126. package/src/matchmaking/protocols.ts +51 -51
  127. package/src/matchmaking/provider-manager.ts +95 -95
  128. package/src/matchmaking/query-handler.ts +88 -88
  129. package/src/matchmaking/query-transport.ts +492 -492
  130. package/src/matchmaking/seeker-manager.ts +64 -64
  131. package/src/matchmaking/seeker-walk-client.ts +293 -293
  132. package/src/matchmaking/traffic-validation.ts +195 -195
  133. package/src/optimystic-node.ts +36 -36
  134. package/src/owned-block-seed.ts +53 -40
  135. package/src/peer-address-book.ts +149 -0
  136. package/src/protocol-limits.ts +33 -33
  137. package/src/reactivity/forwarder-host.ts +438 -438
  138. package/src/reactivity/index.ts +19 -19
  139. package/src/reactivity/notify-transport.ts +144 -144
  140. package/src/reactivity/origination-manager.ts +192 -192
  141. package/src/reactivity/protocols.ts +61 -61
  142. package/src/reactivity/push-state-gossip.ts +291 -291
  143. package/src/reactivity/recover-transport.ts +408 -408
  144. package/src/reactivity/rotation-rereg-scheduler.ts +256 -256
  145. package/src/reactivity/subscriber-registry.ts +96 -96
  146. package/src/reactivity/subscription-manager.ts +450 -450
  147. package/src/reactivity/topic-bytes.ts +37 -37
  148. package/src/repo/client.ts +12 -2
  149. package/src/repo/cluster-coordinator.ts +99 -3
  150. package/src/repo/coordinator-repo.ts +281 -74
  151. package/src/repo/types.ts +7 -7
  152. package/src/rn.ts +39 -36
  153. package/src/rpc-deadline.ts +45 -45
  154. package/src/storage/arachnode-partition.ts +74 -74
  155. package/src/storage/cached-raw-storage.ts +180 -0
  156. package/src/storage/cached-store-driver.ts +859 -0
  157. package/src/storage/i-kv-store.ts +8 -8
  158. package/src/storage/i-raw-storage.ts +12 -5
  159. package/src/storage/kv-raw-storage.ts +135 -135
  160. package/src/storage/memory-kv-store.ts +28 -28
  161. package/src/storage/memory-storage.ts +25 -25
  162. package/src/storage/memory-store-driver.ts +157 -157
  163. package/src/storage/raw-store-codec.ts +42 -42
  164. package/src/storage/raw-store-driver.ts +80 -80
  165. package/src/storage/ring-selector.ts +317 -317
  166. package/src/storage/ring-shift-coordinator.ts +271 -271
  167. package/src/storage/shared-cache-pool.ts +452 -0
  168. package/src/storage/storage-repo.ts +1014 -1014
  169. package/src/testing/cohort-topic-mesh-harness.ts +663 -663
  170. package/src/testing/index.ts +8 -8
  171. package/src/testing/matchmaking-mesh-harness.ts +475 -475
  172. package/src/testing/raw-storage-conformance.ts +453 -417
  173. package/src/testing/reactivity-mesh-harness.ts +922 -922
  174. package/dist/src/storage/restoration-coordinator-v2.d.ts +0 -67
  175. package/dist/src/storage/restoration-coordinator-v2.d.ts.map +0 -1
  176. package/dist/src/storage/restoration-coordinator-v2.js +0 -172
  177. package/dist/src/storage/restoration-coordinator-v2.js.map +0 -1
@@ -0,0 +1,859 @@
1
+ import type { BlockId, ActionId } from "@optimystic/db-core";
2
+ import type { RawStoreDriver } from "./raw-store-driver.js";
3
+ import {
4
+ defaultCachePool,
5
+ SharedCachePool,
6
+ CacheStoreHandle,
7
+ type CacheEntryClass,
8
+ type PoolEntry,
9
+ type PoolEntryOwner,
10
+ } from "./shared-cache-pool.js";
11
+
12
+ /**
13
+ * A cached value at the byte layer. `null` records a PROVEN absence — a confirmed miss read
14
+ * through this wrapper, or a delete that went through it. A plain map miss (`undefined`)
15
+ * means "unknown": the wrapper has never observed this key, so the inner driver must be
16
+ * consulted. The distinction is load-bearing for the absence/unavailability logic one layer
17
+ * up: a cached `null` may only ever mean "provably absent", never "could not confirm".
18
+ */
19
+ type CachedBytes = Uint8Array | null;
20
+
21
+ /**
22
+ * Inclusive integer interval `[lo, hi]`. Distinct from `RevisionRange` (inclusive-exclusive,
23
+ * open-ended) on purpose: coverage tracking wants closed integer intervals with adjacency
24
+ * merging, and reusing the metadata range type here would invite confusing the two.
25
+ */
26
+ type CoveredInterval = [lo: number, hi: number];
27
+
28
+ /** True when `[lo, hi]` is entirely inside one covered interval. `covered` is sorted and disjoint. */
29
+ function coversRange(covered: CoveredInterval[], lo: number, hi: number): boolean {
30
+ for (const [a, b] of covered) {
31
+ if (lo >= a && hi <= b) return true;
32
+ if (a > lo) break;
33
+ }
34
+ return false;
35
+ }
36
+
37
+ /**
38
+ * Add `[lo, hi]` to the sorted disjoint interval list, merging overlaps AND integer
39
+ * adjacency (`[1,3]` + `[4,6]` → `[1,6]`), so contiguous point coverage from successive
40
+ * `putRevision` calls collapses into one interval instead of accumulating per-rev entries.
41
+ */
42
+ function addCovered(covered: CoveredInterval[], lo: number, hi: number): CoveredInterval[] {
43
+ const merged: CoveredInterval[] = [];
44
+ let newLo = lo;
45
+ let newHi = hi;
46
+ let inserted = false;
47
+ for (const [a, b] of covered) {
48
+ if (b < newLo - 1) {
49
+ merged.push([a, b]);
50
+ } else if (a > newHi + 1) {
51
+ if (!inserted) {
52
+ merged.push([newLo, newHi]);
53
+ inserted = true;
54
+ }
55
+ merged.push([a, b]);
56
+ } else {
57
+ newLo = Math.min(newLo, a);
58
+ newHi = Math.max(newHi, b);
59
+ }
60
+ }
61
+ if (!inserted) {
62
+ merged.push([newLo, newHi]);
63
+ }
64
+ return merged;
65
+ }
66
+
67
+ /**
68
+ * Per-block revision map: point values plus the intervals over which the cache's knowledge
69
+ * is COMPLETE. A rev inside `covered` with no `byRev` entry is provably absent; a rev
70
+ * outside `covered` is unknown. `gen` increments on every mutation so an in-flight
71
+ * enumeration can detect that a write landed during its inner drain and decline to claim
72
+ * coverage it can no longer prove.
73
+ */
74
+ interface RevMapState {
75
+ byRev: Map<number, Uint8Array>;
76
+ covered: CoveredInterval[];
77
+ gen: number;
78
+ }
79
+
80
+ /**
81
+ * Per-block pending-id set. `complete` is true only when the set is known to equal the
82
+ * inner driver's set — either seeded by one full enumeration, or maintained from that point
83
+ * by the funnelled writes. The flag lives INSIDE the same entry as the set it describes, so
84
+ * dropping the entry (clear / write-error invalidation / POOL EVICTION) can never strand a
85
+ * half-true completeness claim — an evicted list takes its flag with it, and a fresh entry
86
+ * starts incomplete. `gen` serves the same in-flight-enumeration guard as {@link RevMapState}.
87
+ */
88
+ interface PendListState {
89
+ ids: Set<ActionId>;
90
+ complete: boolean;
91
+ gen: number;
92
+ }
93
+
94
+ /**
95
+ * All cached state for one block. Every field holds (or maps to) a {@link PoolEntry} — the
96
+ * value lives ON the pool entry, so residency, byte accounting and eviction are the shared
97
+ * pool's problem while coherence stays here. Entry classes are keyed in the pool as
98
+ * `(storeId, class, key…)`; block ids alone are NOT globally unique (header block ids are
99
+ * name-derived, so two stores running the same schema collide), which is why the store id
100
+ * leads the key.
101
+ */
102
+ interface BlockCacheState {
103
+ meta?: PoolEntry<CachedBytes>;
104
+ revs?: PoolEntry<RevMapState>;
105
+ pendList?: PoolEntry<PendListState>;
106
+ pending: Map<ActionId, PoolEntry<CachedBytes>>;
107
+ transactions: Map<ActionId, PoolEntry<CachedBytes>>;
108
+ materialized: Map<ActionId, PoolEntry<CachedBytes>>;
109
+ }
110
+
111
+ /** Approximate bytes for JS-object bookkeeping, charged so tiny/negative entries are not free. */
112
+ const CHAR_BYTES = 2;
113
+ /** Fixed cost of one pool entry: entry object + owner map slot + queue map slot (key string charged separately). */
114
+ const ENTRY_BASE = 256;
115
+ /** Per-revision cost inside a revision map: map slot + boxed rev + Uint8Array header. */
116
+ const REV_SLOT = 56;
117
+ /** Per-interval cost of the coverage list. */
118
+ const INTERVAL_SLOT = 56;
119
+ /** Per-id cost inside a pending-id set (id characters charged separately). */
120
+ const ID_SLOT = 40;
121
+
122
+ function idsContent(ids: Set<ActionId>): number {
123
+ let sum = 0;
124
+ for (const id of ids) sum += ID_SLOT + id.length * CHAR_BYTES;
125
+ return sum;
126
+ }
127
+
128
+ /**
129
+ * Write-through coherent cache over any {@link RawStoreDriver}, bounded by a shared
130
+ * {@link SharedCachePool}. Wrap a backend's driver with this before handing it to
131
+ * `KvRawStorage` and every read the kernel issues is served from memory while the entry
132
+ * stays resident in the pool — the pool's 2Q admission keeps hot per-store entries
133
+ * protected while one-off bulk scans die in probation (see the pool's class doc).
134
+ *
135
+ * **Coherence, not eviction policy.** Every save stores its value INTO the cache as it writes
136
+ * the inner driver, rather than invalidating. The cache therefore always holds the last
137
+ * durable value for resident entries and never needs to re-read a key it has seen while that
138
+ * entry survives. This is what a plain invalidate-on-write memo cannot achieve at this seam:
139
+ * the hot reads exist to observe the writes, so invalidation lands between nearly every read
140
+ * pair (measured: only a 23% cut).
141
+ *
142
+ * **Why this is sound** — the invariants in `docs/storage.md` ("Invariants", 1–5):
143
+ * 1. every backend write funnels through `IRawStorage` (and thus this driver) in-process, so
144
+ * the cache sees every mutation;
145
+ * 2. every writer of `meta.latest` holds the per-block commit latch, and each cache update is
146
+ * synchronous with its inner write (no `await` between the inner call resolving and the
147
+ * cache mutation), so latch-protected read-after-write sees the new value exactly as a
148
+ * driver read would;
149
+ * 3. committed revisions and materializations are append-only.
150
+ *
151
+ * **Precondition: one process owns the store** (Invariant 5). A second process writing the
152
+ * same backend bypasses this wrapper and makes cached values stale in ways that feed
153
+ * consensus decisions. Not enforced in code — see docs/storage.md.
154
+ *
155
+ * **The cache is always clean, never dirty.** No write is deferred, reordered, or coalesced;
156
+ * the inner driver's durable state never depends on cache contents. Eviction of ANY entry at
157
+ * ANY instant is therefore correct — the next read falls through — which is precisely what
158
+ * lets the shared pool evict freely, without pins, dirty tracking, or an exhaustion error.
159
+ * Keep it that way: if a change here ever needs a dirty or pinned entry, the design has gone
160
+ * wrong — stop and reconsider.
161
+ *
162
+ * **Pool discipline** (the one rule new code here must follow): mutate this wrapper's own
163
+ * state FIRST, then make the pool call (`admit`/`updated`/`touch`/`drop`) LAST, and never
164
+ * touch cache state after the pool call — pool mutations can synchronously evict any entry,
165
+ * including the one just written. The eviction callback ({@link onPoolEvict}) removes only
166
+ * the wrapper's reference and never calls back into the pool.
167
+ *
168
+ * **Values are cached as bytes**, exactly the encoded value the kernel wrote or the driver
169
+ * returned. The kernel decodes fresh objects from those bytes on every read, so the
170
+ * clone-on-read/clone-on-write discipline stays structural (same argument as the codec
171
+ * boundary itself), and an entry's byte size feeds the pool's budget directly.
172
+ * NOTE: every cache hit still pays one JSON.parse in the kernel; if decode ever shows up hot
173
+ * on large materialized blocks, cache decoded objects plus an explicit clone instead.
174
+ *
175
+ * **Do not wrap `MemoryStoreDriver`.** The memory driver already holds the same byte
176
+ * references in maps; wrapping it duplicates every map entry (the bytes themselves are
177
+ * shared, so no byte copy — but the bookkeeping is pure overhead with nothing to save).
178
+ */
179
+ export class CachedStoreDriver implements RawStoreDriver, PoolEntryOwner {
180
+ private readonly blocks = new Map<BlockId, BlockCacheState>();
181
+ private readonly store: CacheStoreHandle;
182
+
183
+ /**
184
+ * Optional passthroughs are wired only when the inner driver provides them, mirroring
185
+ * `KvRawStorage`'s constructor: feature-detection above this wrapper must observe the
186
+ * inner driver's true capability. `listBlockIds` deliberately bypasses the cache — it
187
+ * enumerates the inner metadata keyspace, which funnelled writes keep authoritative.
188
+ * `close` is the deliberate exception (a real method below): releasing the store's pool
189
+ * registration is THIS wrapper's own capability, needed whether or not the inner driver
190
+ * has anything to close.
191
+ */
192
+ listBlockIds?: () => AsyncIterable<BlockId>;
193
+ approximateBytesUsed?: () => Promise<number>;
194
+
195
+ constructor(
196
+ private readonly inner: RawStoreDriver,
197
+ private readonly pool: SharedCachePool = defaultCachePool(),
198
+ label?: string,
199
+ ) {
200
+ this.store = pool.registerStore(label);
201
+ if (inner.listBlockIds) {
202
+ this.listBlockIds = () => inner.listBlockIds!();
203
+ }
204
+ if (inner.approximateBytesUsed) {
205
+ this.approximateBytesUsed = () => inner.approximateBytesUsed!();
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Drop every cached entry (releasing their pool residency) and this store's ghost keys —
211
+ * pre-clear recency must not fast-track post-clear refills into the protected queue.
212
+ * Always safe (the cache is clean — see class doc); the next read of each key re-consults
213
+ * the inner driver. In-flight enumerations notice the identity change of their entry
214
+ * objects and decline to claim completeness.
215
+ */
216
+ clear(): void {
217
+ for (const s of this.blocks.values()) {
218
+ if (s.meta) this.pool.drop(s.meta);
219
+ if (s.revs) this.pool.drop(s.revs);
220
+ if (s.pendList) this.pool.drop(s.pendList);
221
+ for (const e of s.pending.values()) this.pool.drop(e);
222
+ for (const e of s.transactions.values()) this.pool.drop(e);
223
+ for (const e of s.materialized.values()) this.pool.drop(e);
224
+ }
225
+ this.blocks.clear();
226
+ this.pool.purgeGhosts(this.store);
227
+ }
228
+
229
+ /**
230
+ * Release this store entirely: drop all entries, unregister from the pool (the store id
231
+ * is never reused), and close the inner driver if it can be closed. A departed workspace
232
+ * that skips this leaks only cold entries the pool will evict under pressure — but call
233
+ * it; on a long-lived provider node the polite release is what keeps occupancy honest.
234
+ */
235
+ async close(): Promise<void> {
236
+ this.clear();
237
+ this.pool.unregisterStore(this.store);
238
+ await this.inner.close?.();
239
+ }
240
+
241
+ /** This store's live pool occupancy; pool-wide numbers come from `SharedCachePool.stats()`. */
242
+ storeStats(): { id: string; label: string | undefined; bytes: number; entries: number } {
243
+ return { id: this.store.id, label: this.store.label, bytes: this.store.bytes, entries: this.store.entries };
244
+ }
245
+
246
+ /**
247
+ * Pool eviction callback: remove OUR reference to the entry (identity-checked, so a stale
248
+ * callback can never delete a successor) and reap the block state if that emptied it.
249
+ * Runs synchronously inside a pool mutation — must not call back into the pool.
250
+ */
251
+ onPoolEvict(entry: PoolEntry): void {
252
+ const s = this.blocks.get(entry.blockId);
253
+ if (s === undefined) return;
254
+ switch (entry.cls) {
255
+ case 'meta': if (s.meta === entry) s.meta = undefined; break;
256
+ case 'revs': if (s.revs === entry) s.revs = undefined; break;
257
+ case 'pendList': if (s.pendList === entry) s.pendList = undefined; break;
258
+ case 'pending': evictFromMap(s.pending, entry); break;
259
+ case 'tx': evictFromMap(s.transactions, entry); break;
260
+ case 'mat': evictFromMap(s.materialized, entry); break;
261
+ }
262
+ this.dropIfEmpty(entry.blockId, s);
263
+ }
264
+
265
+ /**
266
+ * NOTE: this allocates an entry for EVERY block id touched, including ids that turn out
267
+ * not to exist (the proven-absent negative is the point). The shared pool charges those
268
+ * negatives — and the bare bookkeeping of empty container entries — against its budget
269
+ * (`ENTRY_BASE` + key), and {@link dropIfEmpty} reaps block states whose last entry is
270
+ * gone, so a remote peer streaming probes for nonexistent blocks (`StorageRepo.get` is
271
+ * reachable with an arbitrary block-id list) churns the probation queue instead of
272
+ * growing this map without bound.
273
+ */
274
+ private state(blockId: BlockId): BlockCacheState {
275
+ let s = this.blocks.get(blockId);
276
+ if (!s) {
277
+ s = { pending: new Map(), transactions: new Map(), materialized: new Map() };
278
+ this.blocks.set(blockId, s);
279
+ }
280
+ return s;
281
+ }
282
+
283
+ /** Reap a block state holding no entries, so evictions and declined fills leave nothing behind. */
284
+ private dropIfEmpty(blockId: BlockId, s: BlockCacheState): void {
285
+ if (s.meta === undefined && s.revs === undefined && s.pendList === undefined
286
+ && s.pending.size === 0 && s.transactions.size === 0 && s.materialized.size === 0
287
+ && this.blocks.get(blockId) === s) {
288
+ this.blocks.delete(blockId);
289
+ }
290
+ }
291
+
292
+ /**
293
+ * An inner read threw after {@link state} allocated: reap the (uncharged) empty state so
294
+ * a stream of probes against a throwing backend cannot grow `blocks` for free.
295
+ */
296
+ private reapOnThrow(blockId: BlockId, started: BlockCacheState): void {
297
+ if (this.blocks.get(blockId) === started) this.dropIfEmpty(blockId, started);
298
+ }
299
+
300
+ /**
301
+ * Install or update a point entry (meta / pending / tx / mat) as the LAST step of a write
302
+ * or read-miss fill. Handles the pool's large-value bypass: an over-limit value is not
303
+ * cached, and an existing entry growing over the limit is dropped to unknown (holding the
304
+ * stale prior value would be wrong; holding the oversized one would defeat the bypass).
305
+ */
306
+ private cachePoint(
307
+ blockId: BlockId,
308
+ s: BlockCacheState,
309
+ cls: CacheEntryClass,
310
+ actionId: ActionId | undefined,
311
+ bytes: CachedBytes,
312
+ existing: PoolEntry<CachedBytes> | undefined,
313
+ attach: (e: PoolEntry<CachedBytes>) => void,
314
+ detach: () => void,
315
+ ): void {
316
+ const len = bytes === null ? 0 : bytes.length;
317
+ if (existing !== undefined) {
318
+ const charge = existing.base + len;
319
+ if (!this.pool.admits(charge)) {
320
+ detach();
321
+ this.pool.drop(existing);
322
+ this.dropIfEmpty(blockId, s);
323
+ return;
324
+ }
325
+ existing.value = bytes;
326
+ this.pool.updated(existing, charge);
327
+ return;
328
+ }
329
+ const key = this.pool.keyFor(this.store, cls, blockId, actionId);
330
+ const base = ENTRY_BASE + key.length * CHAR_BYTES;
331
+ if (!this.pool.admits(base + len)) {
332
+ this.dropIfEmpty(blockId, s);
333
+ return;
334
+ }
335
+ const entry: PoolEntry<CachedBytes> = {
336
+ key, store: this.store, owner: this, cls, blockId, actionId,
337
+ value: bytes, base, charge: base + len, where: 'none',
338
+ };
339
+ attach(entry);
340
+ this.pool.admit(entry);
341
+ }
342
+
343
+ /**
344
+ * Cache a read-miss result into one of the map-backed entry classes, under BOTH fill
345
+ * guards. `started` is the state object the read began on:
346
+ *
347
+ * - **value guard** — fill only while the entry is still unknown, so a newer funnelled
348
+ * write that landed during the inner read is not clobbered by this older value;
349
+ * - **identity guard** — decline entirely if `clear()` (or the empty-state reaper)
350
+ * swapped the state object during the inner read. Without it a resumed read reinstalls
351
+ * its pre-clear value into the fresh state, and the newer write that superseded it went
352
+ * out with the old state — so the stale value would then be served forever. The
353
+ * revision and pending-list paths make the same identity check against their own pool
354
+ * entries.
355
+ */
356
+ private fillMiss(
357
+ blockId: BlockId,
358
+ started: BlockCacheState,
359
+ map: Map<ActionId, PoolEntry<CachedBytes>>,
360
+ cls: CacheEntryClass,
361
+ actionId: ActionId,
362
+ bytes: Uint8Array | undefined
363
+ ): void {
364
+ // `blocks.get`, not `state()` — a declined fill must not resurrect the block entry.
365
+ if (this.blocks.get(blockId) !== started) return;
366
+ if (map.get(actionId) !== undefined) return;
367
+ this.cachePoint(blockId, started, cls, actionId, bytes ?? null, undefined,
368
+ e => map.set(actionId, e), () => map.delete(actionId));
369
+ }
370
+
371
+ // --- metadata ---
372
+
373
+ async getMetadata(blockId: BlockId): Promise<Uint8Array | undefined> {
374
+ const s = this.state(blockId);
375
+ const hit = s.meta;
376
+ if (hit !== undefined) {
377
+ this.pool.touch(hit);
378
+ return hit.value ?? undefined;
379
+ }
380
+ let bytes: Uint8Array | undefined;
381
+ try {
382
+ bytes = await this.inner.getMetadata(blockId);
383
+ } catch (err) {
384
+ this.reapOnThrow(blockId, s);
385
+ throw err;
386
+ }
387
+ // Same two fill guards as {@link fillMiss} (value + state identity), spelled out here
388
+ // because metadata is a property rather than a map entry. Caching the miss (`null`) is
389
+ // deliberate: everything that creates metadata funnels through this wrapper, so a
390
+ // confirmed miss stays provably absent until a funnelled write overwrites it —
391
+ // repeated probes of not-yet-created blocks are a real cold-start pattern.
392
+ if (this.blocks.get(blockId) === s && s.meta === undefined) {
393
+ this.cachePoint(blockId, s, 'meta', undefined, bytes ?? null, undefined,
394
+ e => { s.meta = e; }, () => { s.meta = undefined; });
395
+ }
396
+ return bytes;
397
+ }
398
+
399
+ async putMetadata(blockId: BlockId, value: Uint8Array): Promise<void> {
400
+ try {
401
+ await this.inner.putMetadata(blockId, value);
402
+ } catch (err) {
403
+ // The inner write failed with the backend in an unknown state — drop to unknown so
404
+ // the next read consults the driver. Same recovery shape on every write path below.
405
+ const s = this.blocks.get(blockId);
406
+ const m = s?.meta;
407
+ if (s !== undefined && m !== undefined) {
408
+ s.meta = undefined;
409
+ this.pool.drop(m);
410
+ this.dropIfEmpty(blockId, s);
411
+ }
412
+ throw err;
413
+ }
414
+ const s = this.state(blockId);
415
+ this.cachePoint(blockId, s, 'meta', undefined, value, s.meta,
416
+ e => { s.meta = e; }, () => { s.meta = undefined; });
417
+ }
418
+
419
+ // --- revisions ---
420
+
421
+ /**
422
+ * Get or eagerly admit the block's revision-map entry. Eager (before any inner await) so
423
+ * the fill guards have a stable identity to check across the await; the empty container
424
+ * is charged its base cost, so probe streams pay for their bookkeeping. Returns
425
+ * `undefined` when the pool bypasses even the base charge (absurdly small budget) — the
426
+ * callers then pass straight through to the inner driver, uncached.
427
+ */
428
+ private ensureRevs(blockId: BlockId): PoolEntry<RevMapState> | undefined {
429
+ const s = this.state(blockId);
430
+ if (s.revs !== undefined) return s.revs;
431
+ const key = this.pool.keyFor(this.store, 'revs', blockId);
432
+ const base = ENTRY_BASE + key.length * CHAR_BYTES;
433
+ if (!this.pool.admits(base)) {
434
+ this.dropIfEmpty(blockId, s);
435
+ return undefined;
436
+ }
437
+ const entry: PoolEntry<RevMapState> = {
438
+ key, store: this.store, owner: this, cls: 'revs', blockId, actionId: undefined,
439
+ value: { byRev: new Map(), covered: [], gen: 0 }, base, charge: base, where: 'none',
440
+ };
441
+ s.revs = entry;
442
+ this.pool.admit(entry);
443
+ return entry;
444
+ }
445
+
446
+ async getRevision(blockId: BlockId, rev: number): Promise<Uint8Array | undefined> {
447
+ const entry = this.ensureRevs(blockId);
448
+ if (entry === undefined) return this.inner.getRevision(blockId, rev);
449
+ const revs = entry.value;
450
+ if (coversRange(revs.covered, rev, rev)) {
451
+ this.pool.touch(entry);
452
+ return revs.byRev.get(rev);
453
+ }
454
+ const bytes = await this.inner.getRevision(blockId, rev);
455
+ const current = this.blocks.get(blockId)?.revs;
456
+ if (current === entry && !coversRange(revs.covered, rev, rev)) {
457
+ let charge = entry.charge;
458
+ if (bytes !== undefined) {
459
+ revs.byRev.set(rev, bytes);
460
+ charge += REV_SLOT + bytes.length;
461
+ }
462
+ const before = revs.covered.length;
463
+ revs.covered = addCovered(revs.covered, rev, rev);
464
+ charge += (revs.covered.length - before) * INTERVAL_SLOT;
465
+ this.pool.updated(entry, charge);
466
+ }
467
+ return bytes;
468
+ }
469
+
470
+ async putRevision(blockId: BlockId, rev: number, value: Uint8Array): Promise<void> {
471
+ try {
472
+ await this.inner.putRevision(blockId, rev, value);
473
+ } catch (err) {
474
+ const s = this.blocks.get(blockId);
475
+ const entry = s?.revs;
476
+ if (s !== undefined && entry !== undefined) {
477
+ s.revs = undefined;
478
+ this.pool.drop(entry);
479
+ this.dropIfEmpty(blockId, s);
480
+ }
481
+ throw err;
482
+ }
483
+ const entry = this.ensureRevs(blockId);
484
+ if (entry === undefined) return;
485
+ const revs = entry.value;
486
+ const had = revs.byRev.get(rev);
487
+ revs.byRev.set(rev, value);
488
+ let charge = entry.charge + (had !== undefined ? value.length - had.length : REV_SLOT + value.length);
489
+ const before = revs.covered.length;
490
+ revs.covered = addCovered(revs.covered, rev, rev);
491
+ charge += (revs.covered.length - before) * INTERVAL_SLOT;
492
+ revs.gen++;
493
+ this.pool.updated(entry, charge);
494
+ }
495
+
496
+ async *rangeRevisions(blockId: BlockId, lo: number, hi: number, reverse: boolean): AsyncIterable<[number, Uint8Array]> {
497
+ const entry = this.ensureRevs(blockId);
498
+ if (entry === undefined) {
499
+ const drained: [number, Uint8Array][] = [];
500
+ for await (const item of this.inner.rangeRevisions(blockId, lo, hi, reverse)) {
501
+ drained.push(item);
502
+ }
503
+ yield* drained;
504
+ return;
505
+ }
506
+ const revs = entry.value;
507
+ if (coversRange(revs.covered, lo, hi)) {
508
+ this.pool.touch(entry);
509
+ // Snapshot before yielding (drain-before-yield): concurrent writes during the
510
+ // consumer's awaits must not mutate what this iteration yields.
511
+ // NOTE: this walks every integer in [lo, hi], not just the present revs — fine
512
+ // while revisions are dense (one per commit) and callers bound `hi` by a real
513
+ // `latest.rev`. If a sparse or very wide range ever appears here, iterate
514
+ // `byRev`'s keys sorted instead.
515
+ const out: [number, Uint8Array][] = [];
516
+ if (reverse) {
517
+ for (let rev = hi; rev >= lo; rev--) {
518
+ const bytes = revs.byRev.get(rev);
519
+ if (bytes !== undefined) out.push([rev, bytes]);
520
+ }
521
+ } else {
522
+ for (let rev = lo; rev <= hi; rev++) {
523
+ const bytes = revs.byRev.get(rev);
524
+ if (bytes !== undefined) out.push([rev, bytes]);
525
+ }
526
+ }
527
+ yield* out;
528
+ return;
529
+ }
530
+ const gen = revs.gen;
531
+ const drained: [number, Uint8Array][] = [];
532
+ for await (const item of this.inner.rangeRevisions(blockId, lo, hi, reverse)) {
533
+ drained.push(item);
534
+ }
535
+ // Claim coverage of [lo, hi] only if nothing mutated the map during the drain (gen
536
+ // unchanged, same entry — clear() and pool eviction both swap the entry). A write that
537
+ // landed mid-drain may be missing from `drained`, and recording coverage anyway would
538
+ // turn that miss into a provably-wrong "rev absent" answer forever after.
539
+ const current = this.blocks.get(blockId)?.revs;
540
+ if (current === entry && revs.gen === gen) {
541
+ let charge = entry.charge;
542
+ for (const [rev, bytes] of drained) {
543
+ const had = revs.byRev.get(rev);
544
+ revs.byRev.set(rev, bytes);
545
+ charge += had !== undefined ? bytes.length - had.length : REV_SLOT + bytes.length;
546
+ }
547
+ const before = revs.covered.length;
548
+ revs.covered = addCovered(revs.covered, lo, hi);
549
+ charge += (revs.covered.length - before) * INTERVAL_SLOT;
550
+ this.pool.updated(entry, charge);
551
+ }
552
+ yield* drained;
553
+ }
554
+
555
+ // --- pending ---
556
+
557
+ /** Same eager-admission shape (and bypass fallback) as {@link ensureRevs}, for the pending-id set. */
558
+ private ensurePendList(blockId: BlockId): PoolEntry<PendListState> | undefined {
559
+ const s = this.state(blockId);
560
+ if (s.pendList !== undefined) return s.pendList;
561
+ const key = this.pool.keyFor(this.store, 'pendList', blockId);
562
+ const base = ENTRY_BASE + key.length * CHAR_BYTES;
563
+ if (!this.pool.admits(base)) {
564
+ this.dropIfEmpty(blockId, s);
565
+ return undefined;
566
+ }
567
+ const entry: PoolEntry<PendListState> = {
568
+ key, store: this.store, owner: this, cls: 'pendList', blockId, actionId: undefined,
569
+ value: { ids: new Set(), complete: false, gen: 0 }, base, charge: base, where: 'none',
570
+ };
571
+ s.pendList = entry;
572
+ this.pool.admit(entry);
573
+ return entry;
574
+ }
575
+
576
+ /** Mirror a funnelled pend into the id set, if one is resident. Re-reads the entry — the write that preceded this call may have evicted it. */
577
+ private notePendListAdd(blockId: BlockId, actionId: ActionId): void {
578
+ const entry = this.blocks.get(blockId)?.pendList;
579
+ if (entry === undefined) return;
580
+ const list = entry.value;
581
+ let charge = entry.charge;
582
+ if (!list.ids.has(actionId)) {
583
+ list.ids.add(actionId);
584
+ charge += ID_SLOT + actionId.length * CHAR_BYTES;
585
+ }
586
+ list.gen++;
587
+ this.pool.updated(entry, charge);
588
+ }
589
+
590
+ private notePendListRemove(blockId: BlockId, actionId: ActionId): void {
591
+ const entry = this.blocks.get(blockId)?.pendList;
592
+ if (entry === undefined) return;
593
+ const list = entry.value;
594
+ let charge = entry.charge;
595
+ if (list.ids.delete(actionId)) {
596
+ charge -= ID_SLOT + actionId.length * CHAR_BYTES;
597
+ }
598
+ list.gen++;
599
+ this.pool.updated(entry, charge);
600
+ }
601
+
602
+ /** Failed pending write: the affected value entry AND the id set drop to unknown. */
603
+ private dropPendingState(blockId: BlockId, actionId: ActionId): void {
604
+ const s = this.blocks.get(blockId);
605
+ if (s === undefined) return;
606
+ const p = s.pending.get(actionId);
607
+ if (p !== undefined) {
608
+ s.pending.delete(actionId);
609
+ this.pool.drop(p);
610
+ }
611
+ const list = s.pendList;
612
+ if (list !== undefined) {
613
+ s.pendList = undefined;
614
+ this.pool.drop(list);
615
+ }
616
+ this.dropIfEmpty(blockId, s);
617
+ }
618
+
619
+ async getPending(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
620
+ const s = this.state(blockId);
621
+ const cached = s.pending.get(actionId);
622
+ if (cached !== undefined) {
623
+ this.pool.touch(cached);
624
+ return cached.value ?? undefined;
625
+ }
626
+ let bytes: Uint8Array | undefined;
627
+ try {
628
+ bytes = await this.inner.getPending(blockId, actionId);
629
+ } catch (err) {
630
+ this.reapOnThrow(blockId, s);
631
+ throw err;
632
+ }
633
+ this.fillMiss(blockId, s, s.pending, 'pending', actionId, bytes);
634
+ return bytes;
635
+ }
636
+
637
+ async putPending(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
638
+ try {
639
+ await this.inner.putPending(blockId, actionId, value);
640
+ } catch (err) {
641
+ this.dropPendingState(blockId, actionId);
642
+ throw err;
643
+ }
644
+ const s = this.state(blockId);
645
+ this.cachePoint(blockId, s, 'pending', actionId, value, s.pending.get(actionId),
646
+ e => s.pending.set(actionId, e), () => s.pending.delete(actionId));
647
+ this.notePendListAdd(blockId, actionId);
648
+ }
649
+
650
+ async deletePending(blockId: BlockId, actionId: ActionId): Promise<void> {
651
+ try {
652
+ await this.inner.deletePending(blockId, actionId);
653
+ } catch (err) {
654
+ this.dropPendingState(blockId, actionId);
655
+ throw err;
656
+ }
657
+ const s = this.state(blockId);
658
+ this.cachePoint(blockId, s, 'pending', actionId, null, s.pending.get(actionId),
659
+ e => s.pending.set(actionId, e), () => s.pending.delete(actionId));
660
+ this.notePendListRemove(blockId, actionId);
661
+ }
662
+
663
+ async *listPendingActionIds(blockId: BlockId): AsyncIterable<ActionId> {
664
+ const entry = this.ensurePendList(blockId);
665
+ if (entry === undefined) {
666
+ const drained: ActionId[] = [];
667
+ for await (const id of this.inner.listPendingActionIds(blockId)) {
668
+ drained.push(id);
669
+ }
670
+ yield* drained;
671
+ return;
672
+ }
673
+ const list = entry.value;
674
+ if (list.complete) {
675
+ this.pool.touch(entry);
676
+ yield* Array.from(list.ids);
677
+ return;
678
+ }
679
+ // One full enumeration seeds completeness; funnelled writes maintain it from then on.
680
+ // Completeness is NEVER inferred from metadata birth: at the raw layer a pending
681
+ // record CAN exist for a block with no metadata (the conformance suite writes exactly
682
+ // that), so only an actual drain of the inner driver proves the set.
683
+ const gen = list.gen;
684
+ const drained: ActionId[] = [];
685
+ for await (const id of this.inner.listPendingActionIds(blockId)) {
686
+ drained.push(id);
687
+ }
688
+ const current = this.blocks.get(blockId)?.pendList;
689
+ if (current === entry && list.gen === gen) {
690
+ let charge = entry.charge - idsContent(list.ids);
691
+ list.ids = new Set(drained);
692
+ list.complete = true;
693
+ charge += idsContent(list.ids);
694
+ this.pool.updated(entry, charge);
695
+ }
696
+ yield* drained;
697
+ }
698
+
699
+ // --- transactions ---
700
+
701
+ async getTransaction(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
702
+ const s = this.state(blockId);
703
+ const cached = s.transactions.get(actionId);
704
+ if (cached !== undefined) {
705
+ this.pool.touch(cached);
706
+ return cached.value ?? undefined;
707
+ }
708
+ let bytes: Uint8Array | undefined;
709
+ try {
710
+ bytes = await this.inner.getTransaction(blockId, actionId);
711
+ } catch (err) {
712
+ this.reapOnThrow(blockId, s);
713
+ throw err;
714
+ }
715
+ this.fillMiss(blockId, s, s.transactions, 'tx', actionId, bytes);
716
+ return bytes;
717
+ }
718
+
719
+ async putTransaction(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
720
+ try {
721
+ await this.inner.putTransaction(blockId, actionId, value);
722
+ } catch (err) {
723
+ this.dropMapEntry(blockId, 'transactions', actionId);
724
+ throw err;
725
+ }
726
+ const s = this.state(blockId);
727
+ this.cachePoint(blockId, s, 'tx', actionId, value, s.transactions.get(actionId),
728
+ e => s.transactions.set(actionId, e), () => s.transactions.delete(actionId));
729
+ }
730
+
731
+ // --- materialized ---
732
+
733
+ async getMaterialized(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
734
+ const s = this.state(blockId);
735
+ const cached = s.materialized.get(actionId);
736
+ if (cached !== undefined) {
737
+ this.pool.touch(cached);
738
+ return cached.value ?? undefined;
739
+ }
740
+ let bytes: Uint8Array | undefined;
741
+ try {
742
+ bytes = await this.inner.getMaterialized(blockId, actionId);
743
+ } catch (err) {
744
+ this.reapOnThrow(blockId, s);
745
+ throw err;
746
+ }
747
+ this.fillMiss(blockId, s, s.materialized, 'mat', actionId, bytes);
748
+ return bytes;
749
+ }
750
+
751
+ async putMaterialized(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
752
+ try {
753
+ await this.inner.putMaterialized(blockId, actionId, value);
754
+ } catch (err) {
755
+ this.dropMapEntry(blockId, 'materialized', actionId);
756
+ throw err;
757
+ }
758
+ const s = this.state(blockId);
759
+ this.cachePoint(blockId, s, 'mat', actionId, value, s.materialized.get(actionId),
760
+ e => s.materialized.set(actionId, e), () => s.materialized.delete(actionId));
761
+ }
762
+
763
+ async deleteMaterialized(blockId: BlockId, actionId: ActionId): Promise<void> {
764
+ try {
765
+ await this.inner.deleteMaterialized(blockId, actionId);
766
+ } catch (err) {
767
+ this.dropMapEntry(blockId, 'materialized', actionId);
768
+ throw err;
769
+ }
770
+ // A delete through the funnel is a PROVEN absence, not an unknown.
771
+ const s = this.state(blockId);
772
+ this.cachePoint(blockId, s, 'mat', actionId, null, s.materialized.get(actionId),
773
+ e => s.materialized.set(actionId, e), () => s.materialized.delete(actionId));
774
+ }
775
+
776
+ /** Error-path invalidation of one map-backed entry (write failed → unknown). */
777
+ private dropMapEntry(blockId: BlockId, which: 'transactions' | 'materialized', actionId: ActionId): void {
778
+ const s = this.blocks.get(blockId);
779
+ if (s === undefined) return;
780
+ const map = s[which];
781
+ const e = map.get(actionId);
782
+ if (e !== undefined) {
783
+ map.delete(actionId);
784
+ this.pool.drop(e);
785
+ this.dropIfEmpty(blockId, s);
786
+ }
787
+ }
788
+
789
+ // --- promote (the single hardest coherence point — see "Invariant P" on
790
+ // `IBlockStorage.promotePendingTransaction`, src/storage/i-block-storage.ts) ---
791
+
792
+ /**
793
+ * The inner driver performs the atomic pending → committed move; this wrapper then mirrors
794
+ * it as one synchronous cache mutation sequence. When the pending transform was never
795
+ * cached — pended before this wrapper attached, or its entry EVICTED by the pool — the
796
+ * committed entry is INVALIDATED rather than synthesized: fabricating it would recreate
797
+ * exactly the phantom-record class Invariant P exists to prevent. Invalidation also
798
+ * removes any cached negative for the committed entry, which the promote has just made
799
+ * stale.
800
+ *
801
+ * Eviction landing between the three coupled mutations is safe by construction: the inner
802
+ * atomic move has already resolved before the first cache mutation, so each of the three
803
+ * entries (pending value, pending-id set, committed value) steps from one individually
804
+ * coherent state to another — an eviction merely turns one of those steps into "unknown,
805
+ * fall through", never into a fabricated value.
806
+ */
807
+ async promote(blockId: BlockId, actionId: ActionId): Promise<void> {
808
+ try {
809
+ await this.inner.promote(blockId, actionId);
810
+ } catch (err) {
811
+ // On the contract's missing-pend throw the inner state is unchanged, but the throw
812
+ // may also be a mid-operation fault whose outcome is unknown ("exactly one of the
813
+ // two states") — drop all three affected entries to unknown rather than guess.
814
+ const s = this.blocks.get(blockId);
815
+ if (s !== undefined) {
816
+ const p = s.pending.get(actionId);
817
+ if (p !== undefined) {
818
+ s.pending.delete(actionId);
819
+ this.pool.drop(p);
820
+ }
821
+ const t = s.transactions.get(actionId);
822
+ if (t !== undefined) {
823
+ s.transactions.delete(actionId);
824
+ this.pool.drop(t);
825
+ }
826
+ const list = s.pendList;
827
+ if (list !== undefined) {
828
+ s.pendList = undefined;
829
+ this.pool.drop(list);
830
+ }
831
+ this.dropIfEmpty(blockId, s);
832
+ }
833
+ throw err;
834
+ }
835
+ const s = this.state(blockId);
836
+ const pendingBytes = s.pending.get(actionId)?.value;
837
+ this.cachePoint(blockId, s, 'pending', actionId, null, s.pending.get(actionId),
838
+ e => s.pending.set(actionId, e), () => s.pending.delete(actionId));
839
+ this.notePendListRemove(blockId, actionId);
840
+ if (pendingBytes instanceof Uint8Array) {
841
+ // The block state may have been reaped by an eviction the mutations above caused;
842
+ // re-fetch (or re-create) it before installing the committed value.
843
+ const s2 = this.blocks.get(blockId) ?? this.state(blockId);
844
+ this.cachePoint(blockId, s2, 'tx', actionId, pendingBytes, s2.transactions.get(actionId),
845
+ e => s2.transactions.set(actionId, e), () => s2.transactions.delete(actionId));
846
+ } else {
847
+ // Unknown (never observed, or evicted) — or a cached negative that promote just
848
+ // contradicted, which the funnel makes unreachable but is handled identically for
849
+ // safety. Invalidate; never synthesize.
850
+ this.dropMapEntry(blockId, 'transactions', actionId);
851
+ }
852
+ }
853
+ }
854
+
855
+ function evictFromMap(map: Map<ActionId, PoolEntry<CachedBytes>>, entry: PoolEntry): void {
856
+ if (entry.actionId !== undefined && map.get(entry.actionId) === entry) {
857
+ map.delete(entry.actionId);
858
+ }
859
+ }