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