@serfab/cadre-core 1.16.0 → 1.18.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 (268) hide show
  1. package/README.md +4 -3
  2. package/dist/bootstrap-peer-store-file.js +1 -1
  3. package/dist/bootstrap-peer-store.d.ts +1 -1
  4. package/dist/bootstrap-peer-store.js +4 -4
  5. package/dist/cadre-invite-protocol.d.ts +81 -142
  6. package/dist/cadre-invite-protocol.js +168 -458
  7. package/dist/cadre-invite-protocol.js.map +1 -1
  8. package/dist/cadre-join-request.d.ts +15 -2
  9. package/dist/cadre-join-request.js +22 -3
  10. package/dist/cadre-join-request.js.map +1 -1
  11. package/dist/cadre-node.d.ts +1089 -475
  12. package/dist/cadre-node.js +2170 -1037
  13. package/dist/cadre-node.js.map +1 -1
  14. package/dist/control-authorization.d.ts +36 -14
  15. package/dist/control-authorization.js +20 -3
  16. package/dist/control-authorization.js.map +1 -1
  17. package/dist/control-cohort.d.ts +88 -32
  18. package/dist/control-cohort.js +91 -33
  19. package/dist/control-cohort.js.map +1 -1
  20. package/dist/control-database.d.ts +856 -318
  21. package/dist/control-database.js +1422 -701
  22. package/dist/control-database.js.map +1 -1
  23. package/dist/control-formation-recorder.d.ts +46 -43
  24. package/dist/control-formation-recorder.js +77 -78
  25. package/dist/control-formation-recorder.js.map +1 -1
  26. package/dist/control-protocol-guard.d.ts +11 -4
  27. package/dist/control-protocol-guard.js +20 -5
  28. package/dist/control-protocol-guard.js.map +1 -1
  29. package/dist/control-schema-version.d.ts +97 -0
  30. package/dist/control-schema-version.js +225 -0
  31. package/dist/control-schema-version.js.map +1 -0
  32. package/dist/control-schema.d.ts +45 -5
  33. package/dist/control-schema.js +262 -78
  34. package/dist/control-schema.js.map +1 -1
  35. package/dist/control-write-retry.d.ts +45 -10
  36. package/dist/control-write-retry.js +92 -22
  37. package/dist/control-write-retry.js.map +1 -1
  38. package/dist/delegate-admission.d.ts +13 -0
  39. package/dist/delegate-admission.js +27 -0
  40. package/dist/delegate-admission.js.map +1 -1
  41. package/dist/ed25519-key.d.ts +10 -7
  42. package/dist/ed25519-key.js +23 -20
  43. package/dist/ed25519-key.js.map +1 -1
  44. package/dist/edge-node/config.d.ts +122 -0
  45. package/dist/edge-node/config.js +199 -0
  46. package/dist/edge-node/config.js.map +1 -0
  47. package/dist/edge-node/dissolve.d.ts +95 -0
  48. package/dist/edge-node/dissolve.js +184 -0
  49. package/dist/edge-node/dissolve.js.map +1 -0
  50. package/dist/edge-node/edge-join.d.ts +44 -0
  51. package/dist/edge-node/edge-join.js +227 -0
  52. package/dist/edge-node/edge-join.js.map +1 -0
  53. package/dist/edge-node/edge-node.d.ts +295 -0
  54. package/dist/edge-node/edge-node.js +704 -0
  55. package/dist/edge-node/edge-node.js.map +1 -0
  56. package/dist/edge-node/index.d.ts +18 -0
  57. package/dist/edge-node/index.js +18 -0
  58. package/dist/edge-node/index.js.map +1 -0
  59. package/dist/edge-node/join-credential.d.ts +11 -0
  60. package/dist/edge-node/join-credential.js +11 -0
  61. package/dist/edge-node/join-credential.js.map +1 -0
  62. package/dist/edge-node/lazy-raw-storage.d.ts +40 -0
  63. package/dist/edge-node/lazy-raw-storage.js +134 -0
  64. package/dist/edge-node/lazy-raw-storage.js.map +1 -0
  65. package/dist/edge-node/node-local.d.ts +60 -0
  66. package/dist/edge-node/node-local.js +58 -0
  67. package/dist/edge-node/node-local.js.map +1 -0
  68. package/dist/edge-node/options.d.ts +83 -0
  69. package/dist/edge-node/options.js +110 -0
  70. package/dist/edge-node/options.js.map +1 -0
  71. package/dist/edge-node/owner-grant.d.ts +41 -0
  72. package/dist/edge-node/owner-grant.js +38 -0
  73. package/dist/edge-node/owner-grant.js.map +1 -0
  74. package/dist/edge-node/platform.d.ts +140 -0
  75. package/dist/edge-node/platform.js +12 -0
  76. package/dist/edge-node/platform.js.map +1 -0
  77. package/dist/edge-node/strand-move.d.ts +115 -0
  78. package/dist/edge-node/strand-move.js +223 -0
  79. package/dist/edge-node/strand-move.js.map +1 -0
  80. package/dist/edge-node/strands.d.ts +28 -0
  81. package/dist/edge-node/strands.js +60 -0
  82. package/dist/edge-node/strands.js.map +1 -0
  83. package/dist/enrolled-machine-store.d.ts +3 -3
  84. package/dist/enrolled-machine-store.js +3 -3
  85. package/dist/formation-token.d.ts +48 -0
  86. package/dist/formation-token.js +26 -0
  87. package/dist/formation-token.js.map +1 -0
  88. package/dist/index.d.ts +27 -17
  89. package/dist/index.js +39 -17
  90. package/dist/index.js.map +1 -1
  91. package/dist/joined-strand-store.d.ts +29 -12
  92. package/dist/joined-strand-store.js +66 -27
  93. package/dist/joined-strand-store.js.map +1 -1
  94. package/dist/key-store.d.ts +9 -4
  95. package/dist/key-store.js +9 -4
  96. package/dist/key-store.js.map +1 -1
  97. package/dist/link-budget.d.ts +9 -7
  98. package/dist/link-budget.js +9 -7
  99. package/dist/link-budget.js.map +1 -1
  100. package/dist/machine-removal.d.ts +19 -39
  101. package/dist/machine-removal.js +24 -98
  102. package/dist/machine-removal.js.map +1 -1
  103. package/dist/member-redemption.d.ts +256 -0
  104. package/dist/member-redemption.js +490 -0
  105. package/dist/member-redemption.js.map +1 -0
  106. package/dist/membership-view.d.ts +91 -0
  107. package/dist/membership-view.js +110 -0
  108. package/dist/membership-view.js.map +1 -0
  109. package/dist/owner-anchor-sync.d.ts +4 -4
  110. package/dist/owner-anchor-sync.js +16 -15
  111. package/dist/owner-anchor-sync.js.map +1 -1
  112. package/dist/owner-grant-protocol.d.ts +251 -0
  113. package/dist/owner-grant-protocol.js +344 -0
  114. package/dist/owner-grant-protocol.js.map +1 -0
  115. package/dist/owner-key-export.d.ts +70 -0
  116. package/dist/owner-key-export.js +279 -0
  117. package/dist/owner-key-export.js.map +1 -0
  118. package/dist/owner-key-flows.d.ts +55 -0
  119. package/dist/owner-key-flows.js +60 -0
  120. package/dist/owner-key-flows.js.map +1 -0
  121. package/dist/owner-key-store.d.ts +31 -0
  122. package/dist/owner-key-store.js +81 -0
  123. package/dist/owner-key-store.js.map +1 -0
  124. package/dist/owner-keys.d.ts +78 -0
  125. package/dist/owner-keys.js +133 -0
  126. package/dist/owner-keys.js.map +1 -0
  127. package/dist/owner-signer.d.ts +54 -0
  128. package/dist/owner-signer.js +51 -0
  129. package/dist/owner-signer.js.map +1 -0
  130. package/dist/peer-addr-book.d.ts +10 -1
  131. package/dist/peer-addr-book.js +4 -3
  132. package/dist/peer-addr-book.js.map +1 -1
  133. package/dist/peer-authorization.d.ts +83 -18
  134. package/dist/peer-authorization.js +123 -53
  135. package/dist/peer-authorization.js.map +1 -1
  136. package/dist/peer-join-backfill.d.ts +89 -20
  137. package/dist/peer-join-backfill.js +265 -108
  138. package/dist/peer-join-backfill.js.map +1 -1
  139. package/dist/pending-join-runner.d.ts +48 -18
  140. package/dist/pending-join-runner.js +74 -56
  141. package/dist/pending-join-runner.js.map +1 -1
  142. package/dist/provider/rent-node.js +1 -1
  143. package/dist/provider/rent-node.js.map +1 -1
  144. package/dist/seed-bootstrap.d.ts +162 -133
  145. package/dist/seed-bootstrap.js +300 -283
  146. package/dist/seed-bootstrap.js.map +1 -1
  147. package/dist/seed-trust-policy.js +4 -4
  148. package/dist/strand-addr-protocol.d.ts +4 -1
  149. package/dist/strand-addr-protocol.js +8 -2
  150. package/dist/strand-addr-protocol.js.map +1 -1
  151. package/dist/strand-cohort.d.ts +3 -0
  152. package/dist/strand-cohort.js.map +1 -1
  153. package/dist/strand-database.d.ts +24 -2
  154. package/dist/strand-database.js +29 -6
  155. package/dist/strand-database.js.map +1 -1
  156. package/dist/strand-first-sync-gate.d.ts +176 -88
  157. package/dist/strand-first-sync-gate.js +288 -121
  158. package/dist/strand-first-sync-gate.js.map +1 -1
  159. package/dist/strand-formation-deadlines.d.ts +9 -9
  160. package/dist/strand-formation-deadlines.js +9 -9
  161. package/dist/strand-formation-manager.d.ts +23 -17
  162. package/dist/strand-formation-manager.js +46 -44
  163. package/dist/strand-formation-manager.js.map +1 -1
  164. package/dist/strand-formation-protocol.d.ts +5 -8
  165. package/dist/strand-formation-protocol.js +101 -16
  166. package/dist/strand-formation-protocol.js.map +1 -1
  167. package/dist/strand-instance-manager.d.ts +27 -18
  168. package/dist/strand-instance-manager.js +119 -50
  169. package/dist/strand-instance-manager.js.map +1 -1
  170. package/dist/strand-membership-reconciler.d.ts +16 -13
  171. package/dist/strand-membership-reconciler.js +30 -22
  172. package/dist/strand-membership-reconciler.js.map +1 -1
  173. package/dist/strand-membership-writer.d.ts +45 -22
  174. package/dist/strand-membership-writer.js +226 -131
  175. package/dist/strand-membership-writer.js.map +1 -1
  176. package/dist/strand-move.d.ts +6 -5
  177. package/dist/strand-move.js +36 -32
  178. package/dist/strand-move.js.map +1 -1
  179. package/dist/strand-peer-redial.js +2 -3
  180. package/dist/strand-peer-redial.js.map +1 -1
  181. package/dist/strand-revocation-enforcer.d.ts +134 -60
  182. package/dist/strand-revocation-enforcer.js +144 -71
  183. package/dist/strand-revocation-enforcer.js.map +1 -1
  184. package/dist/strand-solicitation.d.ts +50 -39
  185. package/dist/strand-solicitation.js +10 -3
  186. package/dist/strand-solicitation.js.map +1 -1
  187. package/dist/strand-watcher.d.ts +80 -13
  188. package/dist/strand-watcher.js +152 -48
  189. package/dist/strand-watcher.js.map +1 -1
  190. package/dist/table-change-watch.d.ts +63 -0
  191. package/dist/table-change-watch.js +209 -0
  192. package/dist/table-change-watch.js.map +1 -0
  193. package/dist/timeout-scheduler.d.ts +4 -3
  194. package/dist/timeout-scheduler.js +4 -3
  195. package/dist/timeout-scheduler.js.map +1 -1
  196. package/dist/types.d.ts +374 -150
  197. package/dist/types.js +4 -4
  198. package/dist/types.js.map +1 -1
  199. package/package.json +17 -8
  200. package/src/bootstrap-peer-store-file.ts +44 -44
  201. package/src/bootstrap-peer-store.ts +214 -214
  202. package/src/cadre-invite-protocol.ts +740 -1052
  203. package/src/cadre-join-request.ts +24 -3
  204. package/src/cadre-node.ts +2402 -1079
  205. package/src/control-authorization.ts +47 -14
  206. package/src/control-cohort.ts +204 -128
  207. package/src/control-database.ts +1749 -820
  208. package/src/control-formation-recorder.ts +359 -353
  209. package/src/control-protocol-guard.ts +23 -6
  210. package/src/control-schema-version.ts +301 -0
  211. package/src/control-schema.ts +273 -78
  212. package/src/control-write-retry.ts +641 -567
  213. package/src/delegate-admission.ts +351 -314
  214. package/src/ed25519-key.ts +174 -171
  215. package/src/edge-node/config.ts +277 -0
  216. package/src/edge-node/dissolve.ts +251 -0
  217. package/src/edge-node/edge-join.ts +319 -0
  218. package/src/edge-node/edge-node.ts +1045 -0
  219. package/src/edge-node/index.ts +59 -0
  220. package/src/edge-node/join-credential.ts +16 -0
  221. package/src/edge-node/lazy-raw-storage.ts +178 -0
  222. package/src/edge-node/node-local.ts +84 -0
  223. package/src/edge-node/options.ts +179 -0
  224. package/src/edge-node/owner-grant.ts +63 -0
  225. package/src/edge-node/platform.ts +151 -0
  226. package/src/edge-node/strand-move.ts +270 -0
  227. package/src/edge-node/strands.ts +72 -0
  228. package/src/enrolled-machine-store.ts +3 -3
  229. package/src/formation-token.ts +63 -0
  230. package/src/index.ts +899 -789
  231. package/src/joined-strand-store.ts +73 -28
  232. package/src/key-store.ts +10 -4
  233. package/src/link-budget.ts +9 -7
  234. package/src/machine-removal.ts +26 -111
  235. package/src/member-redemption.ts +649 -0
  236. package/src/membership-view.ts +144 -0
  237. package/src/owner-anchor-sync.ts +19 -18
  238. package/src/owner-grant-protocol.ts +547 -0
  239. package/src/owner-key-export.ts +348 -0
  240. package/src/owner-key-flows.ts +109 -0
  241. package/src/owner-key-store.ts +85 -0
  242. package/src/owner-keys.ts +178 -0
  243. package/src/owner-signer.ts +94 -0
  244. package/src/peer-addr-book.ts +4 -3
  245. package/src/peer-authorization.ts +558 -488
  246. package/src/peer-join-backfill.ts +971 -761
  247. package/src/pending-join-runner.ts +76 -53
  248. package/src/provider/rent-node.ts +1 -1
  249. package/src/seed-bootstrap.ts +343 -349
  250. package/src/seed-trust-policy.ts +4 -4
  251. package/src/strand-addr-protocol.ts +547 -538
  252. package/src/strand-cohort.ts +4 -0
  253. package/src/strand-database.ts +352 -319
  254. package/src/strand-first-sync-gate.ts +334 -133
  255. package/src/strand-formation-deadlines.ts +227 -227
  256. package/src/strand-formation-manager.ts +731 -725
  257. package/src/strand-formation-protocol.ts +122 -24
  258. package/src/strand-instance-manager.ts +2092 -2026
  259. package/src/strand-membership-reconciler.ts +33 -25
  260. package/src/strand-membership-writer.ts +2093 -1974
  261. package/src/strand-move.ts +50 -38
  262. package/src/strand-peer-redial.ts +2 -3
  263. package/src/strand-revocation-enforcer.ts +740 -654
  264. package/src/strand-solicitation.ts +61 -34
  265. package/src/strand-watcher.ts +175 -56
  266. package/src/table-change-watch.ts +285 -0
  267. package/src/timeout-scheduler.ts +29 -28
  268. package/src/types.ts +391 -152
