@serfab/cadre-core 1.4.0 → 1.5.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 +77 -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 +182 -0
  17. package/dist/link-budget.js +195 -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 +165 -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 +43 -5
  31. package/dist/strand-first-sync-gate.js +55 -7
  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 +56 -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 +96 -9
  45. package/dist/types.js +14 -4
  46. package/dist/types.js.map +1 -1
  47. package/package.json +8 -8
  48. package/src/cadre-node.ts +7445 -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 +581 -563
  53. package/src/link-budget.ts +217 -0
  54. package/src/peer-dial.ts +39 -17
  55. package/src/peer-join-backfill.ts +192 -23
  56. package/src/relay-reservation.ts +1119 -951
  57. package/src/seed-bootstrap.ts +2 -1
  58. package/src/strand-first-sync-gate.ts +55 -7
  59. package/src/strand-instance-manager.ts +1516 -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 +95 -8
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Dial and reservation budgets derived from ONE declared link round trip, instead of fixed
3
+ * millisecond numbers chosen on a fast local network.
4
+ *
5
+ * Reaching another machine through a relay costs a FIXED NUMBER OF EXCHANGES, not a fixed
6
+ * number of milliseconds. So every budget written as milliseconds has a link speed above which
7
+ * it can never open a connection at all — and the slower the link, the more of them fall over,
8
+ * silently, because an abandoned dial looks the same as a peer that is not there. Counting round
9
+ * trips instead is what stops that class of defect coming back: the next person to widen a
10
+ * budget changes ONE declaration, and the next person to add a dial writes down its round-trip
11
+ * count beside the arithmetic.
12
+ *
13
+ * ── The instrument ──
14
+ *
15
+ * Every count and every number below comes from
16
+ * `packages/integration-tests/src/scenarios/relayed-dial-cost-by-latency.integration.ts`, which
17
+ * is committed and opt-in (`RELAY_DIAL_COST=1`). **Its doc comment is the single home of the
18
+ * measurement**; this module holds only what the derivation needs. Re-run it before changing
19
+ * anything here.
20
+ *
21
+ * ── The unit ──
22
+ *
23
+ * ONE LINK ROUND TRIP is a message from one machine reaching the other and a reply coming
24
+ * back, over the path those two machines actually use — through the relay, when that is the
25
+ * only way they can reach each other. In the instrument, which injects a constant ONE-WAY
26
+ * frame delay `d`, one link round trip is `2d`.
27
+ *
28
+ * A leg between a node and the RELAY is half a link round trip, because it crosses one of the
29
+ * two hops rather than both. That is why the reservation drive's cost reads as "four
30
+ * node-to-relay round trips" in one telling and "two link round trips" in another: same
31
+ * quantity, different unit. This module uses the LINK round trip throughout, so there is one
32
+ * unit to reason in.
33
+ *
34
+ * ── The counts, and what they cost ──
35
+ *
36
+ * | operation | link round trips | at the declared default |
37
+ * | ---------------------------------------------------- | ---------------- | ----------------------- |
38
+ * | open a relayed connection to another machine | 4 | 8 000 ms |
39
+ * | dial the relay itself | 1 | 2 000 ms |
40
+ * | request a reservation on an open relay connection | 1 | 2 000 ms |
41
+ * | negotiate a protocol over an established circuit | 1 | 2 000 ms |
42
+ *
43
+ * **Measured** 2026-09-26, one Windows machine, loopback dedicated relay, re-run for this
44
+ * change: a relayed dial took 20-25 ms at no delay, **7 255-7 279 ms at 900 ms one-way**, and
45
+ * **12 066-12 094 ms at 1 500 ms one-way**. Four link round trips of pure delay would be 7 200
46
+ * and 12 000, so the real cost sits about 60-95 ms ABOVE the arithmetic — the handshakes and a
47
+ * phone's pure-JS crypto, which no delay figure contains. That residue is small but it is why
48
+ * {@link DECLARED_LINK_ROUND_TRIP_MS} carries headroom over the band sereus supports rather
49
+ * than matching it exactly: a declaration equal to the measured round trip would derive a
50
+ * budget marginally BELOW the dial it has to contain.
51
+ *
52
+ * ── The ceiling this does NOT lift ──
53
+ *
54
+ * Above roughly 1 250 ms one-way — a 2.5-second link round trip — no relayed connection can be
55
+ * established by this stack whatever cadre declares here. Two budgets of 10 000 ms each inside
56
+ * libp2p bound the same dial and cannot be reached from sereus at all:
57
+ * `connectionManager.dialTimeout` (libp2p's own default, which `@optimystic/db-p2p`'s
58
+ * `libp2p-node-base.ts` neither sets nor exposes) and `connectionManager.inboundUpgradeTimeout`
59
+ * (which it sets to 10 000). Both appear in the same re-run: at 1 500 ms one-way the dial under
60
+ * libp2p's default failed with `The operation was aborted due to timeout`, and with the shipped
61
+ * inbound-upgrade budget the DIALER's own 12 094 ms dial resolved while the LISTENER had
62
+ * already thrown the half-built connection away — so the first stream over it died with
63
+ * `Unexpected EOF - stream closed while reading 0/1 bytes` and the listener reported no peer at
64
+ * all. That is why a too-slow link produces silence rather than an error.
65
+ *
66
+ * Two consequences for a reader choosing a declaration. Below that ceiling, the DEFAULT
67
+ * declaration of 2 000 ms does not reach it: four round trips of 2 000 ms is 8 000 ms, which
68
+ * covers a one-way delay up to 1 000 ms, so a deployment somewhere between 1 000 and 1 250 ms
69
+ * one-way has to declare its own (about 2 200-2 500) to use the band libp2p still allows. And
70
+ * declaring much ABOVE 2 500 buys nothing: the budgets here grow, and
71
+ * the connection still fails inside libp2p. Lifting that needs an upstream change and a
72
+ * decision about how slow a link sereus intends to carry —
73
+ * `tickets/blocked/how-slow-a-relayed-link-does-sereus-carry`. A reader who raised these
74
+ * numbers and still cannot connect at 1 500 ms one-way has met that ceiling, not this module.
75
+ */
76
+
77
+ /**
78
+ * The link round trip cadre assumes when a host declares none, in milliseconds. A deployment
79
+ * that knows its own link states it with `NetworkConfig.linkRoundTripMs` instead.
80
+ *
81
+ * **Why 2 000.** It states the slowest link sereus already claims to support, and two other
82
+ * budgets fix that claim independently: `COHORT_READ_DEADLINE_MS`
83
+ * (`quereus-plugin-sereus/src/cluster-size.ts`, 5 000 ms) and
84
+ * `DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS` (`strand-first-sync-gate.ts`, 120 000 ms) were both
85
+ * sized against two parties reaching each other only through a public relay at a round trip
86
+ * near 1.8 s. Declaring 2 000 rounds that band up and leaves about 720 ms over the worst
87
+ * relayed dial measured at it (7 279 ms against a derived 8 000 ms).
88
+ *
89
+ * Raising it is how a deployment that KNOWS its link is slower moves every derived budget at
90
+ * once. The cost is the ordinary cost of a longer deadline: a peer that is genuinely gone holds
91
+ * the operation for that much longer before it is abandoned and retried. Above about 2 500 it
92
+ * buys nothing — see the module doc's ceiling paragraph.
93
+ */
94
+ export const DECLARED_LINK_ROUND_TRIP_MS = 2000;
95
+
96
+ /**
97
+ * Link round trips one relayed connection setup costs: transport, encryption and multiplexer
98
+ * handshakes to the relay, the circuit open, then both handshakes again end to end through it.
99
+ * Measured at 8 one-way delays, which is 4 link round trips.
100
+ */
101
+ export const RELAYED_DIAL_ROUND_TRIPS = 4;
102
+
103
+ /**
104
+ * Link round trips one whole reservation drive is budgeted for
105
+ * (`relay-reservation.ts`'s `driveRelayReservation`, whose ONE deadline covers the dial, the
106
+ * reservation request and the wait together).
107
+ *
108
+ * The protocol work measured is 2 — dial the relay (1) plus request the reservation (1). It is
109
+ * budgeted at 4, the relayed-dial count, because the wait afterwards may instead be satisfied
110
+ * by libp2p's own relay discovery, which repeats both legs after identify has run; 4 is
111
+ * therefore the largest thing this one deadline can be asked to contain, and the poll interval
112
+ * (`DEFAULT_RELAY_RESERVE_POLL_MS`) rounds up on top of it.
113
+ */
114
+ export const RELAY_RESERVATION_ROUND_TRIPS = 4;
115
+
116
+ /**
117
+ * Link round trips one request-and-answer over an ALREADY-OPEN circuit costs: the protocol
118
+ * negotiation (1, measured at 2 one-way delays) plus the request and its response (1). It does
119
+ * not include a dial — a caller that may have to open the connection budgets
120
+ * {@link RELAYED_DIAL_ROUND_TRIPS} separately, which is exactly what the two-field shape of
121
+ * Optimystic's `dialTimeoutMs` / `responseTimeoutMs` pair is for.
122
+ */
123
+ export const CIRCUIT_REQUEST_ROUND_TRIPS = 2;
124
+
125
+ /**
126
+ * What a block-transfer push message's BYTES get to cross, on top of the latency
127
+ * {@link CIRCUIT_REQUEST_ROUND_TRIPS} covers, in milliseconds.
128
+ *
129
+ * This part is bandwidth, not latency, so it does not scale with the declared round trip: a
130
+ * chunk is capped at `PeerJoinBackfillConfig.maxChunkBytes` (1 MiB by default) and crossing it
131
+ * costs whatever the link's throughput costs.
132
+ *
133
+ * NOTE: 6 000 ms is not a measurement of any throughput — it is the residue of the 10 000 ms
134
+ * this deadline shipped as before it was split into a latency part and a transfer part, chosen
135
+ * so that at the default declaration the derived value is the same 10 000 and no fast link got
136
+ * slower. Nobody has measured how long 1 MiB takes to cross a relayed mobile link. If pushes
137
+ * ever time out with the transfer only part done, measure that and raise THIS, not the declared
138
+ * round trip.
139
+ */
140
+ export const PUSH_TRANSFER_ALLOWANCE_MS = 6000;
141
+
142
+ /**
143
+ * Resolve a host's declared link round trip, falling back to
144
+ * {@link DECLARED_LINK_ROUND_TRIP_MS}.
145
+ *
146
+ * Validated here rather than downstream because nothing downstream would: every consumer
147
+ * multiplies this value into a `setTimeout` deadline, where a zero silently turns a budget into
148
+ * "give up immediately" and a `NaN` turns it into "never time out".
149
+ *
150
+ * Both node bring-up paths call this EAGERLY — `CadreNode.start()`, and
151
+ * `StrandInstanceManager.buildStrandRuntime` behind `addStrand`/`resumeStrand` — so a bad
152
+ * declaration fails the same start that Optimystic's own check on `cohortQueryTimeoutMs` fails.
153
+ * The eager call is what makes that true: every budget derived here is behind a condition (a
154
+ * node with no control storage builds no catch-up, a node with no relay addrs drives no
155
+ * reservation), so waiting for a first consumer would let a broken declaration boot and then
156
+ * throw inside a best-effort path that logs and carries on.
157
+ */
158
+ export function resolveLinkRoundTripMs(linkRoundTripMs?: number): number {
159
+ if (linkRoundTripMs === undefined) {
160
+ return DECLARED_LINK_ROUND_TRIP_MS;
161
+ }
162
+ if (!Number.isFinite(linkRoundTripMs) || linkRoundTripMs <= 0) {
163
+ throw new Error(
164
+ `network.linkRoundTripMs must be a finite number of milliseconds above zero, not ${String(linkRoundTripMs)}`
165
+ );
166
+ }
167
+ return linkRoundTripMs;
168
+ }
169
+
170
+ /**
171
+ * Deadline for OPENING a connection to another machine that may only be reachable through a
172
+ * relay: {@link RELAYED_DIAL_ROUND_TRIPS} at the declared link round trip.
173
+ */
174
+ export function relayedDialBudgetMs(linkRoundTripMs?: number): number {
175
+ return RELAYED_DIAL_ROUND_TRIPS * resolveLinkRoundTripMs(linkRoundTripMs);
176
+ }
177
+
178
+ /**
179
+ * Deadline for one whole relay reservation drive: {@link RELAY_RESERVATION_ROUND_TRIPS} at the
180
+ * declared link round trip.
181
+ */
182
+ export function relayReservationBudgetMs(linkRoundTripMs?: number): number {
183
+ return RELAY_RESERVATION_ROUND_TRIPS * resolveLinkRoundTripMs(linkRoundTripMs);
184
+ }
185
+
186
+ /**
187
+ * Deadline for one request and its answer over a circuit that is already open —
188
+ * {@link CIRCUIT_REQUEST_ROUND_TRIPS} at the declared link round trip, plus `transferAllowanceMs`
189
+ * for the payload's own bytes.
190
+ */
191
+ export function circuitRequestBudgetMs(
192
+ linkRoundTripMs?: number,
193
+ transferAllowanceMs = PUSH_TRANSFER_ALLOWANCE_MS
194
+ ): number {
195
+ return CIRCUIT_REQUEST_ROUND_TRIPS * resolveLinkRoundTripMs(linkRoundTripMs) + transferAllowanceMs;
196
+ }
197
+
198
+ /** The two deadlines one peer-join catch-up push needs, both derived from the declared link. */
199
+ export interface PeerJoinPushBudget {
200
+ /** Opening the connection to the peer being caught up — a relayed dial, in the worst case. */
201
+ dialTimeoutMs: number;
202
+ /** The push request and its answer over that connection, including the chunk's own bytes. */
203
+ responseTimeoutMs: number;
204
+ }
205
+
206
+ /**
207
+ * The dial and response deadlines a peer-join catch-up push needs at a declared link. One
208
+ * helper rather than two call-site expressions, because the two construction sites
209
+ * (`CadreNode`'s control catch-up and `StrandInstanceManager`'s per-strand one) and
210
+ * `DEFAULT_PEER_JOIN_BACKFILL` must not drift apart.
211
+ */
212
+ export function peerJoinPushBudget(linkRoundTripMs?: number): PeerJoinPushBudget {
213
+ return {
214
+ dialTimeoutMs: relayedDialBudgetMs(linkRoundTripMs),
215
+ responseTimeoutMs: circuitRequestBudgetMs(linkRoundTripMs)
216
+ };
217
+ }
package/src/peer-dial.ts CHANGED
@@ -27,32 +27,47 @@ import debug from 'debug';
27
27
  import type { Connection } from '@libp2p/interface';
