@optimystic/db-p2p 0.21.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 (219) 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-policy.d.ts +13 -2
  6. package/dist/src/cluster/cluster-policy.d.ts.map +1 -1
  7. package/dist/src/cluster/cluster-policy.js +51 -4
  8. package/dist/src/cluster/cluster-policy.js.map +1 -1
  9. package/dist/src/cluster/cluster-repo.d.ts +42 -17
  10. package/dist/src/cluster/cluster-repo.d.ts.map +1 -1
  11. package/dist/src/cluster/cluster-repo.js +229 -122
  12. package/dist/src/cluster/cluster-repo.js.map +1 -1
  13. package/dist/src/cluster/cluster-size-coupling.d.ts +28 -0
  14. package/dist/src/cluster/cluster-size-coupling.d.ts.map +1 -0
  15. package/dist/src/cluster/cluster-size-coupling.js +35 -0
  16. package/dist/src/cluster/cluster-size-coupling.js.map +1 -0
  17. package/dist/src/cluster/quorum-restore.d.ts +6 -0
  18. package/dist/src/cluster/quorum-restore.d.ts.map +1 -1
  19. package/dist/src/cluster/quorum-restore.js +1 -1
  20. package/dist/src/cluster/quorum-restore.js.map +1 -1
  21. package/dist/src/cluster/reconcile-block.d.ts.map +1 -1
  22. package/dist/src/cluster/reconcile-block.js +15 -3
  23. package/dist/src/cluster/reconcile-block.js.map +1 -1
  24. package/dist/src/cluster/service.d.ts +32 -1
  25. package/dist/src/cluster/service.d.ts.map +1 -1
  26. package/dist/src/cluster/service.js +43 -2
  27. package/dist/src/cluster/service.js.map +1 -1
  28. package/dist/src/cohort-topic/stream-util.d.ts +22 -6
  29. package/dist/src/cohort-topic/stream-util.d.ts.map +1 -1
  30. package/dist/src/cohort-topic/stream-util.js +56 -10
  31. package/dist/src/cohort-topic/stream-util.js.map +1 -1
  32. package/dist/src/dispute/dispute-service.d.ts.map +1 -1
  33. package/dist/src/dispute/dispute-service.js +9 -3
  34. package/dist/src/dispute/dispute-service.js.map +1 -1
  35. package/dist/src/index.d.ts +5 -0
  36. package/dist/src/index.d.ts.map +1 -1
  37. package/dist/src/index.js +5 -0
  38. package/dist/src/index.js.map +1 -1
  39. package/dist/src/libp2p-key-network.d.ts +134 -7
  40. package/dist/src/libp2p-key-network.d.ts.map +1 -1
  41. package/dist/src/libp2p-key-network.js +174 -37
  42. package/dist/src/libp2p-key-network.js.map +1 -1
  43. package/dist/src/libp2p-node-base.d.ts +3 -2
  44. package/dist/src/libp2p-node-base.d.ts.map +1 -1
  45. package/dist/src/libp2p-node-base.js +859 -778
  46. package/dist/src/libp2p-node-base.js.map +1 -1
  47. package/dist/src/libp2p-node-rn.d.ts +2 -2
  48. package/dist/src/libp2p-node-rn.d.ts.map +1 -1
  49. package/dist/src/libp2p-node-rn.js.map +1 -1
  50. package/dist/src/libp2p-node.d.ts +2 -2
  51. package/dist/src/libp2p-node.d.ts.map +1 -1
  52. package/dist/src/libp2p-node.js.map +1 -1
  53. package/dist/src/logger.d.ts +17 -1
  54. package/dist/src/logger.d.ts.map +1 -1
  55. package/dist/src/logger.js +19 -2
  56. package/dist/src/logger.js.map +1 -1
  57. package/dist/src/network/network-manager-service.d.ts +2 -0
  58. package/dist/src/network/network-manager-service.d.ts.map +1 -1
  59. package/dist/src/network/network-manager-service.js +4 -0
  60. package/dist/src/network/network-manager-service.js.map +1 -1
  61. package/dist/src/optimystic-node.d.ts +35 -0
  62. package/dist/src/optimystic-node.d.ts.map +1 -0
  63. package/dist/src/optimystic-node.js +2 -0
  64. package/dist/src/optimystic-node.js.map +1 -0
  65. package/dist/src/owned-block-seed.d.ts +6 -3
  66. package/dist/src/owned-block-seed.d.ts.map +1 -1
  67. package/dist/src/owned-block-seed.js +16 -3
  68. package/dist/src/owned-block-seed.js.map +1 -1
  69. package/dist/src/peer-address-book.d.ts +72 -0
  70. package/dist/src/peer-address-book.d.ts.map +1 -0
  71. package/dist/src/peer-address-book.js +123 -0
  72. package/dist/src/peer-address-book.js.map +1 -0
  73. package/dist/src/repo/client.d.ts.map +1 -1
  74. package/dist/src/repo/client.js +11 -2
  75. package/dist/src/repo/client.js.map +1 -1
  76. package/dist/src/repo/cluster-coordinator.d.ts +30 -0
  77. package/dist/src/repo/cluster-coordinator.d.ts.map +1 -1
  78. package/dist/src/repo/cluster-coordinator.js +95 -3
  79. package/dist/src/repo/cluster-coordinator.js.map +1 -1
  80. package/dist/src/repo/coordinator-repo.d.ts +78 -14
  81. package/dist/src/repo/coordinator-repo.d.ts.map +1 -1
  82. package/dist/src/repo/coordinator-repo.js +266 -81
  83. package/dist/src/repo/coordinator-repo.js.map +1 -1
  84. package/dist/src/rn.d.ts +5 -0
  85. package/dist/src/rn.d.ts.map +1 -1
  86. package/dist/src/rn.js +5 -0
  87. package/dist/src/rn.js.map +1 -1
  88. package/dist/src/storage/block-storage.d.ts.map +1 -1
  89. package/dist/src/storage/block-storage.js +57 -5
  90. package/dist/src/storage/block-storage.js.map +1 -1
  91. package/dist/src/storage/cached-raw-storage.d.ts +83 -0
  92. package/dist/src/storage/cached-raw-storage.d.ts.map +1 -0
  93. package/dist/src/storage/cached-raw-storage.js +152 -0
  94. package/dist/src/storage/cached-raw-storage.js.map +1 -0
  95. package/dist/src/storage/cached-store-driver.d.ts +186 -0
  96. package/dist/src/storage/cached-store-driver.d.ts.map +1 -0
  97. package/dist/src/storage/cached-store-driver.js +775 -0
  98. package/dist/src/storage/cached-store-driver.js.map +1 -0
  99. package/dist/src/storage/i-block-storage.d.ts +20 -1
  100. package/dist/src/storage/i-block-storage.d.ts.map +1 -1
  101. package/dist/src/storage/i-raw-storage.d.ts +12 -5
  102. package/dist/src/storage/i-raw-storage.d.ts.map +1 -1
  103. package/dist/src/storage/shared-cache-pool.d.ts +234 -0
  104. package/dist/src/storage/shared-cache-pool.d.ts.map +1 -0
  105. package/dist/src/storage/shared-cache-pool.js +354 -0
  106. package/dist/src/storage/shared-cache-pool.js.map +1 -0
  107. package/dist/src/storage/storage-repo.d.ts +56 -3
  108. package/dist/src/storage/storage-repo.d.ts.map +1 -1
  109. package/dist/src/storage/storage-repo.js +124 -18
  110. package/dist/src/storage/storage-repo.js.map +1 -1
  111. package/dist/src/testing/raw-storage-conformance.d.ts +2 -1
  112. package/dist/src/testing/raw-storage-conformance.d.ts.map +1 -1
  113. package/dist/src/testing/raw-storage-conformance.js +52 -2
  114. package/dist/src/testing/raw-storage-conformance.js.map +1 -1
  115. package/package.json +3 -3
  116. package/readme.md +668 -653
  117. package/src/cluster/block-transfer.ts +424 -424
  118. package/src/cluster/client.ts +119 -88
  119. package/src/cluster/cluster-error.ts +64 -64
  120. package/src/cluster/cluster-policy.ts +203 -152
  121. package/src/cluster/cluster-repo.ts +245 -125
  122. package/src/cluster/cluster-size-coupling.ts +45 -0
  123. package/src/cluster/commit-cert.ts +139 -139
  124. package/src/cluster/i-transaction-state-store.ts +43 -43
  125. package/src/cluster/memory-transaction-state-store.ts +56 -56
  126. package/src/cluster/peer-key-binding.ts +37 -37
  127. package/src/cluster/persistent-transaction-state-store.ts +92 -92
  128. package/src/cluster/quorum-restore.ts +223 -223
  129. package/src/cluster/reconcile-block.ts +203 -191
  130. package/src/cluster/service.ts +293 -241
  131. package/src/cluster/supermajority-coupling.ts +37 -37
  132. package/src/cohort-topic/bootstrap-evidence-builder.ts +122 -122
  133. package/src/cohort-topic/bootstrap-evidence-verifiers.ts +132 -132
  134. package/src/cohort-topic/bootstrap-parent-reference.ts +159 -159
  135. package/src/cohort-topic/change-bridge.ts +109 -109
  136. package/src/cohort-topic/cohort-gossip-driver.ts +231 -231
  137. package/src/cohort-topic/cohort-gossip-transport.ts +84 -84
  138. package/src/cohort-topic/fret-trust-anchor.ts +153 -153
  139. package/src/cohort-topic/host.ts +2901 -2901
  140. package/src/cohort-topic/index.ts +13 -13
  141. package/src/cohort-topic/membership-publish-sink.ts +20 -20
  142. package/src/cohort-topic/membership-source.ts +68 -68
  143. package/src/cohort-topic/peer-codec.ts +31 -31
  144. package/src/cohort-topic/peer-sig.ts +86 -86
  145. package/src/cohort-topic/protocols.ts +71 -71
  146. package/src/cohort-topic/reactivity-membership-gate.ts +77 -77
  147. package/src/cohort-topic/size-estimator.ts +16 -16
  148. package/src/cohort-topic/stream-util.ts +135 -87
  149. package/src/cohort-topic/threshold-crypto.ts +239 -239
  150. package/src/cohort-topic/topic-router.ts +77 -77
  151. package/src/dispute/arbitrator-selection.ts +138 -138
  152. package/src/dispute/cascade.ts +524 -524
  153. package/src/dispute/dispute-service.ts +11 -5
  154. package/src/dispute/invalidation.ts +625 -625
  155. package/src/inbound-authorization.ts +190 -190
  156. package/src/index.ts +52 -47
  157. package/src/libp2p-key-network.ts +1120 -958
  158. package/src/libp2p-node-base.ts +1675 -1591
  159. package/src/libp2p-node-rn.ts +30 -30
  160. package/src/libp2p-node.ts +36 -36
  161. package/src/logger.ts +19 -2
  162. package/src/matchmaking/aggregate-counts.ts +104 -104
  163. package/src/matchmaking/index.ts +20 -20
  164. package/src/matchmaking/module.ts +363 -363
  165. package/src/matchmaking/protocols.ts +51 -51
  166. package/src/matchmaking/provider-manager.ts +95 -95
  167. package/src/matchmaking/query-handler.ts +88 -88
  168. package/src/matchmaking/query-transport.ts +492 -492
  169. package/src/matchmaking/seeker-manager.ts +64 -64
  170. package/src/matchmaking/seeker-walk-client.ts +293 -293
  171. package/src/matchmaking/traffic-validation.ts +195 -195
  172. package/src/network/network-manager-service.ts +5 -0
  173. package/src/optimystic-node.ts +36 -0
  174. package/src/owned-block-seed.ts +53 -40
  175. package/src/peer-address-book.ts +149 -0
  176. package/src/protocol-limits.ts +33 -33
  177. package/src/reactivity/forwarder-host.ts +438 -438
  178. package/src/reactivity/index.ts +19 -19
  179. package/src/reactivity/notify-transport.ts +144 -144
  180. package/src/reactivity/origination-manager.ts +192 -192
  181. package/src/reactivity/protocols.ts +61 -61
  182. package/src/reactivity/push-state-gossip.ts +291 -291
  183. package/src/reactivity/recover-transport.ts +408 -408
  184. package/src/reactivity/rotation-rereg-scheduler.ts +256 -256
  185. package/src/reactivity/subscriber-registry.ts +96 -96
  186. package/src/reactivity/subscription-manager.ts +450 -450
  187. package/src/reactivity/topic-bytes.ts +37 -37
  188. package/src/repo/client.ts +12 -2
  189. package/src/repo/cluster-coordinator.ts +99 -3
  190. package/src/repo/coordinator-repo.ts +305 -82
  191. package/src/repo/types.ts +7 -7
  192. package/src/rn.ts +39 -34
  193. package/src/rpc-deadline.ts +45 -45
  194. package/src/storage/arachnode-partition.ts +74 -74
  195. package/src/storage/block-storage.ts +59 -6
  196. package/src/storage/cached-raw-storage.ts +180 -0
  197. package/src/storage/cached-store-driver.ts +859 -0
  198. package/src/storage/i-block-storage.ts +20 -1
  199. package/src/storage/i-kv-store.ts +8 -8
  200. package/src/storage/i-raw-storage.ts +12 -5
  201. package/src/storage/kv-raw-storage.ts +135 -135
  202. package/src/storage/memory-kv-store.ts +28 -28
  203. package/src/storage/memory-storage.ts +25 -25
  204. package/src/storage/memory-store-driver.ts +157 -157
  205. package/src/storage/raw-store-codec.ts +42 -42
  206. package/src/storage/raw-store-driver.ts +80 -80
  207. package/src/storage/ring-selector.ts +317 -317
  208. package/src/storage/ring-shift-coordinator.ts +271 -271
  209. package/src/storage/shared-cache-pool.ts +452 -0
  210. package/src/storage/storage-repo.ts +1014 -903
  211. package/src/testing/cohort-topic-mesh-harness.ts +663 -663
  212. package/src/testing/index.ts +8 -8
  213. package/src/testing/matchmaking-mesh-harness.ts +475 -475
  214. package/src/testing/raw-storage-conformance.ts +453 -397
  215. package/src/testing/reactivity-mesh-harness.ts +922 -922
  216. package/dist/src/storage/restoration-coordinator-v2.d.ts +0 -67
  217. package/dist/src/storage/restoration-coordinator-v2.d.ts.map +0 -1
  218. package/dist/src/storage/restoration-coordinator-v2.js +0 -172
  219. package/dist/src/storage/restoration-coordinator-v2.js.map +0 -1
