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