28
28
  import type { Multiaddr } from '@multiformats/multiaddr';
29
29
  import { withDeadline } from './control-stream.js';
30
+ import { relayedDialBudgetMs } from './link-budget.js';
30
31
 
31
32
  const log = debug('sereus:cadre:peer-dial');
32
33
 
33
34
  /**
34
- * Default limit on ONE address's dial attempt, in ms.
35
+ * Default limit on ONE address's dial attempt, in ms, at the DEFAULT declared link round trip:
36
+ * `RELAYED_DIAL_ROUND_TRIPS` (4) x `DECLARED_LINK_ROUND_TRIP_MS` (2000 ms) = 8000 ms, which is
37
+ * what this constant was already set to as a fixed number.
35
38
  *
36
39
  * It has to cover the slowest address that should succeed, because an attempt
37
40
  * that needs longer fails the same way on every retry. That is a relayed dial on
38
41
  * a mobile link: connect to the relay (transport, encryption and multiplexer
39
42
  * handshakes, when no relay connection is open yet), open the circuit, then run
40
- * both handshakes again end to end through the relay at roughly twice the
41
- * round-trip time. At a few hundred ms per round trip that is several seconds.
42
- * A direct dial that works is far quicker — a phone's WebSocket dial to a node
43
- * forwarded over `adb reverse` measured 1.6 s end to end. 8 s covers the relayed
44
- * case with some margin while still abandoning a silently dropped address
45
- * sooner than libp2p's own 10 s dial timeout would.
43
+ * both handshakes again end to end through the relay. `link-budget.ts` is where that
44
+ * reasoning is now a measured count instead of an estimate — four link round trips, measured at
45
+ * 7 279 ms on a link whose round trip is 1.8 s — so the value MOVES with a host's
46
+ * `NetworkConfig.linkRoundTripMs` rather than pinning the band this node can reach to whatever
47
+ * number was typed here. A direct dial that works is far quicker — a phone's WebSocket dial to
48
+ * a node forwarded over `adb reverse` measured 1.6 s end to end.
49
+ *
50
+ * Deriving it rather than leaving it fixed is deliberate: at 8000 ms fixed, the per-address
51
+ * limit — not libp2p's own 10 s dial timeout — was the first thing to cut a relayed dial off,
52
+ * from about 1000 ms of one-way link delay upward. Nothing said so, and a reader raising
53
+ * `DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS` below would not have found it.
46
54
  *
47
55
  * NOTE: a `/p2p-circuit/webrtc` address also negotiates a WebRTC session after
48
56
  * the relay leg. If such dials are ever seen failing at exactly this limit, raise
49
- * it (or `network.controlCohort.perAddressDialTimeoutMs` on the affected nodes)
50
- * rather than the per-peer limit, which cannot help an address that is itself
57
+ * the declared link round trip (or `network.controlCohort.perAddressDialTimeoutMs` on the
58
+ * affected nodes) rather than the per-peer limit, which cannot help an address that is itself
51
59
  * cut off.
52
60
  *
53
61
  * Override per node with `network.controlCohort.perAddressDialTimeoutMs`.
54
62
  */