@@ -0,0 +1,452 @@
1
+ import type { BlockId, ActionId } from "@optimystic/db-core";
2
+
3
+ /**
4
+ * Which of the cache's entry classes a pool entry belongs to. Mirrors the sub-states of
5
+ * `CachedStoreDriver`'s per-block cache state; the pool itself never branches on the class —
6
+ * it exists so the owning store can locate the entry's home when the pool evicts it.
7
+ */
8
+ export type CacheEntryClass = 'meta' | 'revs' | 'pendList' | 'pending' | 'tx' | 'mat';
9
+
10
+ /**
11
+ * The owner side of the eviction contract. When the pool evicts an entry it calls
12
+ * `onPoolEvict` exactly once; the owner must remove its own reference to the entry (and only
13
+ * that) so the evicted value becomes unreachable. The callback runs synchronously inside a
14
+ * pool mutation and MUST NOT call back into any pool method — the pool's accounting is
15
+ * mid-update when it fires.
16
+ */
17
+ export interface PoolEntryOwner {
18
+ onPoolEvict(entry: PoolEntry): void;
19
+ }
20
+
21
+ /**
22
+ * One cached value's residency record: simultaneously the value holder the owning store's
23
+ * maps point at, and the node the pool's queues link. Owners create these as plain object
24
+ * literals (`where: 'none'`), install the reference in their own state FIRST, and then call
25
+ * {@link SharedCachePool.admit} — that order guarantees evictions triggered by the admission
26
+ * can never observe the owner's block state as empty while the new entry is in flight.
27
+ *
28
+ * `charge` is the entry's whole budget cost: `base` (fixed bookkeeping — entry object, owner
29
+ * map slot, queue slot, key string) plus the owner-computed content bytes. Negatives and
30
+ * empty container states therefore still cost `base`, which is what keeps a remote probe
31
+ * stream of nonexistent keys inside the budget instead of growing bookkeeping for free.
32
+ */
33
+ export interface PoolEntry<V = unknown> {
34
+ readonly key: string;
35
+ readonly store: CacheStoreHandle;
36
+ readonly owner: PoolEntryOwner;
37
+ readonly cls: CacheEntryClass;
38
+ readonly blockId: BlockId;
39
+ readonly actionId: ActionId | undefined;
40
+ value: V;
41
+ /** Fixed bookkeeping charge (entry + map slots + key string); never changes. */
42
+ readonly base: number;
43
+ /** Total budgeted bytes: `base` + content. Managed via {@link SharedCachePool.updated}. */
44
+ charge: number;
45
+ /** Which queue currently holds the entry; `'none'` = not resident. Pool-managed. */
46
+ where: 'a1in' | 'am' | 'none';
47
+ }
48
+
49
+ /**
50
+ * A store's registration with the pool. `id` is process-unique and never reused (monotonic
51
+ * counter), so entries and ghost keys of a departed store can never alias a later one.
52
+ * `bytes`/`entries` are live occupancy, maintained by the pool — read-only for callers.
53
+ */
54
+ export class CacheStoreHandle {
55
+ bytes = 0;
56
+ entries = 0;
57
+ constructor(
58
+ readonly id: string,
59
+ readonly label: string | undefined,
60
+ ) {}
61
+ }
62
+
63
+ export interface CachePoolStats {
64
+ maxBytes: number;
65
+ maxEntries: number;
66
+ bytes: number;
67
+ entries: number;
68
+ a1in: { bytes: number; entries: number };
69
+ am: { bytes: number; entries: number };
70
+ /** Ghost (A1out) key count. Ghost keys are bookkeeping outside the byte budget, bounded by their own cap. */
71
+ ghostKeys: number;
72
+ hits: number;
73
+ admissions: number;
74
+ /** Admissions that went straight to Am because the key was in the ghost set (the 2Q reuse signal). */
75
+ ghostHits: number;
76
+ evictions: number;
77
+ bypasses: number;
78
+ stores: { id: string; label: string | undefined; bytes: number; entries: number }[];
79
+ }
80
+
81
+ export interface SharedCachePoolOptions {
82
+ /** Byte budget for all resident entries across all registered stores. Default is per-platform (see {@link defaultCachePool}). */
83
+ maxBytes?: number;
84
+ /** Entry-count secondary rail (guards the many-tiny-entries case). Default `max(16, maxBytes / 512)`. */
85
+ maxEntries?: number;
86
+ /**
87
+ * `'2q'` (default): Johnson & Shasha 2Q — A1in probation FIFO at ~25% of EACH budget rail
88
+ * (bytes and entries), A1out ghost keys at ~50% of the entry cap, Am protected LRU.
89
+ * `'lru'`: a plain shared LRU
90
+ * with no admission control — kept ONLY as the comparison baseline for measuring whether
91
+ * 2Q's pollution resistance earns its complexity (see the pool spec's measurement test).
92
+ */
93
+ admission?: '2q' | 'lru';
94
+ }
95
+
96
+ /**
97
+ * Separator for pool keys: NUL, spelled as an escape so this file stays plain text — a literal
98
+ * NUL byte in the source makes the whole file binary to git (no diff, no blame, no review).
99
+ * NUL is the one character no id can carry: block ids are user-supplied collection URI paths
100
+ * (which may well contain spaces) and action ids are base64url with an optional `tx:`/`stamp:`
101
+ * prefix, so `(storeId, class, blockId, actionId?)` always splits back unambiguously.
102
+ */
103
+ const SEP = '\u0000';
104
+
105
+ /**
106
+ * A shared, bounded, clean-value cache pool: one per process (see {@link defaultCachePool}),
107
+ * shared by every `CachedStoreDriver` so that N stores compete inside ONE memory budget
108
+ * instead of keeping N unbounded caches. The pool owns residency and eviction only; all
109
+ * cache *semantics* (coherence, negatives, completeness) stay in the owning store.
110
+ *
111
+ * **Always evict, never refuse, never grow unbounded.** Entries are never pinned and never
112
+ * dirty (the cache is write-through; see `CachedStoreDriver`), so eviction is always safe
113
+ * and there is no exhaustion condition to raise. At the bound the pool evicts; the one entry
114
+ * class that can grow while resident (a store's revision map) is simply evicted like any
115
+ * other when its growth pushes the pool over budget.
116
+ *
117
+ * **2Q admission** (default): a first-touch entry enters the A1in probation FIFO; re-hits
118
+ * inside A1in do NOT promote (FIFO order stands, which is also what absorbs the several
119
+ * correlated touches one logical operation makes); eviction from A1in demotes the key to
120
+ * the A1out ghost set; a later admission of a ghosted key — reuse across operations — goes
121
+ * straight to the protected Am LRU. Am evictions do NOT ghost. One-pass bulk scans
122
+ * therefore live and die inside A1in without displacing any store's hot Am set.
123
+ *
124
+ * **Large values bypass**: an entry whose charge exceeds 1/16 of the byte budget is not
125
+ * admitted at all (the owner reads/writes through), so one oversized value cannot flush
126
+ * the pool.
127
+ *
128
+ * **Budget sanity**: `maxBytes`/`maxEntries` must be positive finite numbers — anything else
129
+ * throws. Absurdly small values are accepted as-is: they cannot break coherence (the owning
130
+ * cache is correct at any residency, including zero), they just degrade toward read-through.
131
+ *
132
+ * Not safe for use from multiple threads; like the caches it serves, it relies on JS
133
+ * single-threaded execution — every mutation completes synchronously.
134
+ */
135
+ export class SharedCachePool {
136
+ private maxBytesValue: number;
137
+ private maxEntriesValue: number;
138
+ private readonly admission: '2q' | 'lru';
139
+ private bypassLimit = 0;
140
+ private a1inTargetBytes = 0;
141
+ private a1inTargetEntries = 0;
142
+ private ghostCap = 0;
143
+
144
+ private readonly a1in = new Map<string, PoolEntry>();
145
+ private readonly am = new Map<string, PoolEntry>();
146
+ private readonly ghost = new Set<string>();
147
+ private a1inBytes = 0;
148
+
149
+ private bytesTotal = 0;
150
+ private entriesTotal = 0;
151
+ private storeCounter = 0;
152
+ private readonly stores = new Map<string, CacheStoreHandle>();
153
+
154
+ private hits = 0;
155
+ private admissions = 0;
156
+ private ghostHits = 0;
157
+ private evictions = 0;
158
+ private bypasses = 0;
159
+
160
+ constructor(options?: SharedCachePoolOptions) {
161
+ this.admission = options?.admission ?? '2q';
162
+ this.maxBytesValue = validateBound('maxBytes', options?.maxBytes ?? platformDefaultBytes());
163
+ this.maxEntriesValue = validateBound('maxEntries',
164
+ options?.maxEntries ?? Math.max(16, Math.floor(this.maxBytesValue / 512)));
165
+ this.recomputeDerived();
166
+ }
167
+
168
+ get maxBytes(): number { return this.maxBytesValue; }
169
+ get maxEntries(): number { return this.maxEntriesValue; }
170
+ get bytes(): number { return this.bytesTotal; }
171
+ get entries(): number { return this.entriesTotal; }
172
+
173
+ /**
174
+ * Re-budget a live pool (e.g. host config change, or a host correcting the platform
175
+ * default). Shrinking evicts immediately down to the new bound.
176
+ */
177
+ setBudget(budget: { maxBytes?: number; maxEntries?: number }): void {
178
+ if (budget.maxBytes !== undefined) {
179
+ this.maxBytesValue = validateBound('maxBytes', budget.maxBytes);
180
+ }
181
+ if (budget.maxEntries !== undefined) {
182
+ this.maxEntriesValue = validateBound('maxEntries', budget.maxEntries);
183
+ }
184
+ this.recomputeDerived();
185
+ this.evictToFit(0, 0);
186
+ this.trimGhost();
187
+ }
188
+
189
+ /** Register a store. The returned handle's `id` is unique for the pool's lifetime — never reused. */
190
+ registerStore(label?: string): CacheStoreHandle {
191
+ const handle = new CacheStoreHandle(`s${++this.storeCounter}`, label);
192
+ this.stores.set(handle.id, handle);
193
+ return handle;
194
+ }
195
+
196
+ /**
197
+ * Release a departing store: evict any of its entries still resident (defensively — the
198
+ * owner normally clears first), purge its ghost keys, and remove it from the registry.
199
+ * Idempotent. This forced removal notifies the owner like any other eviction — `drop` here
200
+ * would de-account entries the owner still references, leaving it serving values the pool
201
+ * no longer counts. It does NOT ghost (the ghosts are being purged anyway) and does NOT
202
+ * count as a budget eviction: it is a lifecycle release, not memory pressure.
203
+ */
204
+ unregisterStore(handle: CacheStoreHandle): void {
205
+ for (const queue of [this.a1in, this.am]) {
206
+ for (const entry of [...queue.values()]) {
207
+ if (entry.store !== handle) continue;
208
+ this.unlink(entry);
209
+ entry.owner.onPoolEvict(entry);
210
+ }
211
+ }
212
+ this.purgeGhosts(handle);
213
+ this.stores.delete(handle.id);
214
+ }
215
+
216
+ /** Drop every ghost key belonging to `handle` (used by store clear/close — pre-clear recency must not survive the clear). */
217
+ purgeGhosts(handle: CacheStoreHandle): void {
218
+ const prefix = handle.id + SEP;
219
+ for (const key of [...this.ghost]) {
220
+ if (key.startsWith(prefix)) this.ghost.delete(key);
221
+ }
222
+ }
223
+
224
+ /** Build the pool key for an entry. Store-id first: keying by block id alone would alias name-derived header block ids across stores. */
225
+ keyFor(store: CacheStoreHandle, cls: CacheEntryClass, blockId: BlockId, actionId?: ActionId): string {
226
+ return actionId === undefined
227
+ ? store.id + SEP + cls + SEP + blockId
228
+ : store.id + SEP + cls + SEP + blockId + SEP + actionId;
229
+ }
230
+
231
+ /**
232
+ * Would an entry of this total charge be admitted? `false` = large-value bypass (counted);
233
+ * the owner must then read/write through without caching. Also the gate for value
234
+ * *updates*: an update growing past the limit should drop the entry instead.
235
+ */
236
+ admits(charge: number): boolean {
237
+ if (charge > this.bypassLimit) {
238
+ this.bypasses++;
239
+ return false;
240
+ }
241
+ return true;
242
+ }
243
+
244
+ /**
245
+ * Admit a non-resident entry the owner has ALREADY installed in its own state. Evicts
246
+ * first (so the incoming entry can never be its own victim), then links: to Am when the
247
+ * key is in the ghost set (2Q reuse signal), to A1in probation otherwise.
248
+ */
249
+ admit(entry: PoolEntry): void {
250
+ if (entry.where !== 'none') {
251
+ throw new Error(`pool admit of already-resident entry ${entry.key}`);
252
+ }
253
+ this.evictToFit(entry.charge, 1);
254
+ this.admissions++;
255
+ if (this.admission === 'lru') {
256
+ this.link(entry, 'am');
257
+ return;
258
+ }
259
+ if (this.ghost.delete(entry.key)) {
260
+ this.ghostHits++;
261
+ this.link(entry, 'am');
262
+ } else {
263
+ this.link(entry, 'a1in');
264
+ }
265
+ }
266
+
267
+ /** Record a read hit: Am refreshes to MRU; A1in stays put (FIFO — no intra-probation promotion). */
268
+ touch(entry: PoolEntry): void {
269
+ this.hits++;
270
+ this.refresh(entry);
271
+ }
272
+
273
+ /**
274
+ * Re-account a resident entry after the owner mutated its value (write hit, or container
275
+ * growth like a revision-map fill). Queue position refreshes like a touch (without
276
+ * counting a hit); growth over budget evicts — possibly the updated entry itself, which
277
+ * is why owners call this LAST and never touch their cache state after.
278
+ *
279
+ * NOTE: growth here is NOT re-checked against {@link admits}' large-value bypass, so a
280
+ * container entry (a block's revision map or pending-id set) can grow past 1/16 of the
281
+ * budget and squat where a single oversized value would have been refused. Bounded and
282
+ * self-correcting today: an over-share entry keeps `a1inBytes` above its target, so
283
+ * probation evicts it preferentially, and anything past `maxBytes` is evicted outright.
284
+ * If a block ever accumulates enough revisions for one map to hold a real fraction of the
285
+ * budget (order 20k revs at the 32 MB Node default), gate growth on `admits(charge)` in
286
+ * the owner's revision/pending-list paths and drop the entry when it fails, exactly as
287
+ * `CachedStoreDriver.cachePoint` already does for point values.
288
+ */
289
+ updated(entry: PoolEntry, newCharge: number): void {
290
+ if (entry.where === 'none') return;
291
+ const delta = newCharge - entry.charge;
292
+ entry.charge = newCharge;
293
+ this.bytesTotal += delta;
294
+ entry.store.bytes += delta;
295
+ if (entry.where === 'a1in') this.a1inBytes += delta;
296
+ this.refresh(entry);
297
+ if (delta > 0) this.evictToFit(0, 0);
298
+ }
299
+
300
+ /**
301
+ * Remove an entry WITHOUT the eviction callback — for owners invalidating or clearing
302
+ * their own entries (the owner is already removing its reference). Never ghosts: an
303
+ * invalidation says nothing about reuse. No-op if not resident.
304
+ */
305
+ drop(entry: PoolEntry): void {
306
+ if (entry.where === 'none') return;
307
+ this.unlink(entry);
308
+ }
309
+
310
+ stats(): CachePoolStats {
311
+ const amBytes = this.bytesTotal - this.a1inBytes;
312
+ return {
313
+ maxBytes: this.maxBytesValue,
314
+ maxEntries: this.maxEntriesValue,
315
+ bytes: this.bytesTotal,
316
+ entries: this.entriesTotal,
317
+ a1in: { bytes: this.a1inBytes, entries: this.a1in.size },
318
+ am: { bytes: amBytes, entries: this.am.size },
319
+ ghostKeys: this.ghost.size,
320
+ hits: this.hits,
321
+ admissions: this.admissions,
322
+ ghostHits: this.ghostHits,
323
+ evictions: this.evictions,
324
+ bypasses: this.bypasses,
325
+ stores: [...this.stores.values()].map(s => ({ id: s.id, label: s.label, bytes: s.bytes, entries: s.entries })),
326
+ };
327
+ }
328
+
329
+ // ---- internals ----
330
+
331
+ private recomputeDerived(): void {
332
+ this.bypassLimit = Math.floor(this.maxBytesValue / 16);
333
+ this.a1inTargetBytes = Math.floor(this.maxBytesValue / 4);
334
+ this.a1inTargetEntries = Math.floor(this.maxEntriesValue / 4);
335
+ this.ghostCap = Math.floor(this.maxEntriesValue / 2);
336
+ }
337
+
338
+ private link(entry: PoolEntry, where: 'a1in' | 'am'): void {
339
+ entry.where = where;
340
+ (where === 'a1in' ? this.a1in : this.am).set(entry.key, entry);
341
+ if (where === 'a1in') this.a1inBytes += entry.charge;
342
+ this.bytesTotal += entry.charge;
343
+ this.entriesTotal++;
344
+ entry.store.bytes += entry.charge;
345
+ entry.store.entries++;
346
+ }
347
+
348
+ private unlink(entry: PoolEntry): void {
349
+ (entry.where === 'a1in' ? this.a1in : this.am).delete(entry.key);
350
+ if (entry.where === 'a1in') this.a1inBytes -= entry.charge;
351
+ this.bytesTotal -= entry.charge;
352
+ this.entriesTotal--;
353
+ entry.store.bytes -= entry.charge;
354
+ entry.store.entries--;
355
+ entry.where = 'none';
356
+ }
357
+
358
+ /** Map insertion order gives A1in its FIFO and Am its LRU: refresh = delete + re-insert. */
359
+ private refresh(entry: PoolEntry): void {
360
+ if (entry.where !== 'am') return;
361
+ this.am.delete(entry.key);
362
+ this.am.set(entry.key, entry);
363
+ }
364
+
365
+ private evictToFit(incomingCharge: number, incomingEntries: number): void {
366
+ while (this.bytesTotal + incomingCharge > this.maxBytesValue
367
+ || this.entriesTotal + incomingEntries > this.maxEntriesValue) {
368
+ const victim = this.pickVictim();
369
+ if (victim === undefined) break; // pool empty — nothing left to evict
370
+ this.evict(victim);
371
+ }
372
+ }
373
+
374
+ private pickVictim(): PoolEntry | undefined {
375
+ if (this.admission === 'lru') {
376
+ return first(this.am) ?? first(this.a1in);
377
+ }
378
+ // 2Q: take A1in's FIFO head while probation is over its share of EITHER rail (or Am has
379
+ // nothing); otherwise the protected queue's LRU entry. Probation needs a share of the
380
+ // entry rail too, not just the byte rail: entries small enough that the entry count binds
381
+ // first (cached negatives are near-empty) would otherwise leave `a1inBytes` permanently
382
+ // under its byte target, so every admission would evict from Am and a one-pass scan would
383
+ // flush the protected set — 2Q silently degraded to plain LRU.
384
+ const a1inHead = first(this.a1in);
385
+ if (a1inHead !== undefined && (this.a1inBytes > this.a1inTargetBytes
386
+ || this.a1in.size > this.a1inTargetEntries || this.am.size === 0)) {
387
+ return a1inHead;
388
+ }
389
+ return first(this.am) ?? a1inHead;
390
+ }
391
+
392
+ private evict(entry: PoolEntry): void {
393
+ const fromA1in = entry.where === 'a1in';
394
+ this.unlink(entry);
395
+ if (fromA1in && this.admission === '2q') {
396
+ this.pushGhost(entry.key);
397
+ }
398
+ this.evictions++;
399
+ entry.owner.onPoolEvict(entry);
400
+ }
401
+
402
+ private pushGhost(key: string): void {
403
+ this.ghost.delete(key);
404
+ this.ghost.add(key);
405
+ this.trimGhost();
406
+ }
407
+
408
+ private trimGhost(): void {
409
+ while (this.ghost.size > this.ghostCap) {
410
+ const oldest = this.ghost.values().next().value;
411
+ if (oldest === undefined) break;
412
+ this.ghost.delete(oldest);
413
+ }
414
+ }
415
+ }
416
+
417
+ function first(queue: Map<string, PoolEntry>): PoolEntry | undefined {
418
+ return queue.values().next().value;
419
+ }
420
+
421
+ function validateBound(name: string, value: number): number {
422
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
423
+ throw new TypeError(`SharedCachePool ${name} must be a positive finite number, got ${value}`);
424
+ }
425
+ return Math.floor(value);
426
+ }
427
+
428
+ /**
429
+ * Honest per-platform default byte budget: ~8 MB on React Native (the phone running twenty
430
+ * workspaces is the device least able to afford more), 16 MB in browsers, 32 MB on Node
431
+ * (desktop / provider hosts). Hosts with better knowledge should size explicitly — either
432
+ * `defaultCachePool().setBudget(...)` or their own `SharedCachePool` passed to each cache.
433
+ */
434
+ function platformDefaultBytes(): number {
435
+ const g = globalThis as { navigator?: { product?: string }; window?: unknown };
436
+ if (g.navigator?.product === 'ReactNative') return 8 * 1024 * 1024;
437
+ if (g.window !== undefined) return 16 * 1024 * 1024;
438
+ return 32 * 1024 * 1024;
439
+ }
440
+
441
+ let defaultPool: SharedCachePool | undefined;
442
+
443
+ /**
444
+ * The process-wide shared pool every `CachedStoreDriver` joins unless handed a specific one.
445
+ * Lazily created on first use with the platform-default budget; re-budget it live via
446
+ * `setBudget`. One pool per process is the point: twenty workspaces' caches compete inside
447
+ * one budget instead of each sizing itself as if it were alone.
448
+ */
449
+ export function defaultCachePool(): SharedCachePool {
450
+ defaultPool ??= new SharedCachePool();
451
+ return defaultPool;
452
+ }