@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
@@ -20,9 +20,11 @@ import { seedOwnedBlocksFromStorage } from './owned-block-seed.js';
20
20
  import { clusterMember } from './cluster/cluster-repo.js';
21
21
  import { createReconcileBlock } from './cluster/reconcile-block.js';
22
22
  import { resolveClusterPolicy } from './cluster/cluster-policy.js';
23
+ import { assertClusterSizeCoupling } from './cluster/cluster-size-coupling.js';
23
24
  import { createCommitCertStore, makeClusterCommitCertExtractor } from './cluster/commit-cert.js';
24
25
  import { coordinatorRepo } from './repo/coordinator-repo.js';
25
26
  import { Libp2pKeyPeerNetwork } from './libp2p-key-network.js';
27
+ import { mergePeerAddresses } from './peer-address-book.js';
26
28
  import { ClusterClient } from './cluster/client.js';
27
29
  import { networkManagerService } from './network/network-manager-service.js';
28
30
  import { BlockTransferCoordinator } from './cluster/block-transfer.js';
@@ -120,6 +122,14 @@ export async function createLibp2pNodeBase(options, defaults) {
120
122
  void blockCommitLatch;
121
123
  let clusterImpl;
122
124
  let coordinatedRepo;
125
+ // The running node, bound immediately after `createLibp2p` below. Service factories that need
126
+ // the node at REQUEST time must close over this, never over `components.libp2p`: `components`
127
+ // is libp2p's Proxy, whose getter THROWS `MissingServiceError('libp2p not set')` for any key it
128
+ // does not hold — and `libp2p` is not a component. The throw happens on the property read, so
129
+ // neither `?.` nor a following `if (!libp2p) return` can catch it; it escapes as an application
130
+ // error on whatever request touched it. Same reason fret/networkManager/repo take the node via
131
+ // setLibp2p (see the injection block after `createLibp2p`).
132
+ let liveNode;
123
133
  const clusterProxy = {
124
134
  async update(record) {
125
135
  if (!clusterImpl) {
@@ -177,6 +187,15 @@ export async function createLibp2pNodeBase(options, defaults) {
177
187
  // the store first keeps origination correct regardless of the caller sink (`put` never throws).
178
188
  ? (actionId, cert) => { certStore.put(actionId, cert); options.onCommitCertificate?.(actionId, cert); }
179
189
  : options.onCommitCertificate;
190
+ // Every cluster-policy default lives in `cluster/cluster-policy.ts` — including WHY the admission
191
+ // gate and the repair corroboration floor resolve the one operator field
192
+ // (`clusterPolicy.assumedClusterSize`) to different values when it is absent. Resolved ONCE, here,
193
+ // before anything that reads a cluster size is constructed: `networkManagerService` below,
194
+ // `Libp2pKeyPeerNetwork`, and the spread-on-churn monitor init must all read `consensusConfig.clusterSize`
195
+ // rather than `options.clusterSize` directly, or they can each apply their own fallback default and
196
+ // silently disagree (ticket bug-cluster-size-resolution-single-source). `assertClusterSizeCoupling`
197
+ // below is the fail-fast backstop if a future edit reintroduces that split.
198
+ const consensusConfig = resolveClusterPolicy(options);
180
199
  const libp2pOptions = {
181
200
  start: false,
182
201
  privateKey: nodePrivateKey,
@@ -253,6 +272,7 @@ export async function createLibp2pNodeBase(options, defaults) {
253
272
  ...(options.relay ? { relay: circuitRelayServer(options.relayServerInit) } : {}),
254
273
  // Custom services - create wrapper factories that inject dependencies
255
274
  cluster: (components) => {
275
+ const addressLog = components.logger.forComponent('db-p2p:peer-address-book');
256
276
  const serviceFactory = clusterService({
257
277
  protocolPrefix: `/optimystic/${options.networkName}`,
258
278
  responsibilityK: options.responsibilityK ?? 1,
@@ -268,7 +288,7 @@ export async function createLibp2pNodeBase(options, defaults) {
268
288
  // Fallback addr resolver for redirect targets whose multiaddrs are not
269
289
  // already embedded in record.peers.
270
290
  getConnectionAddrs: (peerId) => {
271
- const conns = components.libp2p?.getConnections?.(peerId) ?? [];
291
+ const conns = liveNode?.getConnections?.(peerId) ?? [];
272
292
  const addrs = [];
273
293
  for (const c of conns) {
274
294
  const addr = c.remoteAddr?.toString?.();
@@ -276,6 +296,16 @@ export async function createLibp2pNodeBase(options, defaults) {
276
296
  addrs.push(addr);
277
297
  }
278
298
  return addrs;
299
+ },
300
+ // Inbound cluster records carry each cohort member's multiaddrs. libp2p only
301
+ // propagates addresses between directly-connected peers, so for a cohort chosen
302
+ // by key position this is often the ONLY way this node learns how to reach a
303
+ // relay-only sibling. Same late-binding shape as getConnectionAddrs above:
304
+ // `liveNode` resolves at request time, not at service construction.
305
+ recordPeerAddresses: (peerId, multiaddrs) => {
306
+ if (!liveNode)
307
+ return;
308
+ mergePeerAddresses(liveNode, peerId, multiaddrs, addressLog);
279
309
  }
280
310
  });
281
311
  },
@@ -328,7 +358,7 @@ export async function createLibp2pNodeBase(options, defaults) {
328
358
  },
329
359
  networkManager: (components) => {
330
360
  const svcFactory = networkManagerService({
331
- clusterSize: options.clusterSize ?? 10,
361
+ clusterSize: consensusConfig.clusterSize,
332
362
  expectedRemotes: (options.bootstrapNodes?.length ?? 0) > 0,
333
363
  allowClusterDownsize: options.clusterPolicy?.allowDownsize ?? true,
334
364
  clusterSizeTolerance: options.clusterPolicy?.sizeTolerance ?? 0.5
@@ -375,6 +405,10 @@ export async function createLibp2pNodeBase(options, defaults) {
375
405
  ],
376
406
  };
377
407
  const node = await createLibp2p(libp2pOptions);
408
+ // Bind the closure-captured node BEFORE start(): the cluster service's address-learning and
409
+ // redirect-addr resolvers read it on every inbound request, and the first one can arrive as
410
+ // soon as the protocol handler goes live in start().
411
+ liveNode = node;
378
412
  // Inject the REAL libp2p node into the services that need it, before start(). These are
379
413
  // load-bearing and the node has NOT started yet, so any throw fails fast and rejects node
380
414
  // creation (nothing started leaks) — far better than the service silently falling back to the
@@ -388,585 +422,596 @@ export async function createLibp2pNodeBase(options, defaults) {
388
422
  // handler is live with a resolvable node from its first request.
389
423
  wired.repo.setLibp2p(node);
390
424
  await node.start();
391
- // Initialize peer reputation service
392
- const reputation = new PeerReputationService();
393
- // Initialize cluster coordination components
394
- const networkMode = (options.bootstrapNodes?.length ?? 0) > 0 ? 'joining' : 'forming';
395
- // Network-namespaced protocol prefix, threaded into the key network so coordinator/
396
- // cohort selection is scoped to peers that serve THIS network's cluster/repo protocol.
397
- // A peer that only belongs to another network sharing the same physical nodes/
398
- // bootstraps registers a different (network-namespaced) identify protocol, so it is
399
- // never selected and can't drag this network's super-majority below quorum.
400
- const protocolPrefix = `/optimystic/${options.networkName}`;
401
- const keyNetwork = new Libp2pKeyPeerNetwork(node, options.clusterSize, undefined, networkMode, options.persistence, reputation, protocolPrefix);
402
- await keyNetwork.initFromPersistedState();
403
- const createClusterClient = (peerId) => ClusterClient.create(peerId, keyNetwork, protocolPrefix);
404
- // Inject reputation into NetworkManagerService. Load-bearing and non-optional: the service is
405
- // unconditionally present, so a throw is a real wiring bug. Unlike the pre-start injections above
406
- // the node has already started here, so stop it before rethrowing rather than leaking a started
407
- // node + open transports (mirrors the cohortTopic hard-fail blocks below).
425
+ // Everything from here to the `return` runs against an ALREADY STARTED node (open transports,
426
+ // listening addresses, running services). A rejection out of that span used to hand the caller an
427
+ // error and no handle, leaving the node running with its listener port still bound — unrecoverable
428
+ // for the caller and enough to block the port for the next start attempt. So the whole post-start
429
+ // body rolls back: see the `catch` at the bottom of this function.
408
430
  try {
431
+ // Initialize peer reputation service
432
+ const reputation = new PeerReputationService();
433
+ // Initialize cluster coordination components
434
+ const networkMode = (options.bootstrapNodes?.length ?? 0) > 0 ? 'joining' : 'forming';
435
+ // Network-namespaced protocol prefix, threaded into the key network so coordinator/
436
+ // cohort selection is scoped to peers that serve THIS network's cluster/repo protocol.
437
+ // A peer that only belongs to another network sharing the same physical nodes/
438
+ // bootstraps registers a different (network-namespaced) identify protocol, so it is
439
+ // never selected and can't drag this network's super-majority below quorum.
440
+ const protocolPrefix = `/optimystic/${options.networkName}`;
441
+ const keyNetwork = new Libp2pKeyPeerNetwork(node, consensusConfig.clusterSize, undefined, networkMode, options.persistence, reputation, protocolPrefix);
442
+ await keyNetwork.initFromPersistedState();
443
+ const createClusterClient = (peerId) => ClusterClient.create(peerId, keyNetwork, protocolPrefix);
444
+ // Inject reputation into NetworkManagerService. Load-bearing and non-optional: the service is
445
+ // unconditionally present, so a throw is a real wiring bug. The node has already started here, but
446
+ // no ad-hoc stop is needed: the post-start rollback `catch` at the bottom of this function stops it.
409
447
  wired.networkManager.setReputation(reputation);
410
- }
411
- catch (err) {
412
- await node.stop();
413
- throw err;
414
- }
415
- // Create partition detector and get FRET service
416
- const partitionDetector = new PartitionDetector();
417
- const fretSvc = node.services?.fret;
418
- // Every cluster-policy default lives in `cluster/cluster-policy.ts` — including WHY the admission
419
- // gate and the repair corroboration floor resolve the one operator field
420
- // (`clusterPolicy.assumedClusterSize`) to different values when it is absent. Extracted so those
421
- // defaults can be asserted without booting a node.
422
- const consensusConfig = resolveClusterPolicy(options);
423
- // Fetch a block archive from one cohort peer over the sync protocol, bounded by a
424
- // per-peer timeout so an unreachable peer can't stall reconciliation. Mirrors the
425
- // SyncClient query in `clusterLatestCallback`, but returns the full archive (which
426
- // carries the materialized block) rather than only the latest ActionRev.
427
- const fetchArchiveFromPeer = async (peerIdStr, blockId) => {
428
- let peerId;
429
- try {
430
- peerId = peerIdFromString(peerIdStr);
431
- }
432
- catch {
433
- return undefined;
434
- }
435
- if (peerId.equals(node.peerId))
436
- return undefined;
437
- const syncClient = new SyncClient(peerId, keyNetwork, protocolPrefix);
438
- try {
439
- const response = await Promise.race([
440
- syncClient.requestBlock({ blockId, rev: undefined }),
441
- new Promise(resolve => { setTimeout(() => resolve({ success: false }), 1000).unref(); })
442
- ]);
443
- return response.success ? response.archive : undefined;
444
- }
445
- catch {
446
- // Peer unreachable / no data — caller falls back to the next cohort peer.
447
- return undefined;
448
- }
449
- };
450
- // Active reconciliation for a block this member committed without a materializable base
451
- // (cohort drift, or a refused `missing-base-revision` commit). See `reconcile-block.ts` for
452
- // the corroboration rules — in particular why both quorums are capped by how many peers
453
- // could answer at all, which is what lets a genuinely two-node cohort heal.
454
- // NOTE: this and the CoordinatorRepo below must cap against the SAME
455
- // repairCorroborationClusterSize, or the two restoration paths disagree about how much trust a
456
- // lone peer gets. Safe today because both read the one `resolveClusterPolicy` result above; if
457
- // either ever resolves its own value, add a fail-fast coupling check like
458
- // `assertSuperMajorityCoupling` rather than relying on proximity.
459
- const reconcileBlock = createReconcileBlock({
460
- selfPeerId: node.peerId.toString(),
461
- fetchArchive: fetchArchiveFromPeer,
462
- saveReplicatedBlock: (blockId, block, source) => storageRepo.saveReplicatedBlock(blockId, block, source),
463
- simpleMajorityThreshold: consensusConfig.simpleMajorityThreshold,
464
- repairCorroborationClusterSize: consensusConfig.repairCorroborationClusterSize,
465
- reputation
466
- });
467
- // Member-side membership derivation for the admission gate: independently re-derive this block's
468
- // responsible cluster from the SAME source the coordinator uses (IKeyNetwork.findCluster), plus FRET's
469
- // network-size confidence. A member gates a coordinator-declared peer set against this view before
470
- // voting, so a self-shrunk minority-partition set cannot be voted into super-majority (see cluster-repo
471
- // admitMembership). No FRET ⇒ confidence 0 ⇒ the gate fails closed for any downsize.
472
- const deriveExpectedCluster = async (blockId) => {
473
- const peers = await keyNetwork.findCluster(new TextEncoder().encode(blockId));
474
- let confidence = 0;
475
- if (fretSvc) {
448
+ // Create partition detector and get FRET service
449
+ const partitionDetector = new PartitionDetector();
450
+ const fretSvc = node.services?.fret;
451
+ // Fetch a block archive from one cohort peer over the sync protocol, bounded by a
452
+ // per-peer timeout so an unreachable peer can't stall reconciliation. Mirrors the
453
+ // SyncClient query in `clusterLatestCallback`, but returns the full archive (which
454
+ // carries the materialized block) rather than only the latest ActionRev.
455
+ const fetchArchiveFromPeer = async (peerIdStr, blockId) => {
456
+ let peerId;
476
457
  try {
477
- confidence = fretSvc.getNetworkSizeEstimate().confidence;
458
+ peerId = peerIdFromString(peerIdStr);
478
459
  }
479
460
  catch {
480
- // Leave confidence 0 → fail closed for downsizing.
461
+ return undefined;
481
462
  }
482
- }
483
- return { peers: peers ?? {}, confidence };
484
- };
485
- clusterImpl = clusterMember({
486
- storageRepo,
487
- peerNetwork: keyNetwork,
488
- peerId: node.peerId,
489
- privateKey: nodePrivateKey,
490
- protocolPrefix,
491
- partitionDetector,
492
- fretService: fretSvc,
493
- validator: options.validator,
494
- reputation,
495
- consensusConfig,
496
- stateStore: options.transactionStateStore,
497
- reconcileBlock,
498
- onCommitCertificate,
499
- deriveExpectedCluster
500
- // `recomputeArbitratorSet` (invalidation layer-2) is intentionally NOT wired here yet: a live FRET
501
- // recompute needs a churn-tolerance window so it does not false-reject legitimate certificates from
502
- // late-joiners (a liveness regression). Until that is tuned against live topology — and the
503
- // cohort-topic membership-cert trust anchor (layer 3) lands — invalidation verification runs on the
504
- // challenger-bound set + membership + dedup (layer 1) and LOGS the residual anchoring gap. See
505
- // `verifyInvalidationCertificate` and `tickets/plan/cohort-topic-membership-cert-trust-anchoring.md`.
506
- });
507
- const coordinatorRepoFactory = coordinatorRepo(keyNetwork, createClusterClient, {
508
- // clusterSize is now part of consensusConfig (member + coordinator share one reference).
509
- ...consensusConfig
510
- }, fretSvc, reputation, options.transactionStateStore);
511
- // Create callback for querying cluster peers for their latest block revision. Three-way
512
- // contract (see ClusterLatestCallback): an ActionRev is the peer's claim, a resolved
513
- // `undefined` is the peer answering "I hold nothing", and a REJECTION is silence — the
514
- // coordinator counts it as "did not answer" and refuses to report an authoritative absent
515
- // over it. Transport errors must therefore propagate, not collapse into `undefined` (that
516
- // collapse let a slow two-node cohort report a missing block as authoritatively absent —
517
- // ticket cluster-read-consult-cannot-report-unreachable).
518
- const clusterLatestCallback = async (peerId, blockId, context) => {
519
- // Self-read short-circuit: dialling self via SyncClient is a round trip
520
- // with no remote on the other end, and on nodes without listen addresses
521
- // (solo WebSocket-only, bare-RN, etc.) the self-dial can hang the dial
522
- // queue. Read directly from the local storage repo instead. The catch stays:
523
- // a local storage error is not a cohort peer being unreachable, and the
524
- // coordinator ignores a self rejection anyway.
525
- if (peerId.equals(node.peerId)) {
463
+ if (peerId.equals(node.peerId))
464
+ return undefined;
465
+ const syncClient = new SyncClient(peerId, keyNetwork, protocolPrefix);
526
466
  try {
527
- const result = await storageRepo.get({ blockIds: [blockId], context });
528
- return result[blockId]?.state?.latest;
467
+ const response = await Promise.race([
468
+ syncClient.requestBlock({ blockId, rev: undefined }),
469
+ new Promise(resolve => { setTimeout(() => resolve({ success: false }), 1000).unref(); })
470
+ ]);
471
+ return response.success ? response.archive : undefined;
529
472
  }
530
473
  catch {
474
+ // Peer unreachable / no data — caller falls back to the next cohort peer.
531
475
  return undefined;
532
476
  }
533
- }
534
- const syncClient = new SyncClient(peerId, keyNetwork, protocolPrefix);
535
- // No try/catch: a dial or protocol failure rejects through to the coordinator, whose
536
- // per-peer deadline also bounds a hung request slowness needs no race here.
537
- const response = await syncClient.requestBlock({ blockId, rev: undefined });
538
- if (response.success && response.archive) {
539
- const revisions = Object.keys(response.archive.revisions).map(Number);
540
- if (revisions.length > 0) {
541
- const maxRev = Math.max(...revisions);
542
- const revisionData = response.archive.revisions[maxRev];
543
- if (revisionData?.action) {
544
- return { actionId: revisionData.action.actionId, rev: maxRev };
477
+ };
478
+ // Active reconciliation for a block this member committed without a materializable base
479
+ // (cohort drift, or a refused `missing-base-revision` commit). See `reconcile-block.ts` for
480
+ // the corroboration rules in particular why both quorums are capped by how many peers
481
+ // could answer at all, which is what lets a genuinely two-node cohort heal.
482
+ // NOTE: this and the CoordinatorRepo below must cap against the SAME
483
+ // repairCorroborationClusterSize, or the two restoration paths disagree about how much trust a
484
+ // lone peer gets. Safe today because both read the one `resolveClusterPolicy` result above; if
485
+ // either ever resolves its own value, add a fail-fast coupling check like
486
+ // `assertSuperMajorityCoupling` rather than relying on proximity.
487
+ const reconcileBlock = createReconcileBlock({
488
+ selfPeerId: node.peerId.toString(),
489
+ fetchArchive: fetchArchiveFromPeer,
490
+ saveReplicatedBlock: (blockId, block, source) => storageRepo.saveReplicatedBlock(blockId, block, source),
491
+ simpleMajorityThreshold: consensusConfig.simpleMajorityThreshold,
492
+ repairCorroborationClusterSize: consensusConfig.repairCorroborationClusterSize,
493
+ reputation
494
+ });
495
+ // Member-side membership derivation for the admission gate: independently re-derive this block's
496
+ // responsible cluster from the SAME source the coordinator uses (IKeyNetwork.findCluster), plus FRET's
497
+ // network-size confidence. A member gates a coordinator-declared peer set against this view before
498
+ // voting, so a self-shrunk minority-partition set cannot be voted into super-majority (see cluster-repo
499
+ // admitMembership). No FRET ⇒ confidence 0 ⇒ the gate fails closed for any downsize.
500
+ const deriveExpectedCluster = async (blockId) => {
501
+ const peers = await keyNetwork.findCluster(new TextEncoder().encode(blockId));
502
+ let confidence = 0;
503
+ if (fretSvc) {
504
+ try {
505
+ confidence = fretSvc.getNetworkSizeEstimate().confidence;
506
+ }
507
+ catch {
508
+ // Leave confidence 0 → fail closed for downsizing.
545
509
  }
546
510
  }
547
- }
548
- // The peer DID answer, without data: `success:false` is the sync service's "Block not
549
- // found in local storage", and an archive with no usable revisions holds nothing either
550
- // way. Both are absent claims, not silence.
551
- return undefined;
552
- };
553
- coordinatedRepo = coordinatorRepoFactory({
554
- storageRepo,
555
- localCluster: clusterImpl,
556
- localPeerId: node.peerId,
557
- clusterLatestCallback,
558
- // Read-driven acquisition shares the commit path's reconcile callback verbatim: same bounded
559
- // archive fetch, same (rev, actionId) and content quorums, same monotonic saveReplicatedBlock
560
- // funnel. `clusterLatestCallback` alone can only tell the reader WHICH revision the cohort
561
- // holds; this is what moves the bytes. Only reached once a corroborated revision exists, so a
562
- // genuinely absent block still costs no archive fetch.
563
- acquireBlockFromCohort: reconcileBlock
564
- });
565
- // Fail-fast coupling: the cluster member (what accepts a super-majority as sufficient) and the
566
- // coordinator (what declares a transaction committed on that super-majority) MUST run the same
567
- // threshold, or the node would come up able to disagree with itself mid-consensus. Both are fed from
568
- // the single `consensusConfig` above; this asserts on their RESOLVED values so any future drift throws
569
- // HERE at construction. See `assertSuperMajorityCoupling`.
570
- assertSuperMajorityCoupling(clusterImpl, coordinatedRepo);
571
- // Recover persisted transaction state before accepting new requests
572
- if (options.transactionStateStore) {
573
- await clusterImpl.recoverTransactions();
574
- await coordinatedRepo.recoverTransactions();
575
- }
576
- // --- Shared owned-block set for the resilience monitors ---
577
- // SpreadOnChurnMonitor (sender) and RebalanceMonitor (responsibility tracker) both act on "the
578
- // blocks this node physically holds". They share ONE Set so the two can never drift: a single
579
- // owned-block feed populates it, and the rebalance responsibility-loss signal evicts from it
580
- // (in the rebalance block below). Both monitors take this exact instance via deps.trackedBlocks.
581
- const networkManager = node.services?.networkManager;
582
- const ownedBlocks = new Set();
583
- // Single owned-block feed: every block this node commits OR receives as a replica fires
584
- // storageRepo.onAnyCollectionChange. Subscribe to storageRepo DIRECTLY (not
585
- // node.blockChangeNotifier): the cohort-topic activation block below may replace
586
- // blockChangeNotifier with a decorating bridge, but storageRepo keeps emitting on its own
587
- // surface regardless of that opt-in. NOTE: this feed does NOT re-emit blocks already durable
588
- // from a previous run; those are seeded once at startup by the storage-enumeration scan wired
589
- // below (seedOwnedBlocksFromStorage), so a restarted node protects on-disk data without waiting
590
- // for each block to be touched again. Registered lazily the first time a
591
- // monitor that reads ownedBlocks is wired, so when BOTH monitors are disabled no subscription
592
- // leaks; torn down exactly once in the stop wrapper below.
593
- let offOwnedBlockFeed;
594
- const ensureOwnedBlockFeed = () => {
595
- if (offOwnedBlockFeed)
596
- return;
597
- offOwnedBlockFeed = storageRepo.onAnyCollectionChange((e) => {
598
- for (const blockId of e.blockIds)
599
- ownedBlocks.add(blockId);
511
+ return { peers: peers ?? {}, confidence };
512
+ };
513
+ clusterImpl = clusterMember({
514
+ storageRepo,
515
+ peerNetwork: keyNetwork,
516
+ peerId: node.peerId,
517
+ privateKey: nodePrivateKey,
518
+ protocolPrefix,
519
+ partitionDetector,
520
+ fretService: fretSvc,
521
+ validator: options.validator,
522
+ reputation,
523
+ consensusConfig,
524
+ stateStore: options.transactionStateStore,
525
+ reconcileBlock,
526
+ onCommitCertificate,
527
+ deriveExpectedCluster
528
+ // `recomputeArbitratorSet` (invalidation layer-2) is intentionally NOT wired here yet: a live FRET
529
+ // recompute needs a churn-tolerance window so it does not false-reject legitimate certificates from
530
+ // late-joiners (a liveness regression). Until that is tuned against live topology — and the
531
+ // cohort-topic membership-cert trust anchor (layer 3) lands invalidation verification runs on the
532
+ // challenger-bound set + membership + dedup (layer 1) and LOGS the residual anchoring gap. See
533
+ // `verifyInvalidationCertificate` and `tickets/plan/cohort-topic-membership-cert-trust-anchoring.md`.
600
534
  });
601
- };
602
- // Single owned-block-feed teardown. Registered up front (before either monitor's own stop
603
- // wrapper) so it runs regardless of WHICH monitor subscribed the feed - including the
604
- // spread-disabled / rebalance-only case. Idempotent: offOwnedBlockFeed is undefined-guarded.
605
- {
606
- const previousStop = node.stop.bind(node);
607
- node.stop = async () => {
608
- try {
609
- offOwnedBlockFeed?.();
535
+ // Cleanup cluster member intervals on node stop. Installed HERE, immediately after clusterImpl
536
+ // exists, rather than further down: the post-start rollback only unwinds resources whose stop
537
+ // wrapper is already installed at the moment of the throw, so a wrapper trailing its resource by
538
+ // hundreds of lines leaves those intervals running on a failed startup. Same reasoning as the
539
+ // owned-block-feed wrapper below.
540
+ {
541
+ const previousStop = node.stop.bind(node);
542
+ node.stop = async () => {
543
+ try {
544
+ clusterImpl.dispose();
545
+ }
546
+ finally {
547
+ // Never let a dispose failure strand the transports — same try/finally shape every
548
+ // other wrapper in this chain uses.
549
+ await previousStop();
550
+ }
551
+ };
552
+ }
553
+ const coordinatorRepoFactory = coordinatorRepo(keyNetwork, createClusterClient, {
554
+ // clusterSize is now part of consensusConfig (member + coordinator share one reference).
555
+ ...consensusConfig
556
+ }, fretSvc, reputation, options.transactionStateStore);
557
+ // Create callback for querying cluster peers for their latest block revision. Three-way
558
+ // contract (see ClusterLatestCallback): an ActionRev is the peer's claim, a resolved
559
+ // `undefined` is the peer answering "I hold nothing", and a REJECTION is silence — the
560
+ // coordinator counts it as "did not answer" and refuses to report an authoritative absent
561
+ // over it. Transport errors must therefore propagate, not collapse into `undefined` (that
562
+ // collapse let a slow two-node cohort report a missing block as authoritatively absent —
563
+ // ticket cluster-read-consult-cannot-report-unreachable).
564
+ const clusterLatestCallback = async (peerId, blockId, context) => {
565
+ // Self-read short-circuit: dialling self via SyncClient is a round trip
566
+ // with no remote on the other end, and on nodes without listen addresses
567
+ // (solo WebSocket-only, bare-RN, etc.) the self-dial can hang the dial
568
+ // queue. Read directly from the local storage repo instead. The catch stays:
569
+ // a local storage error is not a cohort peer being unreachable, and the
570
+ // coordinator ignores a self rejection anyway.
571
+ if (peerId.equals(node.peerId)) {
572
+ try {
573
+ const result = await storageRepo.get({ blockIds: [blockId], context });
574
+ return result[blockId]?.state?.latest;
575
+ }
576
+ catch {
577
+ return undefined;
578
+ }
610
579
  }
611
- finally {
612
- await previousStop();
580
+ const syncClient = new SyncClient(peerId, keyNetwork, protocolPrefix);
581
+ // No try/catch: a dial or protocol failure rejects through to the coordinator, whose
582
+ // per-peer deadline also bounds a hung request — slowness needs no race here.
583
+ const response = await syncClient.requestBlock({ blockId, rev: undefined });
584
+ if (response.success && response.archive) {
585
+ const revisions = Object.keys(response.archive.revisions).map(Number);
586
+ if (revisions.length > 0) {
587
+ const maxRev = Math.max(...revisions);
588
+ const revisionData = response.archive.revisions[maxRev];
589
+ if (revisionData?.action) {
590
+ return { actionId: revisionData.action.actionId, rev: maxRev };
591
+ }
592
+ }
613
593
  }
594
+ // The peer DID answer, without data: `success:false` is the sync service's "Block not
595
+ // found in local storage", and an archive with no usable revisions holds nothing either
596
+ // way. Both are absent claims, not silence.
597
+ return undefined;
614
598
  };
615
- }
616
- // --- Churn-resilient spread: drive SpreadOnChurnMonitor on a live node ---
617
- // Nothing previously activated the SENDING side of the churn-resilient spread protocol on a
618
- // real node. Here we init + start the monitor (sharing ownedBlocks) and ensure the single
619
- // owned-block feed is live, so a debounced connection:close re-pushes the node's blocks to
620
- // expansion-cohort peers (the receiver durably persists each push via saveReplicatedBlock).
621
- let spreadMonitor;
622
- if (networkManager && (options.spreadOnChurn?.enabled ?? true) !== false) {
623
- try {
624
- spreadMonitor = networkManager.initSpreadOnChurnMonitor(partitionDetector, storageRepo, keyNetwork, options.clusterSize ?? 10, protocolPrefix, ownedBlocks, options.spreadOnChurn);
625
- await spreadMonitor.start();
626
- ensureOwnedBlockFeed();
599
+ coordinatedRepo = coordinatorRepoFactory({
600
+ storageRepo,
601
+ localCluster: clusterImpl,
602
+ localPeerId: node.peerId,
603
+ clusterLatestCallback,
604
+ // Read-driven acquisition shares the commit path's reconcile callback verbatim: same bounded
605
+ // archive fetch, same (rev, actionId) and content quorums, same monotonic saveReplicatedBlock
606
+ // funnel. `clusterLatestCallback` alone can only tell the reader WHICH revision the cohort
607
+ // holds; this is what moves the bytes. Only reached once a corroborated revision exists, so a
608
+ // genuinely absent block still costs no archive fetch.
609
+ acquireBlockFromCohort: reconcileBlock
610
+ });
611
+ // Fail-fast coupling: the cluster member (what accepts a super-majority as sufficient) and the
612
+ // coordinator (what declares a transaction committed on that super-majority) MUST run the same
613
+ // threshold, or the node would come up able to disagree with itself mid-consensus. Both are fed from
614
+ // the single `consensusConfig` above; this asserts on their RESOLVED values so any future drift throws
615
+ // HERE at construction. See `assertSuperMajorityCoupling`.
616
+ assertSuperMajorityCoupling(clusterImpl, coordinatedRepo);
617
+ // Recover persisted transaction state before accepting new requests
618
+ if (options.transactionStateStore) {
619
+ await clusterImpl.recoverTransactions();
620
+ await coordinatedRepo.recoverTransactions();
627
621
  }
628
- catch (err) {
629
- // Spread is a resilience optimization, not a correctness requirement - a wiring
630
- // failure (e.g. FRET briefly unavailable) must NOT hard-fail node startup, unlike the
631
- // operator-opted-in cohortTopic block. Log and continue with spread inert.
632
- (node.logger?.forComponent?.('db-p2p:spread-on-churn'))?.('init failed: %o', err);
622
+ // --- Shared owned-block set for the resilience monitors ---
623
+ // SpreadOnChurnMonitor (sender) and RebalanceMonitor (responsibility tracker) both act on "the
624
+ // blocks this node physically holds". They share ONE Set so the two can never drift: a single
625
+ // owned-block feed populates it, and the rebalance responsibility-loss signal evicts from it
626
+ // (in the rebalance block below). Both monitors take this exact instance via deps.trackedBlocks.
627
+ const networkManager = node.services?.networkManager;
628
+ // See the comment above `consensusConfig` for why every cluster-size consumer must read the SAME
629
+ // resolved value. This throws at construction (rather than letting a node come up mismatched) if a
630
+ // future edit gives `keyNetwork` or `networkManager` their own fallback again.
631
+ assertClusterSizeCoupling(consensusConfig.clusterSize, { keyNetwork, networkManager });
632
+ const ownedBlocks = new Set();
633
+ // Single owned-block feed: every block this node commits OR receives as a replica fires
634
+ // storageRepo.onAnyCollectionChange. Subscribe to storageRepo DIRECTLY (not
635
+ // node.blockChangeNotifier): the cohort-topic activation block below may replace
636
+ // blockChangeNotifier with a decorating bridge, but storageRepo keeps emitting on its own
637
+ // surface regardless of that opt-in. NOTE: this feed does NOT re-emit blocks already durable
638
+ // from a previous run; those are seeded once at startup by the storage-enumeration scan wired
639
+ // below (seedOwnedBlocksFromStorage), so a restarted node protects on-disk data without waiting
640
+ // for each block to be touched again. Registered lazily the first time a
641
+ // monitor that reads ownedBlocks is wired, so when BOTH monitors are disabled no subscription
642
+ // leaks; torn down exactly once in the stop wrapper below.
643
+ let offOwnedBlockFeed;
644
+ const ensureOwnedBlockFeed = () => {
645
+ if (offOwnedBlockFeed)
646
+ return;
647
+ offOwnedBlockFeed = storageRepo.onAnyCollectionChange((e) => {
648
+ for (const blockId of e.blockIds)
649
+ ownedBlocks.add(blockId);
650
+ });
651
+ };
652
+ // Single owned-block-feed teardown. Registered up front (before either monitor's own stop
653
+ // wrapper) so it runs regardless of WHICH monitor subscribed the feed - including the
654
+ // spread-disabled / rebalance-only case. Idempotent: offOwnedBlockFeed is undefined-guarded.
655
+ {
656
+ const previousStop = node.stop.bind(node);
657
+ node.stop = async () => {
658
+ try {
659
+ offOwnedBlockFeed?.();
660
+ }
661
+ finally {
662
+ await previousStop();
663
+ }
664
+ };
633
665
  }
634
- }
635
- // Expose for tests/diagnostics (mirrors node.keyNetwork / node.reputation).
636
- node.spreadOnChurnMonitor = spreadMonitor;
637
- // Disposal: stop the spread monitor deterministically before the transports close. Composes
638
- // with the arachnode / clusterMember / cohort-topic stop wrappers (each calls its captured
639
- // previousStop last). Idempotent (SpreadOnChurnMonitor.stop early-returns when not running), so
640
- // a double node.stop() does not throw. The owned-block feed teardown is the separate up-front
641
- // wrapper above (shared across both monitors).
642
- {
643
- const previousStop = node.stop.bind(node);
644
- node.stop = async () => {
666
+ // --- Churn-resilient spread: drive SpreadOnChurnMonitor on a live node ---
667
+ // Nothing previously activated the SENDING side of the churn-resilient spread protocol on a
668
+ // real node. Here we init + start the monitor (sharing ownedBlocks) and ensure the single
669
+ // owned-block feed is live, so a debounced connection:close re-pushes the node's blocks to
670
+ // expansion-cohort peers (the receiver durably persists each push via saveReplicatedBlock).
671
+ let spreadMonitor;
672
+ if (networkManager && (options.spreadOnChurn?.enabled ?? true) !== false) {
645
673
  try {
646
- if (spreadMonitor)
647
- await spreadMonitor.stop();
674
+ spreadMonitor = networkManager.initSpreadOnChurnMonitor(partitionDetector, storageRepo, keyNetwork, consensusConfig.clusterSize, protocolPrefix, ownedBlocks, options.spreadOnChurn);
675
+ await spreadMonitor.start();
676
+ ensureOwnedBlockFeed();
648
677
  }
649
- finally {
650
- await previousStop();
678
+ catch (err) {
679
+ // Spread is a resilience optimization, not a correctness requirement - a wiring
680
+ // failure (e.g. FRET briefly unavailable) must NOT hard-fail node startup, unlike the
681
+ // operator-opted-in cohortTopic block. Log and continue with spread inert.
682
+ (node.logger?.forComponent?.('db-p2p:spread-on-churn'))?.('init failed: %o', err);
651
683
  }
652
- };
653
- }
654
- // Initialize Arachnode ring membership and restoration
655
- const enableArachnode = options.arachnode?.enableRingZulu ?? true;
656
- if (enableArachnode) {
657
- const log = node.logger?.forComponent?.('db-p2p:arachnode');
658
- const fret = node.services?.fret;
659
- if (fret) {
660
- const fretAdapter = new ArachnodeFretAdapter(fret, node.peerId.toString());
661
- // Blocks whose shed range has been RELEASED (Phase C of a ring shift, or a confirmed
662
- // rebalance release). This is the GC-eligibility signal the future storage sweep
663
- // (`st-storage-sweep-archival-and-capacity-estimate`) must consult: a block's local bytes may
664
- // be reclaimed ONLY once it appears here, so an unconfirmed / still-served range is never
665
- // swept. Populated strictly after replication is confirmed. See
666
- // docs/arachnode-ring-handoff.md § Part 2 (Local bytes vs. tracking).
667
- // NOTE: no sweep consumes this set yet; it is the coordinated eligibility handoff the sweep
668
- // ticket will read. Until then it grows unbounded — bound it when the sweep lands.
669
- const gcEligible = new Set();
670
- node.gcEligibleBlocks = gcEligible;
671
- // The ring-shift state machine (advertise→confirm→release). Wired inside the rebalance block
672
- // below (it needs the BlockTransferCoordinator confirmer + the cohort-size floor); left
673
- // undefined when the rebalance reaction is not wired, in which case ring shifts stay inert —
674
- // a move-out is unsafe without the confirm/release path.
675
- let ringShift;
676
- const storageMonitor = new StorageMonitor(rawStorage, options.arachnode?.storage ?? {});
677
- const ringSelector = new RingSelector(fretAdapter, storageMonitor, {
678
- minCapacity: 100 * 1024 * 1024,
679
- thresholds: {
680
- moveOut: 0.85,
681
- moveIn: 0.40
682
- },
683
- // Damping so the ring decision cannot thrash near a boundary
684
- // (docs/arachnode-ring-handoff.md § Part 1).
685
- smoothingAlpha: 0.2,
686
- deadband: 0.5,
687
- minDwellMs: 10 * 60 * 1000
688
- });
689
- // Determine and announce ring membership
690
- const peerId = node.peerId.toString();
691
- const arachnodeInfo = await ringSelector.createArachnodeInfo(peerId);
692
- fretAdapter.setArachnodeInfo(arachnodeInfo);
693
- log?.('Announced Arachnode membership: Ring %d', arachnodeInfo.ringDepth);
694
- // Setup restoration coordinator with FRET adapter
695
- const restorationCoordinatorV2 = new RestorationCoordinator(fretAdapter, { connect: (pid, protocol) => node.dialProtocol(pid, [protocol]) }, `/optimystic/${options.networkName}`, node.peerId.toString());
696
- // Update restore callback to use new coordinator
697
- const newRestoreCallback = async (blockId, rev) => {
698
- return await restorationCoordinatorV2.restore(blockId, rev);
699
- };
700
- // Replace the restore callback (this is a bit hacky, but works for now)
701
- storageRepo.createBlockStorage = (blockId) => new BlockStorage(blockId, rawStorage, newRestoreCallback);
702
- // --- Rebalance reaction: drive RebalanceMonitor + react via BlockTransferCoordinator ---
703
- // Nothing previously activated the rebalance path on a real node: initRebalanceMonitor was
704
- // never called, the monitor was never start()ed, and BlockTransferCoordinator (the
705
- // pull-gained / push-lost reaction primitive) was never constructed in src. This block lives
706
- // inside the arachnode `if (fret)` gate because both dependencies only exist here — the
707
- // fretAdapter and the RestorationCoordinator. When arachnode is disabled or FRET is absent the
708
- // rebalance path stays inert (acceptable: rebalance is a resilience optimization). A wiring
709
- // failure here is non-fatal (log + continue), unlike the operator-opted-in cohortTopic block.
710
- if (networkManager && (options.rebalance?.enabled ?? true) !== false) {
684
+ }
685
+ // Expose for tests/diagnostics (mirrors node.keyNetwork / node.reputation).
686
+ node.spreadOnChurnMonitor = spreadMonitor;
687
+ // Disposal: stop the spread monitor deterministically before the transports close. Composes
688
+ // with the arachnode / clusterMember / cohort-topic stop wrappers (each calls its captured
689
+ // previousStop last). Idempotent (SpreadOnChurnMonitor.stop early-returns when not running), so
690
+ // a double node.stop() does not throw. The owned-block feed teardown is the separate up-front
691
+ // wrapper above (shared across both monitors).
692
+ {
693
+ const previousStop = node.stop.bind(node);
694
+ node.stop = async () => {
711
695
  try {
712
- // repo → the LOCAL storageRepo (not repoProxy/coordinatedRepo): a pulled/pushed replica
713
- // must land in / be read from this node's own storage, same reasoning as the
714
- // blockTransfer service handler registration. protocolPrefix (/optimystic/<networkName>)
715
- // MUST match the prefix the node registers its block-transfer handler under, or every
716
- // lost-block push dials the wrong protocol and fails to connect.
717
- const coordinator = new BlockTransferCoordinator(storageRepo, keyNetwork, restorationCoordinatorV2, partitionDetector, protocolPrefix);
718
- const rebalanceMonitor = networkManager.initRebalanceMonitor(partitionDetector, fretAdapter, ownedBlocks, options.rebalance);
719
- await rebalanceMonitor.start();
720
- // onRebalance fires synchronously from the monitor's debounced check; the coordinator's
721
- // reaction (pull gained / push lost, each partition-guarded) is async, so hop it off the
722
- // handler rather than blocking the monitor's emit loop. handleRebalanceEvent can REJECT
723
- // (e.g. RestorationCoordinator.restore() throws while pulling a gained block) and a bare
724
- // `void` would surface that as an unhandled rejection (process-fatal on Node >=15); the
725
- // reaction is a resilience optimization, so swallow + log instead.
726
- //
727
- // ALONGSIDE dispatching to the coordinator, drive the shared owned-block set off this
728
- // authoritative responsibility signal. A GAINED block is added immediately so it is
729
- // tracked even before its next commit/replica touches the feed.
730
- //
731
- // A LOST block is NO LONGER released synchronously: doing so stopped spreading a block
732
- // whose push to the new owners might fail, drop it below the replication floor, and let a
733
- // later sweep reclaim it (docs/arachnode-ring-handoff.md § Why the current code violates
734
- // it #2). Instead the release is GATED on confirmation — the coordinator returns the lost
735
- // blocks it confirmed replicated to ≥ floor new owners, and ONLY those are untracked
736
- // (authoritative eviction from the shared set — complements spread's lazy self-prune) and
737
- // marked GC-eligible. A lost block whose push failed / was partition-skipped stays
738
- // tracked and served, and is retried on the next rebalance.
739
- //
740
- // Best-effort iteration safety: this eviction can mutate ownedBlocks while
741
- // SpreadOnChurnMonitor (or this monitor) is mid for...of over the same Set inside an
742
- // async loop. Adding/deleting a Set entry during iteration does not throw in JS — entries
743
- // are visited best-effort — which is acceptable for a resilience mechanism, so we
744
- // document it here rather than add locking.
745
- rebalanceMonitor.onRebalance((event) => {
746
- for (const blockId of event.gained)
747
- ownedBlocks.add(blockId);
748
- coordinator.handleRebalanceEvent(event).then((result) => {
749
- for (const blockId of result.released) {
750
- rebalanceMonitor.untrackBlock(blockId); // also evicts from the shared ownedBlocks set
751
- gcEligible.add(blockId); // confirmed replicated → safe to sweep
752
- }
753
- }).catch((err) => {
754
- log?.('rebalance reaction failed: %o', err);
755
- });
756
- });
757
- // Ring-shift handoff (advertise→confirm→release). It needs the confirmer (this
758
- // coordinator) and the cohort-size floor (this monitor), so it is wired here. The
759
- // `onRelease` callback runs Phase C's local effect: stop serving/spreading the shed
760
- // range and mark it GC-eligible — the same authoritative eviction the confirmed-rebalance
761
- // release performs.
762
- ringShift = new RingShiftCoordinator({
763
- fretAdapter,
764
- ringSelector,
765
- fret,
766
- partitionDetector,
767
- confirmer: coordinator,
768
- ownedBlocks,
769
- selfPeerId: peerId,
770
- getFloor: () => rebalanceMonitor.getCohortSize(),
771
- onRelease: (blockIds) => {
772
- for (const blockId of blockIds) {
773
- rebalanceMonitor.untrackBlock(blockId);
774
- gcEligible.add(blockId);
775
- }
776
- }
777
- });
778
- // Reconcile any stale `moving` advertisement left by a crash mid-handoff (no-op unless
779
- // arachnode metadata survived a restart still marked `moving`).
780
- ringShift.reconcileOnStart();
781
- // Feed owned blocks via the SINGLE shared feed (idempotent — already live if the spread
782
- // block above wired it). Both monitors read the same ownedBlocks set this populates.
783
- ensureOwnedBlockFeed();
784
- // Expose for tests/diagnostics (mirrors node.spreadOnChurnMonitor).
785
- node.rebalanceMonitor = rebalanceMonitor;
786
- node.blockTransferCoordinator = coordinator;
787
- node.ringShiftCoordinator = ringShift;
788
- // Disposal: stop the monitor before transports close. Composes with the other stop
789
- // wrappers (each calls its captured previousStop last). Idempotent — RebalanceMonitor.stop()
790
- // early-returns when not running (NetworkManagerService.stop() also stops it). The shared
791
- // owned-block feed teardown is the separate up-front wrapper (not duplicated here).
792
- const previousStop = node.stop.bind(node);
793
- node.stop = async () => {
794
- try {
795
- await rebalanceMonitor.stop();
796
- }
797
- finally {
798
- await previousStop();
799
- }
800
- };
696
+ if (spreadMonitor)
697
+ await spreadMonitor.stop();
801
698
  }
802
- catch (err) {
803
- // Rebalance is a resilience optimization, not a correctness requirement - a wiring
804
- // failure (e.g. FRET briefly unavailable) must NOT hard-fail node startup.
805
- log?.('rebalance wiring init failed: %o', err);
699
+ finally {
700
+ await previousStop();
806
701
  }
807
- }
808
- // Monitor capacity and adjust ring periodically. The damped `shouldTransition()` decides
809
- // WHETHER/where to move (docs/arachnode-ring-handoff.md § Part 1); the RingShiftCoordinator
810
- // carries the move out through the advertise→confirm→release handoff (§ Part 2) so a shift
811
- // never drops a key below its replication floor. The old unilateral `setArachnodeInfo` flip —
812
- // which changed advertised responsibility instantly with no data handoff — is gone.
813
- //
814
- // Ring shifts run ONLY when `ringShift` is wired (i.e. the rebalance reaction is enabled): a
815
- // move-out is unsafe without the confirm/release path, so a node with the rebalance reaction
816
- // disabled stays at its bootstrap ring rather than flipping unsafely.
817
- const monitorInterval = setInterval(async () => {
818
- if (!ringShift)
819
- return;
820
- const transition = await ringSelector.shouldTransition();
821
- if (transition.shouldMove && transition.direction && transition.newRingDepth !== undefined) {
822
- log?.('Ring transition needed: moving %s to Ring %d', transition.direction, transition.newRingDepth);
702
+ };
703
+ }
704
+ // Initialize Arachnode ring membership and restoration
705
+ const enableArachnode = options.arachnode?.enableRingZulu ?? true;
706
+ if (enableArachnode) {
707
+ const log = node.logger?.forComponent?.('db-p2p:arachnode');
708
+ const fret = node.services?.fret;
709
+ if (fret) {
710
+ const fretAdapter = new ArachnodeFretAdapter(fret, node.peerId.toString());
711
+ // Blocks whose shed range has been RELEASED (Phase C of a ring shift, or a confirmed
712
+ // rebalance release). This is the GC-eligibility signal the future storage sweep
713
+ // (`st-storage-sweep-archival-and-capacity-estimate`) must consult: a block's local bytes may
714
+ // be reclaimed ONLY once it appears here, so an unconfirmed / still-served range is never
715
+ // swept. Populated strictly after replication is confirmed. See
716
+ // docs/arachnode-ring-handoff.md § Part 2 (Local bytes vs. tracking).
717
+ // NOTE: no sweep consumes this set yet; it is the coordinated eligibility handoff the sweep
718
+ // ticket will read. Until then it grows unbounded — bound it when the sweep lands.
719
+ const gcEligible = new Set();
720
+ node.gcEligibleBlocks = gcEligible;
721
+ // The ring-shift state machine (advertise→confirm→release). Wired inside the rebalance block
722
+ // below (it needs the BlockTransferCoordinator confirmer + the cohort-size floor); left
723
+ // undefined when the rebalance reaction is not wired, in which case ring shifts stay inert —
724
+ // a move-out is unsafe without the confirm/release path.
725
+ let ringShift;
726
+ const storageMonitor = new StorageMonitor(rawStorage, options.arachnode?.storage ?? {});
727
+ const ringSelector = new RingSelector(fretAdapter, storageMonitor, {
728
+ minCapacity: 100 * 1024 * 1024,
729
+ thresholds: {
730
+ moveOut: 0.85,
731
+ moveIn: 0.40
732
+ },
733
+ // Damping so the ring decision cannot thrash near a boundary
734
+ // (docs/arachnode-ring-handoff.md § Part 1).
735
+ smoothingAlpha: 0.2,
736
+ deadband: 0.5,
737
+ minDwellMs: 10 * 60 * 1000
738
+ });
739
+ // Determine and announce ring membership
740
+ const peerId = node.peerId.toString();
741
+ const arachnodeInfo = await ringSelector.createArachnodeInfo(peerId);
742
+ fretAdapter.setArachnodeInfo(arachnodeInfo);
743
+ log?.('Announced Arachnode membership: Ring %d', arachnodeInfo.ringDepth);
744
+ // Setup restoration coordinator with FRET adapter
745
+ const restorationCoordinatorV2 = new RestorationCoordinator(fretAdapter, { connect: (pid, protocol) => node.dialProtocol(pid, [protocol]) }, `/optimystic/${options.networkName}`, node.peerId.toString());
746
+ // Update restore callback to use new coordinator
747
+ const newRestoreCallback = async (blockId, rev) => {
748
+ return await restorationCoordinatorV2.restore(blockId, rev);
749
+ };
750
+ // Replace the restore callback (this is a bit hacky, but works for now)
751
+ storageRepo.createBlockStorage = (blockId) => new BlockStorage(blockId, rawStorage, newRestoreCallback);
752
+ // --- Rebalance reaction: drive RebalanceMonitor + react via BlockTransferCoordinator ---
753
+ // Nothing previously activated the rebalance path on a real node: initRebalanceMonitor was
754
+ // never called, the monitor was never start()ed, and BlockTransferCoordinator (the
755
+ // pull-gained / push-lost reaction primitive) was never constructed in src. This block lives
756
+ // inside the arachnode `if (fret)` gate because both dependencies only exist here — the
757
+ // fretAdapter and the RestorationCoordinator. When arachnode is disabled or FRET is absent the
758
+ // rebalance path stays inert (acceptable: rebalance is a resilience optimization). A wiring
759
+ // failure here is non-fatal (log + continue), unlike the operator-opted-in cohortTopic block.
760
+ if (networkManager && (options.rebalance?.enabled ?? true) !== false) {
823
761
  try {
824
- const outcome = await ringShift.executeShift({
825
- direction: transition.direction,
826
- newRingDepth: transition.newRingDepth
762
+ // repo the LOCAL storageRepo (not repoProxy/coordinatedRepo): a pulled/pushed replica
763
+ // must land in / be read from this node's own storage, same reasoning as the
764
+ // blockTransfer service handler registration. protocolPrefix (/optimystic/<networkName>)
765
+ // MUST match the prefix the node registers its block-transfer handler under, or every
766
+ // lost-block push dials the wrong protocol and fails to connect.
767
+ const coordinator = new BlockTransferCoordinator(storageRepo, keyNetwork, restorationCoordinatorV2, partitionDetector, protocolPrefix);
768
+ const rebalanceMonitor = networkManager.initRebalanceMonitor(partitionDetector, fretAdapter, ownedBlocks, options.rebalance);
769
+ await rebalanceMonitor.start();
770
+ // onRebalance fires synchronously from the monitor's debounced check; the coordinator's
771
+ // reaction (pull gained / push lost, each partition-guarded) is async, so hop it off the
772
+ // handler rather than blocking the monitor's emit loop. handleRebalanceEvent can REJECT
773
+ // (e.g. RestorationCoordinator.restore() throws while pulling a gained block) and a bare
774
+ // `void` would surface that as an unhandled rejection (process-fatal on Node >=15); the
775
+ // reaction is a resilience optimization, so swallow + log instead.
776
+ //
777
+ // ALONGSIDE dispatching to the coordinator, drive the shared owned-block set off this
778
+ // authoritative responsibility signal. A GAINED block is added immediately so it is
779
+ // tracked even before its next commit/replica touches the feed.
780
+ //
781
+ // A LOST block is NO LONGER released synchronously: doing so stopped spreading a block
782
+ // whose push to the new owners might fail, drop it below the replication floor, and let a
783
+ // later sweep reclaim it (docs/arachnode-ring-handoff.md § Why the current code violates
784
+ // it #2). Instead the release is GATED on confirmation — the coordinator returns the lost
785
+ // blocks it confirmed replicated to ≥ floor new owners, and ONLY those are untracked
786
+ // (authoritative eviction from the shared set — complements spread's lazy self-prune) and
787
+ // marked GC-eligible. A lost block whose push failed / was partition-skipped stays
788
+ // tracked and served, and is retried on the next rebalance.
789
+ //
790
+ // Best-effort iteration safety: this eviction can mutate ownedBlocks while
791
+ // SpreadOnChurnMonitor (or this monitor) is mid for...of over the same Set inside an
792
+ // async loop. Adding/deleting a Set entry during iteration does not throw in JS — entries
793
+ // are visited best-effort — which is acceptable for a resilience mechanism, so we
794
+ // document it here rather than add locking.
795
+ rebalanceMonitor.onRebalance((event) => {
796
+ for (const blockId of event.gained)
797
+ ownedBlocks.add(blockId);
798
+ coordinator.handleRebalanceEvent(event).then((result) => {
799
+ for (const blockId of result.released) {
800
+ rebalanceMonitor.untrackBlock(blockId); // also evicts from the shared ownedBlocks set
801
+ gcEligible.add(blockId); // confirmed replicated → safe to sweep
802
+ }
803
+ }).catch((err) => {
804
+ log?.('rebalance reaction failed: %o', err);
805
+ });
806
+ });
807
+ // Ring-shift handoff (advertise→confirm→release). It needs the confirmer (this
808
+ // coordinator) and the cohort-size floor (this monitor), so it is wired here. The
809
+ // `onRelease` callback runs Phase C's local effect: stop serving/spreading the shed
810
+ // range and mark it GC-eligible — the same authoritative eviction the confirmed-rebalance
811
+ // release performs.
812
+ ringShift = new RingShiftCoordinator({
813
+ fretAdapter,
814
+ ringSelector,
815
+ fret,
816
+ partitionDetector,
817
+ confirmer: coordinator,
818
+ ownedBlocks,
819
+ selfPeerId: peerId,
820
+ getFloor: () => rebalanceMonitor.getCohortSize(),
821
+ onRelease: (blockIds) => {
822
+ for (const blockId of blockIds) {
823
+ rebalanceMonitor.untrackBlock(blockId);
824
+ gcEligible.add(blockId);
825
+ }
826
+ }
827
827
  });
828
- log?.('Ring shift outcome: %o', outcome);
828
+ // Reconcile any stale `moving` advertisement left by a crash mid-handoff (no-op unless
829
+ // arachnode metadata survived a restart still marked `moving`).
830
+ ringShift.reconcileOnStart();
831
+ // Feed owned blocks via the SINGLE shared feed (idempotent — already live if the spread
832
+ // block above wired it). Both monitors read the same ownedBlocks set this populates.
833
+ ensureOwnedBlockFeed();
834
+ // Expose for tests/diagnostics (mirrors node.spreadOnChurnMonitor).
835
+ node.rebalanceMonitor = rebalanceMonitor;
836
+ node.blockTransferCoordinator = coordinator;
837
+ node.ringShiftCoordinator = ringShift;
838
+ // Disposal: stop the monitor before transports close. Composes with the other stop
839
+ // wrappers (each calls its captured previousStop last). Idempotent — RebalanceMonitor.stop()
840
+ // early-returns when not running (NetworkManagerService.stop() also stops it). The shared
841
+ // owned-block feed teardown is the separate up-front wrapper (not duplicated here).
842
+ const previousStop = node.stop.bind(node);
843
+ node.stop = async () => {
844
+ try {
845
+ await rebalanceMonitor.stop();
846
+ }
847
+ finally {
848
+ await previousStop();
849
+ }
850
+ };
829
851
  }
830
852
  catch (err) {
831
- log?.('Ring shift failed: %o', err);
832
- }
833
- finally {
834
- // Measure the minimum dwell from the SETTLED shift (completed or rolled back), not
835
- // just the trigger stamped inside shouldTransition (docs/arachnode-ring-handoff.md §1.3).
836
- ringSelector.recordShiftSettled();
853
+ // Rebalance is a resilience optimization, not a correctness requirement - a wiring
854
+ // failure (e.g. FRET briefly unavailable) must NOT hard-fail node startup.
855
+ log?.('rebalance wiring init failed: %o', err);
837
856
  }
838
857
  }
839
- }, 60_000);
840
- // Cleanup on node stop
841
- const originalStop = node.stop.bind(node);
858
+ // Monitor capacity and adjust ring periodically. The damped `shouldTransition()` decides
859
+ // WHETHER/where to move (docs/arachnode-ring-handoff.md § Part 1); the RingShiftCoordinator
860
+ // carries the move out through the advertise→confirm→release handoff (§ Part 2) so a shift
861
+ // never drops a key below its replication floor. The old unilateral `setArachnodeInfo` flip —
862
+ // which changed advertised responsibility instantly with no data handoff — is gone.
863
+ //
864
+ // Ring shifts run ONLY when `ringShift` is wired (i.e. the rebalance reaction is enabled): a
865
+ // move-out is unsafe without the confirm/release path, so a node with the rebalance reaction
866
+ // disabled stays at its bootstrap ring rather than flipping unsafely.
867
+ const monitorInterval = setInterval(async () => {
868
+ if (!ringShift)
869
+ return;
870
+ const transition = await ringSelector.shouldTransition();
871
+ if (transition.shouldMove && transition.direction && transition.newRingDepth !== undefined) {
872
+ log?.('Ring transition needed: moving %s to Ring %d', transition.direction, transition.newRingDepth);
873
+ try {
874
+ const outcome = await ringShift.executeShift({
875
+ direction: transition.direction,
876
+ newRingDepth: transition.newRingDepth
877
+ });
878
+ log?.('Ring shift outcome: %o', outcome);
879
+ }
880
+ catch (err) {
881
+ log?.('Ring shift failed: %o', err);
882
+ }
883
+ finally {
884
+ // Measure the minimum dwell from the SETTLED shift (completed or rolled back), not
885
+ // just the trigger stamped inside shouldTransition (docs/arachnode-ring-handoff.md §1.3).
886
+ ringSelector.recordShiftSettled();
887
+ }
888
+ }
889
+ }, 60_000);
890
+ // Cleanup on node stop
891
+ const originalStop = node.stop.bind(node);
892
+ node.stop = async () => {
893
+ clearInterval(monitorInterval);
894
+ await originalStop();
895
+ };
896
+ }
897
+ else {
898
+ log?.('FRET service not available, Arachnode disabled');
899
+ }
900
+ }
901
+ // --- Seed the shared owned-block set from already-durable storage ---
902
+ // Blocks durable from a previous run are otherwise untracked until next touched (see the
903
+ // onAnyCollectionChange comment above where ownedBlocks is declared). Placed here, AFTER both
904
+ // monitor-wiring blocks (spread ~line 862, rebalance ~line 974) have had their chance to call
905
+ // ensureOwnedBlockFeed():
906
+ // - Gate on offOwnedBlockFeed: only seed when a monitor actually consumes ownedBlocks; if both
907
+ // are disabled the set is unused and the scan (plus the background task) is wasted work.
908
+ // - Feed-before-scan ordering is load-bearing: because the feed is already live, a block
909
+ // committed/replicated DURING the scan is caught by the feed; Set.add is idempotent so the
910
+ // overlap is harmless. Scanning before subscribing would drop a block committed in the gap.
911
+ // - Fire-and-forget so a large store never blocks startup; the .catch keeps a scan rejection
912
+ // from becoming an unhandled rejection.
913
+ // - Cancellable: a stop wrapper flips seedStopping so the scan loop breaks against a
914
+ // stopping/closing backend rather than running the enumeration to completion.
915
+ // NOTE: a concurrent rebalance release can untrackBlock (delete from ownedBlocks) a confirmed-
916
+ // released block while this scan is still running, and the scan could then re-add that id. Benign
917
+ // transient: the block is still in the metadata store (no sweep reclaims metadata yet), so a
918
+ // re-added released block is simply re-evaluated and re-released on the next rebalance tick. Right
919
+ // after a restart, responsibility-loss detection lags this fast metadata scan, so the window is
920
+ // small. Accepted rather than synchronized.
921
+ if (offOwnedBlockFeed && typeof rawStorage.listBlockIds === 'function') {
922
+ let seedStopping = false;
923
+ const previousStop = node.stop.bind(node);
842
924
  node.stop = async () => {
843
- clearInterval(monitorInterval);
844
- await originalStop();
925
+ seedStopping = true;
926
+ await previousStop();
845
927
  };
928
+ void seedOwnedBlocksFromStorage(rawStorage, ownedBlocks, () => seedStopping)
929
+ .catch((err) => (node.logger?.forComponent?.('db-p2p:owned-block-seed'))?.('seed failed: %o', err));
846
930
  }
847
- else {
848
- log?.('FRET service not available, Arachnode disabled');
931
+ // [dispute-subsystem-dormant] The DisputeService object is constructed below so tests and
932
+ // getDisputeStatus() work, but it is unreachable from the live network path:
933
+ // - No inbound handler: disputeProtocolService is NOT in the services map above.
934
+ // - onInvalidation is deliberately unset: maybeInvalidate() is a no-op on live nodes.
935
+ // - revalidate is deliberately unset: handleChallenge always votes inconclusive on live nodes.
936
+ // Full activation requires arbitrator-set anchoring before a forged synthetic cohort can pass resolution.
937
+ // Gate: tickets/backlog/hardening/invalidation-live-wiring-requires-arbitrator-set-anchoring
938
+ // Wiring plan: tickets/backlog/feat-dispute-subsystem-live-activation
939
+ // Initialize dispute service if enabled
940
+ let disputeServiceInstance;
941
+ if (options.dispute?.disputeEnabled) {
942
+ const createDisputeClient = (peerId) => DisputeClient.create(peerId, keyNetwork, protocolPrefix);
943
+ disputeServiceInstance = new DisputeService({
944
+ peerId: node.peerId,
945
+ privateKey: nodePrivateKey,
946
+ peerNetwork: keyNetwork,
947
+ createDisputeClient,
948
+ reputation,
949
+ validator: options.validator,
950
+ config: options.dispute,
951
+ selectArbitrators: async (blockId, excludePeers, count, round, epoch) => {
952
+ const { hashKey: fretHashKey } = await import('p2p-fret');
953
+ const fret = node.services?.fret;
954
+ if (!fret)
955
+ return [];
956
+ // Dispersed sampling: draw `count` peers from coordinates spread across the whole keyspace
957
+ // (hash(blockId ‖ round ‖ epoch ‖ i)) rather than the block's XOR neighborhood, so an attacker
958
+ // who owns the block's locale does not thereby own the arbitrators. `assembleCohort` already
959
+ // filters to known members; excluding the original cluster + self keeps arbitrators independent.
960
+ const excludeSet = new Set(excludePeers);
961
+ // NOTE: adding the local node's own id to `exclude` makes the draw node-relative. Cross-node
962
+ // determinism (the verifiable-recompute property) holds today only because the dissent
963
+ // coordinator running this is itself a member of the original cluster, so `self` is already in
964
+ // `excludePeers` — the add is a no-op and every honest node excludes the identical set. When a
965
+ // verify-path recompute lands, it MUST reconstruct `exclude` from the challenger's identity
966
+ // (`proof.challengerPeerId`) + original cluster, never the verifier's own id, or re-derivation diverges.
967
+ excludeSet.add(node.peerId.toString());
968
+ const picks = await sampleArbitrators({ blockId: new TextEncoder().encode(blockId), round, epoch, count, exclude: excludeSet }, (coord, wants) => fret.assembleCohort(coord, wants), fretHashKey);
969
+ return picks.map(pid => peerIdFromString(pid));
970
+ },
971
+ });
849
972
  }
850
- }
851
- // --- Seed the shared owned-block set from already-durable storage ---
852
- // Blocks durable from a previous run are otherwise untracked until next touched (see the
853
- // onAnyCollectionChange comment above where ownedBlocks is declared). Placed here, AFTER both
854
- // monitor-wiring blocks (spread ~line 862, rebalance ~line 974) have had their chance to call
855
- // ensureOwnedBlockFeed():
856
- // - Gate on offOwnedBlockFeed: only seed when a monitor actually consumes ownedBlocks; if both
857
- // are disabled the set is unused and the scan (plus the background task) is wasted work.
858
- // - Feed-before-scan ordering is load-bearing: because the feed is already live, a block
859
- // committed/replicated DURING the scan is caught by the feed; Set.add is idempotent so the
860
- // overlap is harmless. Scanning before subscribing would drop a block committed in the gap.
861
- // - Fire-and-forget so a large store never blocks startup; the .catch keeps a scan rejection
862
- // from becoming an unhandled rejection.
863
- // - Cancellable: a stop wrapper flips seedStopping so the scan loop breaks against a
864
- // stopping/closing backend rather than running the enumeration to completion.
865
- // NOTE: a concurrent rebalance release can untrackBlock (delete from ownedBlocks) a confirmed-
866
- // released block while this scan is still running, and the scan could then re-add that id. Benign
867
- // transient: the block is still in the metadata store (no sweep reclaims metadata yet), so a
868
- // re-added released block is simply re-evaluated and re-released on the next rebalance tick. Right
869
- // after a restart, responsibility-loss detection lags this fast metadata scan, so the window is
870
- // small. Accepted rather than synchronized.
871
- if (offOwnedBlockFeed && typeof rawStorage.listBlockIds === 'function') {
872
- let seedStopping = false;
873
- const previousStop = node.stop.bind(node);
874
- node.stop = async () => {
875
- seedStopping = true;
876
- await previousStop();
877
- };
878
- void seedOwnedBlocksFromStorage(rawStorage, ownedBlocks, () => seedStopping)
879
- .catch((err) => (node.logger?.forComponent?.('db-p2p:owned-block-seed'))?.('seed failed: %o', err));
880
- }
881
- // [dispute-subsystem-dormant] The DisputeService object is constructed below so tests and
882
- // getDisputeStatus() work, but it is unreachable from the live network path:
883
- // - No inbound handler: disputeProtocolService is NOT in the services map above.
884
- // - onInvalidation is deliberately unset: maybeInvalidate() is a no-op on live nodes.
885
- // - revalidate is deliberately unset: handleChallenge always votes inconclusive on live nodes.
886
- // Full activation requires arbitrator-set anchoring before a forged synthetic cohort can pass resolution.
887
- // Gate: tickets/backlog/hardening/invalidation-live-wiring-requires-arbitrator-set-anchoring
888
- // Wiring plan: tickets/backlog/feat-dispute-subsystem-live-activation
889
- // Initialize dispute service if enabled
890
- let disputeServiceInstance;
891
- if (options.dispute?.disputeEnabled) {
892
- const createDisputeClient = (peerId) => DisputeClient.create(peerId, keyNetwork, protocolPrefix);
893
- disputeServiceInstance = new DisputeService({
894
- peerId: node.peerId,
895
- privateKey: nodePrivateKey,
896
- peerNetwork: keyNetwork,
897
- createDisputeClient,
973
+ // The host-facing attachment surface, declared once in `optimystic-node.ts` and written here
974
+ // through ONE object literal so every field is type-checked AND a field added to
975
+ // `OptimysticNodeAttachments` but never assigned here is a compile error rather than an
976
+ // `undefined` a host reads as present. Keeping it typed is load-bearing: when
977
+ // `node.keyNetwork` was reachable only through a cast, three hosts found it easier to build a
978
+ // SECOND Libp2pKeyPeerNetwork from constructor defaults — a different cohort width and no
979
+ // network-membership filter than this node's own consensus path uses for the same key
980
+ // (ticket bug-second-key-network-built-with-defaults).
981
+ const attachments = {
982
+ coordinatedRepo,
983
+ storageRepo,
984
+ // The StorageRepo is the single commit funnel for both the coordinated and
985
+ // direct paths, so it is the node's per-collection change-notifier origin. This is the
986
+ // default; the cohort-topic activation block below REPLACES it with the origination-decorating
987
+ // bridge notifier when the substrate is enabled.
988
+ blockChangeNotifier: storageRepo,
989
+ keyNetwork,
898
990
  reputation,
899
- validator: options.validator,
900
- config: options.dispute,
901
- selectArbitrators: async (blockId, excludePeers, count, round, epoch) => {
902
- const { hashKey: fretHashKey } = await import('p2p-fret');
903
- const fret = node.services?.fret;
904
- if (!fret)
905
- return [];
906
- // Dispersed sampling: draw `count` peers from coordinates spread across the whole keyspace
907
- // (hash(blockId ‖ round ‖ epoch ‖ i)) rather than the block's XOR neighborhood, so an attacker
908
- // who owns the block's locale does not thereby own the arbitrators. `assembleCohort` already
909
- // filters to known members; excluding the original cluster + self keeps arbitrators independent.
910
- const excludeSet = new Set(excludePeers);
911
- // NOTE: adding the local node's own id to `exclude` makes the draw node-relative. Cross-node
912
- // determinism (the verifiable-recompute property) holds today only because the dissent
913
- // coordinator running this is itself a member of the original cluster, so `self` is already in
914
- // `excludePeers` — the add is a no-op and every honest node excludes the identical set. When a
915
- // verify-path recompute lands, it MUST reconstruct `exclude` from the challenger's identity
916
- // (`proof.challengerPeerId`) + original cluster, never the verifier's own id, or re-derivation diverges.
917
- excludeSet.add(node.peerId.toString());
918
- const picks = await sampleArbitrators({ blockId: new TextEncoder().encode(blockId), round, epoch, count, exclude: excludeSet }, (coord, wants) => fret.assembleCohort(coord, wants), fretHashKey);
919
- return picks.map(pid => peerIdFromString(pid));
920
- },
921
- });
922
- }
923
- // Cleanup cluster member intervals on node stop
924
- {
925
- const previousStop = node.stop.bind(node);
926
- node.stop = async () => {
927
- clusterImpl.dispose();
928
- await previousStop();
991
+ disputeService: disputeServiceInstance,
992
+ // The node's libp2p Ed25519 identity key. Exposed on the same attachment surface as
993
+ // coordinatedRepo/keyNetwork so a host can bind a client-transaction signer to it (the Quereus
994
+ // collection-factory's getSigner reuses this via signPeer). libp2p does not surface the private
995
+ // key on its public `Libp2p` interface, so this attachment is the sanctioned in-process handle.
996
+ // Ed25519 by construction (options.privateKey defaults to generateKeyPair('Ed25519')).
997
+ peerPrivateKey: nodePrivateKey,
929
998
  };
930
- }
931
- // Expose coordinated repo and storage for external use
932
- node.coordinatedRepo = coordinatedRepo;
933
- node.storageRepo = storageRepo;
934
- // The StorageRepo is the single commit funnel for both the coordinated and
935
- // direct paths, so it is the node's per-collection change-notifier origin. This is the
936
- // default; the cohort-topic activation block below REPLACES it with the origination-decorating
937
- // bridge notifier when the substrate is enabled.
938
- node.blockChangeNotifier = storageRepo;
939
- node.keyNetwork = keyNetwork;
940
- node.reputation = reputation;
941
- node.disputeService = disputeServiceInstance;
942
- // The node's libp2p Ed25519 identity key. Exposed on the same `(node as any).*` surface as
943
- // coordinatedRepo/keyNetwork so a host can bind a client-transaction signer to it (the Quereus
944
- // collection-factory's getSigner reuses this via signPeer). libp2p does not surface the private
945
- // key on its public `Libp2p` interface, so this attachment is the sanctioned in-process handle.
946
- // Ed25519 by construction (options.privateKey defaults to generateKeyPair('Ed25519')).
947
- node.peerPrivateKey = nodePrivateKey;
948
- // --- Cohort-topic origination activation (post-node: consumes the fully-assembled node + FRET) ---
949
- // This is the only place that is after the node + FRET are assembled (node.start() done, fretSvc
950
- // available) yet before any caller can capture `blockChangeNotifier` — the Quereus collection-factory
951
- // captures it once, immediately after createLibp2pNode returns, and reuses that reference as
952
- // `localChangeNotifier` for every NetworkTransactor it builds. Installing the bridge here makes the
953
- // origination path live for ALL collections created on the node.
954
- if (cohortEnabled) {
955
- // The host needs the full FRET engine surface; node.services.fret is the wrapper (see resolveFretEngine).
956
- const fret = resolveFretEngine(fretSvc);
957
- if (!fret) {
958
- // Operator opted in; degrading silently to the bare notifier would hide misconfiguration.
959
- // The node has already started (transports open, FRET running), so tear it down before the
960
- // hard-fail rather than leaking a started node + open transports on the rejection.
961
- await node.stop();
962
- throw new Error('cohortTopic enabled but the FRET service is unavailable on the node');
963
- }
964
- // A host-construction failure also hard-fails (operator opted in); stop the started node first so
965
- // the rejection does not leak open transports / a running FRET service. node.stop() runs the
966
- // already-installed arachnode + clusterMember teardown wrappers and closes the node's connections.
967
- let host;
968
- try {
969
- host = await createCohortTopicHost(node, fret, {
999
+ Object.assign(node, attachments);
1000
+ // --- Cohort-topic origination activation (post-node: consumes the fully-assembled node + FRET) ---
1001
+ // This is the only place that is after the node + FRET are assembled (node.start() done, fretSvc
1002
+ // available) yet before any caller can capture `blockChangeNotifier` — the Quereus collection-factory
1003
+ // captures it once, immediately after createLibp2pNode returns, and reuses that reference as
1004
+ // `localChangeNotifier` for every NetworkTransactor it builds. Installing the bridge here makes the
1005
+ // origination path live for ALL collections created on the node.
1006
+ if (cohortEnabled) {
1007
+ // The host needs the full FRET engine surface; node.services.fret is the wrapper (see resolveFretEngine).
1008
+ const fret = resolveFretEngine(fretSvc);
1009
+ if (!fret) {
1010
+ // Operator opted in; degrading silently to the bare notifier would hide misconfiguration.
1011
+ // (The started node is torn down by the post-start rollback `catch` at the bottom of this function.)
1012
+ throw new Error('cohortTopic enabled but the FRET service is unavailable on the node');
1013
+ }
1014
+ const host = await createCohortTopicHost(node, fret, {
970
1015
  ...(options.cohortTopic.host ?? {}),
971
1016
  // Wire the node's reputation service in as the production backing for the bootstrap-evidence
972
1017
  // referee verifier (the `{ isBanned, getScore }` view `PeerReputationService` satisfies), so a
@@ -985,243 +1030,279 @@ export async function createLibp2pNodeBase(options, defaults) {
985
1030
  privateKey: nodePrivateKey, // real k − x threshold signing
986
1031
  wantK: cohortWantK,
987
1032
  });
1033
+ // --- Cohort-topic + reactivity + matchmaking teardown ---
1034
+ // Installed HERE, immediately after `host` exists and BEFORE the ~230 lines of reactivity /
1035
+ // matchmaking wiring below, because the post-start rollback only unwinds resources whose stop
1036
+ // wrapper is already installed at the moment of the throw. With the wrapper at the END of the
1037
+ // block (where it used to live) a throw mid-wiring left the host's gossip timer and cohort-topic
1038
+ // protocol handlers running. The bindings it releases are therefore declared up front and
1039
+ // undefined-guarded — same idiom as `offOwnedBlockFeed` above — so this tears down exactly what
1040
+ // has been created so far, whether that is the host alone or the whole wiring.
1041
+ //
1042
+ // Ordering (load-bearing): release reactivity timers + protocol handlers BEFORE host.stop()
1043
+ // (which clears the cohort gossip timer + unhandles the cohort-topic protocols) BEFORE the node's
1044
+ // transports close (previousStop). Composes with the existing arachnode + clusterMember stop
1045
+ // wrappers (each calls its captured previousStop last). `node.unhandle` on a protocol that was
1046
+ // never registered does not throw — libp2p's registrar deletes each id from its handler map
1047
+ // (a miss is silently ignored) and then re-patches the peer store's advertised protocol list —
1048
+ // so the handler releases need no separate registration flags.
1049
+ const reactivityProtocols = DEFAULT_REACTIVITY_PROTOCOLS;
1050
+ const matchmakingProtocols = DEFAULT_MATCHMAKING_PROTOCOLS;
1051
+ let unsubscribeCohortBridge;
1052
+ let offInboundNotify;
1053
+ let pushStateGossip;
1054
+ let reactivityRotation;
1055
+ {
1056
+ const previousStop = node.stop.bind(node);
1057
+ node.stop = async () => {
1058
+ try {
1059
+ reactivityRotation?.stop();
1060
+ pushStateGossip?.stop();
1061
+ offInboundNotify?.();
1062
+ await node.unhandle(reactivityProtocolList(reactivityProtocols));
1063
+ await node.unhandle(matchmakingProtocolList(matchmakingProtocols));
1064
+ unsubscribeCohortBridge?.();
1065
+ await host.stop();
1066
+ }
1067
+ finally {
1068
+ await previousStop();
1069
+ }
1070
+ };
1071
+ }
1072
+ // selfIsCohortMember: this node owns the collection's reactivity-topic fan-out iff it is in the
1073
+ // FRET cohort around coord_0(H(currentTailId ‖ "reactivity")). Uses db-core's default hashes
1074
+ // (createReactivityTopicAnchor / createTierAddressing / createRingHash), byte-identical to the
1075
+ // host's internal `new RingHash()` and the subscriber-side anchor, and the SAME cohortWantK as
1076
+ // the host — so the coord + cohort line up across origination and subscription.
1077
+ const selfIsCohortMember = createReactivitySelfMembershipGate({
1078
+ fret,
1079
+ selfPeerId: node.peerId.toString(),
1080
+ wantK: cohortWantK,
1081
+ });
1082
+ unsubscribeCohortBridge = attachCohortChangeBridge(node, {
1083
+ source: storageRepo,
1084
+ service: host.service,
1085
+ selfIsCohortMember,
1086
+ extractCommitCert: makeClusterCommitCertExtractor(certStore),
1087
+ }).unsubscribe;
1088
+ // Expose the host so the reactivity origination wiring (and the activation test) can install
1089
+ // `CohortTopicService.onLocalCommit`.
1090
+ node.cohortTopicHost = host;
1091
+ // --- Reactivity notification transport (origination → fan-out → inbound delivery → push-state gossip) ---
1092
+ // Compose notify + forwarder-host + push-state-gossip onto the cohort-topic host so a committed change
1093
+ // on a tail-cohort member actually reaches subscribers on OTHER nodes over real sockets. The change
1094
+ // bridge above fires `onLocalCommit`; this is what the emitted notifications travel over.
1095
+ // (docs/reactivity.md §Notification origination / §Propagation.) Reactivity reuses the canonical,
1096
+ // network-agnostic protocol IDs, matching the cohort-topic family's production default.
1097
+ const selfPeerId = node.peerId.toString();
1098
+ const reactivityProfile = host.profile; // Edge ⇒ subscriber-only via the policy gate; Core forwards.
1099
+ const reactivityPolicy = reactivityNodePolicy(reactivityProfile);
1100
+ // db-core default anchor + tier addressing, byte-identical to the host's `new RingHash()`, the
1101
+ // origination gate, and the subscriber-side anchor — so coord_0 derivation lines up everywhere.
1102
+ const reactivityAddressing = createTierAddressing(createRingHash());
1103
+ // Reactivity's forwarder cohort sits at coord_0 — TREE tier 0 (peer-independent), distinct from the
1104
+ // CAPACITY tier T3 the verifier/willingness use. `registry.findServing` keys on the engine's tree
1105
+ // depth, so the served reactivity engine is found at tree tier 0, never at 3.
1106
+ const REACTIVITY_FORWARDER_TREE_TIER = 0;
1107
+ // Node-level subscriber registry: a constructed ReactivitySubscriptionManager registers here so a
1108
+ // socket-delivered NotificationV1 reaches it. (The Quereus Database.watch → manager bridge that
1109
+ // CONSTRUCTS managers stays the backlog item optimystic-network-reactive-watch-integration-test.)
1110
+ const reactivitySubscribers = new ReactivitySubscriberRegistry();
1111
+ node.reactivitySubscribers = reactivitySubscribers;
1112
+ // 1. Notify transport — unicast NotificationV1 send + inbound subscribe. selfPeerId guards self-dials.
1113
+ const notify = new Libp2pReactivityNotifyTransport(node, { selfPeerId });
1114
+ // 2. Forwarder host — turns the forward decision into live fan-out over the notify transport.
1115
+ const forwarderHost = new ReactivityForwarderHost({
1116
+ transport: notify,
1117
+ selfPeerId,
1118
+ profile: reactivityProfile,
1119
+ pushStateInit: (topicId, n) => ({
1120
+ collectionId: n.collectionId,
1121
+ topicId: bytesToB64url(topicId),
1122
+ tailIdAtJoin: n.tailId,
1123
+ deltaMaxBytes: reactivityPolicy.deltaMaxBytes,
1124
+ }),
1125
+ verifierFor: () => createNotificationVerifier({ verifier: host.service.verifier(), tier: Tier.T3 }),
1126
+ directSubscribers: (topicId) => {
1127
+ // Find the served reactivity engine at TREE tier 0 (see REACTIVITY_FORWARDER_TREE_TIER) and read
1128
+ // its direct-subscriber records. The adapter filters to reactivity appState and maps participantId
1129
+ // bytes → dialable peer-id strings (the transport's `peerIdFromString` space) — NOT base64url,
1130
+ // which would silently fail to dial. `undefined` (no subscriber has registered here yet) ⇒ [].
1131
+ const engine = host.registry.findServing(topicId, REACTIVITY_FORWARDER_TREE_TIER);
1132
+ return engine === undefined ? [] : reactivityDirectSubscribers(engine, topicId);
1133
+ },
1134
+ // No childCohorts until cohort-topic-parent-child-link populates PushState.childCohorts (single
1135
+ // tier-0 reach today); wire the resolver anyway. A child cohort's primary is the FRET-nearest member
1136
+ // of its coord, returned as a peer-id string (the dial space).
1137
+ resolveChildPrimary: (ref) => {
1138
+ const peers = fret.assembleCohort(b64urlToBytes(ref.coord), cohortWantK);
1139
+ return peers.length > 0 ? peers[0] : undefined;
1140
+ },
1141
+ deliverLocal: (topicId, n) => reactivitySubscribers.deliver(topicId, n),
1142
+ });
1143
+ // Inbound notify frames → forwarder host (subscriber role delivers in-process; forwarder role fans out).
1144
+ // NOTE: the four `register*Handler` helpers below (notify / pushStateGossip / recover /
1145
+ // matchmaking query) all call `node.handle(...)` fire-and-forget (`void`), so a rejected
1146
+ // registration escapes the post-start rollback `catch` as an UNHANDLED rejection instead of
1147
+ // failing node creation. Harmless today — every protocol id here is a fixed constant registered
1148
+ // exactly once, so the only realistic rejection is a duplicate, and that needs a caller to pass
1149
+ // overlapping custom `cohortTopic.host.protocols`. If any of these ids ever becomes
1150
+ // caller-configurable, or a helper grows a registration that can genuinely fail, make them await
1151
+ // their `node.handle` so the failure reaches the rollback.
1152
+ registerNotifyHandler(node, reactivityProtocols.notify, notify);
1153
+ offInboundNotify = notify.onNotification((from, n) => { void forwarderHost.onInbound(from, n); });
1154
+ // 3. Origination emit — install onLocalCommit: a member commit builds a NotificationV1 and ingests it.
1155
+ const origination = new ReactivityOriginationManager({
1156
+ service: host.service,
1157
+ resolveContext: (event) => {
1158
+ if (event.tailId === undefined) {
1159
+ return undefined; // tail-less (read-driven promotion) never originates (the gate also returns first)
1160
+ }
1161
+ return {
1162
+ // MUST reuse the gate's `reactivityTailBytes` (utf8), NOT db-core's double-hashing
1163
+ // blockIdToBytes — else origination derives a different coord than subscribers resolve.
1164
+ tailId: reactivityTailBytes(event.tailId),
1165
+ deltaMaxBytes: reactivityPolicy.deltaMaxBytes,
1166
+ // rotationHint stays undefined on a live node: the successor tail id is not knowable at the
1167
+ // filling commit (random block ids; gated on 6.5-block-id-derivation). The authoritative,
1168
+ // observable rotation signal is `event.tailId` CHANGING, which the manager observes via the
1169
+ // `markRotated` binding below. (The pre-announce remains exercised in the mock-tier harness +
1170
+ // the design simulator, both of which can synthesize the successor id.)
1171
+ };
1172
+ },
1173
+ // reactivityNotificationTopicId(n) = reactivityTopicId(b64urlToBytes(n.tailId)); since
1174
+ // n.tailId = b64url(reactivityTailBytes(tail)), this is the SAME topicId the gate assembled coord_0
1175
+ // around and the subscriber/forwarder verifier derives — closing the encoding loop.
1176
+ emit: (n) => { void forwarderHost.ingest(reactivityNotificationTopicId(n), n); },
1177
+ // Observe-rotation: when a collection's tail id changes between commits the OLD tail's reactivity
1178
+ // topic has rotated. Start its drain so the recover serve begins redirecting to the new tree (the
1179
+ // `reactivity-rotation-recover-redirect-drain` markRotated seam). `oldTopicId` is byte-identical to
1180
+ // the topic a subscriber subscribed under (both `reactivityTopicId(reactivityTailBytes(tail))`).
1181
+ markRotated: (oldTopicId, redirect, now) => forwarderHost.markRotated(oldTopicId, redirect, now),
1182
+ });
1183
+ origination.install();
1184
+ // 4. PushState gossip — periodic intra-cohort convergence so any member (not just the primary) can
1185
+ // serve a replay/backfill. Rides the host's cohort gossip transport (no second transport).
1186
+ pushStateGossip = new ReactivityPushStateGossipDriver({
1187
+ gossipTransport: host.gossipTransport,
1188
+ liveCollections: () => forwarderHost.livePushStates().map((pushState) => ({
1189
+ pushState,
1190
+ cohortCoord: reactivityAddressing.coord0(b64urlToBytes(pushState.topicId)),
1191
+ })),
1192
+ pushStateForGossip: (g) => forwarderHost.pushStateFor(b64urlToBytes(g.topicId)),
1193
+ // Authenticity gate: accept gossip only from a member of the cohort around the frame's reactivity
1194
+ // coord (per-frame peer-sig envelope signing is deferred — reactivity-pushstate-gossip's hardening backlog).
1195
+ isCohortMember: (fromPeerId, g) => fret.assembleCohort(reactivityAddressing.coord0(b64urlToBytes(g.topicId)), cohortWantK).includes(fromPeerId),
1196
+ });
1197
+ registerPushStateGossipHandler(node, reactivityProtocols.pushStateGossip, pushStateGossip);
1198
+ pushStateGossip.start();
1199
+ // 5. Recover RPC — the pull companion to notify (docs/reactivity.md §Backfill RPC / §Resume). A
1200
+ // subscriber that detected a gap, or woke from sleep past the live tail, asks a serving cohort member
1201
+ // "what did I miss?" and is brought current over a real request-reply socket. The SERVE side is live
1202
+ // here: this node answers RecoverRequestV1 frames against its live forwarder PushStates. The OUTBOUND
1203
+ // transport + signers are constructed and exposed for the subscribe factory that CONSTRUCTS managers
1204
+ // (the Quereus Database.watch app-bridge — backlog optimystic-network-reactive-watch-integration-test);
1205
+ // no node-internal manager calls them yet, exactly as the notify subscriber side is constructed against
1206
+ // `reactivitySubscribers` rather than from a watch.
1207
+ //
1208
+ // Node-level sticky cohort-hint cache (keyed by collectionId), shared between the outbound transport's
1209
+ // sticky-primary lookup and a future manager's rotation-invalidation so both see ONE cache. It starts
1210
+ // empty ⇒ the transport falls through to the cohort-walk (any member holding the gossiped PushState
1211
+ // answers); populating the sticky primary is a one-RT optimization, not a correctness need.
1212
+ const reactivityCohortHintCache = createStickyCohortHintCache();
1213
+ // topicId → dialable cohort member peer-id strings: the SAME FRET coord_0 assembly the push-state-gossip
1214
+ // authenticity gate uses (`reactivityAddressing.coord0` → `fret.assembleCohort`), so a recover walk
1215
+ // reaches exactly the cohort that holds the topic's gossiped PushState. `assembleCohort` returns peer-id
1216
+ // strings (the recover dialer's `peerIdFromString` space), matching the notify dial-target space.
1217
+ const resolveReactivityCohort = (topicId) => fret.assembleCohort(reactivityAddressing.coord0(topicId), cohortWantK);
1218
+ // Outbound transport: exposes the db-core BackfillTransport / ResumeTransport seams against this node.
1219
+ // maxBytes is omitted so the dialer + handler default to DEFAULT_STREAM_MAX_BYTES, matching the notify
1220
+ // transport's default (constructed above without an override) — one frame ceiling across the family.
1221
+ const recover = new Libp2pReactivityRecoverTransport({
1222
+ dialer: createLibp2pRecoverDialer(node, reactivityProtocols.recover),
1223
+ selfPeerId,
1224
+ cohortHintCache: reactivityCohortHintCache,
1225
+ resolveCohort: resolveReactivityCohort,
1226
+ });
1227
+ // Inbound serve handler: decode (bounded) → verify the dialing peer's signature → freshness/replay gate →
1228
+ // resolve the live PushState off the forwarder host → serveBackfill/serveResume → reply (no reply on any
1229
+ // failure; the stream aborts and the subscriber walks/chain-reads). One node-level replay guard is shared
1230
+ // across all recover requests — a plain pruned-on-access map, so no new timer to tear down.
1231
+ registerRecoverHandler(node, reactivityProtocols.recover, {
1232
+ pushStateFor: forwarderHost.pushStateFor.bind(forwarderHost),
1233
+ pushStateForCollection: forwarderHost.pushStateForCollection.bind(forwarderHost),
1234
+ replayGuard: createCorrelationReplayGuard(),
1235
+ rotationFor: (req, now) => {
1236
+ // Drain-window redirect: a recover reaching an OLD (rotated, still-draining) tail is bounced to
1237
+ // the new tree (reactivity-rotation-recover-redirect-drain). A resume carries the stale topic
1238
+ // (topicId = reactivityTopicId(latestKnownTailId)); a backfill carries no topic, so resolve the
1239
+ // collection's current served topic. rotationRedirectFor returns the gate's redirect while
1240
+ // draining and undefined once drained (then evicting the gate + the old tail's served PushState).
1241
+ const oldTopicId = req.topicId ?? resolveCurrentServedTopic(forwarderHost, req.collectionId);
1242
+ return oldTopicId === undefined ? undefined : forwarderHost.rotationRedirectFor(oldTopicId, now);
1243
+ },
1244
+ });
1245
+ // The subscriber's synchronous request signers over the node's Ed25519 key (resolves the recover wiring's
1246
+ // lone design point — see recover-transport.ts §createRecoverRequestSigners). Fed to a manager by the
1247
+ // subscribe factory alongside recover.backfillTransport(topicId, collectionId) /
1248
+ // recover.resumeTransport(topicId, collectionId).
1249
+ const recoverSigners = createRecoverRequestSigners(nodePrivateKey);
1250
+ // Expose the recover seams so the subscribe factory wires backfill/resume RPC + signers + the shared
1251
+ // sticky cache (mirrors `reactivitySubscribers` above).
1252
+ node.reactivityRecover = recover;
1253
+ node.reactivityRecoverSigners = recoverSigners;
1254
+ node.reactivityCohortHintCache = reactivityCohortHintCache;
1255
+ // 6. Rotation re-registration scheduler — the host timer that moves a subscriber to the rotated tree
1256
+ // when its manager surfaces a `RotationNotice` (`reactivity-rotation-rereg-scheduler`). Constructed with
1257
+ // the default unref'd `setTimeout` timer so an idle re-registration never pins the process. The
1258
+ // `reRegister(plan)` MOVE belongs to the subscribe factory that CONSTRUCTS managers (the deferred Quereus
1259
+ // `Database.watch` bridge — backlog optimystic-network-reactive-watch-integration-test): on fire it builds
1260
+ // a fresh `ReactivitySubscriptionManager` under `plan.newTopicId` carrying `plan.lastRevision`, registers
1261
+ // it, and swaps the `ReactivitySubscriberRegistry` entry — registering the NEW-topic handler BEFORE
1262
+ // unregistering the old, so a notification mid-swap is never dropped. Until that factory lands no
1263
+ // node-internal manager drives `schedule()`, so this seam is a logged no-op — exactly as 12.33 exposed
1264
+ // `reactivitySubscribers` / `reactivityRecover` without a live manager constructor.
1265
+ reactivityRotation = new RotationReRegistrationScheduler({
1266
+ reRegister: (plan) => {
1267
+ reactivityWiringLog("reactivity rotation re-registration fired for successor topic=%s (lastRevision=%d) but no subscribe factory is wired yet — deferred to optimystic-network-reactive-watch-integration-test", bytesToB64url(plan.newTopicId), plan.lastRevision);
1268
+ return Promise.resolve();
1269
+ },
1270
+ });
1271
+ node.reactivityRotation = reactivityRotation;
1272
+ // --- Matchmaking QueryV1 RPC — cohort serve side (docs/matchmaking.md §Seeker query) ---
1273
+ // The server half of the seeker query transport: a remote seeker dials `/optimystic/matchmaking/1.0.0/query`
1274
+ // and this node answers with its cohort's locally-held provider/seeker registrations, signed by the node
1275
+ // peer key. Matchmaking is layered ABOVE the cohort-topic substrate, so it owns its own protocol family
1276
+ // and is wired here (the composition root) over the host's PUBLIC surface only — mirroring the reactivity
1277
+ // registration above; nothing reaches into host.ts internals. The OUTBOUND seeker walk client is the
1278
+ // prereq follow-on `matchmaking-query-rpc-seeker-walk`; only the serve side is live here.
1279
+ registerMatchmakingQueryHandler(node, matchmakingProtocols.query, {
1280
+ registry: host.registry,
1281
+ // Reuse the reactivity addressing: createTierAddressing(createRingHash()) is byte-identical to the
1282
+ // host's internal addressing for the tier-0 coord (peer- and fanout-independent), and the handler
1283
+ // only ever derives coord_0(topicId).
1284
+ addressing: reactivityAddressing,
1285
+ // Single-member reply signature over the node peer key (same pattern reactivity uses for its signers).
1286
+ sign: async (payload) => bytesToB64url(await signPeer(nodePrivateKey, payload)),
1287
+ // Anti-DoS rate-limit seam (backlog matchmaking-query-rate-limit) intentionally left unwired here:
1288
+ // default-allow. When that ticket lands it passes a `gate: (from, topicId) => boolean` that limits on
1289
+ // the connection's verified `from` peer (NOT the self-asserted query.requesterId).
1290
+ });
988
1291
  }
989
- catch (err) {
1292
+ return node;
1293
+ }
1294
+ catch (err) {
1295
+ // Post-start rollback. node.stop() runs whatever teardown wrappers were installed BEFORE the throw
1296
+ // (each wrapper is registered next to the resource it releases, precisely so this unwinds as much as
1297
+ // exists) and closes the transports. A rollback failure must never mask the real startup error, so it
1298
+ // is logged and swallowed; `err` is what the caller sees.
1299
+ try {
990
1300
  await node.stop();
991
- throw err;
992
1301
  }
993
- // selfIsCohortMember: this node owns the collection's reactivity-topic fan-out iff it is in the
994
- // FRET cohort around coord_0(H(currentTailId "reactivity")). Uses db-core's default hashes
995
- // (createReactivityTopicAnchor / createTierAddressing / createRingHash), byte-identical to the
996
- // host's internal `new RingHash()` and the subscriber-side anchor, and the SAME cohortWantK as
997
- // the host — so the coord + cohort line up across origination and subscription.
998
- const selfIsCohortMember = createReactivitySelfMembershipGate({
999
- fret,
1000
- selfPeerId: node.peerId.toString(),
1001
- wantK: cohortWantK,
1002
- });
1003
- const { unsubscribe } = attachCohortChangeBridge(node, {
1004
- source: storageRepo,
1005
- service: host.service,
1006
- selfIsCohortMember,
1007
- extractCommitCert: makeClusterCommitCertExtractor(certStore),
1008
- });
1009
- // Expose the host so the reactivity origination wiring (and the activation test) can install
1010
- // `CohortTopicService.onLocalCommit`.
1011
- node.cohortTopicHost = host;
1012
- // --- Reactivity notification transport (origination → fan-out → inbound delivery → push-state gossip) ---
1013
- // Compose notify + forwarder-host + push-state-gossip onto the cohort-topic host so a committed change
1014
- // on a tail-cohort member actually reaches subscribers on OTHER nodes over real sockets. The change
1015
- // bridge above fires `onLocalCommit`; this is what the emitted notifications travel over.
1016
- // (docs/reactivity.md §Notification origination / §Propagation.) Reactivity reuses the canonical,
1017
- // network-agnostic protocol IDs, matching the cohort-topic family's production default.
1018
- const selfPeerId = node.peerId.toString();
1019
- const reactivityProtocols = DEFAULT_REACTIVITY_PROTOCOLS;
1020
- const reactivityProfile = host.profile; // Edge ⇒ subscriber-only via the policy gate; Core forwards.
1021
- const reactivityPolicy = reactivityNodePolicy(reactivityProfile);
1022
- // db-core default anchor + tier addressing, byte-identical to the host's `new RingHash()`, the
1023
- // origination gate, and the subscriber-side anchor — so coord_0 derivation lines up everywhere.
1024
- const reactivityAddressing = createTierAddressing(createRingHash());
1025
- // Reactivity's forwarder cohort sits at coord_0 — TREE tier 0 (peer-independent), distinct from the
1026
- // CAPACITY tier T3 the verifier/willingness use. `registry.findServing` keys on the engine's tree
1027
- // depth, so the served reactivity engine is found at tree tier 0, never at 3.
1028
- const REACTIVITY_FORWARDER_TREE_TIER = 0;
1029
- // Node-level subscriber registry: a constructed ReactivitySubscriptionManager registers here so a
1030
- // socket-delivered NotificationV1 reaches it. (The Quereus Database.watch → manager bridge that
1031
- // CONSTRUCTS managers stays the backlog item optimystic-network-reactive-watch-integration-test.)
1032
- const reactivitySubscribers = new ReactivitySubscriberRegistry();
1033
- node.reactivitySubscribers = reactivitySubscribers;
1034
- // 1. Notify transport — unicast NotificationV1 send + inbound subscribe. selfPeerId guards self-dials.
1035
- const notify = new Libp2pReactivityNotifyTransport(node, { selfPeerId });
1036
- // 2. Forwarder host — turns the forward decision into live fan-out over the notify transport.
1037
- const forwarderHost = new ReactivityForwarderHost({
1038
- transport: notify,
1039
- selfPeerId,
1040
- profile: reactivityProfile,
1041
- pushStateInit: (topicId, n) => ({
1042
- collectionId: n.collectionId,
1043
- topicId: bytesToB64url(topicId),
1044
- tailIdAtJoin: n.tailId,
1045
- deltaMaxBytes: reactivityPolicy.deltaMaxBytes,
1046
- }),
1047
- verifierFor: () => createNotificationVerifier({ verifier: host.service.verifier(), tier: Tier.T3 }),
1048
- directSubscribers: (topicId) => {
1049
- // Find the served reactivity engine at TREE tier 0 (see REACTIVITY_FORWARDER_TREE_TIER) and read
1050
- // its direct-subscriber records. The adapter filters to reactivity appState and maps participantId
1051
- // bytes → dialable peer-id strings (the transport's `peerIdFromString` space) — NOT base64url,
1052
- // which would silently fail to dial. `undefined` (no subscriber has registered here yet) ⇒ [].
1053
- const engine = host.registry.findServing(topicId, REACTIVITY_FORWARDER_TREE_TIER);
1054
- return engine === undefined ? [] : reactivityDirectSubscribers(engine, topicId);
1055
- },
1056
- // No childCohorts until cohort-topic-parent-child-link populates PushState.childCohorts (single
1057
- // tier-0 reach today); wire the resolver anyway. A child cohort's primary is the FRET-nearest member
1058
- // of its coord, returned as a peer-id string (the dial space).
1059
- resolveChildPrimary: (ref) => {
1060
- const peers = fret.assembleCohort(b64urlToBytes(ref.coord), cohortWantK);
1061
- return peers.length > 0 ? peers[0] : undefined;
1062
- },
1063
- deliverLocal: (topicId, n) => reactivitySubscribers.deliver(topicId, n),
1064
- });
1065
- // Inbound notify frames → forwarder host (subscriber role delivers in-process; forwarder role fans out).
1066
- registerNotifyHandler(node, reactivityProtocols.notify, notify);
1067
- const offInboundNotify = notify.onNotification((from, n) => { void forwarderHost.onInbound(from, n); });
1068
- // 3. Origination emit — install onLocalCommit: a member commit builds a NotificationV1 and ingests it.
1069
- const origination = new ReactivityOriginationManager({
1070
- service: host.service,
1071
- resolveContext: (event) => {
1072
- if (event.tailId === undefined) {
1073
- return undefined; // tail-less (read-driven promotion) never originates (the gate also returns first)
1074
- }
1075
- return {
1076
- // MUST reuse the gate's `reactivityTailBytes` (utf8), NOT db-core's double-hashing
1077
- // blockIdToBytes — else origination derives a different coord than subscribers resolve.
1078
- tailId: reactivityTailBytes(event.tailId),
1079
- deltaMaxBytes: reactivityPolicy.deltaMaxBytes,
1080
- // rotationHint stays undefined on a live node: the successor tail id is not knowable at the
1081
- // filling commit (random block ids; gated on 6.5-block-id-derivation). The authoritative,
1082
- // observable rotation signal is `event.tailId` CHANGING, which the manager observes via the
1083
- // `markRotated` binding below. (The pre-announce remains exercised in the mock-tier harness +
1084
- // the design simulator, both of which can synthesize the successor id.)
1085
- };
1086
- },
1087
- // reactivityNotificationTopicId(n) = reactivityTopicId(b64urlToBytes(n.tailId)); since
1088
- // n.tailId = b64url(reactivityTailBytes(tail)), this is the SAME topicId the gate assembled coord_0
1089
- // around and the subscriber/forwarder verifier derives — closing the encoding loop.
1090
- emit: (n) => { void forwarderHost.ingest(reactivityNotificationTopicId(n), n); },
1091
- // Observe-rotation: when a collection's tail id changes between commits the OLD tail's reactivity
1092
- // topic has rotated. Start its drain so the recover serve begins redirecting to the new tree (the
1093
- // `reactivity-rotation-recover-redirect-drain` markRotated seam). `oldTopicId` is byte-identical to
1094
- // the topic a subscriber subscribed under (both `reactivityTopicId(reactivityTailBytes(tail))`).
1095
- markRotated: (oldTopicId, redirect, now) => forwarderHost.markRotated(oldTopicId, redirect, now),
1096
- });
1097
- origination.install();
1098
- // 4. PushState gossip — periodic intra-cohort convergence so any member (not just the primary) can
1099
- // serve a replay/backfill. Rides the host's cohort gossip transport (no second transport).
1100
- const pushStateGossip = new ReactivityPushStateGossipDriver({
1101
- gossipTransport: host.gossipTransport,
1102
- liveCollections: () => forwarderHost.livePushStates().map((pushState) => ({
1103
- pushState,
1104
- cohortCoord: reactivityAddressing.coord0(b64urlToBytes(pushState.topicId)),
1105
- })),
1106
- pushStateForGossip: (g) => forwarderHost.pushStateFor(b64urlToBytes(g.topicId)),
1107
- // Authenticity gate: accept gossip only from a member of the cohort around the frame's reactivity
1108
- // coord (per-frame peer-sig envelope signing is deferred — reactivity-pushstate-gossip's hardening backlog).
1109
- isCohortMember: (fromPeerId, g) => fret.assembleCohort(reactivityAddressing.coord0(b64urlToBytes(g.topicId)), cohortWantK).includes(fromPeerId),
1110
- });
1111
- registerPushStateGossipHandler(node, reactivityProtocols.pushStateGossip, pushStateGossip);
1112
- pushStateGossip.start();
1113
- // 5. Recover RPC — the pull companion to notify (docs/reactivity.md §Backfill RPC / §Resume). A
1114
- // subscriber that detected a gap, or woke from sleep past the live tail, asks a serving cohort member
1115
- // "what did I miss?" and is brought current over a real request-reply socket. The SERVE side is live
1116
- // here: this node answers RecoverRequestV1 frames against its live forwarder PushStates. The OUTBOUND
1117
- // transport + signers are constructed and exposed for the subscribe factory that CONSTRUCTS managers
1118
- // (the Quereus Database.watch app-bridge — backlog optimystic-network-reactive-watch-integration-test);
1119
- // no node-internal manager calls them yet, exactly as the notify subscriber side is constructed against
1120
- // `reactivitySubscribers` rather than from a watch.
1121
- //
1122
- // Node-level sticky cohort-hint cache (keyed by collectionId), shared between the outbound transport's
1123
- // sticky-primary lookup and a future manager's rotation-invalidation so both see ONE cache. It starts
1124
- // empty ⇒ the transport falls through to the cohort-walk (any member holding the gossiped PushState
1125
- // answers); populating the sticky primary is a one-RT optimization, not a correctness need.
1126
- const reactivityCohortHintCache = createStickyCohortHintCache();
1127
- // topicId → dialable cohort member peer-id strings: the SAME FRET coord_0 assembly the push-state-gossip
1128
- // authenticity gate uses (`reactivityAddressing.coord0` → `fret.assembleCohort`), so a recover walk
1129
- // reaches exactly the cohort that holds the topic's gossiped PushState. `assembleCohort` returns peer-id
1130
- // strings (the recover dialer's `peerIdFromString` space), matching the notify dial-target space.
1131
- const resolveReactivityCohort = (topicId) => fret.assembleCohort(reactivityAddressing.coord0(topicId), cohortWantK);
1132
- // Outbound transport: exposes the db-core BackfillTransport / ResumeTransport seams against this node.
1133
- // maxBytes is omitted so the dialer + handler default to DEFAULT_STREAM_MAX_BYTES, matching the notify
1134
- // transport's default (constructed above without an override) — one frame ceiling across the family.
1135
- const recover = new Libp2pReactivityRecoverTransport({
1136
- dialer: createLibp2pRecoverDialer(node, reactivityProtocols.recover),
1137
- selfPeerId,
1138
- cohortHintCache: reactivityCohortHintCache,
1139
- resolveCohort: resolveReactivityCohort,
1140
- });
1141
- // Inbound serve handler: decode (bounded) → verify the dialing peer's signature → freshness/replay gate →
1142
- // resolve the live PushState off the forwarder host → serveBackfill/serveResume → reply (no reply on any
1143
- // failure; the stream aborts and the subscriber walks/chain-reads). One node-level replay guard is shared
1144
- // across all recover requests — a plain pruned-on-access map, so no new timer to tear down.
1145
- registerRecoverHandler(node, reactivityProtocols.recover, {
1146
- pushStateFor: forwarderHost.pushStateFor.bind(forwarderHost),
1147
- pushStateForCollection: forwarderHost.pushStateForCollection.bind(forwarderHost),
1148
- replayGuard: createCorrelationReplayGuard(),
1149
- rotationFor: (req, now) => {
1150
- // Drain-window redirect: a recover reaching an OLD (rotated, still-draining) tail is bounced to
1151
- // the new tree (reactivity-rotation-recover-redirect-drain). A resume carries the stale topic
1152
- // (topicId = reactivityTopicId(latestKnownTailId)); a backfill carries no topic, so resolve the
1153
- // collection's current served topic. rotationRedirectFor returns the gate's redirect while
1154
- // draining and undefined once drained (then evicting the gate + the old tail's served PushState).
1155
- const oldTopicId = req.topicId ?? resolveCurrentServedTopic(forwarderHost, req.collectionId);
1156
- return oldTopicId === undefined ? undefined : forwarderHost.rotationRedirectFor(oldTopicId, now);
1157
- },
1158
- });
1159
- // The subscriber's synchronous request signers over the node's Ed25519 key (resolves the recover wiring's
1160
- // lone design point — see recover-transport.ts §createRecoverRequestSigners). Fed to a manager by the
1161
- // subscribe factory alongside recover.backfillTransport(topicId, collectionId) /
1162
- // recover.resumeTransport(topicId, collectionId).
1163
- const recoverSigners = createRecoverRequestSigners(nodePrivateKey);
1164
- // Expose the recover seams so the subscribe factory wires backfill/resume RPC + signers + the shared
1165
- // sticky cache (mirrors `reactivitySubscribers` above).
1166
- node.reactivityRecover = recover;
1167
- node.reactivityRecoverSigners = recoverSigners;
1168
- node.reactivityCohortHintCache = reactivityCohortHintCache;
1169
- // 6. Rotation re-registration scheduler — the host timer that moves a subscriber to the rotated tree
1170
- // when its manager surfaces a `RotationNotice` (`reactivity-rotation-rereg-scheduler`). Constructed with
1171
- // the default unref'd `setTimeout` timer so an idle re-registration never pins the process. The
1172
- // `reRegister(plan)` MOVE belongs to the subscribe factory that CONSTRUCTS managers (the deferred Quereus
1173
- // `Database.watch` bridge — backlog optimystic-network-reactive-watch-integration-test): on fire it builds
1174
- // a fresh `ReactivitySubscriptionManager` under `plan.newTopicId` carrying `plan.lastRevision`, registers
1175
- // it, and swaps the `ReactivitySubscriberRegistry` entry — registering the NEW-topic handler BEFORE
1176
- // unregistering the old, so a notification mid-swap is never dropped. Until that factory lands no
1177
- // node-internal manager drives `schedule()`, so this seam is a logged no-op — exactly as 12.33 exposed
1178
- // `reactivitySubscribers` / `reactivityRecover` without a live manager constructor.
1179
- const reactivityRotation = new RotationReRegistrationScheduler({
1180
- reRegister: (plan) => {
1181
- reactivityWiringLog("reactivity rotation re-registration fired for successor topic=%s (lastRevision=%d) but no subscribe factory is wired yet — deferred to optimystic-network-reactive-watch-integration-test", bytesToB64url(plan.newTopicId), plan.lastRevision);
1182
- return Promise.resolve();
1183
- },
1184
- });
1185
- node.reactivityRotation = reactivityRotation;
1186
- // --- Matchmaking QueryV1 RPC — cohort serve side (docs/matchmaking.md §Seeker query) ---
1187
- // The server half of the seeker query transport: a remote seeker dials `/optimystic/matchmaking/1.0.0/query`
1188
- // and this node answers with its cohort's locally-held provider/seeker registrations, signed by the node
1189
- // peer key. Matchmaking is layered ABOVE the cohort-topic substrate, so it owns its own protocol family
1190
- // and is wired here (the composition root) over the host's PUBLIC surface only — mirroring the reactivity
1191
- // registration above; nothing reaches into host.ts internals. The OUTBOUND seeker walk client is the
1192
- // prereq follow-on `matchmaking-query-rpc-seeker-walk`; only the serve side is live here.
1193
- const matchmakingProtocols = DEFAULT_MATCHMAKING_PROTOCOLS;
1194
- registerMatchmakingQueryHandler(node, matchmakingProtocols.query, {
1195
- registry: host.registry,
1196
- // Reuse the reactivity addressing: createTierAddressing(createRingHash()) is byte-identical to the
1197
- // host's internal addressing for the tier-0 coord (peer- and fanout-independent), and the handler
1198
- // only ever derives coord_0(topicId).
1199
- addressing: reactivityAddressing,
1200
- // Single-member reply signature over the node peer key (same pattern reactivity uses for its signers).
1201
- sign: async (payload) => bytesToB64url(await signPeer(nodePrivateKey, payload)),
1202
- // Anti-DoS rate-limit seam (backlog matchmaking-query-rate-limit) intentionally left unwired here:
1203
- // default-allow. When that ticket lands it passes a `gate: (from, topicId) => boolean` that limits on
1204
- // the connection's verified `from` peer (NOT the self-asserted query.requesterId).
1205
- });
1206
- // Teardown: release reactivity timers + protocol handlers BEFORE host.stop() (which clears the cohort
1207
- // gossip timer + unhandles the cohort-topic protocols) BEFORE the node's transports close (previousStop).
1208
- // Composes with the existing arachnode + clusterMember stop wrappers (each calls its captured previousStop last).
1209
- const previousStop = node.stop.bind(node);
1210
- node.stop = async () => {
1211
- try {
1212
- reactivityRotation.stop();
1213
- pushStateGossip.stop();
1214
- offInboundNotify();
1215
- await node.unhandle(reactivityProtocolList(reactivityProtocols));
1216
- await node.unhandle(matchmakingProtocolList(matchmakingProtocols));
1217
- unsubscribe();
1218
- await host.stop();
1219
- }
1220
- finally {
1221
- await previousStop();
1222
- }
1223
- };
1302
+ catch (stopErr) {
1303
+ wiringLog('rollback stop failed after startup error: %o', stopErr);
1304
+ }
1305
+ throw err;
1224
1306
  }
1225
- return node;
1226
1307
  }
1227
1308
  //# sourceMappingURL=libp2p-node-base.js.map