55
- export const DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS = 8_000;
63
+ export const DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS = relayedDialBudgetMs();
64
+
65
+ /**
66
+ * How many whole per-address dial attempts {@link DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS}
67
+ * budgets for: the address that works plus the three dead ones a lent cadre-host node is
68
+ * observed to report ahead of it (loopback and LAN WebSocket addresses, plus virtual adapters).
69
+ */
70
+ export const CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS = 4;
56
71
 
57
72
  /**
58
73
  * Default limit on dialing ONE peer — every candidate address together — in ms.
@@ -66,18 +81,25 @@ export const DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS = 8_000;
66
81
  *
67
82
  * Sized to fit a typical list with dead addresses ahead of the one that works:
68
83
  * a lent cadre-host node reports two to four addresses a phone can dial
69
- * (loopback and LAN WebSocket addresses, plus any virtual adapters). Three
70
- * silently dropped addresses cost 3 × 8 s = 24 s, leaving 6 s for the working
71
- * address after them — well over the 1.6 s the phone measured. A peer whose
72
- * working address sits behind four or more dropped ones does not fit, and fails
73
- * each pass the same way; if that shows up, the remedy is ordering (try the
74
- * address that last connected first), not a larger number here.
84
+ * (loopback and LAN WebSocket addresses, plus any virtual adapters). So it is
85
+ * {@link CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS} whole per-address budgets — three silently
86
+ * dropped addresses, then the one that works, each getting the FULL per-address limit. A peer
87
+ * whose working address sits behind four or more dropped ones does not fit, and fails each pass
88
+ * the same way; if that shows up, the remedy is ordering (try the address that last connected
89
+ * first), not a larger number here.
90
+ *
91
+ * Counted as whole per-address budgets rather than the flat 30_000 it was before, because the
92
+ * old number left only 6 s after three dropped addresses — enough for the 1.6 s direct dial the
93
+ * phone measured, but NOT for the relayed dial the per-address limit is sized to cover. A peer
94
+ * whose only working address was a relayed one behind two dead ones therefore could not be
95
+ * dialled at all, and the arithmetic in this comment was what said otherwise.
75
96
  *
76
97
  * Override per node with `network.controlCohort.dialTimeoutMs` — tests that
77
98
  * drive dead addresses on purpose set it low so a pass's duration is a chosen
78
99
  * number rather than a transitive libp2p default stretched by machine load.
79
100
  */