@@ -1,761 +1,971 @@
1
- import debug from 'debug';
2
- import type { IdentifyResult, Libp2p, PeerId } from '@libp2p/interface';
3
- import type { ActionId, IPeerNetwork } from '@optimystic/db-core';
4
- import { BlockTransferClient, buildBlockTransferProtocol, type BlockCommitProof, type IRawStorage } from '@optimystic/db-p2p';
5
- import { peerJoinPushBudget } from './link-budget.js';
6
-
7
- // Peer-join whole-store block catch-up, shared by the STRAND networks and the CONTROL
8
- // network. On a new peer's `peer:identify` result — libp2p's identify protocol runs once per
9
- // connection and reports the protocols the remote supports — naming this network's own
10
- // block-transfer protocol, it schedules a debounced push of every committed, materialized
11
- // block in the local raw store to that peer, so a machine that joined after blocks were
12
- // committed still ends up physically holding them. Optimystic has no cohort-join catch-up
13
- // of its own; a block committed while its writer was alone has exactly one holder forever
14
- // without this (named collection-header blocks are written once, at collection creation,
15
- // and their revision never moves again — so no later commit ever carries them anywhere).
16
- //
17
- // A peer whose identify does not name the protocol — a bare circuit relay, a bootstrap node,
18
- // or (on the control network) a stranger the inbound gate admits without membership — is
19
- // never scheduled at all: it cannot receive anything, since the protocol id is namespaced per
20
- // network and the dial would simply fail. Before this filter existed, such a peer WAS
21
- // scheduled, failed every dial, and after `PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES` produced a
22
- // `console.warn` naming it — gotchoices/sereus#18 is two relay-only parties restarting and
23
- // printing exactly that warning about their own relay, forever, on every reconnect. See
24
- // {@link speaksBlockTransfer}.
25
- //
26
- // NOTE: this copies the WHOLE local store to every newly connected peer, which is right
27
- // while a network is one party's handful of machines (see docs/architecture.md →
28
- // Replication cluster size — the control network replicates to the whole party by intent,
29
- // and "On a strand, the machine count is not a party count"). If these meshes ever get
30
- // large, filter the pushed set by FRET cohort responsibility for each block id instead of
31
- // pushing everything.
32
- //
33
- // NOTE: this lives in cadre-core only because `../optimystic` is read-only from this repo.
34
- // If Optimystic ever grows a cohort-join catch-up of its own, delete this module rather
35
- // than running two.
36
- //
37
- // NOTE: strand nodes pass db-p2p no `kvStore`, so Optimystic's under-replication ledger (the
38
- // copies a node owes peers) dies at every restart. This module's whole-store push on connect is
39
- // what delivers a write a machine made alone after it restarts (`joiner-first-commit-over-slow-relay`,
40
- // restart arm). If this module is narrowed (the cohort filter above) or deleted, give strand
41
- // nodes a persistent kvStore first.
42
- //
43
- // Membership — the one place the two networks differ, expressed as the optional
44
- // `authorizePeer` dep:
45
- //
46
- // - STRAND networks pass none. Anything that speaks the strand's own block-transfer protocol
47
- // already receives cohort replicas of new commits, so pushing older blocks to it exposes
48
- // nothing new; adding a gate would diverge from what ordinary replication already does
49
- // there.
50
- // - The CONTROL network MUST pass one, because that argument does not carry over: its
51
- // inbound connection gate deliberately admits non-members in several states (an
52
- // un-enrolled node taking its seed, an open enrollment window, an outstanding
53
- // invitation, configured bootstrap/relay peers — see docs/architecture.md, the
54
- // control-network inbound connection gate). Pushing the whole control store to such a
55
- // peer would hand a stranger the party's entire membership, addresses and strand list.
56
- // `CadreNode` passes `isAuthorizedMember`; the gate is consulted at PUSH time, not at
57
- // schedule time, and fails closed on a thrown check. A denied run is not memoized, so
58
- // the peer is retried on its next `peer:identify` (a reconnect re-runs identify) — or
59
- // sooner, via `scheduleConnectedPeers()` on a membership change (the production join order is
60
- // connect-then-authorize, so the denial at dial time is the expected first pass).
61
- //
62
- // Both per-push deadlines are DERIVED from the declared link round trip
63
- // (`link-budget.ts`), not fixed milliseconds. That is not tuning — it is what makes this
64
- // module work at all over a relay. Opening a relayed connection costs a fixed number of
65
- // exchanges, so the 3000 ms this catch-up used to allow its dial could never finish one
66
- // above 375 ms of one-way link delay: the catch-up existed so that a machine which joined
67
- // after blocks were committed physically ends up holding them, and through a relay on any
68
- // link slow enough to matter it had never once managed to. The reproduction is
69
- // `packages/integration-tests/src/scenarios/relayed-dial-cost-by-latency.integration.ts`.
70
- //
71
- // It does NOT work at every speed. Above the declared link, libp2p's own dial and
72
- // inbound-upgrade limits — which Optimystic derives from the same declaration — abandon the
73
- // connection before any deadline here is consulted, and the listener's one makes that failure
74
- // look like an absent peer rather than a timeout. That is also what happens when the machine
75
- // being caught up declared a FASTER link than this one, since its limit is the listener's. See
76
- // `link-budget.ts` ("Optimystic's deadlines, from the same declaration", "What still fails at
77
- // the supported link").
78
- //
79
- // RETRY, and why it backs off. A run whose PUSH FAILED — the transport threw, which is what
80
- // a dial or response deadline expiring looks like here — re-arms on a doubling backoff
81
- // (`retryBackoffMs` to `maxRetryBackoffMs`), and a `peer:identify` arriving while that wait
82
- // is outstanding is DROPPED rather than collapsing it back to the debounce. Both halves are
83
- // load-bearing:
84
- //
85
- // - Without the re-arm, a transient push failure over a stable connection left the peer
86
- // partially copied until its next reconnect (read repair still covered reads meanwhile).
87
- // - Without dropping churn inside the wait, a peer that cannot be reached at all is
88
- // re-dialled on every `peer:identify` forever. That is not hypothetical: the 2026-09-26
89
- // relayed reproduction shows one peer re-opening a connection about every 14.5 s for a
90
- // 200-second run, each event starting a catch-up whose dial could not possibly finish.
91
- // The connection kept re-appearing because Optimystic's own block-transfer push path
92
- // budgets its dial at `transferTimeoutMs ?? 30000` — the one dial budget in the stack
93
- // above the measured relayed setup cost — so it succeeded where this one could not.
94
- //
95
- // A NON-CLEAN run is NOT on its own enough to re-arm, and the distinction is what keeps the
96
- // backoff from becoming a worse problem than the one it fixes. `clean` also goes false for
97
- // outcomes no amount of retrying can change: the membership gate DENIED the peer; this
98
- // network's raw storage implements no `listBlockIds`, so the catch-up is inert; or the
99
- // receiver reported blocks in `missing`, which it does per block for a payload it cannot
100
- // parse and for a revision whose retained commit proof this node does not hold (a push
101
- // carrying no proof is refused outright by a receiver running the default
102
- // `requirePushCertificate: true`, and an unretained proof is the ordinary case — see
103
- // {@link Chunk.proofs}). Re-arming on those would re-push the WHOLE store to that peer every
104
- // `maxRetryBackoffMs` for as long as the node runs, and report the failure below as a link
105
- // budget problem when nothing about the link is wrong. All three still leave the peer
106
- // un-memoized, so its next `peer:identify` retries — the behaviour that predates the
107
- // backoff, and the right one for a verdict rather than a timeout. Denial in particular is
108
- // re-driven on purpose by `scheduleConnectedPeers()` the moment the membership commit lands,
109
- // because the control network's join order is connect-then-authorize.
110
- //
111
- // A re-arm is also skipped when the peer is no longer CONNECTED. This module's trigger is
112
- // `peer:identify`, so a peer that went away already has one: re-arming instead would leave
113
- // a machine dialing a peer it cannot see once a minute for the rest of its uptime.
114
- //
115
- // After `PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES` consecutive failures one `console.warn`
116
- // names the peer and the budget, because otherwise a machine on a too-slow link says
117
- // nothing at all: the connection simply never appears and only a DEBUG log mentions a dial
118
- // timeout.
119
- //
120
- // NOTE: the protocol check happens once — either when a connection's `peer:identify` fires,
121
- // or, for a peer already connected when this instance starts, when `scheduleConnectedPeers()`
122
- // reads its protocols back from the peer store — and is never repeated once a peer is
123
- // scheduled. A peer that stops speaking the protocol after being scheduled (should that ever
124
- // happen) is not de-scheduled; `runCatchUp`'s own unreachable-peer bail is what would catch
125
- // that case instead. `peer:identify` also fires on every identify-push from a connected peer
126
- // (address or protocol changes), which only re-enters the debounce — cheap, and dropped
127
- // outright for caught-up peers and peers inside a backoff wait.
128
- //
129
- // NOTE: a same-network peer whose identify never completes on a connection (the identify
130
- // stream times out over a slow relayed link, say) is not caught up until a later identify
131
- // succeeds — a reconnect, an identify-push, or on the control network a membership-change
132
- // re-drive. Accepted: every db-p2p node runs identify, and read repair still covers reads
133
- // meanwhile; if relayed links ever routinely outlast identify's timeout, raise that timeout
134
- // in the node builder rather than scheduling unidentified peers here.
135
- //
136
- // NOTE: a peer that disconnects INSIDE a backoff wait still costs the one attempt that wait
137
- // was already armed for — the connectivity check is made when the re-arm is decided, not when
138
- // the timer fires, and this module subscribes to `peer:identify` only. One dial, not a
139
- // recurring one; if a node ever holds many transient peers, subscribe to `connection:close`
140
- // and clear the pending timer there.
141
-
142
- const log = debug('sereus:cadre:peer-join-backfill');
143
-
144
- /**
145
- * The block-transfer protocol's hard cap on one length-prefixed message. Mirrors
146
- * `MAX_BLOCK_MESSAGE_BYTES` in `@optimystic/db-p2p`'s `protocol-limits.ts` (8 MiB), which
147
- * that package does not re-export from its index — keep the two in sync if upstream ever
148
- * changes it or starts exporting it.
149
- */
150
- export const MAX_BLOCK_MESSAGE_BYTES = 8 * 1024 * 1024;
151
-
152
- /**
153
- * Whether an identified peer's protocol list names this network's own block-transfer
154
- * protocol — the one gate that decides whether {@link PeerJoinBackfill} schedules a peer at
155
- * all. A peer that lacks it (a bare circuit relay, a bootstrap node, a stranger the control
156
- * network's inbound gate admitted without membership) cannot receive a push no matter how
157
- * long it is dialed, since the protocol id is namespaced per network.
158
- */
159
- function speaksBlockTransfer(protocols: readonly string[], protocolPrefix: string): boolean {
160
- return protocols.includes(buildBlockTransferProtocol(protocolPrefix));
161
- }
162
-
163
- /**
164
- * Consecutive failed catch-up runs against ONE peer before the module says so on
165
- * `console.warn` rather than only in its DEBUG log. At the default backoff that is reached
166
- * about 35 seconds in (5 s + 10 s + 20 s), which is late enough to have ruled out a blip and
167
- * early enough to be the first thing an operator sees about a machine that is not catching up.
168
- */
169
- export const PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES = 3;
170
-
171
- /** Tuning for the per-peer catch-up. Every field optional; defaults in {@link DEFAULT_PEER_JOIN_BACKFILL}. */
172
- export interface PeerJoinBackfillConfig {
173
- /** Default true. False disables the catch-up entirely (the pre-existing behaviour). */
174
- enabled?: boolean;
175
- /** Settle time after a connection opens before catching that peer up, ms. Default 1000. */
176
- debounceMs?: number;
177
- /** Ceiling on blocks copied in one catch-up. Default 10_000. Reaching it is LOGGED, never silent. */
178
- maxBlocks?: number;
179
- /** Soft byte budget per push message. Default 1 MiB. Protocol hard cap is {@link MAX_BLOCK_MESSAGE_BYTES} (8 MiB). */
180
- maxChunkBytes?: number;
181
- /** Max blocks per push message. Default 64. */
182
- maxChunkBlocks?: number;
183
- /**
184
- * Per-push dial deadline, ms. Default {@link peerJoinPushBudget}'s `dialTimeoutMs` — five link
185
- * round trips at the declared link plus two admission decisions (a party-run relay's and the
186
- * called machine's), 21 500 ms as shipped. NOT a fixed number: a relayed dial
187
- * costs a fixed number of exchanges, so a host on a slower link moves this (and every other
188
- * cadre dial budget) by declaring `NetworkConfig.linkRoundTripMs`. Naming it here still wins
189
- * over the derived value — `link-budget.ts` has the counts and the measurement.
190
- */
191
- dialTimeoutMs?: number;
192
- /**
193
- * Per-push response deadline, ms. Default {@link peerJoinPushBudget}'s `responseTimeoutMs` —
194
- * two link round trips at the declared link plus a transfer allowance for the chunk's own
195
- * bytes, 13 000 ms as shipped. Derived differently from {@link dialTimeoutMs} because it
196
- * bounds a data transfer over a connection that is already open, not a dial.
197
- */
198
- responseTimeoutMs?: number;
199
- /**
200
- * First wait before re-running a catch-up whose last run did not complete cleanly, ms.
201
- * Default 5000. Doubles per consecutive failure up to {@link maxRetryBackoffMs}.
202
- */
203
- retryBackoffMs?: number;
204
- /** Ceiling on that doubling wait, ms. Default 60_000. */
205
- maxRetryBackoffMs?: number;
206
- }
207
-
208
- /** The resolved defaults every {@link PeerJoinBackfill} starts from. */
209
- export const DEFAULT_PEER_JOIN_BACKFILL: Required<PeerJoinBackfillConfig> = {
210
- enabled: true,
211
- debounceMs: 1000,
212
- maxBlocks: 10_000,
213
- maxChunkBytes: 1024 * 1024,
214
- maxChunkBlocks: 64,
215
- // Derived at the DEFAULT declared link, for a `PeerJoinBackfill` built without a host's
216
- // declaration (this module's own tests, an embedder driving it directly). The two production
217
- // construction sites pass `peerJoinPushBudget(network?.linkRoundTripMs)` so a host that
218
- // declares a slower link moves both — see `link-budget.ts`.
219
- ...peerJoinPushBudget(),
220
- retryBackoffMs: 5000,
221
- maxRetryBackoffMs: 60_000
222
- };
223
-
224
- /**
225
- * The one capability the catch-up needs from a transfer client. Structural (rather than
226
- * the concrete `BlockTransferClient`) so unit tests can capture pushes without dialing
227
- * libp2p — see {@link PeerJoinBackfillDeps.createPushClient}.
228
- */
229
- export type PeerJoinBackfillPushClient = Pick<BlockTransferClient, 'pushBlocks'>;
230
-
231
- export interface PeerJoinBackfillDeps {
232
- /** Log tag naming which network this catch-up serves (a strand id, or `control-<partyId>`). */
233
- label: string;
234
- /** The libp2p node of the network being caught up — source of connection events and peer ids. */
235
- libp2p: Libp2p;
236
- /** `node.keyNetwork`, the IPeerNetwork BlockTransferClient dials through. */
237
- peerNetwork: IPeerNetwork;
238
- /** This network's own raw block store — the same instance handed to the libp2p node. */
239
- storage: IRawStorage;
240
- /** Must equal the prefix the receiver registered its handler under: `/optimystic/<networkName>`. */
241
- protocolPrefix: string;
242
- /**
243
- * Membership gate, consulted at PUSH time (fails closed on a throw). Absent = push to
244
- * every connected peer — correct for strand networks, NEVER for the control network;
245
- * see the module comment for why the strand no-gate argument does not carry over.
246
- */
247
- authorizePeer?: (peerId: string) => Promise<boolean>;
248
- /**
249
- * Test seam: build the per-peer push client. Defaults to a real
250
- * `BlockTransferClient` over {@link peerNetwork} + {@link protocolPrefix}.
251
- */
252
- createPushClient?: (peerId: PeerId) => PeerJoinBackfillPushClient;
253
- }
254
-
255
- /** What one peer's catch-up actually did. Returned for tests and logged at the end of each run. */
256
- export interface PeerJoinBackfillResult {
257
- /** Blocks offered: had a committed `latest` AND materialized content locally. */
258
- offered: number;
259
- /** Blocks the remote reported it persisted. */
260
- accepted: number;
261
- /** Block ids the remote reported in `missing` (parse or persist failure on its side). */
262
- rejected: string[];
263
- /** Skipped: metadata has no `latest` (pending-only — not yet a durability claim here). */
264
- uncommitted: number;
265
- /** Skipped: `latest` exists but no materialized block is stored for that actionId. */
266
- unmaterialized: number;
267
- /** Not attempted because `maxBlocks` was reached. */
268
- capped: number;
269
- /** Skipped: a single block whose wire size alone exceeds {@link MAX_BLOCK_MESSAGE_BYTES}. */
270
- oversized: string[];
271
- /** True when the `authorizePeer` gate refused (or threw) — nothing was pushed, peer not memoized. */
272
- denied: boolean;
273
- }
274
-
275
- function emptyResult(): PeerJoinBackfillResult {
276
- return { offered: 0, accepted: 0, rejected: [], uncommitted: 0, unmaterialized: 0, capped: 0, oversized: [], denied: false };
277
- }
278
-
279
- /** One in-flight push message being accumulated. */
280
- interface Chunk {
281
- ids: string[];
282
- buffers: Uint8Array[];
283
- meta: Record<string, { rev: number; actionId: ActionId }>;
284
- /**
285
- * The cohort commit proof retained for each block's pushed revision, where one exists.
286
- *
287
- * A receiver running the default `requirePushCertificate: true` REJECTS a block pushed
288
- * without one, so this is what makes peer-join catch-up land at all — a push carrying only
289
- * `meta` is the legacy shape and is refused. Sparse deliberately: a block whose proof was
290
- * never retained is still offered with its meta, which is the only thing that lets a
291
- * receiver migrating with the flag off land the replica at this node's revision rather than
292
- * a fabricated rev 1. Upstream's rule is the other direction and holds here by construction:
293
- * a proof is never attached WITHOUT its meta, because both are written from the same
294
- * `latest` in one place.
295
- */
296
- proofs: Record<string, BlockCommitProof>;
297
- bytes: number;
298
- }
299
-
300
- /**
301
- * Base64 wire size of a raw buffer — `pushBlocks` base64-encodes each block into the JSON
302
- * request, so the protocol cap must be judged against the encoded size, not the raw bytes.
303
- */
304
- function base64WireBytes(rawBytes: number): number {
305
- return Math.ceil(rawBytes / 3) * 4;
306
- }
307
-
308
- /**
309
- * Copies every block in one network's own raw store to each peer its libp2p node connects
310
- * to, so a peer that joined the network after blocks were committed still ends up holding
311
- * them physically (the receiver persists each push via `saveReplicatedBlock`, which is
312
- * monotonic and idempotent — crossing pushes from both ends cannot regress a revision).
313
- *
314
- * Best-effort throughout: nothing here throws into a libp2p event handler or into a
315
- * runtime bring-up; a failed chunk is logged and the run continues. A peer is marked
316
- * fully caught up ONLY after a run with no thrown chunk and an empty `missing` list, so
317
- * the next `peer:identify` from a peer whose catch-up failed retries it.
318
- */
319
- export class PeerJoinBackfill {
320
- private readonly config: Required<PeerJoinBackfillConfig>;
321
- private readonly createPushClient: (peerId: PeerId) => PeerJoinBackfillPushClient;
322
- private started = false;
323
- private stopped = false;
324
- /**
325
- * Peers fully caught up this runtime (never rescheduled until the runtime is rebuilt; only
326
- * {@link forceCatchUpPeer} pushes to one again).
327
- */
328
- private readonly done = new Set<string>();
329
- /**
330
- * Peers with a catch-up currently running, each with that run (suppresses concurrent
331
- * duplicates; {@link forceCatchUpPeer} waits on the run).
332
- */
333
- private readonly inFlight = new Map<string, Promise<PeerJoinBackfillResult>>();
334
- /**
335
- * Peers whose (re-)schedule arrived while their OWN run was in flight, replayed once
336
- * that run finishes. Load-bearing for the gated path: the gate's authorization check is
337
- * a control-database read, so the window between it and the run's end is wide enough for
338
- * the very membership commit that would have authorized the peer to land inside it —
339
- * dropping that schedule (rather than deferring it) leaves the denied peer waiting for a
340
- * reconnect, which is exactly what the re-arm exists to avoid.
341
- */
342
- private readonly rearmAfterFlight = new Set<string>();
343
- /** Pending per-peer timers — the debounce, or a backoff re-arm. Cleared on stop. */
344
- private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
345
- /** Consecutive non-clean runs per peer, cleared when one finishes cleanly. */
346
- private readonly failures = new Map<string, number>();
347
- /**
348
- * Epoch ms before which a peer's catch-up must not be re-run, set alongside a backoff timer
349
- * that will run it. Its presence is what makes `peer:identify` churn free: a schedule
350
- * arriving inside the wait is dropped, rather than collapsing the backoff to the debounce.
351
- */
352
- private readonly retryAfter = new Map<string, number>();
353
- /** Peers already reported on `console.warn`; reset when a run finally lands cleanly. */
354
- private readonly warned = new Set<string>();
355
- private readonly onPeerIdentify: (evt: CustomEvent<IdentifyResult>) => void;
356
- private loggedNoListBlockIds = false;
357
-
358
- constructor(private readonly deps: PeerJoinBackfillDeps, config?: PeerJoinBackfillConfig) {
359
- this.config = { ...DEFAULT_PEER_JOIN_BACKFILL, ...config };
360
- this.createPushClient = deps.createPushClient
361
- ?? ((peerId) => new BlockTransferClient(peerId, deps.peerNetwork, deps.protocolPrefix));
362
- this.onPeerIdentify = (evt) => {
363
- const { peerId, protocols } = evt.detail;
364
- if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
365
- this.schedulePeer(peerId);
366
- }
367
- };
368
- }
369
-
370
- /**
371
- * Subscribe to `peer:identify` AND schedule a catch-up for already-connected peers whose
372
- * stored protocols already name this network's block-transfer protocol — a peer that does
373
- * not speak it (a bare circuit relay, a bootstrap node) is never scheduled at all. See
374
- * {@link speaksBlockTransfer} and the module comment.
375
- */
376
- start(): void {
377
- if (this.started || this.stopped || !this.config.enabled) return;
378
- this.started = true;
379
- this.deps.libp2p.addEventListener('peer:identify', this.onPeerIdentify);
380
- // A runtime rebuilt over live connections (resumeStrand) never sees their peer:identify —
381
- // it already fired before this instance existed, but its result is persisted in the peer
382
- // store — so walk what is already connected once.
383
- void this.scheduleConnectedPeers().then((scheduled) => {
384
- log('[%s] started (%d peer(s) already connected)', this.deps.label, scheduled);
385
- });
386
- }
387
-
388
- /** Unsubscribe, clear timers; in-flight runs observe the stopped flag and bail. */
389
- stop(): void {
390
- if (this.stopped) return;
391
- this.stopped = true;
392
- if (this.started) {
393
- this.deps.libp2p.removeEventListener('peer:identify', this.onPeerIdentify);
394
- }
395
- for (const timer of this.timers.values()) {
396
- clearTimeout(timer);
397
- }
398
- this.timers.clear();
399
- this.rearmAfterFlight.clear();
400
- this.retryAfter.clear();
401
- log('[%s] stopped', this.deps.label);
402
- }
403
-
404
- /**
405
- * (Re-)schedule a debounced catch-up for every currently-connected peer whose protocols, as
406
- * already stored in the libp2p peer store, name this network's block-transfer protocol. A
407
- * peer not yet in the peer store — its identify has not finished — is left to the
408
- * `peer:identify` handler rather than dialed blind; one whose stored protocols are known
409
- * and lack ours is skipped outright. Idempotent and cheap otherwise (caught-up peers are
410
- * skipped before any timer is set, and a peer whose run is in flight is deferred to the end
411
- * of that run rather than dropped). Driven by {@link start}, and — on a gated network — by
412
- * the embedder whenever membership changes, so a peer whose first pass was denied (connected
413
- * before it was authorized: the production join order) is retried without waiting for a
414
- * reconnect. Returns how many distinct peers were considered (for the start() log) — a peer
415
- * holding several connections is one peer, and is scheduled once.
416
- */
417
- async scheduleConnectedPeers(): Promise<number> {
418
- if (this.stopped) return 0;
419
- const peers = new Map<string, PeerId>();
420
- for (const connection of this.deps.libp2p.getConnections()) {
421
- peers.set(connection.remotePeer.toString(), connection.remotePeer);
422
- }
423
- await Promise.all([...peers.values()].map((peerId) => this.scheduleIfKnownToSpeak(peerId)));
424
- return peers.size;
425
- }
426
-
427
- /** Schedules `peerId` only if the peer store already knows it speaks this network's protocol. */
428
- private async scheduleIfKnownToSpeak(peerId: PeerId): Promise<void> {
429
- let protocols: string[];
430
- try {
431
- ({ protocols } = await this.deps.libp2p.peerStore.get(peerId));
432
- } catch (error) {
433
- // NotFoundError: identify has not finished. Leave it to the `peer:identify` handler
434
- // rather than dialing blind. Anything else is unexpected — log it and skip the peer.
435
- if ((error as Error).name !== 'NotFoundError') {
436
- log('[%s] peer store read for %s failed — not scheduling: %o', this.deps.label, peerId.toString(), error);
437
- }
438
- return;
439
- }
440
- if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
441
- this.schedulePeer(peerId);
442
- }
443
- }
444
-
445
- /** Debounced entry point for connection churn: one run per peer per settle window. */
446
- private schedulePeer(peerId: PeerId): void {
447
- const key = peerId.toString();
448
- if (this.stopped || this.done.has(key)) return;
449
- if (this.inFlight.has(key)) {
450
- // Defer rather than drop: the running pass may already be past its gate check (or
451
- // past the block this schedule was meant to carry), so replay it when that pass ends.
452
- this.rearmAfterFlight.add(key);
453
- return;
454
- }
455
- // A peer whose last run failed is already re-armed on a backoff timer that will run it, so
456
- // DROP this schedule instead of shortening the wait — otherwise a peer that cannot be
457
- // reached is re-dialled on every peer:identify forever (see the module comment's retry
458
- // paragraph). A denied run never gets here: it does not set a backoff.
459
- const retryAt = this.retryAfter.get(key);
460
- if (retryAt !== undefined && Date.now() < retryAt) return;
461
- const existing = this.timers.get(key);
462
- if (existing) clearTimeout(existing);
463
- this.timers.set(key, setTimeout(() => {
464
- this.timers.delete(key);
465
- void this.catchUpPeer(peerId);
466
- }, this.config.debounceMs));
467
- }
468
-
469
- /**
470
- * Run one peer's catch-up now, bypassing the debounce. Never rejects. Returns an
471
- * all-zero result without pushing when the peer is already caught up, already being
472
- * caught up, or this backfill is stopped.
473
- */
474
- async catchUpPeer(peerId: PeerId): Promise<PeerJoinBackfillResult> {
475
- const key = peerId.toString();
476
- if (this.stopped || this.done.has(key) || this.inFlight.has(key)) {
477
- return emptyResult();
478
- }
479
- return await this.trackRun(peerId);
480
- }
481
-
482
- /**
483
- * Run one peer's catch-up now and wait for it, whatever this instance remembers about the
484
- * peer: wait out a run already in flight for it, then push the whole store again even when
485
- * the peer is memoized as caught up. Never rejects; an all-zero result only when stopped.
486
- *
487
- * For a caller that must know the peer holds this store before it proceeds, where
488
- * {@link catchUpPeer}'s empty answer would hide a run that was denied (a `peer:identify`
489
- * run can pass the gate a moment before the caller authorized the peer) or a memo older
490
- * than the commits since.
491
- */
492
- async forceCatchUpPeer(peerId: PeerId): Promise<PeerJoinBackfillResult> {
493
- const key = peerId.toString();
494
- for (let pending = this.inFlight.get(key); pending; pending = this.inFlight.get(key)) {
495
- await pending;
496
- }
497
- if (this.stopped) {
498
- return emptyResult();
499
- }
500
- return await this.trackRun(peerId);
501
- }
502
-
503
- /**
504
- * Register one run in {@link inFlight} before its first await, so no second run for the
505
- * peer can start beside it, and replay a schedule that arrived while it ran.
506
- */
507
- private async trackRun(peerId: PeerId): Promise<PeerJoinBackfillResult> {
508
- const key = peerId.toString();
509
- const run = this.settleRun(peerId);
510
- this.inFlight.set(key, run);
511
- try {
512
- return await run;
513
- } finally {
514
- this.inFlight.delete(key);
515
- // Replay a schedule that arrived mid-run. `schedulePeer` re-checks `done`, so a run
516
- // that finished clean re-arms nothing; a denied or failed one gets its retry.
517
- if (this.rearmAfterFlight.delete(key)) {
518
- this.schedulePeer(peerId);
519
- }
520
- }
521
- }
522
-
523
- /** One run and what follows from its outcome: the memo, or a backoff re-arm. Never rejects. */
524
- private async settleRun(peerId: PeerId): Promise<PeerJoinBackfillResult> {
525
- const key = peerId.toString();
526
- try {
527
- const { result, clean, pushFailed } = await this.runCatchUp(peerId);
528
- // NOTE: a run that hit `maxBlocks` is still "clean" and still memoizes the peer, so
529
- // the tail past the ceiling never reaches it. Deliberate: enumeration is not
530
- // resumable, so not memoizing would re-push the same prefix on every reconnect
531
- // without ever advancing. Loud in the log below (capped > 0). If a store can
532
- // realistically exceed maxBlocks, the fix is a resumable cursor, not either policy.
533
- if (clean && !this.stopped) {
534
- this.done.add(key);
535
- this.failures.delete(key);
536
- this.retryAfter.delete(key);
537
- this.warned.delete(key);
538
- } else if (pushFailed && !this.stopped && this.started && this.isConnected(peerId)) {
539
- // `pushFailed`, not `!clean`: a denial, an inert store and a receiver's per-block
540
- // rejection are all verdicts a retry cannot change, and re-arming on them would
541
- // re-push the whole store to that peer forever. See the module comment.
542
- //
543
- // Gated on `started` too: the re-arm exists to REPLACE a peer:identify-driven retry,
544
- // so a caller driving `catchUpPeer` by hand against a backfill that was never started
545
- // owns its own retry policy and must not be left holding a background timer.
546
- this.scheduleRetryWithBackoff(peerId);
547
- }
548
- log('[%s] catch-up peer=%s offered=%d accepted=%d rejected=%d uncommitted=%d unmaterialized=%d capped=%d oversized=%d denied=%s done=%s',
549
- this.deps.label, key, result.offered, result.accepted, result.rejected.length,
550
- result.uncommitted, result.unmaterialized, result.capped, result.oversized.length, result.denied, clean);
551
- return result;
552
- } catch (error) {
553
- // runCatchUp already contains a per-chunk catch; this guards the enumeration and
554
- // metadata reads too — a backfill fault must never surface through a libp2p event.
555
- log('[%s] catch-up peer=%s failed: %o', this.deps.label, key, error);
556
- return emptyResult();
557
- }
558
- }
559
-
560
- /** Whether this network's libp2p node still holds a connection to that peer. */
561
- private isConnected(peerId: PeerId): boolean {
562
- return this.deps.libp2p.getConnections(peerId).length > 0;
563
- }
564
-
565
- /**
566
- * Re-arm one peer's catch-up after a run whose push failed, on a wait that doubles
567
- * per consecutive failure up to `maxRetryBackoffMs`. Sets {@link retryAfter} alongside the
568
- * timer, which is what makes `peer:identify` churn inside the wait free.
569
- */
570
- private scheduleRetryWithBackoff(peerId: PeerId): void {
571
- const key = peerId.toString();
572
- const failures = (this.failures.get(key) ?? 0) + 1;
573
- this.failures.set(key, failures);
574
- const delayMs = Math.min(
575
- this.config.retryBackoffMs * 2 ** (failures - 1),
576
- this.config.maxRetryBackoffMs
577
- );
578
- this.retryAfter.set(key, Date.now() + delayMs);
579
- const existing = this.timers.get(key);
580
- if (existing) clearTimeout(existing);
581
- this.timers.set(key, setTimeout(() => {
582
- this.timers.delete(key);
583
- this.retryAfter.delete(key);
584
- void this.catchUpPeer(peerId);
585
- }, delayMs));
586
- log('[%s] catch-up peer=%s failed %d time(s) in a row; retrying in %dms',
587
- this.deps.label, key, failures, delayMs);
588
- this.warnPersistentFailure(key, failures);
589
- }
590
-
591
- /**
592
- * Say ONCE per peer, outside the DEBUG log, that its catch-up is not landing. Without this a
593
- * machine on a link too slow for a relayed dial produces no statement that anything is wrong:
594
- * the peer never appears to hold the blocks, and the only trace is a DEBUG line naming a dial
595
- * timeout. Reset when a run finally lands cleanly, so a peer that recovers can report again.
596
- */
597
- private warnPersistentFailure(key: string, failures: number): void {
598
- if (failures < PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES || this.warned.has(key)) return;
599
- this.warned.add(key);
600
- console.warn(
601
- `[cadre:${this.deps.label}] peer-join block catch-up to peer ${key} has failed ${failures} times in a row `
602
- + `(dial budget ${this.config.dialTimeoutMs}ms, response budget ${this.config.responseTimeoutMs}ms). `
603
- + 'That peer may not be holding blocks committed before it joined. If it is reachable only through a relay, '
604
- + 'these budgets and libp2p\'s own connection limits are derived from network.linkRoundTripMs (see link-budget.ts); '
605
- + 'a link slower than that declaration, or a peer that declared a faster one, cannot open a relayed connection at all.'
606
- );
607
- }
608
-
609
- /**
610
- * The actual copy. `clean` = every chunk pushed and the remote persisted every block.
611
- * `pushFailed` = at least one push THREW, which is the only non-clean outcome a retry can
612
- * change; the others are verdicts (denied, inert store, blocks the receiver refused).
613
- */
614
- private async runCatchUp(peerId: PeerId): Promise<{ result: PeerJoinBackfillResult; clean: boolean; pushFailed: boolean }> {
615
- const result = emptyResult();
616
- const { storage } = this.deps;
617
-
618
- // The membership gate, judged at push time (never at schedule time — authorization can
619
- // change during the debounce window in either direction). Fails CLOSED on a throw: a
620
- // gate that cannot answer must not leak the store. A denied run is not clean, so the
621
- // peer is retried later rather than memoized as caught up.
622
- if (this.deps.authorizePeer) {
623
- let authorized = false;
624
- try {
625
- authorized = await this.deps.authorizePeer(peerId.toString());
626
- } catch (error) {
627
- log('[%s] authorizePeer(%s) threw — treating as denied: %o', this.deps.label, peerId.toString(), error);
628
- }
629
- if (!authorized) {
630
- result.denied = true;
631
- return { result, clean: false, pushFailed: false };
632
- }
633
- }
634
-
635
- if (!storage.listBlockIds) {
636
- if (!this.loggedNoListBlockIds) {
637
- this.loggedNoListBlockIds = true;
638
- log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.label);
639
- }
640
- return { result, clean: false, pushFailed: false };
641
- }
642
-
643
- const client = this.createPushClient(peerId);
644
- const encoder = new TextEncoder();
645
- let chunk: Chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
646
- let chunkFailed = false;
647
- let anyChunkDelivered = false;
648
- /**
649
- * A peer that has answered no push at all, and failed one, is not reachable on this
650
- * protocol — abandon rather than spend a dial timeout per remaining chunk. Once ONE
651
- * push has been answered the peer demonstrably speaks it, so a later failure is a
652
- * transient blip and the rest of the store is still worth pushing.
653
- */
654
- const peerUnreachable = (): boolean => chunkFailed && !anyChunkDelivered;
655
-
656
- const flush = async (): Promise<void> => {
657
- if (chunk.ids.length === 0) return;
658
- const { ids, buffers, meta, proofs } = chunk;
659
- chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
660
- try {
661
- // ONE certification value rather than two arguments, so a caller cannot pair a proof
662
- // for one revision with meta for another — both were written from the same `latest`.
663
- const response = await client.pushBlocks(ids, buffers, 'replication',
664
- { blockMeta: meta, blockProofs: proofs }, {
665
- dialTimeoutMs: this.config.dialTimeoutMs,
666
- responseTimeoutMs: this.config.responseTimeoutMs
667
- });
668
- anyChunkDelivered = true;
669
- const missing = new Set(response.missing);
670
- for (const id of ids) {
671
- if (missing.has(id)) {
672
- result.rejected.push(id);
673
- } else {
674
- result.accepted += 1;
675
- }
676
- }
677
- if (response.missing.length > 0) {
678
- log('[%s] peer=%s rejected %d block(s): %o', this.deps.label, peerId.toString(), response.missing.length, response.missing);
679
- }
680
- } catch (error) {
681
- chunkFailed = true;
682
- log('[%s] push to peer=%s failed for %d block(s): %s', this.deps.label, peerId.toString(), ids.length, (error as Error).message);
683
- }
684
- };
685
-
686
- for await (const blockId of storage.listBlockIds()) {
687
- if (this.stopped) break;
688
- if (result.offered >= this.config.maxBlocks) {
689
- // Past the ceiling: count what is left (id enumeration only — no more reads or
690
- // pushes) so the cap is loud in the end-of-run log rather than silent.
691
- result.capped += 1;
692
- continue;
693
- }
694
-
695
- const metadata = await storage.getMetadata(blockId);
696
- const latest = metadata?.latest;
697
- if (!latest) {
698
- result.uncommitted += 1;
699
- continue;
700
- }
701
- // NOTE: a block whose latest revision is a DELETE materializes to nothing (a
702
- // tombstone), so it is skipped here — a peer that joins after such a delete never
703
- // receives the tombstone from this path and relies on read repair for it. Fine
704
- // while nothing deletes whole blocks pre-join; if the whole-store coverage gate in
705
- // strand-membership-closed-strand-e2e ever reports a tombstone residue, teach this
706
- // to push the promoted delete transform instead of skipping.
707
- const block = await storage.getMaterializedBlock(blockId, latest.actionId);
708
- if (!block) {
709
- result.unmaterialized += 1;
710
- log('[%s] block=%s has latest rev %d but no materialized content; skipped', this.deps.label, blockId, latest.rev);
711
- continue;
712
- }
713
-
714
- const buffer = encoder.encode(JSON.stringify(block));
715
- // NOTE: MAX_BLOCK_MESSAGE_BYTES caps the whole framed request, not one block, and
716
- // this test ignores the request envelope (ids array, blockMeta, JSON punctuation).
717
- // A lone block within a few KiB of the cap therefore still ships and is rejected by
718
- // the receiver's length-prefix decoder — a permanent chunk failure for that peer. No
719
- // block comes close today; if one ever can, subtract a measured envelope allowance
720
- // here rather than raising the cap.
721
- if (base64WireBytes(buffer.length) >= MAX_BLOCK_MESSAGE_BYTES) {
722
- result.oversized.push(blockId);
723
- log('[%s] block=%s is %d bytes (%d on the wire) — exceeds the %d-byte protocol cap alone; skipped',
724
- this.deps.label, blockId, buffer.length, base64WireBytes(buffer.length), MAX_BLOCK_MESSAGE_BYTES);
725
- continue;
726
- }
727
-
728
- // Flush before adding when this block would overflow either budget. A single block
729
- // larger than maxChunkBytes still ships — alone, in its own chunk.
730
- if (chunk.ids.length > 0
731
- && (chunk.ids.length + 1 > this.config.maxChunkBlocks || chunk.bytes + buffer.length > this.config.maxChunkBytes)) {
732
- await flush();
733
- if (this.stopped || peerUnreachable()) break;
734
- }
735
- chunk.ids.push(blockId);
736
- chunk.buffers.push(buffer);
737
- chunk.meta[blockId] = { rev: latest.rev, actionId: latest.actionId };
738
- // Read the proof for EXACTLY the revision being pushed, from the same `latest` the meta
739
- // above was written from. Absent is normal (nothing retained a proof for that revision);
740
- // the block still ships with its meta and the receiver decides.
741
- const proof = await storage.getBlockProof(blockId, latest.rev);
742
- if (proof) {
743
- chunk.proofs[blockId] = proof;
744
- }
745
- chunk.bytes += buffer.length;
746
- result.offered += 1;
747
- }
748
-
749
- if (!this.stopped && !peerUnreachable()) {
750
- await flush();
751
- }
752
-
753
- if (result.capped > 0) {
754
- log('[%s] peer=%s catch-up CAPPED at %d blocks; %d block id(s) not attempted',
755
- this.deps.label, peerId.toString(), this.config.maxBlocks, result.capped);
756
- }
757
-
758
- const clean = !chunkFailed && result.rejected.length === 0;
759
- return { result, clean, pushFailed: chunkFailed };
760
- }
761
- }
1
+ import debug from 'debug';
2
+ import type { IdentifyResult, Libp2p, PeerId } from '@libp2p/interface';
3
+ import type { ActionId, ActionRev, IPeerNetwork } from '@optimystic/db-core';
4
+ import { BlockTransferClient, buildBlockTransferProtocol, type BlockCommitProof, type IRawStorage } from '@optimystic/db-p2p';
5
+ import { peerJoinPushBudget } from './link-budget.js';
6
+ import type { Libp2pNodeWithRepo } from './types.js';
7
+
8
+ // Peer-join whole-store block catch-up, shared by the STRAND networks and the CONTROL
9
+ // network. On a new peer's `peer:identify` result — libp2p's identify protocol runs once per
10
+ // connection and reports the protocols the remote supports — naming this network's own
11
+ // block-transfer protocol, it schedules a push of every committed, materialized block in the
12
+ // local raw store that the peer does not already hold (see "What is pushed" below), so a
13
+ // machine that joined after blocks were committed still ends up physically holding them.
14
+ // Optimystic has no cohort-join catch-up of its own; a block committed while its writer was
15
+ // alone has exactly one holder forever without this (named collection-header blocks are
16
+ // written once, at collection creation, and their revision never moves again — so no later
17
+ // commit ever carries them anywhere).
18
+ //
19
+ // A peer this instance has never started a run for is run at once; later schedules for it wait
20
+ // out `debounceMs`. The joining machine's first-sync gate waits for this push rather than
21
+ // fetching the same blocks one read at a time, so on first contact a settle window only delays
22
+ // the joiner. Identify churn during that first run is replayed once the run ends.
23
+ //
24
+ // A peer whose identify does not name the protocol — a bare circuit relay, a bootstrap node,
25
+ // or (on the control network) a stranger the inbound gate admits without membership — is
26
+ // never scheduled at all: it cannot receive anything, since the protocol id is namespaced per
27
+ // network and the dial would simply fail. Before this filter existed, such a peer WAS
28
+ // scheduled, failed every dial, and after `PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES` produced a
29
+ // `console.warn` naming it — gotchoices/sereus#18 is two relay-only parties restarting and
30
+ // printing exactly that warning about their own relay, forever, on every reconnect. See
31
+ // {@link speaksBlockTransfer}.
32
+ //
33
+ // NOTE: this offers the WHOLE local store to every newly connected peer, which is right
34
+ // while a network is one party's handful of machines (see docs/architecture.md →
35
+ // Replication cluster size — the control network replicates to the whole party by intent,
36
+ // and "On a strand, the machine count is not a party count"). If these meshes ever get
37
+ // large, filter the pushed set by FRET cohort responsibility for each block id instead of
38
+ // pushing everything.
39
+ //
40
+ // NOTE: this lives in cadre-core only because `../optimystic` is read-only from this repo.
41
+ // If Optimystic ever grows a cohort-join catch-up of its own, delete this module rather
42
+ // than running two.
43
+ //
44
+ // NOTE: strand nodes pass db-p2p no `kvStore`, so Optimystic's under-replication ledger (the
45
+ // copies a node owes peers) dies at every restart. This module's push on connect is what
46
+ // delivers a write a machine made alone after it restarts (`joiner-first-commit-over-slow-relay`,
47
+ // restart arm): the peer did not sign that commit, so the block is still offered to it. If this
48
+ // module is narrowed (the cohort filter above) or deleted, give strand nodes a persistent
49
+ // kvStore first.
50
+ //
51
+ // Membership — the one place the two networks differ, expressed as the optional
52
+ // `authorizePeer` dep:
53
+ //
54
+ // - STRAND networks pass none. Anything that speaks the strand's own block-transfer protocol
55
+ // already receives cohort replicas of new commits, so pushing older blocks to it exposes
56
+ // nothing new; adding a gate would diverge from what ordinary replication already does
57
+ // there.
58
+ // - The CONTROL network MUST pass one, because that argument does not carry over: its
59
+ // inbound connection gate deliberately admits non-members in several states (an
60
+ // un-enrolled node taking its seed, an open enrollment window, an outstanding
61
+ // invitation, configured bootstrap/relay peers — see docs/architecture.md, the
62
+ // control-network inbound connection gate). Pushing the whole control store to such a
63
+ // peer would hand a stranger the party's entire membership, addresses and strand list.
64
+ // `CadreNode` passes a lookup in its in-memory authorized-member snapshot; the gate is
65
+ // consulted at PUSH time, not at schedule time, and fails closed on a thrown check. A denied
66
+ // run is not memoized, so the peer is retried on its next `peer:identify` (a reconnect
67
+ // re-runs identify) — or sooner, via `scheduleConnectedPeers()` on a membership change (the
68
+ // production join order is connect-then-authorize, so the denial at dial time is the
69
+ // expected first pass).
70
+ //
71
+ // Both per-push deadlines are DERIVED from the declared link round trip
72
+ // (`link-budget.ts`), not fixed milliseconds. That is not tuning — it is what makes this
73
+ // module work at all over a relay. Opening a relayed connection costs a fixed number of
74
+ // exchanges, so the 3000 ms this catch-up used to allow its dial could never finish one
75
+ // above 375 ms of one-way link delay: the catch-up existed so that a machine which joined
76
+ // after blocks were committed physically ends up holding them, and through a relay on any
77
+ // link slow enough to matter it had never once managed to. The reproduction is
78
+ // `packages/integration-tests/src/scenarios/relayed-dial-cost-by-latency.integration.ts`.
79
+ //
80
+ // It does NOT work at every speed. Above the declared link, libp2p's own dial and
81
+ // inbound-upgrade limits — which Optimystic derives from the same declaration — abandon the
82
+ // connection before any deadline here is consulted, and the listener's one makes that failure
83
+ // look like an absent peer rather than a timeout. That is also what happens when the machine
84
+ // being caught up declared a FASTER link than this one, since its limit is the listener's. See
85
+ // `link-budget.ts` ("Optimystic's deadlines, from the same declaration", "What still fails at
86
+ // the supported link").
87
+ //
88
+ // RETRY, and why it backs off. A run whose PUSH FAILED — the transport threw, which is what
89
+ // a dial or response deadline expiring looks like here — re-arms on a doubling backoff
90
+ // (`retryBackoffMs` to `maxRetryBackoffMs`), and a `peer:identify` arriving while that wait
91
+ // is outstanding is DROPPED rather than collapsing it back to the debounce. Both halves are
92
+ // load-bearing:
93
+ //
94
+ // - Without the re-arm, a transient push failure over a stable connection left the peer
95
+ // partially copied until its next reconnect (read repair still covered reads meanwhile).
96
+ // - Without dropping churn inside the wait, a peer that cannot be reached at all is
97
+ // re-dialled on every `peer:identify` forever. That is not hypothetical: the 2026-09-26
98
+ // relayed reproduction shows one peer re-opening a connection about every 14.5 s for a
99
+ // 200-second run, each event starting a catch-up whose dial could not possibly finish.
100
+ // The connection kept re-appearing because Optimystic's own block-transfer push path
101
+ // budgets its dial at `transferTimeoutMs ?? 30000` — the one dial budget in the stack
102
+ // above the measured relayed setup cost — so it succeeded where this one could not.
103
+ //
104
+ // A retry re-sends only the blocks the peer has not yet accepted (see "What is pushed"), so a
105
+ // run that died part-way through the store resumes where it stopped.
106
+ //
107
+ // Only a failed push re-arms. Two other outcomes also leave a run short of catching the peer
108
+ // up, and no amount of retrying changes them: the membership gate DENIED the peer, or this
109
+ // network's raw storage implements no `listBlockIds`, so the catch-up is inert. Re-arming on
110
+ // those would retry every `maxRetryBackoffMs` for as long as the node runs, and report the
111
+ // failure below as a link budget problem when nothing about the link is wrong. Neither marks
112
+ // the peer caught up, so its next `peer:identify` retries. Denial in particular is re-driven on
113
+ // purpose by `scheduleConnectedPeers()` the moment the membership commit lands, because the
114
+ // control network's join order is connect-then-authorize.
115
+ //
116
+ // A re-arm is also skipped when the peer is no longer CONNECTED. This module's trigger is
117
+ // `peer:identify`, so a peer that went away already has one: re-arming instead would leave
118
+ // a machine dialing a peer it cannot see once a minute for the rest of its uptime.
119
+ //
120
+ // After `PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES` consecutive failures one `console.warn`
121
+ // names the peer and the budget, because otherwise a machine on a too-slow link says
122
+ // nothing at all: the connection simply never appears and only a DEBUG log mentions a dial
123
+ // timeout.
124
+ //
125
+ // WHAT IS PUSHED: each block once per peer. Per peer, this module remembers for the runtime the
126
+ // revision of each block the peer accepted and the revision it refused ({@link PeerMemo}). A
127
+ // refusal is the receiver's `missing` list: a payload it cannot parse, a block it failed to
128
+ // persist, or a revision whose retained commit proof this node does not hold (a receiver running the default
129
+ // `requirePushCertificate: true` refuses a push carrying no proof, and an unretained proof is
130
+ // the ordinary case — see {@link Chunk.proofs}). A refusal is a per-block verdict: logged once
131
+ // when it happens, and the block is offered to that peer again only once its local revision
132
+ // moves past the refused one. A run skips a block, counting it in `alreadyHeld`, when:
133
+ //
134
+ // - the peer accepted that revision or a later one from this node;
135
+ // - the peer refused that revision;
136
+ // - the commit proof retained for that revision carries the peer's own commit-round approval.
137
+ // A block's proof lists the cohort members that signed the commit round for exactly that
138
+ // revision, so a founder's solo commit is never pushed back to it by a joiner now holding it,
139
+ // and a revision two machines committed together is not pushed between them.
140
+ //
141
+ // The proof rule stands in for "do not push a block back to the peer it came from": Optimystic
142
+ // reports a push's sender only to its own rebalance monitor and exposes it to no embedder.
143
+ //
144
+ // NOTE: accepted tradeoff — a signer that crashed between signing and applying, or later lost its
145
+ // store, is not re-sent that revision by this path; read repair covers its reads, as for any block
146
+ // a cohort member lacks. Revisit if Optimystic tells embedders who holds what (it takes reports,
147
+ // `reportBlockHeld`, but gives none) or a measurement shows pushes this rule misses.
148
+ //
149
+ // NOTE: the reply does not say why a block is missing, so a receiver's transient persist failure
150
+ // is remembered as a refusal too and not retried this runtime; read repair covers that block's
151
+ // reads. If receivers log `persist:fail` in practice, ask Optimystic for a per-block reason in
152
+ // the push reply and remember only the verdicts a retry cannot change.
153
+ //
154
+ // A peer is marked caught up (`done`) once a run finishes with no push that threw, the gate
155
+ // admitted it and the store is listable. A refusal does not hold that back, since it is
156
+ // remembered per block. It stays caught up until its last connection closes
157
+ // (`peer:disconnect`): `peer:identify` churn for a connected, caught-up peer is dropped before
158
+ // any work, and a reconnect re-runs past the debounce, pushing only what the memo and the
159
+ // proofs do not cover. {@link PeerJoinBackfill.forceCatchUpPeer} runs past `done` too, with the
160
+ // same skips.
161
+ //
162
+ // NOTE: the protocol check happens once — either when a connection's `peer:identify` fires,
163
+ // or, for a peer already connected when this instance starts, when `scheduleConnectedPeers()`
164
+ // reads its protocols back from the peer store — and is never repeated once a peer is
165
+ // scheduled. A peer that stops speaking the protocol after being scheduled (should that ever
166
+ // happen) is not de-scheduled; `runCatchUp`'s own unreachable-peer bail is what would catch
167
+ // that case instead. `peer:identify` also fires on every identify-push from a connected peer
168
+ // (address or protocol changes), which only re-enters the debounce — cheap, and dropped
169
+ // outright for caught-up peers and peers inside a backoff wait.
170
+ //
171
+ // NOTE: a same-network peer whose identify never completes on a connection (the identify
172
+ // stream times out over a slow relayed link, say) is not caught up until a later identify
173
+ // succeeds — a reconnect, an identify-push, or on the control network a membership-change
174
+ // re-drive. Accepted: every db-p2p node runs identify, and read repair still covers reads
175
+ // meanwhile; if relayed links ever routinely outlast identify's timeout, raise that timeout
176
+ // in the node builder rather than scheduling unidentified peers here.
177
+ //
178
+ // NOTE: a peer that disconnects INSIDE a backoff wait still costs the one attempt that wait
179
+ // was already armed for — the connectivity check is made when the re-arm is decided, not when
180
+ // the timer fires, and the `peer:disconnect` handler leaves backoff state alone (see
181
+ // `forgetCaughtUp`). One dial, not a recurring one; if a node ever holds many transient peers,
182
+ // clear the pending timer in that handler.
183
+
184
+ const log = debug('sereus:cadre:peer-join-backfill');
185
+ const blockEncoder = new TextEncoder();
186
+
187
+ /**
188
+ * The block-transfer protocol's hard cap on one length-prefixed message. Mirrors
189
+ * `MAX_BLOCK_MESSAGE_BYTES` in `@optimystic/db-p2p`'s `protocol-limits.ts` (8 MiB), which
190
+ * that package does not re-export from its index — keep the two in sync if upstream ever
191
+ * changes it or starts exporting it.
192
+ */
193
+ export const MAX_BLOCK_MESSAGE_BYTES = 8 * 1024 * 1024;
194
+
195
+ /**
196
+ * Whether an identified peer's protocol list names this network's own block-transfer
197
+ * protocol — the one gate that decides whether {@link PeerJoinBackfill} schedules a peer at
198
+ * all. A peer that lacks it (a bare circuit relay, a bootstrap node, a stranger the control
199
+ * network's inbound gate admitted without membership) cannot receive a push no matter how
200
+ * long it is dialed, since the protocol id is namespaced per network.
201
+ */
202
+ function speaksBlockTransfer(protocols: readonly string[], protocolPrefix: string): boolean {
203
+ return protocols.includes(buildBlockTransferProtocol(protocolPrefix));
204
+ }
205
+
206
+ /**
207
+ * Consecutive failed catch-up runs against ONE peer before the module says so on
208
+ * `console.warn` rather than only in its DEBUG log. At the default backoff that is reached
209
+ * about 35 seconds in (5 s + 10 s + 20 s), which is late enough to have ruled out a blip and
210
+ * early enough to be the first thing an operator sees about a machine that is not catching up.
211
+ */
212
+ export const PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES = 3;
213
+
214
+ /** Tuning for the per-peer catch-up. Every field optional; defaults in {@link DEFAULT_PEER_JOIN_BACKFILL}. */
215
+ export interface PeerJoinBackfillConfig {
216
+ /** Default true. False disables the catch-up entirely (the pre-existing behaviour). */
217
+ enabled?: boolean;
218
+ /**
219
+ * Settle time before re-running a peer this instance has already run for (a denied or failed
220
+ * peer's next schedule), ms. Default 1000. A peer never run for is run at once.
221
+ */
222
+ debounceMs?: number;
223
+ /** Ceiling on blocks copied in one catch-up. Default 10_000. Reaching it is LOGGED, never silent. */
224
+ maxBlocks?: number;
225
+ /** Soft byte budget per push message. Default 1 MiB. Protocol hard cap is {@link MAX_BLOCK_MESSAGE_BYTES} (8 MiB). */
226
+ maxChunkBytes?: number;
227
+ /** Max blocks per push message. Default 64. */
228
+ maxChunkBlocks?: number;
229
+ /**
230
+ * Per-push dial deadline, ms. Default {@link peerJoinPushBudget}'s `dialTimeoutMs` — five link
231
+ * round trips at the declared link plus two admission decisions (a party-run relay's and the
232
+ * called machine's), 21 500 ms as shipped. NOT a fixed number: a relayed dial
233
+ * costs a fixed number of exchanges, so a host on a slower link moves this (and every other
234
+ * cadre dial budget) by declaring `NetworkConfig.linkRoundTripMs`. Naming it here still wins
235
+ * over the derived value — `link-budget.ts` has the counts and the measurement.
236
+ */
237
+ dialTimeoutMs?: number;
238
+ /**
239
+ * Per-push response deadline, ms. Default {@link peerJoinPushBudget}'s `responseTimeoutMs` —
240
+ * two link round trips at the declared link plus a transfer allowance for the chunk's own
241
+ * bytes, 13 000 ms as shipped. Derived differently from {@link dialTimeoutMs} because it
242
+ * bounds a data transfer over a connection that is already open, not a dial.
243
+ */
244
+ responseTimeoutMs?: number;
245
+ /**
246
+ * First wait before re-running a catch-up whose last run did not complete cleanly, ms.
247
+ * Default 5000. Doubles per consecutive failure up to {@link maxRetryBackoffMs}.
248
+ */
249
+ retryBackoffMs?: number;
250
+ /** Ceiling on that doubling wait, ms. Default 60_000. */
251
+ maxRetryBackoffMs?: number;
252
+ }
253
+
254
+ /** The resolved defaults every {@link PeerJoinBackfill} starts from. */
255
+ export const DEFAULT_PEER_JOIN_BACKFILL: Required<PeerJoinBackfillConfig> = {
256
+ enabled: true,
257
+ debounceMs: 1000,
258
+ maxBlocks: 10_000,
259
+ maxChunkBytes: 1024 * 1024,
260
+ maxChunkBlocks: 64,
261
+ // Derived at the DEFAULT declared link, for a `PeerJoinBackfill` built without a host's
262
+ // declaration (this module's own tests, an embedder driving it directly). The two production
263
+ // construction sites pass `peerJoinPushBudget(network?.linkRoundTripMs)` so a host that
264
+ // declares a slower link moves both — see `link-budget.ts`.
265
+ ...peerJoinPushBudget(),
266
+ retryBackoffMs: 5000,
267
+ maxRetryBackoffMs: 60_000
268
+ };
269
+
270
+ /**
271
+ * The one capability the catch-up needs from a transfer client. Structural (rather than
272
+ * the concrete `BlockTransferClient`) so unit tests can capture pushes without dialing
273
+ * libp2p — see {@link PeerJoinBackfillDeps.createPushClient}.
274
+ */
275
+ export type PeerJoinBackfillPushClient = Pick<BlockTransferClient, 'pushBlocks'>;
276
+
277
+ export interface PeerJoinBackfillDeps {
278
+ /** Log tag naming which network this catch-up serves (a strand id, or `control-<partyId>`). */
279
+ label: string;
280
+ /** The libp2p node of the network being caught up — source of connection events and peer ids. */
281
+ libp2p: Libp2p;
282
+ /** `node.keyNetwork`, the IPeerNetwork BlockTransferClient dials through. */
283
+ peerNetwork: IPeerNetwork;
284
+ /** This network's own raw block store — the same instance handed to the libp2p node. */
285
+ storage: IRawStorage;
286
+ /** Must equal the prefix the receiver registered its handler under: `/optimystic/<networkName>`. */
287
+ protocolPrefix: string;
288
+ /**
289
+ * Membership gate, consulted at PUSH time (fails closed on a throw). Absent = push to
290
+ * every connected peer — correct for strand networks, NEVER for the control network;
291
+ * see the module comment for why the strand no-gate argument does not carry over.
292
+ */
293
+ authorizePeer?: (peerId: string) => Promise<boolean>;
294
+ /**
295
+ * The node's `reportBlockHeld` ({@link Libp2pNodeWithRepo.reportBlockHeld}), told of each block a
296
+ * peer accepted so Optimystic's under-replication drain does not push the peer the same block
297
+ * again, one request per block. Absent = nothing reported, and the drain re-sends.
298
+ */
299
+ reportBlockHeld?: Libp2pNodeWithRepo['reportBlockHeld'];
300
+ /**
301
+ * Test seam: build the per-peer push client. Defaults to a real
302
+ * `BlockTransferClient` over {@link peerNetwork} + {@link protocolPrefix}.
303
+ */
304
+ createPushClient?: (peerId: PeerId) => PeerJoinBackfillPushClient;
305
+ }
306
+
307
+ /** What one peer's catch-up actually did. Returned for tests and logged at the end of each run. */
308
+ export interface PeerJoinBackfillResult {
309
+ /** Blocks offered: had a committed `latest` AND materialized content locally, and the peer was not known to hold it. */
310
+ offered: number;
311
+ /**
312
+ * Skipped: the peer already accepted or refused this revision from this node, or signed its
313
+ * commit (see "What is pushed" in the module comment). Not offered, so not counted toward
314
+ * `maxBlocks`.
315
+ */
316
+ alreadyHeld: number;
317
+ /** Blocks the remote reported it persisted. */
318
+ accepted: number;
319
+ /**
320
+ * Block ids the remote reported in `missing` (unparseable, not persisted, or pushed without a
321
+ * commit proof it accepts). Remembered per revision; not offered to that peer again until the
322
+ * local revision moves.
323
+ */
324
+ rejected: string[];
325
+ /** Skipped: metadata has no `latest` (pending-only — not yet a durability claim here). */
326
+ uncommitted: number;
327
+ /** Skipped: `latest` exists but no materialized block is stored for that actionId. */
328
+ unmaterialized: number;
329
+ /** Not attempted because `maxBlocks` was reached. */
330
+ capped: number;
331
+ /** Skipped: a single block whose wire size alone exceeds {@link MAX_BLOCK_MESSAGE_BYTES}. */
332
+ oversized: string[];
333
+ /** True when the `authorizePeer` gate refused (or threw) — nothing was pushed, peer not memoized. */
334
+ denied: boolean;
335
+ }
336
+
337
+ function emptyResult(): PeerJoinBackfillResult {
338
+ return { offered: 0, alreadyHeld: 0, accepted: 0, rejected: [], uncommitted: 0, unmaterialized: 0, capped: 0, oversized: [], denied: false };
339
+ }
340
+
341
+ /**
342
+ * What one peer's replies said it holds from this node, per block. Lives for the runtime and,
343
+ * unlike {@link PeerJoinBackfill.done}, survives the peer's disconnect; nothing is persisted.
344
+ *
345
+ * NOTE: a peer that empties its store and comes back under the same peer id (a strand transport id
346
+ * is derived from the machine identity and the strand id, so a machine that deleted its strand
347
+ * storage and rejoins does) is not re-sent what this memo, or a proof it signed, says it holds,
348
+ * for the rest of this runtime; its reads are served by fetch. Nothing in Sereus identifies a
349
+ * store apart from its peer id. If a machine can rejoin a strand with an emptied store while other
350
+ * members' runtimes stay up, and must hold blocks physically before its first read, clear the
351
+ * peer's memo on a full disconnect; that re-pushes the whole store on every reconnect (next NOTE).
352
+ *
353
+ * NOTE: size is at most (blocks in the store, capped by `maxBlocks`) × (peers ever identified this
354
+ * runtime) small entries. If a strand's peer count grows into the hundreds (open strands), bound it
355
+ * some other way than dropping a peer's memo on `peer:disconnect`: the memo is what keeps a
356
+ * reconnect's re-run cheap, and without it every reconnect re-pushes the whole store.
357
+ */
358
+ interface PeerMemo {
359
+ /** blockId → highest revision this peer accepted from this node. */
360
+ accepted: Map<string, number>;
361
+ /** blockId → revision this peer refused (its `missing` list). Not re-pushed until the local revision moves past it. */
362
+ rejected: Map<string, number>;
363
+ }
364
+
365
+ /** Whether the peer's replies already settled revision `rev` of `blockId`, either way. */
366
+ function memoSettled(memo: PeerMemo, blockId: string, rev: number): boolean {
367
+ return (memo.accepted.get(blockId) ?? -Infinity) >= rev
368
+ || (memo.rejected.get(blockId) ?? -Infinity) >= rev;
369
+ }
370
+
371
+ /** Whether `peerId` approved the commit round that `proof` certifies. */
372
+ function signedBy(proof: BlockCommitProof | undefined, peerId: string): boolean {
373
+ return proof?.commits[peerId]?.type === 'approve';
374
+ }
375
+
376
+ /** Record one push reply in the memo: each block as accepted or refused at the revision pushed. */
377
+ function recordReply(memo: PeerMemo, revs: Readonly<Record<string, { rev: number }>>, ids: readonly string[], missing: ReadonlySet<string>): void {
378
+ for (const id of ids) {
379
+ const rev = revs[id]!.rev;
380
+ const verdicts = missing.has(id) ? memo.rejected : memo.accepted;
381
+ verdicts.set(id, Math.max(verdicts.get(id) ?? -Infinity, rev));
382
+ }
383
+ }
384
+
385
+ /** One in-flight push message being accumulated. */
386
+ interface Chunk {
387
+ ids: string[];
388
+ buffers: Uint8Array[];
389
+ meta: Record<string, { rev: number; actionId: ActionId }>;
390
+ /**
391
+ * The cohort commit proof retained for each block's pushed revision, where one exists.
392
+ *
393
+ * A receiver running the default `requirePushCertificate: true` REJECTS a block pushed
394
+ * without one, so this is what makes peer-join catch-up land at all — a push carrying only
395
+ * `meta` is the legacy shape and is refused. Sparse deliberately: a block whose proof was
396
+ * never retained is still offered with its meta, which is the only thing that lets a
397
+ * receiver migrating with the flag off land the replica at this node's revision rather than
398
+ * a fabricated rev 1. Upstream's rule is the other direction and holds here by construction:
399
+ * a proof is never attached WITHOUT its meta, because both are written from the same
400
+ * `latest` in one place.
401
+ */
402
+ proofs: Record<string, BlockCommitProof>;
403
+ bytes: number;
404
+ }
405
+
406
+ /**
407
+ * Base64 wire size of a raw buffer — `pushBlocks` base64-encodes each block into the JSON
408
+ * request, so the protocol cap must be judged against the encoded size, not the raw bytes.
409
+ */
410
+ function base64WireBytes(rawBytes: number): number {
411
+ return Math.ceil(rawBytes / 3) * 4;
412
+ }
413
+
414
+ /**
415
+ * Copies every block in one network's own raw store to each peer its libp2p node connects
416
+ * to, so a peer that joined the network after blocks were committed still ends up holding
417
+ * them physically (the receiver persists each push via `saveReplicatedBlock`, which is
418
+ * monotonic and idempotent — crossing pushes from both ends cannot regress a revision).
419
+ *
420
+ * Best-effort throughout: nothing here throws into a libp2p event handler or into a
421
+ * runtime bring-up; a failed chunk is logged and the run continues. A peer is marked
422
+ * caught up only after a run with no thrown chunk, so a peer whose catch-up failed is
423
+ * retried; each block is pushed to each peer once (see "What is pushed" in the module comment).
424
+ */
425
+ export class PeerJoinBackfill {
426
+ private readonly config: Required<PeerJoinBackfillConfig>;
427
+ private readonly createPushClient: (peerId: PeerId) => PeerJoinBackfillPushClient;
428
+ private started = false;
429
+ private stopped = false;
430
+ /**
431
+ * Peers caught up since their current connection opened. Cleared for a peer when its last
432
+ * connection closes, so a reconnect re-runs; {@link forceCatchUpPeer} runs past it.
433
+ */
434
+ private readonly done = new Set<string>();
435
+ /**
436
+ * Peers that disconnected while their run was in flight, so that run does not mark them
437
+ * {@link done} after the disconnect cleared it. Cleared when the run ends.
438
+ */
439
+ private readonly disconnectedInFlight = new Set<string>();
440
+ /** Per-peer, per-block verdicts from push replies; see {@link PeerMemo}. */
441
+ private readonly memos = new Map<string, PeerMemo>();
442
+ /**
443
+ * Peers a run has been started for. A peer not in it is run at once on its first schedule;
444
+ * later schedules wait out `debounceMs`.
445
+ */
446
+ private readonly contacted = new Set<string>();
447
+ /**
448
+ * Peers with a catch-up currently running, each with that run (suppresses concurrent
449
+ * duplicates; {@link forceCatchUpPeer} waits on the run).
450
+ */
451
+ private readonly inFlight = new Map<string, Promise<PeerJoinBackfillResult>>();
452
+ /**
453
+ * Peers whose (re-)schedule arrived while their OWN run was in flight, replayed once
454
+ * that run finishes. Load-bearing for the gated path: the gate is judged once, at the start
455
+ * of a run, and the run's pushes take long enough for the very membership commit that would
456
+ * have authorized the peer to land after that check —
457
+ * dropping that schedule (rather than deferring it) leaves the denied peer waiting for a
458
+ * reconnect, which is exactly what the re-arm exists to avoid.
459
+ */
460
+ private readonly rearmAfterFlight = new Set<string>();
461
+ /** Pending per-peer timers — the debounce, or a backoff re-arm. Cleared on stop. */
462
+ private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
463
+ /** Consecutive non-clean runs per peer, cleared when one finishes cleanly. */
464
+ private readonly failures = new Map<string, number>();
465
+ /**
466
+ * Epoch ms before which a peer's catch-up must not be re-run, set alongside a backoff timer
467
+ * that will run it. Its presence is what makes `peer:identify` churn free: a schedule
468
+ * arriving inside the wait is dropped, rather than collapsing the backoff to the debounce.
469
+ */
470
+ private readonly retryAfter = new Map<string, number>();
471
+ /** Peers already reported on `console.warn`; reset when a run finally lands cleanly. */
472
+ private readonly warned = new Set<string>();
473
+ private readonly onPeerIdentify: (evt: CustomEvent<IdentifyResult>) => void;
474
+ private readonly onPeerDisconnect: (evt: CustomEvent<PeerId>) => void;
475
+ private loggedNoListBlockIds = false;
476
+
477
+ constructor(private readonly deps: PeerJoinBackfillDeps, config?: PeerJoinBackfillConfig) {
478
+ this.config = { ...DEFAULT_PEER_JOIN_BACKFILL, ...config };
479
+ this.createPushClient = deps.createPushClient
480
+ ?? ((peerId) => new BlockTransferClient(peerId, deps.peerNetwork, deps.protocolPrefix));
481
+ this.onPeerIdentify = (evt) => {
482
+ const { peerId, protocols } = evt.detail;
483
+ if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
484
+ this.schedulePeer(peerId);
485
+ }
486
+ };
487
+ this.onPeerDisconnect = (evt) => {
488
+ this.forgetCaughtUp(evt.detail.toString());
489
+ };
490
+ }
491
+
492
+ /**
493
+ * Subscribe to `peer:identify` AND schedule a catch-up for already-connected peers whose
494
+ * stored protocols already name this network's block-transfer protocol — a peer that does
495
+ * not speak it (a bare circuit relay, a bootstrap node) is never scheduled at all. Also
496
+ * subscribes to `peer:disconnect`, so a peer caught up before it went away is run again on
497
+ * its return. See {@link speaksBlockTransfer} and the module comment.
498
+ */
499
+ start(): void {
500
+ if (this.started || this.stopped || !this.config.enabled) return;
501
+ this.started = true;
502
+ this.deps.libp2p.addEventListener('peer:identify', this.onPeerIdentify);
503
+ this.deps.libp2p.addEventListener('peer:disconnect', this.onPeerDisconnect);
504
+ // A runtime rebuilt over live connections (resumeStrand) never sees their peer:identify —
505
+ // it already fired before this instance existed, but its result is persisted in the peer
506
+ // store — so walk what is already connected once.
507
+ void this.scheduleConnectedPeers().then((scheduled) => {
508
+ log('[%s] started (%d peer(s) already connected)', this.deps.label, scheduled);
509
+ });
510
+ }
511
+
512
+ /** Unsubscribe, clear timers; in-flight runs observe the stopped flag and bail. */
513
+ stop(): void {
514
+ if (this.stopped) return;
515
+ this.stopped = true;
516
+ if (this.started) {
517
+ this.deps.libp2p.removeEventListener('peer:identify', this.onPeerIdentify);
518
+ this.deps.libp2p.removeEventListener('peer:disconnect', this.onPeerDisconnect);
519
+ }
520
+ for (const timer of this.timers.values()) {
521
+ clearTimeout(timer);
522
+ }
523
+ this.timers.clear();
524
+ this.rearmAfterFlight.clear();
525
+ this.retryAfter.clear();
526
+ log('[%s] stopped', this.deps.label);
527
+ }
528
+
529
+ /**
530
+ * A peer's last connection closed: it is no longer caught up, so its next `peer:identify`
531
+ * re-runs. Only `done` is cleared. The memo stays (it keeps the re-run to what moved),
532
+ * `contacted` stays (a link flapping inside one settle window costs one run), and the
533
+ * backoff state stays (clearing it re-dials an unreachable peer on every reconnect; see the
534
+ * module comment's retry paragraph).
535
+ *
536
+ * When the returning peer wrote while away with a cohort that named this node, its own
537
+ * re-run pushes those blocks here and reports them through `reportBlockHeld`, so its
538
+ * under-replication drain does not push them again. Revisit if a measurement shows reconnect
539
+ * re-runs dominating push traffic.
540
+ */
541
+ private forgetCaughtUp(key: string): void {
542
+ this.done.delete(key);
543
+ if (this.inFlight.has(key)) {
544
+ this.disconnectedInFlight.add(key);
545
+ }
546
+ }
547
+
548
+ /**
549
+ * (Re-)schedule a debounced catch-up for every currently-connected peer whose protocols, as
550
+ * already stored in the libp2p peer store, name this network's block-transfer protocol. A
551
+ * peer not yet in the peer store — its identify has not finished — is left to the
552
+ * `peer:identify` handler rather than dialed blind; one whose stored protocols are known
553
+ * and lack ours is skipped outright. Idempotent and cheap otherwise (caught-up peers are
554
+ * skipped before any timer is set, and a peer whose run is in flight is deferred to the end
555
+ * of that run rather than dropped). Driven by {@link start}, and — on a gated network — by
556
+ * the embedder whenever membership changes, so a peer whose first pass was denied (connected
557
+ * before it was authorized: the production join order) is retried without waiting for a
558
+ * reconnect. Returns how many distinct peers were considered (for the start() log) — a peer
559
+ * holding several connections is one peer, and is scheduled once.
560
+ */
561
+ async scheduleConnectedPeers(): Promise<number> {
562
+ if (this.stopped) return 0;
563
+ const peers = new Map<string, PeerId>();
564
+ for (const connection of this.deps.libp2p.getConnections()) {
565
+ peers.set(connection.remotePeer.toString(), connection.remotePeer);
566
+ }
567
+ await Promise.all([...peers.values()].map((peerId) => this.scheduleIfKnownToSpeak(peerId)));
568
+ return peers.size;
569
+ }
570
+
571
+ /** Schedules `peerId` only if the peer store already knows it speaks this network's protocol. */
572
+ private async scheduleIfKnownToSpeak(peerId: PeerId): Promise<void> {
573
+ let protocols: string[];
574
+ try {
575
+ ({ protocols } = await this.deps.libp2p.peerStore.get(peerId));
576
+ } catch (error) {
577
+ // NotFoundError: identify has not finished. Leave it to the `peer:identify` handler
578
+ // rather than dialing blind. Anything else is unexpected — log it and skip the peer.
579
+ if ((error as Error).name !== 'NotFoundError') {
580
+ log('[%s] peer store read for %s failed — not scheduling: %o', this.deps.label, peerId.toString(), error);
581
+ }
582
+ return;
583
+ }
584
+ if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
585
+ this.schedulePeer(peerId);
586
+ }
587
+ }
588
+
589
+ /**
590
+ * Entry point for connection churn: one run per peer per settle window, except that a peer
591
+ * never run for is run at once (on a zero-delay timer, so a burst of identify events in one
592
+ * turn still collapses, and no work happens inside the libp2p event dispatch).
593
+ */
594
+ private schedulePeer(peerId: PeerId): void {
595
+ const key = peerId.toString();
596
+ if (this.stopped || this.done.has(key)) return;
597
+ if (this.inFlight.has(key)) {
598
+ // Defer rather than drop: the running pass may already be past its gate check (or
599
+ // past the block this schedule was meant to carry), so replay it when that pass ends.
600
+ this.rearmAfterFlight.add(key);
601
+ return;
602
+ }
603
+ // A peer whose last run failed is already re-armed on a backoff timer that will run it, so
604
+ // DROP this schedule instead of shortening the wait — otherwise a peer that cannot be
605
+ // reached is re-dialled on every peer:identify forever (see the module comment's retry
606
+ // paragraph). A denied run never gets here: it does not set a backoff.
607
+ const retryAt = this.retryAfter.get(key);
608
+ if (retryAt !== undefined && Date.now() < retryAt) return;
609
+ const existing = this.timers.get(key);
610
+ if (existing) clearTimeout(existing);
611
+ const delayMs = this.contacted.has(key) ? this.config.debounceMs : 0;
612
+ this.timers.set(key, setTimeout(() => {
613
+ this.timers.delete(key);
614
+ void this.catchUpPeer(peerId);
615
+ }, delayMs));
616
+ }
617
+
618
+ /**
619
+ * Run one peer's catch-up now, bypassing the debounce. Never rejects. Returns an
620
+ * all-zero result without pushing when the peer is already caught up, already being
621
+ * caught up, or this backfill is stopped.
622
+ */
623
+ async catchUpPeer(peerId: PeerId): Promise<PeerJoinBackfillResult> {
624
+ const key = peerId.toString();
625
+ if (this.stopped || this.done.has(key) || this.inFlight.has(key)) {
626
+ return emptyResult();
627
+ }
628
+ return await this.trackRun(peerId);
629
+ }
630
+
631
+ /**
632
+ * Run one peer's catch-up now and wait for it, even when the peer is memoized as caught up:
633
+ * wait out a run already in flight for it, then run again. The run still skips every block the
634
+ * peer is known to hold (it accepted or refused that revision, or signed it), so for a peer that
635
+ * holds the whole store it pushes nothing and returns `alreadyHeld` equal to the store size.
636
+ * Never rejects; an all-zero result only when stopped.
637
+ *
638
+ * For a caller that must know the peer holds this store before it proceeds, where
639
+ * {@link catchUpPeer}'s empty answer would hide a run that was denied (a `peer:identify`
640
+ * run can pass the gate a moment before the caller authorized the peer) or commits made
641
+ * since the peer was caught up.
642
+ */
643
+ async forceCatchUpPeer(peerId: PeerId): Promise<PeerJoinBackfillResult> {
644
+ const key = peerId.toString();
645
+ for (let pending = this.inFlight.get(key); pending; pending = this.inFlight.get(key)) {
646
+ await pending;
647
+ }
648
+ if (this.stopped) {
649
+ return emptyResult();
650
+ }
651
+ return await this.trackRun(peerId);
652
+ }
653
+
654
+ /**
655
+ * Register one run in {@link inFlight} before its first await, so no second run for the
656
+ * peer can start beside it, and replay a schedule that arrived while it ran.
657
+ */
658
+ private async trackRun(peerId: PeerId): Promise<PeerJoinBackfillResult> {
659
+ const key = peerId.toString();
660
+ this.contacted.add(key);
661
+ const run = this.settleRun(peerId);
662
+ this.inFlight.set(key, run);
663
+ try {
664
+ return await run;
665
+ } finally {
666
+ this.inFlight.delete(key);
667
+ this.disconnectedInFlight.delete(key);
668
+ // Replay a schedule that arrived mid-run. `schedulePeer` re-checks `done`, so a run
669
+ // that finished clean re-arms nothing; a denied or failed one gets its retry.
670
+ if (this.rearmAfterFlight.delete(key)) {
671
+ this.schedulePeer(peerId);
672
+ }
673
+ }
674
+ }
675
+
676
+ /** One run and what follows from its outcome: the memo, or a backoff re-arm. Never rejects. */
677
+ private async settleRun(peerId: PeerId): Promise<PeerJoinBackfillResult> {
678
+ const key = peerId.toString();
679
+ try {
680
+ const { result, clean, pushFailed } = await this.runCatchUp(peerId);
681
+ // NOTE: a run that hit `maxBlocks` is still "clean" and still marks the peer caught up,
682
+ // so no `peer:identify` run reaches the tail past the ceiling. Loud in the log below
683
+ // (capped > 0). Blocks the peer is known to hold are not offered and do not count toward
684
+ // the ceiling, so a forced run resumes past the prefix already sent. If a store can
685
+ // realistically exceed maxBlocks, leave a capped run out of `done` so each identify run
686
+ // sends the next `maxBlocks`.
687
+ if (clean && !this.stopped) {
688
+ // A disconnect mid-run cleared `done` already; re-adding it would drop the reconnect.
689
+ // Not judged by `isConnected`: hand-driven runs target peers with no connection.
690
+ if (!this.disconnectedInFlight.has(key)) {
691
+ this.done.add(key);
692
+ }
693
+ this.failures.delete(key);
694
+ this.retryAfter.delete(key);
695
+ this.warned.delete(key);
696
+ } else if (pushFailed && !this.stopped && this.started && this.isConnected(peerId)) {
697
+ // `pushFailed`, not `!clean`: a denial and an inert store are verdicts a retry cannot
698
+ // change, and re-arming on them would retry forever. See the module comment.
699
+ //
700
+ // Gated on `started` too: the re-arm exists to REPLACE a peer:identify-driven retry,
701
+ // so a caller driving `catchUpPeer` by hand against a backfill that was never started
702
+ // owns its own retry policy and must not be left holding a background timer.
703
+ this.scheduleRetryWithBackoff(peerId);
704
+ }
705
+ log('[%s] catch-up peer=%s offered=%d alreadyHeld=%d accepted=%d rejected=%d uncommitted=%d unmaterialized=%d capped=%d oversized=%d denied=%s done=%s',
706
+ this.deps.label, key, result.offered, result.alreadyHeld, result.accepted, result.rejected.length,
707
+ result.uncommitted, result.unmaterialized, result.capped, result.oversized.length, result.denied, clean);
708
+ return result;
709
+ } catch (error) {
710
+ // runCatchUp already contains a per-chunk catch; this guards the enumeration and
711
+ // metadata reads too — a backfill fault must never surface through a libp2p event.
712
+ log('[%s] catch-up peer=%s failed: %o', this.deps.label, key, error);
713
+ return emptyResult();
714
+ }
715
+ }
716
+
717
+ /** Whether this network's libp2p node still holds a connection to that peer. */
718
+ private isConnected(peerId: PeerId): boolean {
719
+ return this.deps.libp2p.getConnections(peerId).length > 0;
720
+ }
721
+
722
+ /**
723
+ * Re-arm one peer's catch-up after a run whose push failed, on a wait that doubles
724
+ * per consecutive failure up to `maxRetryBackoffMs`. Sets {@link retryAfter} alongside the
725
+ * timer, which is what makes `peer:identify` churn inside the wait free.
726
+ */
727
+ private scheduleRetryWithBackoff(peerId: PeerId): void {
728
+ const key = peerId.toString();
729
+ const failures = (this.failures.get(key) ?? 0) + 1;
730
+ this.failures.set(key, failures);
731
+ const delayMs = Math.min(
732
+ this.config.retryBackoffMs * 2 ** (failures - 1),
733
+ this.config.maxRetryBackoffMs
734
+ );
735
+ this.retryAfter.set(key, Date.now() + delayMs);
736
+ const existing = this.timers.get(key);
737
+ if (existing) clearTimeout(existing);
738
+ this.timers.set(key, setTimeout(() => {
739
+ this.timers.delete(key);
740
+ this.retryAfter.delete(key);
741
+ void this.catchUpPeer(peerId);
742
+ }, delayMs));
743
+ log('[%s] catch-up peer=%s failed %d time(s) in a row; retrying in %dms',
744
+ this.deps.label, key, failures, delayMs);
745
+ this.warnPersistentFailure(key, failures);
746
+ }
747
+
748
+ /**
749
+ * Say ONCE per peer, outside the DEBUG log, that its catch-up is not landing. Without this a
750
+ * machine on a link too slow for a relayed dial produces no statement that anything is wrong:
751
+ * the peer never appears to hold the blocks, and the only trace is a DEBUG line naming a dial
752
+ * timeout. Reset when a run finally lands cleanly, so a peer that recovers can report again.
753
+ */
754
+ private warnPersistentFailure(key: string, failures: number): void {
755
+ if (failures < PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES || this.warned.has(key)) return;
756
+ this.warned.add(key);
757
+ console.warn(
758
+ `[cadre:${this.deps.label}] peer-join block catch-up to peer ${key} has failed ${failures} times in a row `
759
+ + `(dial budget ${this.config.dialTimeoutMs}ms, response budget ${this.config.responseTimeoutMs}ms). `
760
+ + 'That peer may not be holding blocks committed before it joined. If it is reachable only through a relay, '
761
+ + 'these budgets and libp2p\'s own connection limits are derived from network.linkRoundTripMs (see link-budget.ts); '
762
+ + 'a link slower than that declaration, or a peer that declared a faster one, cannot open a relayed connection at all.'
763
+ );
764
+ }
765
+
766
+ /** This peer's memo, created empty on first use. */
767
+ private memoFor(key: string): PeerMemo {
768
+ let memo = this.memos.get(key);
769
+ if (!memo) {
770
+ memo = { accepted: new Map(), rejected: new Map() };
771
+ this.memos.set(key, memo);
772
+ }
773
+ return memo;
774
+ }
775
+
776
+ /**
777
+ * Tell the node which blocks of one push reply the peer accepted, at the revision pushed.
778
+ * Best-effort: a failed report is logged and costs only the drain's duplicate push.
779
+ */
780
+ private async reportAccepted(key: string, revs: Readonly<Record<string, { rev: number }>>, ids: readonly string[], missing: ReadonlySet<string>): Promise<void> {
781
+ const report = this.deps.reportBlockHeld;
782
+ if (!report) return;
783
+ for (const id of ids) {
784
+ if (missing.has(id)) continue;
785
+ try {
786
+ await report(id, revs[id]!.rev, key);
787
+ } catch (error) {
788
+ log('[%s] reportBlockHeld for peer=%s block=%s failed: %s', this.deps.label, key, id, (error as Error).message);
789
+ }
790
+ }
791
+ }
792
+
793
+ /**
794
+ * The actual copy. `clean` = the gate admitted the peer, the store is listable and no push
795
+ * threw (a block the receiver refused is remembered per block instead, see {@link PeerMemo}).
796
+ * `pushFailed` = at least one push THREW, which is the only non-clean outcome a retry can
797
+ * change; the others are verdicts (denied, inert store).
798
+ */
799
+ private async runCatchUp(peerId: PeerId): Promise<{ result: PeerJoinBackfillResult; clean: boolean; pushFailed: boolean }> {
800
+ const result = emptyResult();
801
+ const { storage } = this.deps;
802
+ const key = peerId.toString();
803
+
804
+ // The membership gate, judged at push time (never at schedule time — authorization can
805
+ // change during the debounce window in either direction). Fails CLOSED on a throw: a
806
+ // gate that cannot answer must not leak the store. A denied run is not clean, so the
807
+ // peer is retried later rather than memoized as caught up.
808
+ if (this.deps.authorizePeer) {
809
+ let authorized = false;
810
+ try {
811
+ authorized = await this.deps.authorizePeer(peerId.toString());
812
+ } catch (error) {
813
+ log('[%s] authorizePeer(%s) threw — treating as denied: %o', this.deps.label, peerId.toString(), error);
814
+ }
815
+ if (!authorized) {
816
+ result.denied = true;
817
+ return { result, clean: false, pushFailed: false };
818
+ }
819
+ }
820
+
821
+ if (!storage.listBlockIds) {
822
+ if (!this.loggedNoListBlockIds) {
823
+ this.loggedNoListBlockIds = true;
824
+ log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.label);
825
+ }
826
+ return { result, clean: false, pushFailed: false };
827
+ }
828
+
829
+ const client = this.createPushClient(peerId);
830
+ const memo = this.memoFor(key);
831
+ let chunk: Chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
832
+ let chunkFailed = false;
833
+ let anyChunkDelivered = false;
834
+ /**
835
+ * A peer that has answered no push at all, and failed one, is not reachable on this
836
+ * protocol — abandon rather than spend a dial timeout per remaining chunk. Once ONE
837
+ * push has been answered the peer demonstrably speaks it, so a later failure is a
838
+ * transient blip and the rest of the store is still worth pushing.
839
+ */
840
+ const peerUnreachable = (): boolean => chunkFailed && !anyChunkDelivered;
841
+
842
+ const flush = async (): Promise<void> => {
843
+ if (chunk.ids.length === 0) return;
844
+ const { ids, buffers, meta, proofs } = chunk;
845
+ chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
846
+ try {
847
+ // ONE certification value rather than two arguments, so a caller cannot pair a proof
848
+ // for one revision with meta for another — both were written from the same `latest`.
849
+ const response = await client.pushBlocks(ids, buffers, 'replication',
850
+ { blockMeta: meta, blockProofs: proofs }, {
851
+ dialTimeoutMs: this.config.dialTimeoutMs,
852
+ responseTimeoutMs: this.config.responseTimeoutMs
853
+ });
854
+ anyChunkDelivered = true;
855
+ const missing = new Set(response.missing);
856
+ recordReply(memo, meta, ids, missing);
857
+ await this.reportAccepted(key, meta, ids, missing);
858
+ for (const id of ids) {
859
+ if (missing.has(id)) {
860
+ result.rejected.push(id);
861
+ } else {
862
+ result.accepted += 1;
863
+ }
864
+ }
865
+ if (response.missing.length > 0) {
866
+ log('[%s] peer=%s rejected %d block(s), not offered to it again at these revisions: %o',
867
+ this.deps.label, key, response.missing.length, response.missing);
868
+ }
869
+ } catch (error) {
870
+ chunkFailed = true;
871
+ log('[%s] push to peer=%s failed for %d block(s): %s', this.deps.label, key, ids.length, (error as Error).message);
872
+ }
873
+ };
874
+
875
+ for await (const blockId of storage.listBlockIds()) {
876
+ if (this.stopped) break;
877
+ if (result.offered >= this.config.maxBlocks) {
878
+ // Past the ceiling: count what is left (id enumeration only — no more reads or
879
+ // pushes) so the cap is loud in the end-of-run log rather than silent.
880
+ result.capped += 1;
881
+ continue;
882
+ }
883
+
884
+ const offer = await this.readOffer(blockId, key, memo, result);
885
+ if (!offer) continue;
886
+
887
+ // Flush before adding when this block would overflow either budget. A single block
888
+ // larger than maxChunkBytes still ships — alone, in its own chunk.
889
+ if (chunk.ids.length > 0
890
+ && (chunk.ids.length + 1 > this.config.maxChunkBlocks || chunk.bytes + offer.buffer.length > this.config.maxChunkBytes)) {
891
+ await flush();
892
+ if (this.stopped || peerUnreachable()) break;
893
+ }
894
+ chunk.ids.push(blockId);
895
+ chunk.buffers.push(offer.buffer);
896
+ chunk.meta[blockId] = { rev: offer.latest.rev, actionId: offer.latest.actionId };
897
+ if (offer.proof) {
898
+ chunk.proofs[blockId] = offer.proof;
899
+ }
900
+ chunk.bytes += offer.buffer.length;
901
+ result.offered += 1;
902
+ }
903
+
904
+ if (!this.stopped && !peerUnreachable()) {
905
+ await flush();
906
+ }
907
+
908
+ if (result.capped > 0) {
909
+ log('[%s] peer=%s catch-up CAPPED at %d blocks; %d block id(s) not attempted',
910
+ this.deps.label, key, this.config.maxBlocks, result.capped);
911
+ }
912
+
913
+ return { result, clean: !chunkFailed, pushFailed: chunkFailed };
914
+ }
915
+
916
+ /**
917
+ * Read one block for the push to `key`, or count why it is skipped in `result` and return
918
+ * nothing: not committed, already held by the peer (memo or its own commit signature), not
919
+ * materialized, or too large for one message. The proof is read for EXACTLY the revision the
920
+ * meta will name, from the same `latest`; absent is normal (nothing retained a proof for that
921
+ * revision), and the block still ships with its meta for the receiver to decide.
922
+ */
923
+ private async readOffer(
924
+ blockId: string,
925
+ key: string,
926
+ memo: PeerMemo,
927
+ result: PeerJoinBackfillResult
928
+ ): Promise<{ latest: ActionRev; buffer: Uint8Array; proof: BlockCommitProof | undefined } | undefined> {
929
+ const { storage } = this.deps;
930
+ const latest = (await storage.getMetadata(blockId))?.latest;
931
+ if (!latest) {
932
+ result.uncommitted += 1;
933
+ return undefined;
934
+ }
935
+ if (memoSettled(memo, blockId, latest.rev)) {
936
+ result.alreadyHeld += 1;
937
+ return undefined;
938
+ }
939
+ const proof = await storage.getBlockProof(blockId, latest.rev);
940
+ if (signedBy(proof, key)) {
941
+ result.alreadyHeld += 1;
942
+ return undefined;
943
+ }
944
+ // NOTE: a block whose latest revision is a DELETE materializes to nothing (a
945
+ // tombstone), so it is skipped here — a peer that joins after such a delete never
946
+ // receives the tombstone from this path and relies on read repair for it. Fine
947
+ // while nothing deletes whole blocks pre-join; if the whole-store coverage gate in
948
+ // strand-membership-closed-strand-e2e ever reports a tombstone residue, teach this
949
+ // to push the promoted delete transform instead of skipping.
950
+ const block = await storage.getMaterializedBlock(blockId, latest.actionId);
951
+ if (!block) {
952
+ result.unmaterialized += 1;
953
+ log('[%s] block=%s has latest rev %d but no materialized content; skipped', this.deps.label, blockId, latest.rev);
954
+ return undefined;
955
+ }
956
+ const buffer = blockEncoder.encode(JSON.stringify(block));
957
+ // NOTE: MAX_BLOCK_MESSAGE_BYTES caps the whole framed request, not one block, and
958
+ // this test ignores the request envelope (ids array, blockMeta, JSON punctuation).
959
+ // A lone block within a few KiB of the cap therefore still ships and is rejected by
960
+ // the receiver's length-prefix decoder — a permanent chunk failure for that peer. No
961
+ // block comes close today; if one ever can, subtract a measured envelope allowance
962
+ // here rather than raising the cap.
963
+ if (base64WireBytes(buffer.length) >= MAX_BLOCK_MESSAGE_BYTES) {
964
+ result.oversized.push(blockId);
965
+ log('[%s] block=%s is %d bytes (%d on the wire) — exceeds the %d-byte protocol cap alone; skipped',
966
+ this.deps.label, blockId, buffer.length, base64WireBytes(buffer.length), MAX_BLOCK_MESSAGE_BYTES);
967
+ return undefined;
968
+ }
969
+ return { latest, buffer, proof };
970
+ }
971
+ }