@serfab/cadre-core 1.9.0 → 1.11.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 (119) hide show
  1. package/dist/cadre-node.d.ts +148 -44
  2. package/dist/cadre-node.js +363 -139
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-authorization.d.ts +2 -2
  5. package/dist/control-authorization.js +1 -0
  6. package/dist/control-authorization.js.map +1 -1
  7. package/dist/control-cohort.d.ts +1 -1
  8. package/dist/control-cohort.js +1 -1
  9. package/dist/control-database.d.ts +105 -14
  10. package/dist/control-database.js +242 -73
  11. package/dist/control-database.js.map +1 -1
  12. package/dist/control-formation-recorder.d.ts +6 -6
  13. package/dist/control-formation-recorder.js +7 -8
  14. package/dist/control-formation-recorder.js.map +1 -1
  15. package/dist/control-schema.d.ts +1 -1
  16. package/dist/control-schema.js +1066 -979
  17. package/dist/control-schema.js.map +1 -1
  18. package/dist/control-write-retry.d.ts +21 -15
  19. package/dist/control-write-retry.js +21 -15
  20. package/dist/control-write-retry.js.map +1 -1
  21. package/dist/diagnostics/connection-path.d.ts +1 -18
  22. package/dist/diagnostics/connection-path.js +1 -20
  23. package/dist/diagnostics/connection-path.js.map +1 -1
  24. package/dist/identity-key.d.ts +0 -30
  25. package/dist/identity-key.js +7 -40
  26. package/dist/identity-key.js.map +1 -1
  27. package/dist/index.d.ts +8 -5
  28. package/dist/index.js +12 -6
  29. package/dist/index.js.map +1 -1
  30. package/dist/invitation-bootstrap.d.ts +32 -0
  31. package/dist/invitation-bootstrap.js +30 -0
  32. package/dist/invitation-bootstrap.js.map +1 -0
  33. package/dist/link-budget.d.ts +204 -119
  34. package/dist/link-budget.js +208 -120
  35. package/dist/link-budget.js.map +1 -1
  36. package/dist/membership-connection-gater.d.ts +3 -3
  37. package/dist/membership-connection-gater.js +3 -3
  38. package/dist/peer-dial.d.ts +18 -14
  39. package/dist/peer-dial.js +18 -14
  40. package/dist/peer-dial.js.map +1 -1
  41. package/dist/peer-join-backfill.d.ts +3 -3
  42. package/dist/pending-join-runner.d.ts +186 -0
  43. package/dist/pending-join-runner.js +649 -0
  44. package/dist/pending-join-runner.js.map +1 -0
  45. package/dist/push-fanout.d.ts +1 -1
  46. package/dist/push-fanout.js +1 -1
  47. package/dist/relay-stun.d.ts +24 -0
  48. package/dist/relay-stun.js +51 -0
  49. package/dist/relay-stun.js.map +1 -0
  50. package/dist/seed-bootstrap.d.ts +2 -2
  51. package/dist/seed-bootstrap.js +5 -5
  52. package/dist/strand-addr-protocol.js +2 -2
  53. package/dist/strand-formation-deadlines.d.ts +5 -5
  54. package/dist/strand-formation-deadlines.js +5 -5
  55. package/dist/strand-formation-manager.d.ts +18 -4
  56. package/dist/strand-formation-manager.js +48 -33
  57. package/dist/strand-formation-manager.js.map +1 -1
  58. package/dist/strand-formation-protocol.d.ts +71 -14
  59. package/dist/strand-formation-protocol.js +222 -47
  60. package/dist/strand-formation-protocol.js.map +1 -1
  61. package/dist/strand-formation-rejection.d.ts +94 -0
  62. package/dist/strand-formation-rejection.js +77 -0
  63. package/dist/strand-formation-rejection.js.map +1 -0
  64. package/dist/strand-instance-manager.js +4 -1
  65. package/dist/strand-instance-manager.js.map +1 -1
  66. package/dist/strand-membership-writer.js +32 -32
  67. package/dist/strand-solicitation.d.ts +11 -3
  68. package/dist/strand-solicitation.js +9 -0
  69. package/dist/strand-solicitation.js.map +1 -1
  70. package/dist/types.d.ts +103 -17
  71. package/dist/types.js +5 -9
  72. package/dist/types.js.map +1 -1
  73. package/package.json +22 -22
  74. package/src/cadre-node.ts +8654 -8400
  75. package/src/control-authorization.ts +2 -1
  76. package/src/control-cohort.ts +128 -128
  77. package/src/control-database.ts +303 -82
  78. package/src/control-formation-recorder.ts +353 -354
  79. package/src/control-read-retry.ts +216 -216
  80. package/src/control-schema.ts +1078 -991
  81. package/src/control-write-retry.ts +567 -561
  82. package/src/diagnostics/connection-path.ts +1 -29
  83. package/src/formation-approval.ts +610 -610
  84. package/src/hibernation-manager.ts +638 -638
  85. package/src/identity-key.ts +7 -62
  86. package/src/index.ts +644 -627
  87. package/src/invitation-bootstrap.ts +40 -0
  88. package/src/joined-strand-store.ts +498 -498
  89. package/src/link-budget.ts +684 -583
  90. package/src/membership-connection-gater.ts +570 -570
  91. package/src/node-local-snapshot.ts +298 -298
  92. package/src/peer-dial.ts +315 -311
  93. package/src/peer-join-backfill.ts +710 -710
  94. package/src/pending-join-runner.ts +735 -0
  95. package/src/push-fanout.ts +1 -1
  96. package/src/relay-reservation.ts +1121 -1121
  97. package/src/relay-server.ts +98 -98
  98. package/src/relay-stun.ts +58 -0
  99. package/src/seed-bootstrap.ts +1448 -1448
  100. package/src/strand-addr-protocol.ts +547 -547
  101. package/src/strand-database.ts +287 -287
  102. package/src/strand-first-sync-gate.ts +391 -391
  103. package/src/strand-formation-deadlines.ts +227 -227
  104. package/src/strand-formation-manager.ts +725 -700
  105. package/src/strand-formation-protocol.ts +1036 -802
  106. package/src/strand-formation-rejection.ts +129 -0
  107. package/src/strand-fret-addrs.ts +145 -145
  108. package/src/strand-instance-manager.ts +1789 -1786
  109. package/src/strand-membership-writer.ts +1974 -1974
  110. package/src/strand-network-state-file.ts +40 -40
  111. package/src/strand-network-state.ts +243 -243
  112. package/src/strand-revocation-enforcer.ts +654 -654
  113. package/src/strand-solicitation.ts +532 -519
  114. package/src/strand-wake-protocol.ts +401 -401
  115. package/src/types.ts +2222 -2140
  116. package/dist/diagnostics/webrtc-turn-tracker.d.ts +0 -50
  117. package/dist/diagnostics/webrtc-turn-tracker.js +0 -196
  118. package/dist/diagnostics/webrtc-turn-tracker.js.map +0 -1
  119. package/src/diagnostics/webrtc-turn-tracker.ts +0 -222