80
- export const DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS = 30_000;
101
+ export const DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS =
102
+ CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS * DEFAULT_CONTROL_COHORT_PER_ADDRESS_DIAL_TIMEOUT_MS;
81
103
 
82
104
  /** Time limits for dialing one peer from a list of candidate addresses. */
83
105
  export interface PeerDialBudget {
@@ -2,6 +2,7 @@ import debug from 'debug';
2
2
  import type { Connection, Libp2p, PeerId } from '@libp2p/interface';
3
3
  import type { ActionId, IPeerNetwork } from '@optimystic/db-core';
4
4
  import { BlockTransferClient, type BlockCommitProof, type IRawStorage } from '@optimystic/db-p2p';
5
+ import { peerJoinPushBudget } from './link-budget.js';
5
6
 
6
7
  // Peer-join whole-store block catch-up, shared by the STRAND networks and the CONTROL
7
8
  // network. On `connection:open` (debounced) it pushes every committed, materialized block
@@ -43,19 +44,74 @@ import { BlockTransferClient, type BlockCommitProof, type IRawStorage } from '@o
43
44
  // `scheduleConnectedPeers()` on a membership change (the production join order is
44
45
  // connect-then-authorize, so the denial at dial time is the expected first pass).
45
46
  //
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.
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`.
52
55
  //
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.
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.
59
115
 
60
116
  const log = debug('sereus:cadre:peer-join-backfill');
61
117
 
@@ -67,6 +123,14 @@ const log = debug('sereus:cadre:peer-join-backfill');
67
123
  */
68
124
  export const MAX_BLOCK_MESSAGE_BYTES = 8 * 1024 * 1024;
69
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
+
70
134
  /** Tuning for the per-peer catch-up. Every field optional; defaults in {@link DEFAULT_PEER_JOIN_BACKFILL}. */
71
135
  export interface PeerJoinBackfillConfig {
72
136
  /** Default true. False disables the catch-up entirely (the pre-existing behaviour). */
@@ -79,10 +143,28 @@ export interface PeerJoinBackfillConfig {
79
143
  maxChunkBytes?: number;
80
144
  /** Max blocks per push message. Default 64. */
81
145
  maxChunkBlocks?: number;
82
- /** Per-push dial deadline, ms. Default 3000 (matches SpreadOnChurnMonitor). */
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
+ */
83
153
  dialTimeoutMs?: number;
84
- /** Per-push response deadline, ms. Default 10_000 (matches SpreadOnChurnMonitor). */
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
+ */
85
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;
86
168
  }
87
169
 
88
170
  /** The resolved defaults every {@link PeerJoinBackfill} starts from. */
@@ -92,8 +174,13 @@ export const DEFAULT_PEER_JOIN_BACKFILL: Required<PeerJoinBackfillConfig> = {
92
174
  maxBlocks: 10_000,
93
175
  maxChunkBytes: 1024 * 1024,
94
176
  maxChunkBlocks: 64,
95
- dialTimeoutMs: 3000,
96
- responseTimeoutMs: 10_000
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
97
184
  };
98
185
 
99
186
  /**
@@ -209,8 +296,18 @@ export class PeerJoinBackfill {
209
296
  * reconnect, which is exactly what the re-arm exists to avoid.
210
297
  */
211
298
  private readonly rearmAfterFlight = new Set<string>();
212
- /** Pending per-peer debounce timers, cleared on stop. */
299
+ /** Pending per-peer timers — the debounce, or a backoff re-arm. Cleared on stop. */
213
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>();
214
311
  private readonly onConnectionOpen: (evt: CustomEvent<Connection>) => void;
215
312
  private loggedNoListBlockIds = false;
216
313
 
@@ -244,6 +341,7 @@ export class PeerJoinBackfill {
244
341
  }
245
342
  this.timers.clear();
246
343
  this.rearmAfterFlight.clear();
344
+ this.retryAfter.clear();
247
345
  log('[%s] stopped', this.deps.label);
248
346
  }
249
347
 
@@ -279,6 +377,12 @@ export class PeerJoinBackfill {
279
377
  this.rearmAfterFlight.add(key);
280
378
  return;
281
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;
282
386
  const existing = this.timers.get(key);
283
387
  if (existing) clearTimeout(existing);
284
388
  this.timers.set(key, setTimeout(() => {
@@ -299,7 +403,7 @@ export class PeerJoinBackfill {
299
403
  }
300
404
  this.inFlight.add(key);
301
405
  try {
302
- const { result, clean } = await this.runCatchUp(peerId);
406
+ const { result, clean, pushFailed } = await this.runCatchUp(peerId);
303
407
  // NOTE: a run that hit `maxBlocks` is still "clean" and still memoizes the peer, so
304
408
  // the tail past the ceiling never reaches it. Deliberate: enumeration is not
305
409
  // resumable, so not memoizing would re-push the same prefix on every reconnect
@@ -307,6 +411,18 @@ export class PeerJoinBackfill {
307
411
  // realistically exceed maxBlocks, the fix is a resumable cursor, not either policy.
308
412
  if (clean && !this.stopped) {
309
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);
310
426
  }
311
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',
312
428
  this.deps.label, key, result.offered, result.accepted, result.rejected.length,
@@ -327,8 +443,61 @@ export class PeerJoinBackfill {
327
443
  }
328
444
  }
329
445
 
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 }> {
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 }> {
332
501
  const result = emptyResult();
333
502
  const { storage } = this.deps;
334
503
 
@@ -345,7 +514,7 @@ export class PeerJoinBackfill {
345
514
  }
346
515
  if (!authorized) {
347
516
  result.denied = true;
348
- return { result, clean: false };
517
+ return { result, clean: false, pushFailed: false };
349
518
  }
350
519
  }
351
520
 
@@ -354,7 +523,7 @@ export class PeerJoinBackfill {
354
523
  this.loggedNoListBlockIds = true;
355
524
  log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.label);
356
525
  }
357
- return { result, clean: false };
526
+ return { result, clean: false, pushFailed: false };
358
527
  }
359
528
 
360
529
  const client = this.createPushClient(peerId);
@@ -473,6 +642,6 @@ export class PeerJoinBackfill {
473
642
  }
474
643
 
475
644
  const clean = !chunkFailed && result.rejected.length === 0;
476
- return { result, clean };
645
+ return { result, clean, pushFailed: chunkFailed };
477
646
  }
478
647
  }