1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Provider selection algorithm (ADR 001 § Node Selection Algorithm + ADR 008
//! § Tie-Breaking).
//!
//! `rank_candidates` returns the input list ordered best-first (lowest score
//! first) with the three-tier tie-breaker applied. The caller iterates the
//! result in order and stops after `MAX_PROVIDER_ATTEMPTS` failed providers.
use RngExt;
use HashSet;
use Duration;
use Coverage;
use crate;
/// Maximum providers to attempt before reporting a fetch failure to the
/// caller (issue #322 — "max 3 provider attempts before returning error").
pub const MAX_PROVIDER_ATTEMPTS: usize = 3;
/// Per-candidate probe timeout. Because candidates are probed concurrently, this also
/// bounds the whole probe-collection phase. The budget covers connection setup plus one
/// unpaid probe request/response. `probe_once` dials a fresh connection every call, and
/// the protocol has no 0-RTT path, so even a resumable session pays a handshake round trip
/// before the request goes out — every probe costs two RTTs, not one. At the 250-300 ms
/// inter-continental RTTs this budget is sized against, that puts the furthest candidates
/// at or past this ceiling. Dropping them is the intended trade (a slow candidate must not
/// burn the caller's miss-latency budget), but this is the first term to revisit if
/// distant-region selection looks too sparse. Both the figure and the trade are ADR 001
/// § Probe response collection.
///
/// What is left of the budget after the exchange goes to `probe_once`'s wait for hole
/// punching to select a direct path. A candidate whose answer arrives in time is kept even
/// when that wait runs out: it ranks on its exchange RTT, which can be the relay detour, and
/// that RTT still feeds the ADR 030 region-latency penalty.
///
/// Lives here, beside the deadline arithmetic that has to budget for it, rather than in
/// `node_origin` where it is used (#1145 review). Every term of [`outer_pull_deadline`] is
/// then visible in one file, which is what stops the next one from being guessed.
pub const PROBE_TIMEOUT: Duration = from_millis;
/// How many blob-holding candidates a SINGLE-SOURCE probe round collects before
/// it stops waiting on the rest. [`PROBE_TIMEOUT`] stays the ceiling — a sparse
/// round that never reaches this count still waits it out — but when this many
/// good providers have already answered, the round selects among them instead of
/// waiting the full window for a straggler or a dead peer that will only time
/// out. The count leaves at least one alternate in hand for per-blob failover
/// while keeping cold-miss discovery latency at the speed of the fastest good
/// answers rather than the ceiling. ADR 001 § Probe response collection.
///
/// Equal to [`MAX_PROVIDER_ATTEMPTS`] on purpose: the single-source pull loop
/// tries at most that many providers, so collecting that many viable candidates
/// already fills the failover budget — waiting for more only serves stragglers
/// the loop would never reach.
///
/// This fixed count is CORRECT only when one working provider is enough — the
/// buffered single-source pull. The ranged-drive assembly path (#1506, ADR 039)
/// needs a candidate set whose coverage UNION spans the requested range, not a
/// fixed count: three responders that all hold discovery block 0 do not cover a
/// three-block blob, yet stopping at this count would drop the block-1/block-2
/// holders in the same fanout. That path gathers by coverage union instead (see
/// `node_origin::probe_and_rank`'s `ProbeGather::CoverageUnion`), bounded only by
/// the probe fanout.
pub const PROBE_EARLY_EXIT_CANDIDATES: usize = MAX_PROVIDER_ATTEMPTS;
/// One-time headroom added on top of the `MAX_PROVIDER_ATTEMPTS` sequential per-candidate
/// costs when computing the outer pull-through deadline (#859). It covers the *one-time*
/// `discover → probe → rank` overhead: work that runs under the outer deadline but does not
/// scale with the attempt count.
///
/// **Derived, not chosen** (#1145 review). A flat constant would be smaller than the thing
/// it is named for:
///
/// - probing is concurrent, so it costs one [`PROBE_TIMEOUT`] — 500 ms; but
/// - discovery is `find_providers`, whose rounds are each bounded by
/// [`DEFAULT_ROUND_TIMEOUT`] (8 s) and whose round count is capped by
/// [`MAX_LOOKUP_ROUNDS`] (4).
///
/// At those defaults, four discovery rounds plus the probe phase can cost 32.5 s. A flat
/// budget short of that leaves the outer deadline short of what the fetch can actually spend,
/// so the `tokio::time::timeout` around `discover → probe → rank → pull` can fire while
/// candidate #3 is still in its stall window — the #859 fallback starvation this formula
/// exists to prevent, reachable at the defaults.
///
/// The fix is in two halves, and both are necessary: [`MAX_LOOKUP_ROUNDS`] makes discovery's
/// worst case finite, and this makes it a TERM. An unbounded cost cannot be budgeted for by
/// any constant, however generous.
pub const PULL_THROUGH_OUTER_SLACK: Duration =
PROBE_TIMEOUT.saturating_add;
/// How long a pull is willing to WAIT on a buyer-pool open before giving up on
/// that candidate — not how long the open itself is allowed to take (#1143).
///
/// The `openPool` runs in a detached task that owns the tx, so a
/// caller that stops waiting costs nothing: the open continues, the pool lands,
/// and the next pull, to any provider, reuses it. What the caller buys by waiting is
/// only the chance to use the pool on *this* pull. That makes a short budget the
/// right trade — a cache miss must fall through to another candidate in seconds,
/// while an `openPool` may legitimately need minutes to mine on a slow L2.
///
/// Deliberately much smaller than `cache.node_pull_timeout_sec`: the pool open, the
/// stream open, and the streaming stage are SEQUENTIAL stages of one candidate attempt,
/// and [`outer_pull_deadline`] has to cover all three for every candidate.
pub const POOL_OPEN_CALLER_BUDGET: Duration = from_secs;
/// Outer deadline for a node-to-node pull-through, derived from the two configured
/// per-candidate budgets: the stream-open timeout (`cache.node_pull_timeout_sec`) and
/// the streaming throughput-floor window (`cache.node_pull_stall_window_sec`).
///
/// The delivery handler wraps the whole `discover → probe → rank → pull` fetch
/// in a single `tokio::time::timeout`. For the sequential `MAX_PROVIDER_ATTEMPTS`
/// fallback loop to actually reach candidates #2..N when candidate #1 *stalls*,
/// this outer deadline must strictly exceed the sum of all per-candidate costs —
/// otherwise both clocks expire
/// together and the outer timeout cancels the whole fetch at the instant candidate
/// #1's own timeout fires, killing the fallback.
///
/// # What one candidate actually costs
///
/// THREE sequential bounded stages:
///
/// 1. the **pool open** — [`POOL_OPEN_CALLER_BUDGET`] (#1143); then
/// 2. the **stream open** — connect → handshake → verified `StreamResponse`,
/// bounded by `per_candidate` (#1134); then
/// 3. **streaming**, which for a peer that opens honestly and then goes SILENT costs
/// one full throughput-floor window (`stall`) before the pull gives up on it (#1797).
///
/// So the worst case for a candidate is `POOL_OPEN_CALLER_BUDGET + per_candidate + stall`,
/// and that is what this must budget `MAX_PROVIDER_ATTEMPTS` of, plus
/// [`PULL_THROUGH_OUTER_SLACK`] of one-time discovery overhead.
///
/// Every stage has to be a term here. Budgeting only `per_candidate` would let a cold
/// cache against a slow L2 burn the whole deadline on candidates #1 and #2 and never
/// dial #3. Covering the pool open but not the stall window would leave the same hole
/// for a peer that goes silent mid-stream instead of failing to open — and a worse one,
/// because `stall` is operator-tunable: at `node_pull_stall_window_sec = 120` a single
/// silent candidate outlasts a two-term deadline on its own. Taking `stall` as an
/// argument keeps this deadline in step with `node_pull_stall_window_sec`.
///
/// # What this deadline does not bound
///
/// A candidate's streaming stage is bounded by *inactivity* rather than a wall clock,
/// because a wall clock over the bytes caps the blob size a node can pull through
/// (#1134). The `stall` term above is therefore the cost of a candidate that **stops**
/// — not a ceiling on one that keeps going. A candidate that is **slow but progressing**
/// resets that clock on every byte and can consume the whole outer deadline on its own.
///
/// That is correct: it is succeeding, and falling through mid-stream would restart the
/// download from zero against another peer, throwing away the bytes already paid for.
/// On expiry the foreground request gives up with a clean miss and nothing continues in
/// the background — there is no detached warm, so a pull only ever runs while a
/// client is waiting, and the blob is re-acquired on the next real client request.
///
/// So this bounds how long a **client** waits; no acquisition outlives that wait.
/// Reputation floor in the score denominator (ADR 001).
const REPUTATION_FLOOR: f32 = 0.1;
/// Reputation ceiling in the score denominator — the top of
/// [`Candidate::reputation`]'s documented domain (#1458). Named rather than
/// written inline so the code, the doc prose, and the tests that pin it move
/// together, the way [`REPUTATION_FLOOR`] already does.
const REPUTATION_CEILING: f32 = 1.0;
/// Score-equivalence threshold for tie-break activation (ADR 001 — "scores
/// within 1% of each other").
const TIE_THRESHOLD: f64 = 0.01;
/// A candidate provider produced by content discovery, ready to be ranked.
/// A candidate paired with its computed selection score. Lower score is better.
/// Compute the unified selection score (ADR 001). Lower is better.
///
/// `score = rate_per_mb × max(rtt_ms, 1) × (1 / clamp(reputation, 0.1, 1.0)²)`
///
/// The RTT has a floor of 1 ms. A probe faster than 1 ms truncates to
/// `rtt_ms = 0`, and a zero factor would make the score 0 for any rate: two
/// such peers would tie whatever they quote, and a dear one would outrank every
/// cheaper peer at 1 ms or more. With the floor, sub-millisecond peers rank on
/// rate and reputation, and only `rate_per_mb = 0` gives a score of 0.
///
/// ADR 001 § Node Selection Algorithm states the denominator as
/// `max(reputation, 0.1)`; the upper bound here is a defensive extension
/// (#1458), a no-op for any input inside the ADR's `[0.0, 1.0]` domain.
///
/// Reputation is clamped between [`REPUTATION_FLOOR`] and
/// [`REPUTATION_CEILING`] before squaring — both ends, and both ends matter.
/// The floor prevents division by zero and caps the worst-case penalty
/// multiplier at 100×; the ceiling stops an out-of-domain value from buying an
/// unearned *bonus*. Without it, `reputation = 10.0` divides the score by 100
/// and outranks a perfect-reputation peer by 100×, and `f32::INFINITY` yields
/// score `0.0` — which [`tie_group_end`] treats as a tie group of one, so it
/// takes the top slot outright, beyond the reach of every tie-break tier.
// f64 has 53-bit mantissa; ULP-level imprecision on huge u64 rates does not
// affect ordering decisions here.
/// Rank candidates by selection score, lowest (best) first.
///
/// Within-1%-score tie groups are reordered by the three-tier ADR 008
/// tie-breaker (geo → stake → random). The random tier uses a fresh
/// thread-local RNG; tests inside this module use the private
/// `rank_candidates_with_rng` variant for determinism.
/// Variant of [`rank_candidates`] taking an explicit RNG. Internal — used by
/// tests for deterministic random tie-breaking.
/// Walk the score-sorted slice and emit each within-1% tie group using the
/// ADR 008 § Tie-Breaking tiers. Geo diversity is scoped to the current tie
/// group: candidates within a single within-1% group are spread across
/// regions, but the tracker is reset between groups so unrelated tie groups
/// don't bias each other's geo tier.
/// Return the index in `group` of the candidate that wins the tie under the
/// geo (relative to `emitted_regions`) → stake → random tiers.
///
/// Filters a single index pool in place across the three tiers, so the
/// function allocates exactly one Vec per call regardless of group size or
/// tier depth.
///
/// **INVARIANT:** the returned index is independent of element order in
/// `group`. The caller (`apply_tiebreaker`) relies on this to use `swap_remove`
/// for O(1) removal, which reorders surviving elements. Any future
/// optimization that reuses state across calls must preserve this property.
/// Return the exclusive end index of the tie group beginning at `start`.
/// Two adjacent candidates are in the same group iff their relative score
/// difference is ≤ [`TIE_THRESHOLD`]. Two candidates with score `0.0` are
/// always grouped together; a zero-score candidate is strictly better than
/// any positive-score candidate and ends the group.
///
/// **Termination contract:** returns `> start` whenever `start < ranked.len()`,
/// so the caller's drain-the-front loop in [`apply_tiebreaker`] always makes
/// progress on a non-empty `ranked`.