@@ -1,710 +1,710 @@
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
- // Membership — the one place the two networks differ, expressed as the optional
38
- // `authorizePeer` dep:
39
- //
40
- // - STRAND networks pass none. Anything that speaks the strand's own block-transfer protocol
41
- // already receives cohort replicas of new commits, so pushing older blocks to it exposes
42
- // nothing new; adding a gate would diverge from what ordinary replication already does
43
- // there.
44
- // - The CONTROL network MUST pass one, because that argument does not carry over: its
45
- // inbound connection gate deliberately admits non-members in several states (an
46
- // un-enrolled node taking its seed, an open enrollment window, an outstanding
47
- // invitation, configured bootstrap/relay peers — see docs/architecture.md, the
48
- // control-network inbound connection gate). Pushing the whole control store to such a
49
- // peer would hand a stranger the party's entire membership, addresses and strand list.
50
- // `CadreNode` passes `isAuthorizedMember`; the gate is consulted at PUSH time, not at
51
- // schedule time, and fails closed on a thrown check. A denied run is not memoized, so
52
- // the peer is retried on its next `peer:identify` (a reconnect re-runs identify) — or
53
- // sooner, via `scheduleConnectedPeers()` on a membership change (the production join order is
54
- // connect-then-authorize, so the denial at dial time is the expected first pass).
55
- //
56
- // Both per-push deadlines are DERIVED from the declared link round trip
57
- // (`link-budget.ts`), not fixed milliseconds. That is not tuning — it is what makes this
58
- // module work at all over a relay. Opening a relayed connection costs a fixed number of
59
- // exchanges, so the 3000 ms this catch-up used to allow its dial could never finish one
60
- // above 375 ms of one-way link delay: the catch-up existed so that a machine which joined
61
- // after blocks were committed physically ends up holding them, and through a relay on any
62
- // link slow enough to matter it had never once managed to. The reproduction is
63
- // `packages/integration-tests/src/scenarios/relayed-dial-cost-by-latency.integration.ts`.
64
- //
65
- // It does NOT work at every speed. Above the declared link, libp2p's own dial and
66
- // inbound-upgrade limits — which Optimystic derives from the same declaration — abandon the
67
- // connection before any deadline here is consulted, and the listener's one makes that failure
68
- // look like an absent peer rather than a timeout. That is also what happens when the machine
69
- // being caught up declared a FASTER link than this one, since its limit is the listener's. See
70
- // `link-budget.ts` ("Optimystic's deadlines, from the same declaration", "What still fails at
71
- // the supported link").
72
- //
73
- // RETRY, and why it backs off. A run whose PUSH FAILED — the transport threw, which is what
74
- // a dial or response deadline expiring looks like here — re-arms on a doubling backoff
75
- // (`retryBackoffMs` to `maxRetryBackoffMs`), and a `peer:identify` arriving while that wait
76
- // is outstanding is DROPPED rather than collapsing it back to the debounce. Both halves are
77
- // load-bearing:
78
- //
79
- // - Without the re-arm, a transient push failure over a stable connection left the peer
80
- // partially copied until its next reconnect (read repair still covered reads meanwhile).
81
- // - Without dropping churn inside the wait, a peer that cannot be reached at all is
82
- // re-dialled on every `peer:identify` forever. That is not hypothetical: the 2026-09-26
83
- // relayed reproduction shows one peer re-opening a connection about every 14.5 s for a
84
- // 200-second run, each event starting a catch-up whose dial could not possibly finish.
85
- // The connection kept re-appearing because Optimystic's own block-transfer push path
86
- // budgets its dial at `transferTimeoutMs ?? 30000` — the one dial budget in the stack
87
- // above the measured relayed setup cost — so it succeeded where this one could not.
88
- //
89
- // A NON-CLEAN run is NOT on its own enough to re-arm, and the distinction is what keeps the
90
- // backoff from becoming a worse problem than the one it fixes. `clean` also goes false for
91
- // outcomes no amount of retrying can change: the membership gate DENIED the peer; this
92
- // network's raw storage implements no `listBlockIds`, so the catch-up is inert; or the
93
- // receiver reported blocks in `missing`, which it does per block for a payload it cannot
94
- // parse and for a revision whose retained commit proof this node does not hold (a push
95
- // carrying no proof is refused outright by a receiver running the default
96
- // `requirePushCertificate: true`, and an unretained proof is the ordinary case — see
97
- // {@link Chunk.proofs}). Re-arming on those would re-push the WHOLE store to that peer every
98
- // `maxRetryBackoffMs` for as long as the node runs, and report the failure below as a link
99
- // budget problem when nothing about the link is wrong. All three still leave the peer
100
- // un-memoized, so its next `peer:identify` retries — the behaviour that predates the
101
- // backoff, and the right one for a verdict rather than a timeout. Denial in particular is
102
- // re-driven on purpose by `scheduleConnectedPeers()` the moment the membership commit lands,
103
- // because the control network's join order is connect-then-authorize.
104
- //
105
- // A re-arm is also skipped when the peer is no longer CONNECTED. This module's trigger is
106
- // `peer:identify`, so a peer that went away already has one: re-arming instead would leave
107
- // a machine dialing a peer it cannot see once a minute for the rest of its uptime.
108
- //
109
- // After `PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES` consecutive failures one `console.warn`
110
- // names the peer and the budget, because otherwise a machine on a too-slow link says
111
- // nothing at all: the connection simply never appears and only a DEBUG log mentions a dial
112
- // timeout.
113
- //
114
- // NOTE: the protocol check happens once — either when a connection's `peer:identify` fires,
115
- // or, for a peer already connected when this instance starts, when `scheduleConnectedPeers()`
116
- // reads its protocols back from the peer store — and is never repeated once a peer is
117
- // scheduled. A peer that stops speaking the protocol after being scheduled (should that ever
118
- // happen) is not de-scheduled; `runCatchUp`'s own unreachable-peer bail is what would catch
119
- // that case instead. `peer:identify` also fires on every identify-push from a connected peer
120
- // (address or protocol changes), which only re-enters the debounce — cheap, and dropped
121
- // outright for caught-up peers and peers inside a backoff wait.
122
- //
123
- // NOTE: a same-network peer whose identify never completes on a connection (the identify
124
- // stream times out over a slow relayed link, say) is not caught up until a later identify
125
- // succeeds — a reconnect, an identify-push, or on the control network a membership-change
126
- // re-drive. Accepted: every db-p2p node runs identify, and read repair still covers reads
127
- // meanwhile; if relayed links ever routinely outlast identify's timeout, raise that timeout
128
- // in the node builder rather than scheduling unidentified peers here.
129
- //
130
- // NOTE: a peer that disconnects INSIDE a backoff wait still costs the one attempt that wait
131
- // was already armed for — the connectivity check is made when the re-arm is decided, not when
132
- // the timer fires, and this module subscribes to `peer:identify` only. One dial, not a
133
- // recurring one; if a node ever holds many transient peers, subscribe to `connection:close`
134
- // and clear the pending timer there.
135
-
136
- const log = debug('sereus:cadre:peer-join-backfill');
137
-
138
- /**
139
- * The block-transfer protocol's hard cap on one length-prefixed message. Mirrors
140
- * `MAX_BLOCK_MESSAGE_BYTES` in `@optimystic/db-p2p`'s `protocol-limits.ts` (8 MiB), which
141
- * that package does not re-export from its index — keep the two in sync if upstream ever
142
- * changes it or starts exporting it.
143
- */
144
- export const MAX_BLOCK_MESSAGE_BYTES = 8 * 1024 * 1024;
145
-
146
- /**
147
- * Whether an identified peer's protocol list names this network's own block-transfer
148
- * protocol — the one gate that decides whether {@link PeerJoinBackfill} schedules a peer at
149
- * all. A peer that lacks it (a bare circuit relay, a bootstrap node, a stranger the control
150
- * network's inbound gate admitted without membership) cannot receive a push no matter how
151
- * long it is dialed, since the protocol id is namespaced per network.
152
- */
153
- function speaksBlockTransfer(protocols: readonly string[], protocolPrefix: string): boolean {
154
- return protocols.includes(buildBlockTransferProtocol(protocolPrefix));
155
- }
156
-
157
- /**
158
- * Consecutive failed catch-up runs against ONE peer before the module says so on
159
- * `console.warn` rather than only in its DEBUG log. At the default backoff that is reached
160
- * about 35 seconds in (5 s + 10 s + 20 s), which is late enough to have ruled out a blip and
161
- * early enough to be the first thing an operator sees about a machine that is not catching up.
162
- */
163
- export const PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES = 3;
164
-
165
- /** Tuning for the per-peer catch-up. Every field optional; defaults in {@link DEFAULT_PEER_JOIN_BACKFILL}. */
166
- export interface PeerJoinBackfillConfig {
167
- /** Default true. False disables the catch-up entirely (the pre-existing behaviour). */
168
- enabled?: boolean;
169
- /** Settle time after a connection opens before catching that peer up, ms. Default 1000. */
170
- debounceMs?: number;
171
- /** Ceiling on blocks copied in one catch-up. Default 10_000. Reaching it is LOGGED, never silent. */
172
- maxBlocks?: number;
173
- /** Soft byte budget per push message. Default 1 MiB. Protocol hard cap is {@link MAX_BLOCK_MESSAGE_BYTES} (8 MiB). */
174
- maxChunkBytes?: number;
175
- /** Max blocks per push message. Default 64. */
176
- maxChunkBlocks?: number;
177
- /**
178
- * Per-push dial deadline, ms. Default {@link peerJoinPushBudget}'s `dialTimeoutMs` — four link
179
- * round trips at the declared link plus the called machine's admission decision, 16 000 ms as
180
- * shipped. NOT a fixed number: a relayed dial
181
- * costs a fixed number of exchanges, so a host on a slower link moves this (and every other
182
- * cadre dial budget) by declaring `NetworkConfig.linkRoundTripMs`. Naming it here still wins
183
- * over the derived value — `link-budget.ts` has the counts and the measurement.
184
- */
185
- dialTimeoutMs?: number;
186
- /**
187
- * Per-push response deadline, ms. Default {@link peerJoinPushBudget}'s `responseTimeoutMs` —
188
- * two link round trips at the declared link plus a transfer allowance for the chunk's own
189
- * bytes, 13 000 ms as shipped. Derived differently from {@link dialTimeoutMs} because it
190
- * bounds a data transfer over a connection that is already open, not a dial.
191
- */
192
- responseTimeoutMs?: number;
193
- /**
194
- * First wait before re-running a catch-up whose last run did not complete cleanly, ms.
195
- * Default 5000. Doubles per consecutive failure up to {@link maxRetryBackoffMs}.
196
- */
197
- retryBackoffMs?: number;
198
- /** Ceiling on that doubling wait, ms. Default 60_000. */
199
- maxRetryBackoffMs?: number;
200
- }
201
-
202
- /** The resolved defaults every {@link PeerJoinBackfill} starts from. */
203
- export const DEFAULT_PEER_JOIN_BACKFILL: Required<PeerJoinBackfillConfig> = {
204
- enabled: true,
205
- debounceMs: 1000,
206
- maxBlocks: 10_000,
207
- maxChunkBytes: 1024 * 1024,
208
- maxChunkBlocks: 64,
209
- // Derived at the DEFAULT declared link, for a `PeerJoinBackfill` built without a host's
210
- // declaration (this module's own tests, an embedder driving it directly). The two production
211
- // construction sites pass `peerJoinPushBudget(network?.linkRoundTripMs)` so a host that
212
- // declares a slower link moves both — see `link-budget.ts`.
213
- ...peerJoinPushBudget(),
214
- retryBackoffMs: 5000,
215
- maxRetryBackoffMs: 60_000
216
- };
217
-
218
- /**
219
- * The one capability the catch-up needs from a transfer client. Structural (rather than
220
- * the concrete `BlockTransferClient`) so unit tests can capture pushes without dialing
221
- * libp2p — see {@link PeerJoinBackfillDeps.createPushClient}.
222
- */
223
- export type PeerJoinBackfillPushClient = Pick<BlockTransferClient, 'pushBlocks'>;
224
-
225
- export interface PeerJoinBackfillDeps {
226
- /** Log tag naming which network this catch-up serves (a strand id, or `control-<partyId>`). */
227
- label: string;
228
- /** The libp2p node of the network being caught up — source of connection events and peer ids. */
229
- libp2p: Libp2p;
230
- /** `node.keyNetwork`, the IPeerNetwork BlockTransferClient dials through. */
231
- peerNetwork: IPeerNetwork;
232
- /** This network's own raw block store — the same instance handed to the libp2p node. */
233
- storage: IRawStorage;
234
- /** Must equal the prefix the receiver registered its handler under: `/optimystic/<networkName>`. */
235
- protocolPrefix: string;
236
- /**
237
- * Membership gate, consulted at PUSH time (fails closed on a throw). Absent = push to
238
- * every connected peer — correct for strand networks, NEVER for the control network;
239
- * see the module comment for why the strand no-gate argument does not carry over.
240
- */
241
- authorizePeer?: (peerId: string) => Promise<boolean>;
242
- /**
243
- * Test seam: build the per-peer push client. Defaults to a real
244
- * `BlockTransferClient` over {@link peerNetwork} + {@link protocolPrefix}.
245
- */
246
- createPushClient?: (peerId: PeerId) => PeerJoinBackfillPushClient;
247
- }
248
-
249
- /** What one peer's catch-up actually did. Returned for tests and logged at the end of each run. */
250
- export interface PeerJoinBackfillResult {
251
- /** Blocks offered: had a committed `latest` AND materialized content locally. */
252
- offered: number;
253
- /** Blocks the remote reported it persisted. */
254
- accepted: number;
255
- /** Block ids the remote reported in `missing` (parse or persist failure on its side). */
256
- rejected: string[];
257
- /** Skipped: metadata has no `latest` (pending-only — not yet a durability claim here). */
258
- uncommitted: number;
259
- /** Skipped: `latest` exists but no materialized block is stored for that actionId. */
260
- unmaterialized: number;
261
- /** Not attempted because `maxBlocks` was reached. */
262
- capped: number;
263
- /** Skipped: a single block whose wire size alone exceeds {@link MAX_BLOCK_MESSAGE_BYTES}. */
264
- oversized: string[];
265
- /** True when the `authorizePeer` gate refused (or threw) — nothing was pushed, peer not memoized. */
266
- denied: boolean;
267
- }
268
-
269
- function emptyResult(): PeerJoinBackfillResult {
270
- return { offered: 0, accepted: 0, rejected: [], uncommitted: 0, unmaterialized: 0, capped: 0, oversized: [], denied: false };
271
- }
272
-
273
- /** One in-flight push message being accumulated. */
274
- interface Chunk {
275
- ids: string[];
276
- buffers: Uint8Array[];
277
- meta: Record<string, { rev: number; actionId: ActionId }>;
278
- /**
279
- * The cohort commit proof retained for each block's pushed revision, where one exists.
280
- *
281
- * A receiver running the default `requirePushCertificate: true` REJECTS a block pushed
282
- * without one, so this is what makes peer-join catch-up land at all — a push carrying only
283
- * `meta` is the legacy shape and is refused. Sparse deliberately: a block whose proof was
284
- * never retained is still offered with its meta, which is the only thing that lets a
285
- * receiver migrating with the flag off land the replica at this node's revision rather than
286
- * a fabricated rev 1. Upstream's rule is the other direction and holds here by construction:
287
- * a proof is never attached WITHOUT its meta, because both are written from the same
288
- * `latest` in one place.
289
- */
290
- proofs: Record<string, BlockCommitProof>;
291
- bytes: number;
292
- }
293
-
294
- /**
295
- * Base64 wire size of a raw buffer — `pushBlocks` base64-encodes each block into the JSON
296
- * request, so the protocol cap must be judged against the encoded size, not the raw bytes.
297
- */
298
- function base64WireBytes(rawBytes: number): number {
299
- return Math.ceil(rawBytes / 3) * 4;
300
- }
301
-
302
- /**
303
- * Copies every block in one network's own raw store to each peer its libp2p node connects
304
- * to, so a peer that joined the network after blocks were committed still ends up holding
305
- * them physically (the receiver persists each push via `saveReplicatedBlock`, which is
306
- * monotonic and idempotent — crossing pushes from both ends cannot regress a revision).
307
- *
308
- * Best-effort throughout: nothing here throws into a libp2p event handler or into a
309
- * runtime bring-up; a failed chunk is logged and the run continues. A peer is marked
310
- * fully caught up ONLY after a run with no thrown chunk and an empty `missing` list, so
311
- * the next `peer:identify` from a peer whose catch-up failed retries it.
312
- */
313
- export class PeerJoinBackfill {
314
- private readonly config: Required<PeerJoinBackfillConfig>;
315
- private readonly createPushClient: (peerId: PeerId) => PeerJoinBackfillPushClient;
316
- private started = false;
317
- private stopped = false;
318
- /** Peers fully caught up this runtime (never retried until the runtime is rebuilt). */
319
- private readonly done = new Set<string>();
320
- /** Peers with a catch-up currently running (suppresses concurrent duplicates). */
321
- private readonly inFlight = new Set<string>();
322
- /**
323
- * Peers whose (re-)schedule arrived while their OWN run was in flight, replayed once
324
- * that run finishes. Load-bearing for the gated path: the gate's authorization check is
325
- * a control-database read, so the window between it and the run's end is wide enough for
326
- * the very membership commit that would have authorized the peer to land inside it —
327
- * dropping that schedule (rather than deferring it) leaves the denied peer waiting for a
328
- * reconnect, which is exactly what the re-arm exists to avoid.
329
- */
330
- private readonly rearmAfterFlight = new Set<string>();
331
- /** Pending per-peer timers — the debounce, or a backoff re-arm. Cleared on stop. */
332
- private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
333
- /** Consecutive non-clean runs per peer, cleared when one finishes cleanly. */
334
- private readonly failures = new Map<string, number>();
335
- /**
336
- * Epoch ms before which a peer's catch-up must not be re-run, set alongside a backoff timer
337
- * that will run it. Its presence is what makes `peer:identify` churn free: a schedule
338
- * arriving inside the wait is dropped, rather than collapsing the backoff to the debounce.
339
- */
340
- private readonly retryAfter = new Map<string, number>();
341
- /** Peers already reported on `console.warn`; reset when a run finally lands cleanly. */
342
- private readonly warned = new Set<string>();
343
- private readonly onPeerIdentify: (evt: CustomEvent<IdentifyResult>) => void;
344
- private loggedNoListBlockIds = false;
345
-
346
- constructor(private readonly deps: PeerJoinBackfillDeps, config?: PeerJoinBackfillConfig) {
347
- this.config = { ...DEFAULT_PEER_JOIN_BACKFILL, ...config };
348
- this.createPushClient = deps.createPushClient
349
- ?? ((peerId) => new BlockTransferClient(peerId, deps.peerNetwork, deps.protocolPrefix));
350
- this.onPeerIdentify = (evt) => {
351
- const { peerId, protocols } = evt.detail;
352
- if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
353
- this.schedulePeer(peerId);
354
- }
355
- };
356
- }
357
-
358
- /**
359
- * Subscribe to `peer:identify` AND schedule a catch-up for already-connected peers whose
360
- * stored protocols already name this network's block-transfer protocol — a peer that does
361
- * not speak it (a bare circuit relay, a bootstrap node) is never scheduled at all. See
362
- * {@link speaksBlockTransfer} and the module comment.
363
- */
364
- start(): void {
365
- if (this.started || this.stopped || !this.config.enabled) return;
366
- this.started = true;
367
- this.deps.libp2p.addEventListener('peer:identify', this.onPeerIdentify);
368
- // A runtime rebuilt over live connections (resumeStrand) never sees their peer:identify —
369
- // it already fired before this instance existed, but its result is persisted in the peer
370
- // store — so walk what is already connected once.
371
- void this.scheduleConnectedPeers().then((scheduled) => {
372
- log('[%s] started (%d peer(s) already connected)', this.deps.label, scheduled);
373
- });
374
- }
375
-
376
- /** Unsubscribe, clear timers; in-flight runs observe the stopped flag and bail. */
377
- stop(): void {
378
- if (this.stopped) return;
379
- this.stopped = true;
380
- if (this.started) {
381
- this.deps.libp2p.removeEventListener('peer:identify', this.onPeerIdentify);
382
- }
383
- for (const timer of this.timers.values()) {
384
- clearTimeout(timer);
385
- }
386
- this.timers.clear();
387
- this.rearmAfterFlight.clear();
388
- this.retryAfter.clear();
389
- log('[%s] stopped', this.deps.label);
390
- }
391
-
392
- /**
393
- * (Re-)schedule a debounced catch-up for every currently-connected peer whose protocols, as
394
- * already stored in the libp2p peer store, name this network's block-transfer protocol. A
395
- * peer not yet in the peer store — its identify has not finished — is left to the
396
- * `peer:identify` handler rather than dialed blind; one whose stored protocols are known
397
- * and lack ours is skipped outright. Idempotent and cheap otherwise (caught-up peers are
398
- * skipped before any timer is set, and a peer whose run is in flight is deferred to the end
399
- * of that run rather than dropped). Driven by {@link start}, and — on a gated network — by
400
- * the embedder whenever membership changes, so a peer whose first pass was denied (connected
401
- * before it was authorized: the production join order) is retried without waiting for a
402
- * reconnect. Returns how many distinct peers were considered (for the start() log) — a peer
403
- * holding several connections is one peer, and is scheduled once.
404
- */
405
- async scheduleConnectedPeers(): Promise<number> {
406
- if (this.stopped) return 0;
407
- const peers = new Map<string, PeerId>();
408
- for (const connection of this.deps.libp2p.getConnections()) {
409
- peers.set(connection.remotePeer.toString(), connection.remotePeer);
410
- }
411
- await Promise.all([...peers.values()].map((peerId) => this.scheduleIfKnownToSpeak(peerId)));
412
- return peers.size;
413
- }
414
-
415
- /** Schedules `peerId` only if the peer store already knows it speaks this network's protocol. */
416
- private async scheduleIfKnownToSpeak(peerId: PeerId): Promise<void> {
417
- let protocols: string[];
418
- try {
419
- ({ protocols } = await this.deps.libp2p.peerStore.get(peerId));
420
- } catch (error) {
421
- // NotFoundError: identify has not finished. Leave it to the `peer:identify` handler
422
- // rather than dialing blind. Anything else is unexpected — log it and skip the peer.
423
- if ((error as Error).name !== 'NotFoundError') {
424
- log('[%s] peer store read for %s failed — not scheduling: %o', this.deps.label, peerId.toString(), error);
425
- }
426
- return;
427
- }
428
- if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
429
- this.schedulePeer(peerId);
430
- }
431
- }
432
-
433
- /** Debounced entry point for connection churn: one run per peer per settle window. */
434
- private schedulePeer(peerId: PeerId): void {
435
- const key = peerId.toString();
436
- if (this.stopped || this.done.has(key)) return;
437
- if (this.inFlight.has(key)) {
438
- // Defer rather than drop: the running pass may already be past its gate check (or
439
- // past the block this schedule was meant to carry), so replay it when that pass ends.
440
- this.rearmAfterFlight.add(key);
441
- return;
442
- }
443
- // A peer whose last run failed is already re-armed on a backoff timer that will run it, so
444
- // DROP this schedule instead of shortening the wait — otherwise a peer that cannot be
445
- // reached is re-dialled on every peer:identify forever (see the module comment's retry
446
- // paragraph). A denied run never gets here: it does not set a backoff.
447
- const retryAt = this.retryAfter.get(key);
448
- if (retryAt !== undefined && Date.now() < retryAt) return;
449
- const existing = this.timers.get(key);
450
- if (existing) clearTimeout(existing);
451
- this.timers.set(key, setTimeout(() => {
452
- this.timers.delete(key);
453
- void this.catchUpPeer(peerId);
454
- }, this.config.debounceMs));
455
- }
456
-
457
- /**
458
- * Run one peer's catch-up now, bypassing the debounce. Never rejects. Returns an
459
- * all-zero result without pushing when the peer is already caught up, already being
460
- * caught up, or this backfill is stopped.
461
- */
462
- async catchUpPeer(peerId: PeerId): Promise<PeerJoinBackfillResult> {
463
- const key = peerId.toString();
464
- if (this.stopped || this.done.has(key) || this.inFlight.has(key)) {
465
- return emptyResult();
466
- }
467
- this.inFlight.add(key);
468
- try {
469
- const { result, clean, pushFailed } = await this.runCatchUp(peerId);
470
- // NOTE: a run that hit `maxBlocks` is still "clean" and still memoizes the peer, so
471
- // the tail past the ceiling never reaches it. Deliberate: enumeration is not
472
- // resumable, so not memoizing would re-push the same prefix on every reconnect
473
- // without ever advancing. Loud in the log below (capped > 0). If a store can
474
- // realistically exceed maxBlocks, the fix is a resumable cursor, not either policy.
475
- if (clean && !this.stopped) {
476
- this.done.add(key);
477
- this.failures.delete(key);
478
- this.retryAfter.delete(key);
479
- this.warned.delete(key);
480
- } else if (pushFailed && !this.stopped && this.started && this.isConnected(peerId)) {
481
- // `pushFailed`, not `!clean`: a denial, an inert store and a receiver's per-block
482
- // rejection are all verdicts a retry cannot change, and re-arming on them would
483
- // re-push the whole store to that peer forever. See the module comment.
484
- //
485
- // Gated on `started` too: the re-arm exists to REPLACE a peer:identify-driven retry,
486
- // so a caller driving `catchUpPeer` by hand against a backfill that was never started
487
- // owns its own retry policy and must not be left holding a background timer.
488
- this.scheduleRetryWithBackoff(peerId);
489
- }
490
- log('[%s] catch-up peer=%s offered=%d accepted=%d rejected=%d uncommitted=%d unmaterialized=%d capped=%d oversized=%d denied=%s done=%s',
491
- this.deps.label, key, result.offered, result.accepted, result.rejected.length,
492
- result.uncommitted, result.unmaterialized, result.capped, result.oversized.length, result.denied, clean);
493
- return result;
494
- } catch (error) {
495
- // runCatchUp already contains a per-chunk catch; this guards the enumeration and
496
- // metadata reads too — a backfill fault must never surface through a libp2p event.
497
- log('[%s] catch-up peer=%s failed: %o', this.deps.label, key, error);
498
- return emptyResult();
499
- } finally {
500
- this.inFlight.delete(key);
501
- // Replay a schedule that arrived mid-run. `schedulePeer` re-checks `done`, so a run
502
- // that finished clean re-arms nothing; a denied or failed one gets its retry.
503
- if (this.rearmAfterFlight.delete(key)) {
504
- this.schedulePeer(peerId);
505
- }
506
- }
507
- }
508
-
509
- /** Whether this network's libp2p node still holds a connection to that peer. */
510
- private isConnected(peerId: PeerId): boolean {
511
- return this.deps.libp2p.getConnections(peerId).length > 0;
512
- }
513
-
514
- /**
515
- * Re-arm one peer's catch-up after a run whose push failed, on a wait that doubles
516
- * per consecutive failure up to `maxRetryBackoffMs`. Sets {@link retryAfter} alongside the
517
- * timer, which is what makes `peer:identify` churn inside the wait free.
518
- */
519
- private scheduleRetryWithBackoff(peerId: PeerId): void {
520
- const key = peerId.toString();
521
- const failures = (this.failures.get(key) ?? 0) + 1;
522
- this.failures.set(key, failures);
523
- const delayMs = Math.min(
524
- this.config.retryBackoffMs * 2 ** (failures - 1),
525
- this.config.maxRetryBackoffMs
526
- );
527
- this.retryAfter.set(key, Date.now() + delayMs);
528
- const existing = this.timers.get(key);
529
- if (existing) clearTimeout(existing);
530
- this.timers.set(key, setTimeout(() => {
531
- this.timers.delete(key);
532
- this.retryAfter.delete(key);
533
- void this.catchUpPeer(peerId);
534
- }, delayMs));
535
- log('[%s] catch-up peer=%s failed %d time(s) in a row; retrying in %dms',
536
- this.deps.label, key, failures, delayMs);
537
- this.warnPersistentFailure(key, failures);
538
- }
539
-
540
- /**
541
- * Say ONCE per peer, outside the DEBUG log, that its catch-up is not landing. Without this a
542
- * machine on a link too slow for a relayed dial produces no statement that anything is wrong:
543
- * the peer never appears to hold the blocks, and the only trace is a DEBUG line naming a dial
544
- * timeout. Reset when a run finally lands cleanly, so a peer that recovers can report again.
545
- */
546
- private warnPersistentFailure(key: string, failures: number): void {
547
- if (failures < PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES || this.warned.has(key)) return;
548
- this.warned.add(key);
549
- console.warn(
550
- `[cadre:${this.deps.label}] peer-join block catch-up to peer ${key} has failed ${failures} times in a row `
551
- + `(dial budget ${this.config.dialTimeoutMs}ms, response budget ${this.config.responseTimeoutMs}ms). `
552
- + 'That peer may not be holding blocks committed before it joined. If it is reachable only through a relay, '
553
- + 'these budgets and libp2p\'s own connection limits are derived from network.linkRoundTripMs (see link-budget.ts); '
554
- + 'a link slower than that declaration, or a peer that declared a faster one, cannot open a relayed connection at all.'
555
- );
556
- }
557
-
558
- /**
559
- * The actual copy. `clean` = every chunk pushed and the remote persisted every block.
560
- * `pushFailed` = at least one push THREW, which is the only non-clean outcome a retry can
561
- * change; the others are verdicts (denied, inert store, blocks the receiver refused).
562
- */
563
- private async runCatchUp(peerId: PeerId): Promise<{ result: PeerJoinBackfillResult; clean: boolean; pushFailed: boolean }> {
564
- const result = emptyResult();
565
- const { storage } = this.deps;
566
-
567
- // The membership gate, judged at push time (never at schedule time — authorization can
568
- // change during the debounce window in either direction). Fails CLOSED on a throw: a
569
- // gate that cannot answer must not leak the store. A denied run is not clean, so the
570
- // peer is retried later rather than memoized as caught up.
571
- if (this.deps.authorizePeer) {
572
- let authorized = false;
573
- try {
574
- authorized = await this.deps.authorizePeer(peerId.toString());
575
- } catch (error) {
576
- log('[%s] authorizePeer(%s) threw — treating as denied: %o', this.deps.label, peerId.toString(), error);
577
- }
578
- if (!authorized) {
579
- result.denied = true;
580
- return { result, clean: false, pushFailed: false };
581
- }
582
- }
583
-
584
- if (!storage.listBlockIds) {
585
- if (!this.loggedNoListBlockIds) {
586
- this.loggedNoListBlockIds = true;
587
- log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.label);
588
- }
589
- return { result, clean: false, pushFailed: false };
590
- }
591
-
592
- const client = this.createPushClient(peerId);
593
- const encoder = new TextEncoder();
594
- let chunk: Chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
595
- let chunkFailed = false;
596
- let anyChunkDelivered = false;
597
- /**
598
- * A peer that has answered no push at all, and failed one, is not reachable on this
599
- * protocol — abandon rather than spend a dial timeout per remaining chunk. Once ONE
600
- * push has been answered the peer demonstrably speaks it, so a later failure is a
601
- * transient blip and the rest of the store is still worth pushing.
602
- */
603
- const peerUnreachable = (): boolean => chunkFailed && !anyChunkDelivered;
604
-
605
- const flush = async (): Promise<void> => {
606
- if (chunk.ids.length === 0) return;
607
- const { ids, buffers, meta, proofs } = chunk;
608
- chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
609
- try {
610
- // ONE certification value rather than two arguments, so a caller cannot pair a proof
611
- // for one revision with meta for another — both were written from the same `latest`.
612
- const response = await client.pushBlocks(ids, buffers, 'replication',
613
- { blockMeta: meta, blockProofs: proofs }, {
614
- dialTimeoutMs: this.config.dialTimeoutMs,
615
- responseTimeoutMs: this.config.responseTimeoutMs
616
- });
617
- anyChunkDelivered = true;
618
- const missing = new Set(response.missing);
619
- for (const id of ids) {
620
- if (missing.has(id)) {
621
- result.rejected.push(id);
622
- } else {
623
- result.accepted += 1;
624
- }
625
- }
626
- if (response.missing.length > 0) {
627
- log('[%s] peer=%s rejected %d block(s): %o', this.deps.label, peerId.toString(), response.missing.length, response.missing);
628
- }
629
- } catch (error) {
630
- chunkFailed = true;
631
- log('[%s] push to peer=%s failed for %d block(s): %s', this.deps.label, peerId.toString(), ids.length, (error as Error).message);
632
- }
633
- };
634
-
635
- for await (const blockId of storage.listBlockIds()) {
636
- if (this.stopped) break;
637
- if (result.offered >= this.config.maxBlocks) {
638
- // Past the ceiling: count what is left (id enumeration only — no more reads or
639
- // pushes) so the cap is loud in the end-of-run log rather than silent.
640
- result.capped += 1;
641
- continue;
642
- }
643
-
644
- const metadata = await storage.getMetadata(blockId);
645
- const latest = metadata?.latest;
646
- if (!latest) {
647
- result.uncommitted += 1;
648
- continue;
649
- }
650
- // NOTE: a block whose latest revision is a DELETE materializes to nothing (a
651
- // tombstone), so it is skipped here — a peer that joins after such a delete never
652
- // receives the tombstone from this path and relies on read repair for it. Fine
653
- // while nothing deletes whole blocks pre-join; if the whole-store coverage gate in
654
- // strand-membership-closed-strand-e2e ever reports a tombstone residue, teach this
655
- // to push the promoted delete transform instead of skipping.
656
- const block = await storage.getMaterializedBlock(blockId, latest.actionId);
657
- if (!block) {
658
- result.unmaterialized += 1;
659
- log('[%s] block=%s has latest rev %d but no materialized content; skipped', this.deps.label, blockId, latest.rev);
660
- continue;
661
- }
662
-
663
- const buffer = encoder.encode(JSON.stringify(block));
664
- // NOTE: MAX_BLOCK_MESSAGE_BYTES caps the whole framed request, not one block, and
665
- // this test ignores the request envelope (ids array, blockMeta, JSON punctuation).
666
- // A lone block within a few KiB of the cap therefore still ships and is rejected by
667
- // the receiver's length-prefix decoder — a permanent chunk failure for that peer. No
668
- // block comes close today; if one ever can, subtract a measured envelope allowance
669
- // here rather than raising the cap.
670
- if (base64WireBytes(buffer.length) >= MAX_BLOCK_MESSAGE_BYTES) {
671
- result.oversized.push(blockId);
672
- log('[%s] block=%s is %d bytes (%d on the wire) — exceeds the %d-byte protocol cap alone; skipped',
673
- this.deps.label, blockId, buffer.length, base64WireBytes(buffer.length), MAX_BLOCK_MESSAGE_BYTES);
674
- continue;
675
- }
676
-
677
- // Flush before adding when this block would overflow either budget. A single block
678
- // larger than maxChunkBytes still ships — alone, in its own chunk.
679
- if (chunk.ids.length > 0
680
- && (chunk.ids.length + 1 > this.config.maxChunkBlocks || chunk.bytes + buffer.length > this.config.maxChunkBytes)) {
681
- await flush();
682
- if (this.stopped || peerUnreachable()) break;
683
- }
684
- chunk.ids.push(blockId);
685
- chunk.buffers.push(buffer);
686
- chunk.meta[blockId] = { rev: latest.rev, actionId: latest.actionId };
687
- // Read the proof for EXACTLY the revision being pushed, from the same `latest` the meta
688
- // above was written from. Absent is normal (nothing retained a proof for that revision);
689
- // the block still ships with its meta and the receiver decides.
690
- const proof = await storage.getBlockProof(blockId, latest.rev);
691
- if (proof) {
692
- chunk.proofs[blockId] = proof;
693
- }
694
- chunk.bytes += buffer.length;
695
- result.offered += 1;
696
- }
697
-
698
- if (!this.stopped && !peerUnreachable()) {
699
- await flush();
700
- }
701
-
702
- if (result.capped > 0) {
703
- log('[%s] peer=%s catch-up CAPPED at %d blocks; %d block id(s) not attempted',
704
- this.deps.label, peerId.toString(), this.config.maxBlocks, result.capped);
705
- }
706
-
707
- const clean = !chunkFailed && result.rejected.length === 0;
708
- return { result, clean, pushFailed: chunkFailed };
709
- }
710
- }
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
+ // Membership — the one place the two networks differ, expressed as the optional
38
+ // `authorizePeer` dep:
39
+ //
40
+ // - STRAND networks pass none. Anything that speaks the strand's own block-transfer protocol
41
+ // already receives cohort replicas of new commits, so pushing older blocks to it exposes
42
+ // nothing new; adding a gate would diverge from what ordinary replication already does
43
+ // there.
44
+ // - The CONTROL network MUST pass one, because that argument does not carry over: its
45
+ // inbound connection gate deliberately admits non-members in several states (an
46
+ // un-enrolled node taking its seed, an open enrollment window, an outstanding
47
+ // invitation, configured bootstrap/relay peers — see docs/architecture.md, the
48
+ // control-network inbound connection gate). Pushing the whole control store to such a
49
+ // peer would hand a stranger the party's entire membership, addresses and strand list.
50
+ // `CadreNode` passes `isAuthorizedMember`; the gate is consulted at PUSH time, not at
51
+ // schedule time, and fails closed on a thrown check. A denied run is not memoized, so
52
+ // the peer is retried on its next `peer:identify` (a reconnect re-runs identify) — or
53
+ // sooner, via `scheduleConnectedPeers()` on a membership change (the production join order is
54
+ // connect-then-authorize, so the denial at dial time is the expected first pass).
55
+ //
56
+ // Both per-push deadlines are DERIVED from the declared link round trip
57
+ // (`link-budget.ts`), not fixed milliseconds. That is not tuning — it is what makes this
58
+ // module work at all over a relay. Opening a relayed connection costs a fixed number of
59
+ // exchanges, so the 3000 ms this catch-up used to allow its dial could never finish one
60
+ // above 375 ms of one-way link delay: the catch-up existed so that a machine which joined
61
+ // after blocks were committed physically ends up holding them, and through a relay on any
62
+ // link slow enough to matter it had never once managed to. The reproduction is
63
+ // `packages/integration-tests/src/scenarios/relayed-dial-cost-by-latency.integration.ts`.
64
+ //
65
+ // It does NOT work at every speed. Above the declared link, libp2p's own dial and
66
+ // inbound-upgrade limits — which Optimystic derives from the same declaration — abandon the
67
+ // connection before any deadline here is consulted, and the listener's one makes that failure
68
+ // look like an absent peer rather than a timeout. That is also what happens when the machine
69
+ // being caught up declared a FASTER link than this one, since its limit is the listener's. See
70
+ // `link-budget.ts` ("Optimystic's deadlines, from the same declaration", "What still fails at
71
+ // the supported link").
72
+ //
73
+ // RETRY, and why it backs off. A run whose PUSH FAILED — the transport threw, which is what
74
+ // a dial or response deadline expiring looks like here — re-arms on a doubling backoff
75
+ // (`retryBackoffMs` to `maxRetryBackoffMs`), and a `peer:identify` arriving while that wait
76
+ // is outstanding is DROPPED rather than collapsing it back to the debounce. Both halves are
77
+ // load-bearing:
78
+ //
79
+ // - Without the re-arm, a transient push failure over a stable connection left the peer
80
+ // partially copied until its next reconnect (read repair still covered reads meanwhile).
81
+ // - Without dropping churn inside the wait, a peer that cannot be reached at all is
82
+ // re-dialled on every `peer:identify` forever. That is not hypothetical: the 2026-09-26
83
+ // relayed reproduction shows one peer re-opening a connection about every 14.5 s for a
84
+ // 200-second run, each event starting a catch-up whose dial could not possibly finish.
85
+ // The connection kept re-appearing because Optimystic's own block-transfer push path
86
+ // budgets its dial at `transferTimeoutMs ?? 30000` — the one dial budget in the stack
87
+ // above the measured relayed setup cost — so it succeeded where this one could not.
88
+ //
89
+ // A NON-CLEAN run is NOT on its own enough to re-arm, and the distinction is what keeps the
90
+ // backoff from becoming a worse problem than the one it fixes. `clean` also goes false for
91
+ // outcomes no amount of retrying can change: the membership gate DENIED the peer; this
92
+ // network's raw storage implements no `listBlockIds`, so the catch-up is inert; or the
93
+ // receiver reported blocks in `missing`, which it does per block for a payload it cannot
94
+ // parse and for a revision whose retained commit proof this node does not hold (a push
95
+ // carrying no proof is refused outright by a receiver running the default
96
+ // `requirePushCertificate: true`, and an unretained proof is the ordinary case — see
97
+ // {@link Chunk.proofs}). Re-arming on those would re-push the WHOLE store to that peer every
98
+ // `maxRetryBackoffMs` for as long as the node runs, and report the failure below as a link
99
+ // budget problem when nothing about the link is wrong. All three still leave the peer
100
+ // un-memoized, so its next `peer:identify` retries — the behaviour that predates the
101
+ // backoff, and the right one for a verdict rather than a timeout. Denial in particular is
102
+ // re-driven on purpose by `scheduleConnectedPeers()` the moment the membership commit lands,
103
+ // because the control network's join order is connect-then-authorize.
104
+ //
105
+ // A re-arm is also skipped when the peer is no longer CONNECTED. This module's trigger is
106
+ // `peer:identify`, so a peer that went away already has one: re-arming instead would leave
107
+ // a machine dialing a peer it cannot see once a minute for the rest of its uptime.
108
+ //
109
+ // After `PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES` consecutive failures one `console.warn`
110
+ // names the peer and the budget, because otherwise a machine on a too-slow link says
111
+ // nothing at all: the connection simply never appears and only a DEBUG log mentions a dial
112
+ // timeout.
113
+ //
114
+ // NOTE: the protocol check happens once — either when a connection's `peer:identify` fires,
115
+ // or, for a peer already connected when this instance starts, when `scheduleConnectedPeers()`
116
+ // reads its protocols back from the peer store — and is never repeated once a peer is
117
+ // scheduled. A peer that stops speaking the protocol after being scheduled (should that ever
118
+ // happen) is not de-scheduled; `runCatchUp`'s own unreachable-peer bail is what would catch
119
+ // that case instead. `peer:identify` also fires on every identify-push from a connected peer
120
+ // (address or protocol changes), which only re-enters the debounce — cheap, and dropped
121
+ // outright for caught-up peers and peers inside a backoff wait.
122
+ //
123
+ // NOTE: a same-network peer whose identify never completes on a connection (the identify
124
+ // stream times out over a slow relayed link, say) is not caught up until a later identify
125
+ // succeeds — a reconnect, an identify-push, or on the control network a membership-change
126
+ // re-drive. Accepted: every db-p2p node runs identify, and read repair still covers reads
127
+ // meanwhile; if relayed links ever routinely outlast identify's timeout, raise that timeout
128
+ // in the node builder rather than scheduling unidentified peers here.
129
+ //
130
+ // NOTE: a peer that disconnects INSIDE a backoff wait still costs the one attempt that wait
131
+ // was already armed for — the connectivity check is made when the re-arm is decided, not when
132
+ // the timer fires, and this module subscribes to `peer:identify` only. One dial, not a
133
+ // recurring one; if a node ever holds many transient peers, subscribe to `connection:close`
134
+ // and clear the pending timer there.
135
+
136
+ const log = debug('sereus:cadre:peer-join-backfill');
137
+
138
+ /**
139
+ * The block-transfer protocol's hard cap on one length-prefixed message. Mirrors
140
+ * `MAX_BLOCK_MESSAGE_BYTES` in `@optimystic/db-p2p`'s `protocol-limits.ts` (8 MiB), which
141
+ * that package does not re-export from its index — keep the two in sync if upstream ever
142
+ * changes it or starts exporting it.
143
+ */
144
+ export const MAX_BLOCK_MESSAGE_BYTES = 8 * 1024 * 1024;
145
+
146
+ /**
147
+ * Whether an identified peer's protocol list names this network's own block-transfer
148
+ * protocol — the one gate that decides whether {@link PeerJoinBackfill} schedules a peer at
149
+ * all. A peer that lacks it (a bare circuit relay, a bootstrap node, a stranger the control
150
+ * network's inbound gate admitted without membership) cannot receive a push no matter how
151
+ * long it is dialed, since the protocol id is namespaced per network.
152
+ */
153
+ function speaksBlockTransfer(protocols: readonly string[], protocolPrefix: string): boolean {
154
+ return protocols.includes(buildBlockTransferProtocol(protocolPrefix));
155
+ }
156
+
157
+ /**
158
+ * Consecutive failed catch-up runs against ONE peer before the module says so on
159
+ * `console.warn` rather than only in its DEBUG log. At the default backoff that is reached
160
+ * about 35 seconds in (5 s + 10 s + 20 s), which is late enough to have ruled out a blip and
161
+ * early enough to be the first thing an operator sees about a machine that is not catching up.
162
+ */
163
+ export const PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES = 3;
164
+
165
+ /** Tuning for the per-peer catch-up. Every field optional; defaults in {@link DEFAULT_PEER_JOIN_BACKFILL}. */
166
+ export interface PeerJoinBackfillConfig {
167
+ /** Default true. False disables the catch-up entirely (the pre-existing behaviour). */
168
+ enabled?: boolean;
169
+ /** Settle time after a connection opens before catching that peer up, ms. Default 1000. */
170
+ debounceMs?: number;
171
+ /** Ceiling on blocks copied in one catch-up. Default 10_000. Reaching it is LOGGED, never silent. */
172
+ maxBlocks?: number;
173
+ /** Soft byte budget per push message. Default 1 MiB. Protocol hard cap is {@link MAX_BLOCK_MESSAGE_BYTES} (8 MiB). */
174
+ maxChunkBytes?: number;
175
+ /** Max blocks per push message. Default 64. */
176
+ maxChunkBlocks?: number;
177
+ /**
178
+ * Per-push dial deadline, ms. Default {@link peerJoinPushBudget}'s `dialTimeoutMs` — five link
179
+ * round trips at the declared link plus two admission decisions (a party-run relay's and the
180
+ * called machine's), 21 500 ms as shipped. NOT a fixed number: a relayed dial
181
+ * costs a fixed number of exchanges, so a host on a slower link moves this (and every other
182
+ * cadre dial budget) by declaring `NetworkConfig.linkRoundTripMs`. Naming it here still wins
183
+ * over the derived value — `link-budget.ts` has the counts and the measurement.
184
+ */
185
+ dialTimeoutMs?: number;
186
+ /**
187
+ * Per-push response deadline, ms. Default {@link peerJoinPushBudget}'s `responseTimeoutMs` —
188
+ * two link round trips at the declared link plus a transfer allowance for the chunk's own
189
+ * bytes, 13 000 ms as shipped. Derived differently from {@link dialTimeoutMs} because it
190
+ * bounds a data transfer over a connection that is already open, not a dial.
191
+ */
192
+ responseTimeoutMs?: number;
193
+ /**
194
+ * First wait before re-running a catch-up whose last run did not complete cleanly, ms.
195
+ * Default 5000. Doubles per consecutive failure up to {@link maxRetryBackoffMs}.
196
+ */
197
+ retryBackoffMs?: number;
198
+ /** Ceiling on that doubling wait, ms. Default 60_000. */
199
+ maxRetryBackoffMs?: number;
200
+ }
201
+
202
+ /** The resolved defaults every {@link PeerJoinBackfill} starts from. */
203
+ export const DEFAULT_PEER_JOIN_BACKFILL: Required<PeerJoinBackfillConfig> = {
204
+ enabled: true,
205
+ debounceMs: 1000,
206
+ maxBlocks: 10_000,
207
+ maxChunkBytes: 1024 * 1024,
208
+ maxChunkBlocks: 64,
209
+ // Derived at the DEFAULT declared link, for a `PeerJoinBackfill` built without a host's
210
+ // declaration (this module's own tests, an embedder driving it directly). The two production
211
+ // construction sites pass `peerJoinPushBudget(network?.linkRoundTripMs)` so a host that
212
+ // declares a slower link moves both — see `link-budget.ts`.
213
+ ...peerJoinPushBudget(),
214
+ retryBackoffMs: 5000,
215
+ maxRetryBackoffMs: 60_000
216
+ };
217
+
218
+ /**
219
+ * The one capability the catch-up needs from a transfer client. Structural (rather than
220
+ * the concrete `BlockTransferClient`) so unit tests can capture pushes without dialing
221
+ * libp2p — see {@link PeerJoinBackfillDeps.createPushClient}.
222
+ */
223
+ export type PeerJoinBackfillPushClient = Pick<BlockTransferClient, 'pushBlocks'>;
224
+
225
+ export interface PeerJoinBackfillDeps {
226
+ /** Log tag naming which network this catch-up serves (a strand id, or `control-<partyId>`). */
227
+ label: string;
228
+ /** The libp2p node of the network being caught up — source of connection events and peer ids. */
229
+ libp2p: Libp2p;
230
+ /** `node.keyNetwork`, the IPeerNetwork BlockTransferClient dials through. */
231
+ peerNetwork: IPeerNetwork;
232
+ /** This network's own raw block store — the same instance handed to the libp2p node. */
233
+ storage: IRawStorage;
234
+ /** Must equal the prefix the receiver registered its handler under: `/optimystic/<networkName>`. */
235
+ protocolPrefix: string;
236
+ /**
237
+ * Membership gate, consulted at PUSH time (fails closed on a throw). Absent = push to
238
+ * every connected peer — correct for strand networks, NEVER for the control network;
239
+ * see the module comment for why the strand no-gate argument does not carry over.
240
+ */
241
+ authorizePeer?: (peerId: string) => Promise<boolean>;
242
+ /**
243
+ * Test seam: build the per-peer push client. Defaults to a real
244
+ * `BlockTransferClient` over {@link peerNetwork} + {@link protocolPrefix}.
245
+ */
246
+ createPushClient?: (peerId: PeerId) => PeerJoinBackfillPushClient;
247
+ }
248
+
249
+ /** What one peer's catch-up actually did. Returned for tests and logged at the end of each run. */
250
+ export interface PeerJoinBackfillResult {
251
+ /** Blocks offered: had a committed `latest` AND materialized content locally. */
252
+ offered: number;
253
+ /** Blocks the remote reported it persisted. */
254
+ accepted: number;
255
+ /** Block ids the remote reported in `missing` (parse or persist failure on its side). */
256
+ rejected: string[];
257
+ /** Skipped: metadata has no `latest` (pending-only — not yet a durability claim here). */
258
+ uncommitted: number;
259
+ /** Skipped: `latest` exists but no materialized block is stored for that actionId. */
260
+ unmaterialized: number;
261
+ /** Not attempted because `maxBlocks` was reached. */
262
+ capped: number;
263
+ /** Skipped: a single block whose wire size alone exceeds {@link MAX_BLOCK_MESSAGE_BYTES}. */
264
+ oversized: string[];
265
+ /** True when the `authorizePeer` gate refused (or threw) — nothing was pushed, peer not memoized. */
266
+ denied: boolean;
267
+ }
268
+
269
+ function emptyResult(): PeerJoinBackfillResult {
270
+ return { offered: 0, accepted: 0, rejected: [], uncommitted: 0, unmaterialized: 0, capped: 0, oversized: [], denied: false };
271
+ }
272
+
273
+ /** One in-flight push message being accumulated. */
274
+ interface Chunk {
275
+ ids: string[];
276
+ buffers: Uint8Array[];
277
+ meta: Record<string, { rev: number; actionId: ActionId }>;
278
+ /**
279
+ * The cohort commit proof retained for each block's pushed revision, where one exists.
280
+ *
281
+ * A receiver running the default `requirePushCertificate: true` REJECTS a block pushed
282
+ * without one, so this is what makes peer-join catch-up land at all — a push carrying only
283
+ * `meta` is the legacy shape and is refused. Sparse deliberately: a block whose proof was
284
+ * never retained is still offered with its meta, which is the only thing that lets a
285
+ * receiver migrating with the flag off land the replica at this node's revision rather than
286
+ * a fabricated rev 1. Upstream's rule is the other direction and holds here by construction:
287
+ * a proof is never attached WITHOUT its meta, because both are written from the same
288
+ * `latest` in one place.
289
+ */
290
+ proofs: Record<string, BlockCommitProof>;
291
+ bytes: number;
292
+ }
293
+
294
+ /**
295
+ * Base64 wire size of a raw buffer — `pushBlocks` base64-encodes each block into the JSON
296
+ * request, so the protocol cap must be judged against the encoded size, not the raw bytes.
297
+ */
298
+ function base64WireBytes(rawBytes: number): number {
299
+ return Math.ceil(rawBytes / 3) * 4;
300
+ }
301
+
302
+ /**
303
+ * Copies every block in one network's own raw store to each peer its libp2p node connects
304
+ * to, so a peer that joined the network after blocks were committed still ends up holding
305
+ * them physically (the receiver persists each push via `saveReplicatedBlock`, which is
306
+ * monotonic and idempotent — crossing pushes from both ends cannot regress a revision).
307
+ *
308
+ * Best-effort throughout: nothing here throws into a libp2p event handler or into a
309
+ * runtime bring-up; a failed chunk is logged and the run continues. A peer is marked
310
+ * fully caught up ONLY after a run with no thrown chunk and an empty `missing` list, so
311
+ * the next `peer:identify` from a peer whose catch-up failed retries it.
312
+ */
313
+ export class PeerJoinBackfill {
314
+ private readonly config: Required<PeerJoinBackfillConfig>;
315
+ private readonly createPushClient: (peerId: PeerId) => PeerJoinBackfillPushClient;
316
+ private started = false;
317
+ private stopped = false;
318
+ /** Peers fully caught up this runtime (never retried until the runtime is rebuilt). */
319
+ private readonly done = new Set<string>();
320
+ /** Peers with a catch-up currently running (suppresses concurrent duplicates). */
321
+ private readonly inFlight = new Set<string>();
322
+ /**
323
+ * Peers whose (re-)schedule arrived while their OWN run was in flight, replayed once
324
+ * that run finishes. Load-bearing for the gated path: the gate's authorization check is
325
+ * a control-database read, so the window between it and the run's end is wide enough for
326
+ * the very membership commit that would have authorized the peer to land inside it —
327
+ * dropping that schedule (rather than deferring it) leaves the denied peer waiting for a
328
+ * reconnect, which is exactly what the re-arm exists to avoid.
329
+ */
330
+ private readonly rearmAfterFlight = new Set<string>();
331
+ /** Pending per-peer timers — the debounce, or a backoff re-arm. Cleared on stop. */
332
+ private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
333
+ /** Consecutive non-clean runs per peer, cleared when one finishes cleanly. */
334
+ private readonly failures = new Map<string, number>();
335
+ /**
336
+ * Epoch ms before which a peer's catch-up must not be re-run, set alongside a backoff timer
337
+ * that will run it. Its presence is what makes `peer:identify` churn free: a schedule
338
+ * arriving inside the wait is dropped, rather than collapsing the backoff to the debounce.
339
+ */
340
+ private readonly retryAfter = new Map<string, number>();
341
+ /** Peers already reported on `console.warn`; reset when a run finally lands cleanly. */
342
+ private readonly warned = new Set<string>();
343
+ private readonly onPeerIdentify: (evt: CustomEvent<IdentifyResult>) => void;
344
+ private loggedNoListBlockIds = false;
345
+
346
+ constructor(private readonly deps: PeerJoinBackfillDeps, config?: PeerJoinBackfillConfig) {
347
+ this.config = { ...DEFAULT_PEER_JOIN_BACKFILL, ...config };
348
+ this.createPushClient = deps.createPushClient
349
+ ?? ((peerId) => new BlockTransferClient(peerId, deps.peerNetwork, deps.protocolPrefix));
350
+ this.onPeerIdentify = (evt) => {
351
+ const { peerId, protocols } = evt.detail;
352
+ if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
353
+ this.schedulePeer(peerId);
354
+ }
355
+ };
356
+ }
357
+
358
+ /**
359
+ * Subscribe to `peer:identify` AND schedule a catch-up for already-connected peers whose
360
+ * stored protocols already name this network's block-transfer protocol — a peer that does
361
+ * not speak it (a bare circuit relay, a bootstrap node) is never scheduled at all. See
362
+ * {@link speaksBlockTransfer} and the module comment.
363
+ */
364
+ start(): void {
365
+ if (this.started || this.stopped || !this.config.enabled) return;
366
+ this.started = true;
367
+ this.deps.libp2p.addEventListener('peer:identify', this.onPeerIdentify);
368
+ // A runtime rebuilt over live connections (resumeStrand) never sees their peer:identify —
369
+ // it already fired before this instance existed, but its result is persisted in the peer
370
+ // store — so walk what is already connected once.
371
+ void this.scheduleConnectedPeers().then((scheduled) => {
372
+ log('[%s] started (%d peer(s) already connected)', this.deps.label, scheduled);
373
+ });
374
+ }
375
+
376
+ /** Unsubscribe, clear timers; in-flight runs observe the stopped flag and bail. */
377
+ stop(): void {
378
+ if (this.stopped) return;
379
+ this.stopped = true;
380
+ if (this.started) {
381
+ this.deps.libp2p.removeEventListener('peer:identify', this.onPeerIdentify);
382
+ }
383
+ for (const timer of this.timers.values()) {
384
+ clearTimeout(timer);
385
+ }
386
+ this.timers.clear();
387
+ this.rearmAfterFlight.clear();
388
+ this.retryAfter.clear();
389
+ log('[%s] stopped', this.deps.label);
390
+ }
391
+
392
+ /**
393
+ * (Re-)schedule a debounced catch-up for every currently-connected peer whose protocols, as
394
+ * already stored in the libp2p peer store, name this network's block-transfer protocol. A
395
+ * peer not yet in the peer store — its identify has not finished — is left to the
396
+ * `peer:identify` handler rather than dialed blind; one whose stored protocols are known
397
+ * and lack ours is skipped outright. Idempotent and cheap otherwise (caught-up peers are
398
+ * skipped before any timer is set, and a peer whose run is in flight is deferred to the end
399
+ * of that run rather than dropped). Driven by {@link start}, and — on a gated network — by
400
+ * the embedder whenever membership changes, so a peer whose first pass was denied (connected
401
+ * before it was authorized: the production join order) is retried without waiting for a
402
+ * reconnect. Returns how many distinct peers were considered (for the start() log) — a peer
403
+ * holding several connections is one peer, and is scheduled once.
404
+ */
405
+ async scheduleConnectedPeers(): Promise<number> {
406
+ if (this.stopped) return 0;
407
+ const peers = new Map<string, PeerId>();
408
+ for (const connection of this.deps.libp2p.getConnections()) {
409
+ peers.set(connection.remotePeer.toString(), connection.remotePeer);
410
+ }
411
+ await Promise.all([...peers.values()].map((peerId) => this.scheduleIfKnownToSpeak(peerId)));
412
+ return peers.size;
413
+ }
414
+
415
+ /** Schedules `peerId` only if the peer store already knows it speaks this network's protocol. */
416
+ private async scheduleIfKnownToSpeak(peerId: PeerId): Promise<void> {
417
+ let protocols: string[];
418
+ try {
419
+ ({ protocols } = await this.deps.libp2p.peerStore.get(peerId));
420
+ } catch (error) {
421
+ // NotFoundError: identify has not finished. Leave it to the `peer:identify` handler
422
+ // rather than dialing blind. Anything else is unexpected — log it and skip the peer.
423
+ if ((error as Error).name !== 'NotFoundError') {
424
+ log('[%s] peer store read for %s failed — not scheduling: %o', this.deps.label, peerId.toString(), error);
425
+ }
426
+ return;
427
+ }
428
+ if (speaksBlockTransfer(protocols, this.deps.protocolPrefix)) {
429
+ this.schedulePeer(peerId);
430
+ }
431
+ }
432
+
433
+ /** Debounced entry point for connection churn: one run per peer per settle window. */
434
+ private schedulePeer(peerId: PeerId): void {
435
+ const key = peerId.toString();
436
+ if (this.stopped || this.done.has(key)) return;
437
+ if (this.inFlight.has(key)) {
438
+ // Defer rather than drop: the running pass may already be past its gate check (or
439
+ // past the block this schedule was meant to carry), so replay it when that pass ends.
440
+ this.rearmAfterFlight.add(key);
441
+ return;
442
+ }
443
+ // A peer whose last run failed is already re-armed on a backoff timer that will run it, so
444
+ // DROP this schedule instead of shortening the wait — otherwise a peer that cannot be
445
+ // reached is re-dialled on every peer:identify forever (see the module comment's retry
446
+ // paragraph). A denied run never gets here: it does not set a backoff.
447
+ const retryAt = this.retryAfter.get(key);
448
+ if (retryAt !== undefined && Date.now() < retryAt) return;
449
+ const existing = this.timers.get(key);
450
+ if (existing) clearTimeout(existing);
451
+ this.timers.set(key, setTimeout(() => {
452
+ this.timers.delete(key);
453
+ void this.catchUpPeer(peerId);
454
+ }, this.config.debounceMs));
455
+ }
456
+
457
+ /**
458
+ * Run one peer's catch-up now, bypassing the debounce. Never rejects. Returns an
459
+ * all-zero result without pushing when the peer is already caught up, already being
460
+ * caught up, or this backfill is stopped.
461
+ */
462
+ async catchUpPeer(peerId: PeerId): Promise<PeerJoinBackfillResult> {
463
+ const key = peerId.toString();
464
+ if (this.stopped || this.done.has(key) || this.inFlight.has(key)) {
465
+ return emptyResult();
466
+ }
467
+ this.inFlight.add(key);
468
+ try {
469
+ const { result, clean, pushFailed } = await this.runCatchUp(peerId);
470
+ // NOTE: a run that hit `maxBlocks` is still "clean" and still memoizes the peer, so
471
+ // the tail past the ceiling never reaches it. Deliberate: enumeration is not
472
+ // resumable, so not memoizing would re-push the same prefix on every reconnect
473
+ // without ever advancing. Loud in the log below (capped > 0). If a store can
474
+ // realistically exceed maxBlocks, the fix is a resumable cursor, not either policy.
475
+ if (clean && !this.stopped) {
476
+ this.done.add(key);
477
+ this.failures.delete(key);
478
+ this.retryAfter.delete(key);
479
+ this.warned.delete(key);
480
+ } else if (pushFailed && !this.stopped && this.started && this.isConnected(peerId)) {
481
+ // `pushFailed`, not `!clean`: a denial, an inert store and a receiver's per-block
482
+ // rejection are all verdicts a retry cannot change, and re-arming on them would
483
+ // re-push the whole store to that peer forever. See the module comment.
484
+ //
485
+ // Gated on `started` too: the re-arm exists to REPLACE a peer:identify-driven retry,
486
+ // so a caller driving `catchUpPeer` by hand against a backfill that was never started
487
+ // owns its own retry policy and must not be left holding a background timer.
488
+ this.scheduleRetryWithBackoff(peerId);
489
+ }
490
+ log('[%s] catch-up peer=%s offered=%d accepted=%d rejected=%d uncommitted=%d unmaterialized=%d capped=%d oversized=%d denied=%s done=%s',
491
+ this.deps.label, key, result.offered, result.accepted, result.rejected.length,
492
+ result.uncommitted, result.unmaterialized, result.capped, result.oversized.length, result.denied, clean);
493
+ return result;
494
+ } catch (error) {
495
+ // runCatchUp already contains a per-chunk catch; this guards the enumeration and
496
+ // metadata reads too — a backfill fault must never surface through a libp2p event.
497
+ log('[%s] catch-up peer=%s failed: %o', this.deps.label, key, error);
498
+ return emptyResult();
499
+ } finally {
500
+ this.inFlight.delete(key);
501
+ // Replay a schedule that arrived mid-run. `schedulePeer` re-checks `done`, so a run
502
+ // that finished clean re-arms nothing; a denied or failed one gets its retry.
503
+ if (this.rearmAfterFlight.delete(key)) {
504
+ this.schedulePeer(peerId);
505
+ }
506
+ }
507
+ }
508
+
509
+ /** Whether this network's libp2p node still holds a connection to that peer. */
510
+ private isConnected(peerId: PeerId): boolean {
511
+ return this.deps.libp2p.getConnections(peerId).length > 0;
512
+ }
513
+
514
+ /**
515
+ * Re-arm one peer's catch-up after a run whose push failed, on a wait that doubles
516
+ * per consecutive failure up to `maxRetryBackoffMs`. Sets {@link retryAfter} alongside the
517
+ * timer, which is what makes `peer:identify` churn inside the wait free.
518
+ */
519
+ private scheduleRetryWithBackoff(peerId: PeerId): void {
520
+ const key = peerId.toString();
521
+ const failures = (this.failures.get(key) ?? 0) + 1;
522
+ this.failures.set(key, failures);
523
+ const delayMs = Math.min(
524
+ this.config.retryBackoffMs * 2 ** (failures - 1),
525
+ this.config.maxRetryBackoffMs
526
+ );
527
+ this.retryAfter.set(key, Date.now() + delayMs);
528
+ const existing = this.timers.get(key);
529
+ if (existing) clearTimeout(existing);
530
+ this.timers.set(key, setTimeout(() => {
531
+ this.timers.delete(key);
532
+ this.retryAfter.delete(key);
533
+ void this.catchUpPeer(peerId);
534
+ }, delayMs));
535
+ log('[%s] catch-up peer=%s failed %d time(s) in a row; retrying in %dms',
536
+ this.deps.label, key, failures, delayMs);
537
+ this.warnPersistentFailure(key, failures);
538
+ }
539
+
540
+ /**
541
+ * Say ONCE per peer, outside the DEBUG log, that its catch-up is not landing. Without this a
542
+ * machine on a link too slow for a relayed dial produces no statement that anything is wrong:
543
+ * the peer never appears to hold the blocks, and the only trace is a DEBUG line naming a dial
544
+ * timeout. Reset when a run finally lands cleanly, so a peer that recovers can report again.
545
+ */
546
+ private warnPersistentFailure(key: string, failures: number): void {
547
+ if (failures < PEER_JOIN_BACKFILL_WARN_AFTER_FAILURES || this.warned.has(key)) return;
548
+ this.warned.add(key);
549
+ console.warn(
550
+ `[cadre:${this.deps.label}] peer-join block catch-up to peer ${key} has failed ${failures} times in a row `
551
+ + `(dial budget ${this.config.dialTimeoutMs}ms, response budget ${this.config.responseTimeoutMs}ms). `
552
+ + 'That peer may not be holding blocks committed before it joined. If it is reachable only through a relay, '
553
+ + 'these budgets and libp2p\'s own connection limits are derived from network.linkRoundTripMs (see link-budget.ts); '
554
+ + 'a link slower than that declaration, or a peer that declared a faster one, cannot open a relayed connection at all.'
555
+ );
556
+ }
557
+
558
+ /**
559
+ * The actual copy. `clean` = every chunk pushed and the remote persisted every block.
560
+ * `pushFailed` = at least one push THREW, which is the only non-clean outcome a retry can
561
+ * change; the others are verdicts (denied, inert store, blocks the receiver refused).
562
+ */
563
+ private async runCatchUp(peerId: PeerId): Promise<{ result: PeerJoinBackfillResult; clean: boolean; pushFailed: boolean }> {
564
+ const result = emptyResult();
565
+ const { storage } = this.deps;
566
+
567
+ // The membership gate, judged at push time (never at schedule time — authorization can
568
+ // change during the debounce window in either direction). Fails CLOSED on a throw: a
569
+ // gate that cannot answer must not leak the store. A denied run is not clean, so the
570
+ // peer is retried later rather than memoized as caught up.
571
+ if (this.deps.authorizePeer) {
572
+ let authorized = false;
573
+ try {
574
+ authorized = await this.deps.authorizePeer(peerId.toString());
575
+ } catch (error) {
576
+ log('[%s] authorizePeer(%s) threw — treating as denied: %o', this.deps.label, peerId.toString(), error);
577
+ }
578
+ if (!authorized) {
579
+ result.denied = true;
580
+ return { result, clean: false, pushFailed: false };
581
+ }
582
+ }
583
+
584
+ if (!storage.listBlockIds) {
585
+ if (!this.loggedNoListBlockIds) {
586
+ this.loggedNoListBlockIds = true;
587
+ log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.label);
588
+ }
589
+ return { result, clean: false, pushFailed: false };
590
+ }
591
+
592
+ const client = this.createPushClient(peerId);
593
+ const encoder = new TextEncoder();
594
+ let chunk: Chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
595
+ let chunkFailed = false;
596
+ let anyChunkDelivered = false;
597
+ /**
598
+ * A peer that has answered no push at all, and failed one, is not reachable on this
599
+ * protocol — abandon rather than spend a dial timeout per remaining chunk. Once ONE
600
+ * push has been answered the peer demonstrably speaks it, so a later failure is a
601
+ * transient blip and the rest of the store is still worth pushing.
602
+ */
603
+ const peerUnreachable = (): boolean => chunkFailed && !anyChunkDelivered;
604
+
605
+ const flush = async (): Promise<void> => {
606
+ if (chunk.ids.length === 0) return;
607
+ const { ids, buffers, meta, proofs } = chunk;
608
+ chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
609
+ try {
610
+ // ONE certification value rather than two arguments, so a caller cannot pair a proof
611
+ // for one revision with meta for another — both were written from the same `latest`.
612
+ const response = await client.pushBlocks(ids, buffers, 'replication',
613
+ { blockMeta: meta, blockProofs: proofs }, {
614
+ dialTimeoutMs: this.config.dialTimeoutMs,
615
+ responseTimeoutMs: this.config.responseTimeoutMs
616
+ });
617
+ anyChunkDelivered = true;
618
+ const missing = new Set(response.missing);
619
+ for (const id of ids) {
620
+ if (missing.has(id)) {
621
+ result.rejected.push(id);
622
+ } else {
623
+ result.accepted += 1;
624
+ }
625
+ }
626
+ if (response.missing.length > 0) {
627
+ log('[%s] peer=%s rejected %d block(s): %o', this.deps.label, peerId.toString(), response.missing.length, response.missing);
628
+ }
629
+ } catch (error) {
630
+ chunkFailed = true;
631
+ log('[%s] push to peer=%s failed for %d block(s): %s', this.deps.label, peerId.toString(), ids.length, (error as Error).message);
632
+ }
633
+ };
634
+
635
+ for await (const blockId of storage.listBlockIds()) {
636
+ if (this.stopped) break;
637
+ if (result.offered >= this.config.maxBlocks) {
638
+ // Past the ceiling: count what is left (id enumeration only — no more reads or
639
+ // pushes) so the cap is loud in the end-of-run log rather than silent.
640
+ result.capped += 1;
641
+ continue;
642
+ }
643
+
644
+ const metadata = await storage.getMetadata(blockId);
645
+ const latest = metadata?.latest;
646
+ if (!latest) {
647
+ result.uncommitted += 1;
648
+ continue;
649
+ }
650
+ // NOTE: a block whose latest revision is a DELETE materializes to nothing (a
651
+ // tombstone), so it is skipped here — a peer that joins after such a delete never
652
+ // receives the tombstone from this path and relies on read repair for it. Fine
653
+ // while nothing deletes whole blocks pre-join; if the whole-store coverage gate in
654
+ // strand-membership-closed-strand-e2e ever reports a tombstone residue, teach this
655
+ // to push the promoted delete transform instead of skipping.
656
+ const block = await storage.getMaterializedBlock(blockId, latest.actionId);
657
+ if (!block) {
658
+ result.unmaterialized += 1;
659
+ log('[%s] block=%s has latest rev %d but no materialized content; skipped', this.deps.label, blockId, latest.rev);
660
+ continue;
661
+ }
662
+
663
+ const buffer = encoder.encode(JSON.stringify(block));
664
+ // NOTE: MAX_BLOCK_MESSAGE_BYTES caps the whole framed request, not one block, and
665
+ // this test ignores the request envelope (ids array, blockMeta, JSON punctuation).
666
+ // A lone block within a few KiB of the cap therefore still ships and is rejected by
667
+ // the receiver's length-prefix decoder — a permanent chunk failure for that peer. No
668
+ // block comes close today; if one ever can, subtract a measured envelope allowance
669
+ // here rather than raising the cap.
670
+ if (base64WireBytes(buffer.length) >= MAX_BLOCK_MESSAGE_BYTES) {
671
+ result.oversized.push(blockId);
672
+ log('[%s] block=%s is %d bytes (%d on the wire) — exceeds the %d-byte protocol cap alone; skipped',
673
+ this.deps.label, blockId, buffer.length, base64WireBytes(buffer.length), MAX_BLOCK_MESSAGE_BYTES);
674
+ continue;
675
+ }
676
+
677
+ // Flush before adding when this block would overflow either budget. A single block
678
+ // larger than maxChunkBytes still ships — alone, in its own chunk.
679
+ if (chunk.ids.length > 0
680
+ && (chunk.ids.length + 1 > this.config.maxChunkBlocks || chunk.bytes + buffer.length > this.config.maxChunkBytes)) {
681
+ await flush();
682
+ if (this.stopped || peerUnreachable()) break;
683
+ }
684
+ chunk.ids.push(blockId);
685
+ chunk.buffers.push(buffer);
686
+ chunk.meta[blockId] = { rev: latest.rev, actionId: latest.actionId };
687
+ // Read the proof for EXACTLY the revision being pushed, from the same `latest` the meta
688
+ // above was written from. Absent is normal (nothing retained a proof for that revision);
689
+ // the block still ships with its meta and the receiver decides.
690
+ const proof = await storage.getBlockProof(blockId, latest.rev);
691
+ if (proof) {
692
+ chunk.proofs[blockId] = proof;
693
+ }
694
+ chunk.bytes += buffer.length;
695
+ result.offered += 1;
696
+ }
697
+
698
+ if (!this.stopped && !peerUnreachable()) {
699
+ await flush();
700
+ }
701
+
702
+ if (result.capped > 0) {
703
+ log('[%s] peer=%s catch-up CAPPED at %d blocks; %d block id(s) not attempted',
704
+ this.deps.label, peerId.toString(), this.config.maxBlocks, result.capped);
705
+ }
706
+
707
+ const clean = !chunkFailed && result.rejected.length === 0;
708
+ return { result, clean, pushFailed: chunkFailed };
709
+ }
710
+ }