Skip to main content

hya_core/
sched.rs

1//! The scheduler kernel: pure state machine, no I/O, no clock, no allocation
2//! in the steady state.
3//!
4//! The caller drives it: feed observations (`on_bytes`, `on_complete`), call
5//! `tick(now)`, and act on the returned `Action`s. This is what lets the same
6//! code run under the discrete-event simulator and under real HTTP.
7//!
8//! Implements dynamic range partitioning, divergence-triggered steal-to-equalize,
9//! work-conserving assignment, queue dispatch, stall reclamation, and greedy concurrency.
10
11use crate::intervals::{IntervalSet, Range};
12
13/// Minimum steal quantum. A range rebalance smaller than this is not worth request overhead.
14pub const STEAL_QUANTUM: u64 = 64 * 1024;
15
16/// Bounded repairs per tick, so a tick is O(R * n).
17const MAX_REPAIRS_PER_TICK: usize = 4;
18
19/// EWMA weight on the newest goodput sample.
20const RATE_ALPHA: f64 = 0.3;
21
22/// Minimum wall clock a rate sample must span, in seconds.
23///
24/// Below this the quotient is dominated by socket buffering rather than by the
25/// link: consecutive `read()` calls draining one already-arrived TCP window return
26/// in microseconds and imply a rate the network never achieved. 200 ms is long
27/// enough to average over several windows and short enough that a genuine collapse
28/// is still graded within the stall timeout.
29const RATE_WINDOW: f64 = 0.2;
30
31#[derive(Clone, Copy, PartialEq, Eq, Debug)]
32pub enum Action {
33    /// Issue `GET` with `Range: bytes=lo-(hi-1)` on this connection.
34    Request { conn: usize, range: Range },
35    /// Stop reading this connection's current response; its range was reclaimed.
36    Cancel { conn: usize },
37    /// The far end of this connection's in-flight range moved DOWN to `hi`: a
38    /// repair handed the tail `[hi, old_hi)` to another connection. Stop reading
39    /// at `hi`.
40    ///
41    /// # Why this action has to exist
42    ///
43    /// The whole claim of this scheduler is that shrinking a laggard's range is
44    /// free, because an HTTP range request names both ends and the far end is
45    /// enforced by the client. That is true of the protocol. It was NOT true of
46    /// this implementation: the repair below moved `conns[vi].range` and emitted
47    /// nothing, while the transport's fetch loop runs `while off < hi` against
48    /// the `hi` it captured when the request was spawned. The victim therefore
49    /// kept pulling the bytes it had just been relieved of, at the same time as
50    /// the taker pulled them, over the same bottleneck.
51    ///
52    /// So each repair cost roughly one stolen span of duplicated traffic instead
53    /// of nothing, and since the duplicate traffic slowed the honest
54    /// connections, it manufactured the very divergence that triggers a repair.
55    /// That positive feedback loop is the measured "repair storm": at n=8 on a
56    /// stationary 5.3 MB transfer, 32-49 repairs where the correct count is 0,
57    /// with in-run throughput decaying 439 -> 306 KiB/s.
58    ///
59    /// A caller that ignores this action is not merely leaving an optimisation
60    /// on the table; it reintroduces the storm.
61    Shrink { conn: usize, hi: u64 },
62}
63
64#[derive(Clone, Copy, PartialEq, Eq, Debug)]
65pub enum Capability {
66    /// Ranges honoured, length known, strong validator: full scheduling.
67    Full,
68    /// Ranges honoured but no validator: partition, but pin to one source.
69    NoValidator,
70    /// Ranges ignored or unsupported: race whole-object fetches.
71    Race,
72    /// Length unknown: single stream per source, no range arithmetic.
73    Stream,
74}
75
76#[derive(Clone, Debug)]
77pub struct Source {
78    pub caps: Capability,
79    /// Per-connection goodput ceiling estimate, bytes/s.
80    pub gamma_est: f64,
81    /// Per-source shaping cap estimate, bytes/s.
82    pub rho_est: f64,
83    /// Measured request setup cost, seconds.
84    pub delta_est: f64,
85    /// Suspended until this time (429/503 Retry-After, or stall backoff).
86    pub suspended_until: f64,
87    /// Consecutive stalls observed on this source; drives exponential backoff.
88    pub consecutive_stalls: u32,
89}
90
91impl Default for Source {
92    fn default() -> Self {
93        Source {
94            caps: Capability::Full,
95            gamma_est: 0.0,
96            rho_est: f64::INFINITY,
97            delta_est: 0.05,
98            suspended_until: 0.0,
99            consecutive_stalls: 0,
100        }
101    }
102}
103
104#[derive(Clone, Debug)]
105struct Conn {
106    source: usize,
107    /// Active range and how far into it we are.
108    range: Option<Range>,
109    pos: u64,
110    /// One-slot pipeline: a range handed over by a repair.
111    queued: Option<Range>,
112    rate_est: f64,
113    /// Changepoint detector. `rate_est` remains the smoothed rate used for ETA
114    /// projection; this grades the connection so repair can pre-empt a collapse
115    /// instead of waiting for the stall timeout (see `detect.rs`).
116    detector: crate::detect::CollapseDetector,
117    last_progress: f64,
118    setup_end: f64,
119    /// When the request this connection is running now was issued.
120    ///
121    /// Arrivals older than this belong to a request that has been superseded —
122    /// reclaimed after a stall, cancelled, or failed — and must not be credited,
123    /// even when they land exactly at the cursor. See `on_bytes_at`.
124    started_at: f64,
125    stalled: bool,
126    /// Bytes and wall clock accumulated since the last RATE sample.
127    ///
128    /// Rate is measured over a fixed WINDOW, not per arrival. An arrival is one
129    /// `read()` return, and a read served from the socket's already-buffered data
130    /// completes in microseconds, so `bytes/dt` for that arrival measures memcpy
131    /// speed rather than network speed — observed as 128 MiB/s on a connection
132    /// whose link was doing well under 1 MiB/s.
133    ///
134    /// That is not merely a cosmetic display bug. Those inflated samples raise the
135    /// detector's reference level, after which every honest sample looks like a
136    /// collapse against it, and the CUSUM grades a perfectly healthy connection
137    /// `Degraded` — which is why all eight connections of a working transfer
138    /// showed as `bad`. Byte accounting stays exactly per-arrival (coverage must
139    /// be exact); only the rate estimate is windowed.
140    rate_acc_bytes: u64,
141    rate_acc_dt: f64,
142}
143
144impl Conn {
145    fn new(source: usize) -> Self {
146        Conn {
147            source,
148            range: None,
149            pos: 0,
150            queued: None,
151            rate_est: 0.0,
152            detector: crate::detect::CollapseDetector::new(),
153            rate_acc_bytes: 0,
154            rate_acc_dt: 0.0,
155            last_progress: 0.0,
156            setup_end: 0.0,
157            started_at: f64::NEG_INFINITY,
158            stalled: false,
159        }
160    }
161
162    #[inline]
163    fn busy(&self) -> bool {
164        self.range.map(|r| self.pos < r.hi).unwrap_or(false)
165    }
166
167    /// Bytes still owed on the active range plus anything pipelined.
168    #[inline]
169    fn outstanding(&self) -> u64 {
170        let active = self
171            .range
172            .map(|r| r.hi.saturating_sub(self.pos))
173            .unwrap_or(0);
174        active + self.queued.map(|r| r.len()).unwrap_or(0)
175    }
176
177    /// Projected seconds to drain. A stalled or unmeasured connection projects
178    /// to infinity so it is always chosen as the repair victim.
179    fn eta(&self) -> f64 {
180        let out = self.outstanding();
181        if out == 0 {
182            return 0.0;
183        }
184        if self.rate_est <= 0.0 {
185            return f64::INFINITY;
186        }
187        out as f64 / self.rate_est
188    }
189}
190
191#[derive(Clone, Copy, Debug, Default)]
192pub struct Stats {
193    pub requests: u64,
194    pub repairs: u64,
195    pub reclaims: u64,
196    pub bytes_held: u64,
197}
198
199pub struct Scheduler {
200    size: u64,
201    unassigned: IntervalSet,
202    held: u64,
203    conns: Vec<Conn>,
204    sources: Vec<Source>,
205    /// Repair deadband scale; theta = scale * sqrt(delta * T_rem / n).
206    /// Reused index buffer for the per-tick stalled-connection scan.
207    ///
208    /// The scan runs 50 times a second at the default tick and allocated a fresh `Vec`
209    /// each time, to hold at most `n_conns` indices. Reusing one buffer costs a field
210    /// and removes the allocation from the hot loop.
211    scratch_idx: Vec<usize>,
212    theta_scale: f64,
213    stall_timeout: f64,
214    /// How many connections may hold work at once. Adjustable mid-transfer so the
215    /// concurrency search can run on the real transfer rather than on probe
216    /// traffic; see `set_active_limit`.
217    active_limit: usize,
218    /// When false, victim selection ignores detector health and ranks purely by
219    /// projected ETA (the pre-detector behaviour). Exists so the detector's
220    /// contribution can be A/B measured rather than assumed.
221    health_ranking: bool,
222    started: bool,
223    pub stats: Stats,
224}
225
226impl Scheduler {
227    pub fn new(size: u64, sources: Vec<Source>, conns_per_source: &[usize]) -> Self {
228        let mut conns = Vec::new();
229        for (i, &k) in conns_per_source.iter().enumerate() {
230            for _ in 0..k {
231                conns.push(Conn::new(i));
232            }
233        }
234        Scheduler {
235            size,
236            unassigned: IntervalSet::full(size),
237            held: 0,
238            conns,
239            sources,
240            scratch_idx: Vec::new(),
241            theta_scale: 1.0,
242            stall_timeout: 1.0,
243            health_ranking: true,
244            // Default: every connection active, so nothing changes for callers that
245            // do not opt into the ramp.
246            active_limit: usize::MAX,
247            started: false,
248            stats: Stats::default(),
249        }
250    }
251
252    /// Cap how many connections may hold work at once, adjustable mid-transfer.
253    ///
254    /// # Why the concurrency search belongs here and not in a probe
255    ///
256    /// Finding the useful connection count by *probing* — fetch a slab with one
257    /// connection, then with two, then three, comparing goodput — is the standard
258    /// approach and it is what this client did. HARP (Kim, Yildirim, Kosar, SC'16)
259    /// names the cost directly: probing "may bring too much probing overhead",
260    /// because the samples are extra transfers whose price is paid before the real
261    /// one starts. Measured here on a 3.15 MB object over a live path, the climbing
262    /// probe made the transfer **1.96x slower** than not probing at all
263    /// (paired over 9 interleaved reps, p = 0.004) — the search cost more than the
264    /// concurrency it found could save.
265    ///
266    /// The probe is only necessary because concurrency is fixed when the transfer
267    /// starts. Make it adjustable and the same search runs on the *real* transfer:
268    /// start at one connection, measure aggregate goodput over a short window,
269    /// admit another connection while the marginal gain justifies it, and stop.
270    /// Every byte moved during the search is a byte of the object, so the search
271    /// is free — the object had to be fetched anyway. What HARP buys with a
272    /// historical corpus, this buys by putting the measurement in-band.
273    ///
274    /// Connections above the limit stay dormant: they are not given work and open
275    /// no socket. Raising the limit lets the next tick hand them work through the
276    /// ordinary work-conserving path, so no new admission machinery is needed.
277    pub fn set_active_limit(&mut self, n: usize) {
278        self.active_limit = n.clamp(1, self.conns.len().max(1));
279    }
280
281    /// The current concurrency cap.
282    pub fn active_limit(&self) -> usize {
283        self.active_limit
284    }
285
286    /// When every source is deliberately suspended, the earliest time one returns.
287    ///
288    /// `None` means at least one source is usable now, so a lack of progress is a
289    /// genuine stall. `Some(t)` means the scheduler has *chosen* to pause every
290    /// source until `t` — nothing can move before then, and that silence is planned
291    /// rather than pathological.
292    ///
293    /// # Why a caller must consult this
294    ///
295    /// The transport's no-progress watchdog exists to fail a transfer where nothing
296    /// will ever happen again. A scheduled retry is the opposite of that, and
297    /// conflating the two is not hypothetical: with one source (the common case —
298    /// one URL, one CDN), `stall_timeout` 4.0s gives a watchdog of
299    /// `4 * (4.0 + delta)` = 16.2s, while five consecutive stalls suspend that sole
300    /// source for `min(4.0 * 2^3, 30)` = 30s. The transfer is then killed at 16.2s
301    /// for failing to make progress it had itself forbidden.
302    ///
303    /// Measured consequence on a 121.7 MiB GitHub release asset: 4 of 8 runs at
304    /// `-x 8`/`-x 16` aborted with a digest mismatch, three of them having already
305    /// received 126.9-127.0 MB of 127.6 MB — 99.6% complete, killed during a
306    /// deliberate backoff over the last half-megabyte.
307    pub fn all_sources_suspended_until(&self, now: f64) -> Option<f64> {
308        let mut earliest = f64::INFINITY;
309        for s in &self.sources {
310            if s.suspended_until <= now {
311                return None;
312            }
313            earliest = earliest.min(s.suspended_until);
314        }
315        if earliest.is_finite() {
316            Some(earliest)
317        } else {
318            None
319        }
320    }
321
322    /// Whether any work is still unclaimed by any connection.
323    ///
324    /// Exposed so the ramp's contract is testable: while concurrency is below the
325    /// budget, work must remain here for connections admitted later to pick up.
326    pub fn unassigned_is_empty(&self) -> bool {
327        self.unassigned.is_empty()
328    }
329
330    /// How many connections currently hold a range.
331    pub fn busy_conns(&self) -> usize {
332        self.conns.iter().filter(|c| c.busy()).count()
333    }
334
335    /// Start with only `n` connections active, ramping up from there.
336    pub fn with_active_limit(mut self, n: usize) -> Self {
337        self.set_active_limit(n);
338        self
339    }
340
341    pub fn with_theta_scale(mut self, s: f64) -> Self {
342        self.theta_scale = s;
343        self
344    }
345
346    /// Disable health-ranked victim selection (for A/B measurement only).
347    pub fn with_health_ranking(mut self, on: bool) -> Self {
348        self.health_ranking = on;
349        self
350    }
351
352    pub fn with_stall_timeout(mut self, t: f64) -> Self {
353        self.stall_timeout = t;
354        self
355    }
356
357    /// Mark `[lo, hi)` as already held, for resuming a partial transfer.
358    ///
359    /// Must be called before the first `tick`: the initial split assigns all
360    /// unassigned work, and bytes already on disk must not be part of it.
361    pub fn mark_done(&mut self, lo: u64, hi: u64) {
362        let (lo, hi) = (lo.min(self.size), hi.min(self.size));
363        if hi <= lo {
364            return;
365        }
366        // Credit only the bytes this call actually claims, measured as the drop in
367        // the unassigned set — NOT the width of the span asked for.
368        //
369        // Callers legitimately overlap. A `-c` resume marks the sidecar's ranges
370        // held, and the concurrency probe separately reports the bytes it fetched;
371        // both start at offset 0, so the same prefix is marked twice. Crediting
372        // `hi - lo` each time made `held` exceed the bytes that exist, and `held`
373        // is what `is_complete()` tests: the transfer stopped early believing it
374        // was finished, leaving a zero-filled hole in the tail of a file reported
375        // as a success. Measured on an interrupted-then-resumed 11 200 900-byte
376        // object: 240 138 bytes of tail never written, `ok: true`, and the gzip
377        // refused to decompress.
378        let before = self.unassigned.total();
379        self.unassigned.remove(lo, hi);
380        let claimed = before.saturating_sub(self.unassigned.total());
381        self.held = self.held.saturating_add(claimed);
382    }
383
384    /// Health grade of a connection, for the progress UI and for tests.
385    pub fn conn_health(&self, j: usize) -> crate::detect::Health {
386        self.conns
387            .get(j)
388            .map(|c| c.detector.health())
389            .unwrap_or_default()
390    }
391
392    /// Source index a connection belongs to, for the progress UI.
393    pub fn conn_source(&self, j: usize) -> usize {
394        self.conns.get(j).map(|c| c.source).unwrap_or(0)
395    }
396
397    /// Smoothed rate estimate of a connection (bytes/s), for the progress UI.
398    pub fn conn_rate(&self, j: usize) -> f64 {
399        self.conns.get(j).map(|c| c.rate_est).unwrap_or(0.0)
400    }
401
402    /// Active range of a connection, for the progress UI.
403    pub fn conn_range(&self, j: usize) -> Option<(u64, u64, u64)> {
404        self.conns
405            .get(j)
406            .and_then(|c| c.range.map(|r| (r.lo, c.pos, r.hi)))
407    }
408
409    pub fn n_conns(&self) -> usize {
410        self.conns.len()
411    }
412
413    pub fn is_complete(&self) -> bool {
414        self.held >= self.size
415    }
416
417    pub fn bytes_held(&self) -> u64 {
418        self.held
419    }
420
421    /// The ranges that are complete on disk, as `(lo, hi)` pairs.
422    ///
423    /// This is the complement of the unassigned set minus what is still in flight, and
424    /// it is what a resume record must contain. Reporting only a byte COUNT is not
425    /// enough: positioned writes land ranges out of order, so "2 MB held" says nothing
426    /// about which 2 MB, and a resume that assumed a contiguous prefix would skip holes
427    /// and silently corrupt the file.
428    pub fn held_ranges(&self) -> Vec<(u64, u64)> {
429        // Start from everything, then subtract what is unassigned and what is
430        // outstanding on a connection; what remains has arrived.
431        let mut done = IntervalSet::full(self.size);
432        for r in self.unassigned.ranges() {
433            done.remove(r.lo, r.hi);
434        }
435        for c in &self.conns {
436            if let Some(r) = c.range {
437                // Bytes before the cursor have arrived; the rest has not.
438                done.remove(c.pos, r.hi);
439            }
440            if let Some(q) = c.queued {
441                done.remove(q.lo, q.hi);
442            }
443        }
444        done.ranges().iter().map(|r| (r.lo, r.hi)).collect()
445    }
446
447    /// Coverage audit: held + outstanding + unassigned == size.
448    ///
449    /// This is a SAFETY invariant and it does NOT imply liveness -- the
450    /// livelock this code is written to avoid (a fully-stolen range leaving a
451    /// connection idle with a non-empty queue) satisfies it at every instant.
452    /// `liveness_holds` is the property that matters.
453    /// The largest measured request setup cost across sources, in seconds.
454    ///
455    /// Exposed because a transport-layer watchdog must express its patience in
456    /// units of what a request actually costs on this path rather than as a
457    /// hardcoded constant: `delta` differs by an order of magnitude between a
458    /// LAN mirror and a TLS connection through a proxy, and a fixed timeout is
459    /// either trigger-happy on the slow path or useless on the fast one.
460    ///
461    /// This is the same quantity the repair deadband is built from
462    /// (`theta = scale * sqrt(delta * T_rem / n)`), so a client that widens
463    /// `delta` widens both together, which is the intended coupling.
464    pub fn worst_delta(&self) -> f64 {
465        self.sources
466            .iter()
467            .map(|s| s.delta_est)
468            .fold(0.0f64, f64::max)
469    }
470
471    /// The configured stall timeout, in seconds.
472    pub fn stall_timeout(&self) -> f64 {
473        self.stall_timeout
474    }
475
476    pub fn coverage_holds(&self) -> bool {
477        let outstanding: u64 = self.conns.iter().map(|c| c.outstanding()).sum();
478        self.held + outstanding + self.unassigned.total() == self.size
479            && self.unassigned.invariant_holds()
480    }
481
482    /// True when some enabled transition strictly decreases the unheld-byte count.
483    /// False means the scheduler is stuck.
484    pub fn liveness_holds(&self) -> bool {
485        if self.is_complete() {
486            return true;
487        }
488        // progress possible if: someone is receiving, or work is assignable,
489        // or a connection holds a queue it can start, or a stall can be reclaimed
490        self.conns.iter().any(|c| c.busy() && !c.stalled)
491            || !self.unassigned.is_empty()
492            || self.conns.iter().any(|c| c.queued.is_some())
493            || self.conns.iter().any(|c| c.stalled)
494    }
495
496    // ---------------------------------------------------------------- input
497
498    /// Record `n` bytes arriving on `conn` at time `now` over `dt` seconds.
499    ///
500    /// Convenience wrapper that assumes the arrival is contiguous at the
501    /// connection's cursor. Real transports must use [`Scheduler::on_bytes_at`]:
502    /// a response still draining from a range that was completed or stolen would
503    /// otherwise be credited against whatever range the connection holds NOW,
504    /// silently advancing a cursor over bytes that never arrived and leaving a
505    /// hole of zeros in the output file.
506    pub fn on_bytes(&mut self, conn: usize, n: u64, now: f64, dt: f64) {
507        let at = self.conns[conn].pos;
508        self.on_bytes_at(conn, at, n, now, dt);
509    }
510
511    /// Record `n` bytes that landed at absolute offset `off`.
512    ///
513    /// Arrivals that do not begin exactly at the connection's cursor are stale
514    /// (they belong to a superseded request) and are discarded: the bytes are
515    /// still written to the file by the transport, but they are not credited,
516    /// so the scheduler's coverage accounting stays exact.
517    pub fn on_bytes_at(&mut self, conn: usize, off: u64, n: u64, now: f64, dt: f64) {
518        let c = &mut self.conns[conn];
519        let Some(r) = c.range else { return };
520        if off != c.pos || off < r.lo {
521            return; // stale arrival from a superseded range
522        }
523        // ---- and stale by TIME, not only by offset --------------------------
524        //
525        // Matching the cursor is not enough to prove an arrival belongs to the
526        // request in flight. When a connection is reclaimed and re-requested, the
527        // new request starts at exactly the cursor the old one stopped at — so
528        // the last writes of the aborted request, still in the caller's queue,
529        // land at precisely the offset the new request is waiting for.
530        //
531        // Crediting them is not a coverage error (the bytes are on disk) but it
532        // desynchronises the connection: the cursor moves past where the new
533        // response begins, so every arrival that response produces fails the test
534        // above and is discarded. The connection then delivers bytes that are
535        // never counted, reads as silent, and is rescued only by the stall
536        // timeout — seconds of dead air, and the transfer visibly frozen for them
537        // once the endgame has left one connection carrying the remainder.
538        //
539        // A request cannot be answered before it was issued, so the arrival's own
540        // timestamp settles it.
541        if now < c.started_at {
542            return;
543        }
544        let room = r.hi.saturating_sub(c.pos);
545        let step = n.min(room);
546        if step == 0 {
547            return;
548        }
549        c.pos += step;
550        self.held += step;
551        c.last_progress = now;
552        c.stalled = false;
553        let src = c.source;
554        self.sources[src].consecutive_stalls = 0;
555        if dt > 0.0 {
556            // Accumulate, and only take a rate sample once the window has enough
557            // wall clock in it to mean something.
558            c.rate_acc_bytes += step;
559            c.rate_acc_dt += dt;
560            if c.rate_acc_dt >= RATE_WINDOW {
561                let sample = c.rate_acc_bytes as f64 / c.rate_acc_dt;
562                c.rate_acc_bytes = 0;
563                c.rate_acc_dt = 0.0;
564                c.detector.observe_rate(sample);
565                c.rate_est = if c.rate_est <= 0.0 {
566                    sample
567                } else {
568                    RATE_ALPHA * sample + (1.0 - RATE_ALPHA) * c.rate_est
569                };
570            }
571        }
572        if c.pos >= r.hi {
573            c.range = None;
574        }
575    }
576
577    /// Suspend a source (429/503 with Retry-After) and reclaim its ranges.
578    pub fn suspend_source(&mut self, src: usize, until: f64) {
579        self.sources[src].suspended_until = until;
580        let idxs: Vec<usize> = (0..self.conns.len())
581            .filter(|&j| self.conns[j].source == src)
582            .collect();
583        for j in idxs {
584            self.reclaim(j);
585        }
586    }
587
588    /// A connection's transport failed: reclaim its range NOW, and hold that
589    /// connection back for `retry_after` seconds.
590    ///
591    /// # Why silence is not the right signal for a failure
592    ///
593    /// The stall timeout exists to grade a connection that is *delivering
594    /// nothing*, and it has to be patient — several seconds at least, scaled to
595    /// the measured setup cost, because a slow path is not a broken one. A fetch
596    /// that has already returned an error needs none of that patience: the
597    /// question the timeout is there to answer has been answered, by the
598    /// transport, definitively.
599    ///
600    /// Without this the two are conflated, and the cost is paid in whole stall
601    /// timeouts. A connection whose socket was closed by the peer, whose body was
602    /// truncated, or whose request was refused looks exactly like a slow one, so
603    /// the range is not re-requested for 4-45 s (the range `stall_timeout` covers
604    /// on real paths). Early in a transfer the other connections cover for it and
605    /// nothing is visible; at the end, when the remaining work has concentrated
606    /// onto one or two connections, the whole transfer freezes for it — the
607    /// reported "downloads stall past 90%, transfer rate falls to zero, every
608    /// connection shows disconnected" failure.
609    ///
610    /// `retry_after` is the caller's backoff for THIS connection only. The range
611    /// goes back to the unassigned set immediately either way, so an idle
612    /// connection can pick it up on the next tick without waiting for it.
613    pub fn on_conn_error(&mut self, conn: usize, now: f64, retry_after: f64) {
614        if conn >= self.conns.len() {
615            return;
616        }
617        self.reclaim(conn);
618        let until = now + retry_after.max(0.0);
619        let c = &mut self.conns[conn];
620        c.setup_end = until;
621        // The stall clock starts when the connection is allowed to work again;
622        // otherwise the backoff it was told to take is charged against it as
623        // silence and it is graded stalled the moment it comes back.
624        c.last_progress = until;
625    }
626
627    fn reclaim(&mut self, j: usize) {
628        let c = &mut self.conns[j];
629        if let Some(r) = c.range {
630            if c.pos < r.hi {
631                let back = Range::new(c.pos, r.hi);
632                c.range = None;
633                let q = c.queued.take();
634                self.unassigned.insert(back);
635                if let Some(q) = q {
636                    self.unassigned.insert(q);
637                }
638                self.stats.reclaims += 1;
639            } else {
640                c.range = None;
641            }
642        } else if let Some(q) = c.queued.take() {
643            self.unassigned.insert(q);
644            self.stats.reclaims += 1;
645        }
646        let c = &mut self.conns[j];
647        c.rate_est = 0.0;
648        c.stalled = true;
649    }
650
651    // ---------------------------------------------------------------- tick
652
653    /// Advance the scheduler. Returns the actions the caller must perform.
654    pub fn tick(&mut self, now: f64) -> Vec<Action> {
655        let mut acts = Vec::new();
656
657        if !self.started {
658            self.initial_split(now, &mut acts);
659            self.started = true;
660            return acts;
661        }
662
663        // ---- feed wall-clock silence to the detectors ----------------------
664        // A connection delivering nothing produces no rate samples at all, so
665        // silence is evidence that only the clock can supply. Grading it here
666        // lets repair pre-empt at half the stall timeout instead of waiting for
667        // the full timeout to expire.
668        for j in 0..self.conns.len() {
669            let c = &self.conns[j];
670            if c.busy() && now >= c.setup_end {
671                let quiet = now - c.last_progress.max(c.setup_end);
672                let st = self.stall_timeout;
673                self.conns[j].detector.observe_silence(quiet, st);
674            }
675        }
676
677        // ---- liveness path 1: reclaim stalled connections -----------------
678        //
679        // Collected into a reused buffer rather than a fresh `Vec` each tick. The
680        // indices cannot be reclaimed in the same pass that finds them — `reclaim`
681        // takes `&mut self` while the filter borrows `self.conns` — so the two-phase
682        // shape stays, but the allocation does not have to. `std::mem::take` moves the
683        // buffer out so the loop below can hold it while `self` is borrowed mutably,
684        // and it is put back at the end for the next tick.
685        let mut stalled = std::mem::take(&mut self.scratch_idx);
686        stalled.clear();
687        stalled.extend((0..self.conns.len()).filter(|&j| {
688            let c = &self.conns[j];
689            c.busy()
690                && now >= c.setup_end
691                && (now - c.last_progress.max(c.setup_end)) > self.stall_timeout
692        }));
693        for j in stalled.drain(..) {
694            self.reclaim(j);
695            acts.push(Action::Cancel { conn: j });
696            // A source that keeps stalling must be suspended, not merely
697            // retried: otherwise work-conserving assignment hands it the same
698            // bytes repeatedly without making forward progress.
699            let src = self.conns[j].source;
700            self.sources[src].consecutive_stalls += 1;
701            let k = self.sources[src].consecutive_stalls;
702            if k >= 2 {
703                let mut backoff = (self.stall_timeout * (1u64 << (k - 2).min(5)) as f64).min(30.0);
704                // Never suspend the LAST usable source for longer than a caller's
705                // watchdog will wait. Exponential backoff is right when there is
706                // somewhere else to send the work; when this is the only source it
707                // is a self-inflicted outage, and a transport that fails on silence
708                // cannot tell it apart from the source being gone.
709                //
710                // Callers should also consult `all_sources_suspended_until` so a
711                // planned pause is not charged against a no-progress deadline. This
712                // clamp is the second line of defence: it keeps the invariant local
713                // to the scheduler, so a caller that does not know about deliberate
714                // suspension still cannot be starved by it.
715                if self.sources.len() == 1 {
716                    backoff = backoff.min(self.stall_timeout.max(1.0));
717                }
718                self.sources[src].suspended_until = now + backoff;
719            }
720        }
721
722        // ---- liveness path 2: an idle connection holding a queue MUST start it
723        //
724        // Mandatory: a connection whose active range was entirely stolen goes
725        // idle WITHOUT completing, so the completion path in on_bytes never fires
726        // and the queued bytes would be owned by an idle connection that never
727        // requests them.
728        for j in 0..self.conns.len() {
729            if !self.conns[j].busy()
730                && self.conns[j].queued.is_some()
731                && now >= self.conns[j].setup_end
732            {
733                let r = self.conns[j].queued.take().unwrap();
734                self.start(j, r, now);
735                acts.push(Action::Request { conn: j, range: r });
736            }
737        }
738
739        // ---- divergence-triggered repair ---------------------------------
740        let theta = self.theta(now);
741        for _ in 0..MAX_REPAIRS_PER_TICK {
742            let Some((vi, ti)) = self.pick_victim_taker(now) else {
743                break;
744            };
745            let (v_eta, t_eta) = (self.conns[vi].eta(), self.conns[ti].eta());
746            // Explicit ordering test: an unknown ETA yields NaN, and a NaN
747            // divergence must NOT trigger a repair (a repair costs a full delta,
748            // so acting on an unmeasured quantity is strictly a loss).
749            if !matches!(
750                (v_eta - t_eta).partial_cmp(&theta),
751                Some(core::cmp::Ordering::Greater)
752            ) {
753                break;
754            }
755            if self.conns[ti].queued.is_some() {
756                break;
757            }
758            let Some(vr) = self.conns[vi].range else {
759                break;
760            };
761            let left = vr.hi.saturating_sub(self.conns[vi].pos) as f64;
762            let rv = self.conns[vi].rate_est;
763            let rt = self.conns[ti].rate_est;
764            let delta = self.sources[self.conns[ti].source].delta_est;
765            // Equalise projected finishes, charging the taker one setup:
766            //   (left - x)/rv == t_eta + delta + x/rt
767            let x = if rv <= 0.0 {
768                // Victim is stalled: hand over everything it has not received.
769                left
770            } else if rt <= 0.0 {
771                0.0
772            } else {
773                ((left / rv - t_eta - delta) * (rv * rt) / (rv + rt)).clamp(0.0, left)
774            };
775            if x <= STEAL_QUANTUM as f64 {
776                break;
777            }
778
779            // ---- does this repair actually pay for itself? -------------------
780            //
781            // The equalisation above solves `(left - x)/rv == t_eta + delta + x/rt`,
782            // which treats `rt` as capacity that `x` bytes can be moved ONTO. That
783            // is true when the connections have independent bottlenecks — separate
784            // mirrors, separate paths. It is false in the case that dominates real
785            // use: several connections to one origin, sharing one bottleneck. There
786            // the taker's rate is not spare capacity, it is a share of the same
787            // capacity the victim is using, so moving bytes across does not make
788            // them arrive faster. It only re-labels which connection carries them,
789            // and charges a setup for the privilege.
790            //
791            // Worse, the per-connection rate divergence that triggers the repair is
792            // largely a property of the PATH, not of the assignment: flows sharing
793            // a bottleneck settle at persistently unequal shares (roughly 1/RTT,
794            // with cwnd history making the asymmetry outlive any round trip). A
795            // repair cannot move that. So the divergence survives the repair, and
796            // re-triggers it.
797            //
798            // The test: compare the makespan now against the makespan after, where
799            // "after" charges the setup and credits only the improvement in the
800            // WORST finishing time — because the makespan is a max, not a sum, and
801            // improving anything other than the laggard buys nothing.
802            let makespan_now =
803                self.conns
804                    .iter()
805                    .map(|c| c.eta())
806                    .fold(0.0f64, |a, b| if b > a { b } else { a });
807            // The victim keeps `left - x` at its own rate; the taker takes on `x`
808            // after paying `delta`, on top of what it already owes.
809            let v_after = if rv > 0.0 {
810                (left - x) / rv
811            } else {
812                f64::INFINITY
813            };
814            let t_after = if rt > 0.0 {
815                t_eta + delta + x / rt
816            } else {
817                f64::INFINITY
818            };
819            // Every other connection is unaffected by this particular exchange.
820            let others = self
821                .conns
822                .iter()
823                .enumerate()
824                .filter(|(j, _)| *j != vi && *j != ti)
825                .map(|(_, c)| c.eta())
826                .fold(0.0f64, |a, b| if b > a { b } else { a });
827            let makespan_after = v_after.max(t_after).max(others);
828            // Require the gain to exceed the setup it costs, not merely to be
829            // positive: a repair that improves the projected makespan by less than
830            // one delta has not accounted for its own price. `theta` above is the
831            // hysteresis that stops oscillation; this is the profitability test,
832            // and both are needed — the first keeps jitter from triggering repair,
833            // the second keeps a real-but-unprofitable divergence from doing so.
834            // Explicit ordering, matching the theta test above: an unmeasured rate
835            // makes this difference NaN, and a NaN must REFUSE the repair rather
836            // than fall through either way. Acting on an unmeasured quantity is
837            // strictly a loss, because the setup cost is certain and the gain is not.
838            if !matches!(
839                (makespan_now - makespan_after).partial_cmp(&delta),
840                Some(core::cmp::Ordering::Greater)
841            ) {
842                break;
843            }
844
845            let x = x as u64;
846            let new_hi = vr.hi - x;
847            let stolen = Range::new(new_hi, vr.hi);
848            // Client-side shrink: the victim's target end moves and the server is
849            // never told. Free on the WIRE — no cancellation, no round trip — but
850            // only if the local fetch loop is told, which is what `Shrink` does.
851            // Without it the victim streams the stolen span anyway; see the
852            // `Action::Shrink` docs for what that costs.
853            self.conns[vi].range = Some(Range::new(vr.lo, new_hi));
854            self.conns[ti].queued = Some(stolen);
855            acts.push(Action::Shrink {
856                conn: vi,
857                hi: new_hi,
858            });
859            self.stats.repairs += 1;
860        }
861
862        // ---- work-conserving assignment (Lemma 2) -------------------------
863        //
864        // A connection above the active limit is DORMANT: it is skipped here, so it
865        // is never given work and never opens a socket. This is the whole mechanism
866        // behind the in-band concurrency ramp — raising the limit makes the next
867        // tick admit the connection through this ordinary path, and lowering it
868        // lets an already-busy connection finish its range and then go quiet, with
869        // no cancellation and no wasted bytes.
870        for j in 0..self.conns.len().min(self.active_limit) {
871            if self.conns[j].busy() || now < self.conns[j].setup_end {
872                continue;
873            }
874            let src = self.conns[j].source;
875            if now < self.sources[src].suspended_until {
876                continue;
877            }
878            // How much to hand this connection.
879            //
880            // `u64::MAX` — take everything — is right once concurrency has settled:
881            // maximal ranges mean the fewest requests, which is the whole point of
882            // range scheduling. It is wrong while the ramp is still growing, because
883            // the first idle connection would swallow the reserve that connections
884            // admitted later are supposed to pick up, and they would be left to
885            // STEAL from it. That is a repair per admission, and the repair
886            // undoes a split that had just been made for no reason.
887            //
888            // So while ramping, hand out a budget-sized share and leave the rest.
889            // The cost of being wrong in this direction is one extra request later —
890            // now nearly free on a pooled connection — against one repair per
891            // admitted connection the other way.
892            let want = if self.active_limit < self.conns.len() {
893                let remaining = self.unassigned.total();
894                let share = remaining / self.conns.len().max(1) as u64;
895                share.max(STEAL_QUANTUM * 4)
896            } else {
897                u64::MAX
898            };
899            if let Some(r) = self.unassigned.take_front(want) {
900                self.start(j, r, now);
901                acts.push(Action::Request { conn: j, range: r });
902                continue;
903            }
904            // Nothing unassigned: steal from the worst laggard.
905            //
906            // This is the steal-half heuristic, and it fires on a DIFFERENT
907            // trigger from the divergence repair above: not "the finishes have
908            // diverged" but "a connection has gone idle and there is nothing left
909            // to give it". Splitting the laggard's remainder down the middle is the
910            // right move when the idle connection has capacity the laggard cannot
911            // use. It is churn when they share one bottleneck — the same span is
912            // re-requested, a setup is paid, and the aggregate rate is unchanged
913            // because it was never the assignment that limited it.
914            //
915            // So the same profitability test applies. An idle connection is not a
916            // reason to move work; it is a reason to ASK whether moving work helps.
917            if let Some(vi) = self.worst_busy(j) {
918                let vr = self.conns[vi].range.unwrap();
919                let left = vr.hi.saturating_sub(self.conns[vi].pos);
920                let half = left / 2;
921                // Will the taker, paying one setup, actually finish this half
922                // sooner than the victim would have finished the whole remainder?
923                // With `rt` unknown (a connection that has just gone idle may have
924                // no estimate yet) fall back to the victim's own rate, which makes
925                // the test neutral rather than optimistic.
926                let rv = self.conns[vi].rate_est;
927                let rt = if self.conns[j].rate_est > 0.0 {
928                    self.conns[j].rate_est
929                } else {
930                    rv
931                };
932                let delta = self.sources[self.conns[j].source].delta_est;
933                let worth_it = if rv <= 0.0 {
934                    // The victim is delivering nothing measurable: anything is better.
935                    true
936                } else if rt <= 0.0 {
937                    false
938                } else {
939                    let before = left as f64 / rv;
940                    let after = (half as f64 / rv).max(delta + half as f64 / rt);
941                    before - after > delta
942                };
943                if half > STEAL_QUANTUM && worth_it {
944                    let new_hi = vr.hi - half;
945                    self.conns[vi].range = Some(Range::new(vr.lo, new_hi));
946                    let stolen = Range::new(new_hi, vr.hi);
947                    // Same shrink discipline as the divergence repair above: the
948                    // victim must be told its far end moved, or it streams the
949                    // half we just handed away.
950                    acts.push(Action::Shrink {
951                        conn: vi,
952                        hi: new_hi,
953                    });
954                    self.start(j, stolen, now);
955                    acts.push(Action::Request {
956                        conn: j,
957                        range: stolen,
958                    });
959                    self.stats.repairs += 1;
960                }
961            }
962            // NOTE: no hedging. Redundant requests waste bandwidth on non-erasure channels.
963        }
964
965        self.stats.bytes_held = self.held;
966        // Hand the scratch buffer back so its capacity survives to the next tick.
967        // Without this the `mem::take` above would leave an empty Vec in the field and
968        // the next tick would allocate again — the reuse would be nominal only.
969        self.scratch_idx = stalled;
970        acts
971    }
972
973    fn start(&mut self, j: usize, r: Range, now: f64) {
974        let delta = self.sources[self.conns[j].source].delta_est;
975        let c = &mut self.conns[j];
976        c.range = Some(r);
977        c.pos = r.lo;
978        c.started_at = now;
979        c.setup_end = now + delta;
980        c.last_progress = now + delta;
981        c.stalled = false;
982        self.stats.requests += 1;
983    }
984
985    fn initial_split(&mut self, now: f64, acts: &mut Vec<Action>) {
986        // Maximal ranges, proportional to rate estimate where known, else equal.
987        //
988        // Only the ACTIVE prefix takes part. With the ramp enabled the transfer
989        // opens one connection, and the rest are admitted by `set_active_limit` as
990        // the in-band search finds them worth their setup cost. Splitting the
991        // object across connections that will not run would strand those bytes in
992        // a quota nobody fetches.
993        let n = self.conns.len().min(self.active_limit);
994        if n == 0 || self.size == 0 {
995            return;
996        }
997        let weights: Vec<f64> = self
998            .conns
999            .iter()
1000            .take(n)
1001            .map(|c| {
1002                let g = self.sources[c.source].gamma_est;
1003                if g > 0.0 {
1004                    g
1005                } else {
1006                    1.0
1007                }
1008            })
1009            .collect();
1010        let total: f64 = weights.iter().sum();
1011
1012        // Split what is ACTUALLY unassigned, not `[0, size)`.
1013        //
1014        // An earlier version partitioned the whole object arithmetically, which
1015        // silently ignored `mark_done`. That broke both features that depend on
1016        // it: `--range` fetched from offset 0 instead of the requested interval,
1017        // and `--continue` re-fetched bytes already on disk. The unassigned set is
1018        // the single source of truth for what remains, so the split must be taken
1019        // from it.
1020        let remaining: Vec<Range> = self.unassigned.ranges().to_vec();
1021        let avail: u64 = remaining.iter().map(|r| r.hi - r.lo).sum();
1022        if avail == 0 {
1023            return;
1024        }
1025        // Per-connection byte quotas, proportional to rate estimate.
1026        //
1027        // Divided over the FULL connection budget, not just the active prefix, and
1028        // this matters specifically when the ramp is running. With one connection
1029        // active, dividing by the active count alone hands that connection the
1030        // entire object — so a connection admitted later finds the unassigned set
1031        // empty and its only route to work is to STEAL, which pays a repair to
1032        // undo a split that should never have been made. Measured cost of getting
1033        // this wrong: every ramped transfer of a 3.15 MB object took ~21 s against
1034        // 6.3 s for fixed concurrency, and several were reported as failures
1035        // despite delivering byte-exact files.
1036        //
1037        // Quotas over the full budget leave the remainder UNASSIGNED, which is
1038        // exactly where a newly admitted connection takes work from through
1039        // ordinary work-conserving assignment — no repair, no steal, no duplicate
1040        // request. If the ramp never grows, nothing is lost: the active connection
1041        // finishes its quota and work-conserving assignment gives it the next
1042        // piece, which connection reuse now makes nearly free.
1043        let budget = self.conns.len().max(1);
1044        let mut quota: Vec<u64> = weights
1045            .iter()
1046            .map(|w| ((w / total) * (avail as f64 / budget as f64) * n as f64) as u64)
1047            .collect();
1048        // Rounding must not strand bytes — but only when every connection is
1049        // active. While ramping, the unclaimed remainder is deliberate.
1050        if n >= budget {
1051            let assigned: u64 = quota.iter().sum();
1052            if let Some(last) = quota.last_mut() {
1053                *last += avail.saturating_sub(assigned);
1054            }
1055        }
1056
1057        // Walk the unassigned ranges, carving each connection's quota out of them
1058        // in order. A connection may receive a range that is not contiguous with
1059        // its neighbours' — that is fine, since ranges are independent requests.
1060        let mut it = remaining.into_iter();
1061        let mut cur = it.next();
1062        for (j, want_total) in quota.iter().enumerate() {
1063            let mut want = *want_total;
1064            while want > 0 {
1065                let Some(seg) = cur else { break };
1066                let take = want.min(seg.hi - seg.lo);
1067                let r = Range::new(seg.lo, seg.lo + take);
1068                // A connection holds one active range plus a one-slot pipeline.
1069                // Anything beyond that stays UNASSIGNED rather than being stashed:
1070                // work-conserving assignment will hand it out as connections free
1071                // up, and leaving it in the set is what keeps the coverage
1072                // invariant checkable.
1073                if self.conns[j].range.is_none() {
1074                    self.unassigned.remove(r.lo, r.hi);
1075                    self.start(j, r, now);
1076                    acts.push(Action::Request { conn: j, range: r });
1077                } else if self.conns[j].queued.is_none() {
1078                    self.unassigned.remove(r.lo, r.hi);
1079                    self.conns[j].queued = Some(r);
1080                } else {
1081                    break;
1082                }
1083                want -= take;
1084                cur = if seg.hi - seg.lo > take {
1085                    Some(Range::new(seg.lo + take, seg.hi))
1086                } else {
1087                    it.next()
1088                };
1089            }
1090        }
1091    }
1092
1093    /// The current repair deadband, in seconds. Exposed for measurement.
1094    pub fn theta_now(&self, now: f64) -> f64 {
1095        self.theta(now)
1096    }
1097
1098    fn theta(&self, now: f64) -> f64 {
1099        // One fold, no allocation. This is called from the tick loop — 50 times a
1100        // second at the default 20 ms tick, for the whole transfer — and it collected
1101        // a `Vec<&Conn>` on every call only to take its length and sum one field.
1102        // Nothing here needs the intermediate collection.
1103        let (live_count, agg) = self
1104            .conns
1105            .iter()
1106            .filter(|c| now >= self.sources[c.source].suspended_until)
1107            .fold((0usize, 0.0f64), |(k, sum), c| {
1108                (k + 1, sum + c.rate_est.max(0.0))
1109            });
1110        let n = live_count.max(1) as f64;
1111        let agg = if agg > 0.0 { agg } else { 1.0 };
1112        let remaining = self.size.saturating_sub(self.held) as f64;
1113        let t_rem = remaining / agg;
1114        let delta = self
1115            .sources
1116            .iter()
1117            .map(|s| s.delta_est)
1118            .fold(0.0f64, f64::max);
1119        let band = self.theta_scale * (delta * t_rem.max(0.0) / n).sqrt();
1120
1121        // ---- floor the deadband at what a repair actually costs --------------
1122        //
1123        // `sqrt(delta * T_rem / n)` is the right SHAPE — it is the granularity
1124        // trade-off — but it is unbounded below, and it approaches zero from two
1125        // directions that both make repair a worse idea, not a better one:
1126        // `T_rem` shrinks as the transfer finishes, and `n` grows with
1127        // concurrency. So the deadband is narrowest exactly when a repair has the
1128        // least remaining time to earn its cost back and the most competitors to
1129        // pay it against.
1130        //
1131        // Measured on the shared-bottleneck harness (examples/storm.rs, 12 seeds):
1132        // theta reached 0.061-0.081 s against a delta of 0.12 s. Every repair
1133        // triggered in that regime spends one full setup to recover a divergence
1134        // smaller than the setup — a guaranteed loss, taken deliberately, dozens
1135        // of times per transfer.
1136        //
1137        // A repair cannot be worth making unless the divergence it corrects
1138        // exceeds what correcting it costs, so `delta` is the floor. This is not a
1139        // tuning constant: it is the break-even point, and it is measured per
1140        // source rather than guessed, so a high-RTT path widens it automatically.
1141        band.max(delta)
1142    }
1143
1144    fn pick_victim_taker(&self, now: f64) -> Option<(usize, usize)> {
1145        // Victim ranking is (health, ETA), health first. A connection the
1146        // detector has graded Suspect is a victim even when its *projected* ETA
1147        // still looks acceptable -- which is the whole point of detecting a
1148        // collapse early, since the ETA is computed from a rate estimate that
1149        // the collapse has not yet dragged down.
1150        let mut victim: Option<(usize, crate::detect::Health, f64)> = None;
1151        let mut taker: Option<(usize, f64)> = None;
1152        // Dormant connections (above the active limit) are excluded from BOTH
1153        // roles. As taker, admitting one would open a socket the concurrency ramp
1154        // has not yet justified — quietly defeating the limit through the repair
1155        // path. As victim, one cannot be: it holds no range.
1156        for j in 0..self.conns.len().min(self.active_limit) {
1157            let c = &self.conns[j];
1158            if now < c.setup_end || now < self.sources[c.source].suspended_until {
1159                continue;
1160            }
1161            let e = c.eta();
1162            let h = if self.health_ranking {
1163                c.detector.health()
1164            } else {
1165                crate::detect::Health::Healthy
1166            };
1167            if c.busy() && victim.map(|(_, vh, ve)| (h, e) > (vh, ve)).unwrap_or(true) {
1168                victim = Some((j, h, e));
1169            }
1170            // A degraded connection must never be chosen as the TAKER: handing
1171            // work to a collapsing connection is the failure mode this whole
1172            // mechanism exists to prevent.
1173            if !h.is_suspect_or_worse() && taker.map(|(_, te)| e < te).unwrap_or(true) {
1174                taker = Some((j, e));
1175            }
1176        }
1177        let (vi, _, _) = victim?;
1178        let (ti, _) = taker?;
1179        if vi == ti {
1180            return None;
1181        }
1182        Some((vi, ti))
1183    }
1184
1185    fn worst_busy(&self, exclude: usize) -> Option<usize> {
1186        let mut best: Option<(usize, u64)> = None;
1187        for j in 0..self.conns.len() {
1188            if j == exclude {
1189                continue;
1190            }
1191            let c = &self.conns[j];
1192            if !c.busy() {
1193                continue;
1194            }
1195            let left = c.range.unwrap().hi.saturating_sub(c.pos);
1196            if best.map(|(_, bl)| left > bl).unwrap_or(true) {
1197                best = Some((j, left));
1198            }
1199        }
1200        best.map(|(j, _)| j)
1201    }
1202}
1203
1204/// Greedy concurrency allocation across multiple sources.
1205pub fn greedy_concurrency(
1206    rho: &[f64],
1207    gamma: &[f64],
1208    access_cap: f64,
1209    budget: usize,
1210) -> Vec<usize> {
1211    let m = rho.len();
1212    let mut n = vec![0usize; m];
1213    let g = |n: &[usize]| -> f64 {
1214        let sum: f64 = (0..m).map(|i| rho[i].min(n[i] as f64 * gamma[i])).sum();
1215        sum.min(access_cap)
1216    };
1217    let mut cur = g(&n);
1218    for _ in 0..budget {
1219        let mut best = (0usize, 0.0f64);
1220        for i in 0..m {
1221            n[i] += 1;
1222            let gain = g(&n) - cur;
1223            n[i] -= 1;
1224            if gain > best.1 {
1225                best = (i, gain);
1226            }
1227        }
1228        if best.1 <= 0.0 {
1229            break; // saturated: further connections are pure cost
1230        }
1231        n[best.0] += 1;
1232        cur += best.1;
1233    }
1234    n
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239    use super::*;
1240
1241    fn src(gamma: f64) -> Source {
1242        Source {
1243            gamma_est: gamma,
1244            delta_est: 0.05,
1245            ..Default::default()
1246        }
1247    }
1248
1249    /// An arrival from a request that has already been superseded must not be
1250    /// credited against the request that replaced it.
1251    ///
1252    /// The bytes are real and on disk, so crediting them looks harmless — but it
1253    /// advances the cursor past where the NEW request starts reading, and every
1254    /// arrival from that request then fails the `off == pos` test and is
1255    /// discarded. The connection delivers bytes the scheduler never counts, so it
1256    /// reads as silent and is only rescued by the stall timeout, seconds later.
1257    /// That is the same dead air the transport's error handling exists to remove,
1258    /// reintroduced through the arrival path.
1259    #[test]
1260    fn a_late_arrival_from_a_superseded_request_is_not_credited() {
1261        let mut s = Scheduler::new(1000, vec![src(1.0)], &[1]);
1262        s.tick(0.0);
1263        assert_eq!(s.conn_range(0), Some((0, 0, 1000)));
1264        // 100 bytes land and are credited.
1265        s.on_bytes_at(0, 0, 100, 1.0, 0.5);
1266        assert_eq!(s.bytes_held(), 100);
1267        // The connection is reclaimed and re-requested from where it got to.
1268        s.on_conn_error(0, 9.0, 0.0);
1269        let acts = s.tick(10.0);
1270        assert!(
1271            matches!(acts.as_slice(), [Action::Request { conn: 0, range }] if range.lo == 100),
1272            "the reclaimed remainder must be re-requested from 100: {acts:?}"
1273        );
1274        // Now the aborted request's last write arrives, timestamped BEFORE the new
1275        // request was issued.
1276        s.on_bytes_at(0, 100, 50, 9.5, 0.1);
1277        assert_eq!(
1278            s.bytes_held(),
1279            100,
1280            "an arrival older than the request in flight was credited to it"
1281        );
1282        // And the new request's own first arrival, at the same offset, must land.
1283        s.on_bytes_at(0, 100, 50, 10.2, 0.1);
1284        assert_eq!(
1285            s.bytes_held(),
1286            150,
1287            "the live request's arrival was discarded as stale"
1288        );
1289    }
1290
1291    #[test]
1292    fn initial_split_covers_exactly() {
1293        let mut s = Scheduler::new(1000, vec![src(1.0), src(1.0)], &[1, 1]);
1294        let acts = s.tick(0.0);
1295        assert_eq!(acts.len(), 2);
1296        assert!(s.coverage_holds());
1297        assert!(s.unassigned.is_empty());
1298    }
1299
1300    #[test]
1301    fn coverage_and_liveness_hold_through_a_transfer() {
1302        let mut s = Scheduler::new(1_000_000, vec![src(1e5), src(5e4)], &[2, 2]);
1303        let mut now = 0.0;
1304        for _ in 0..4000 {
1305            s.tick(now);
1306            for j in 0..s.n_conns() {
1307                s.on_bytes(j, 500, now, 0.01);
1308            }
1309            assert!(s.coverage_holds(), "coverage broke at t={now}");
1310            assert!(s.liveness_holds(), "stuck at t={now}");
1311            now += 0.01;
1312            if s.is_complete() {
1313                break;
1314            }
1315        }
1316        assert!(
1317            s.is_complete(),
1318            "did not finish: {} / {}",
1319            s.bytes_held(),
1320            1_000_000
1321        );
1322    }
1323
1324    #[test]
1325    fn fully_stolen_range_does_not_livelock() {
1326        // Regression: a connection whose active range is stolen down to its
1327        // current position goes idle WITHOUT completing. If the queue-start
1328        // path is missing, its queued bytes are never requested.
1329        let mut s = Scheduler::new(200_000, vec![src(1e5), src(1e5)], &[1, 1]);
1330        s.tick(0.0);
1331        // conn 0 makes progress, conn 1 stalls entirely
1332        let mut now = 0.06;
1333        for _ in 0..50 {
1334            s.on_bytes(0, 1000, now, 0.01);
1335            now += 0.01;
1336            s.tick(now);
1337        }
1338        // force a steal by making conn 1 look terrible, then run to completion
1339        for _ in 0..20000 {
1340            s.tick(now);
1341            s.on_bytes(0, 1000, now, 0.01);
1342            now += 0.01;
1343            assert!(s.liveness_holds(), "livelocked at t={now}");
1344            if s.is_complete() {
1345                break;
1346            }
1347        }
1348        assert!(s.is_complete());
1349    }
1350
1351    #[test]
1352    fn stall_reclaim_returns_bytes() {
1353        let mut s = Scheduler::new(100_000, vec![src(1e5), src(1e5)], &[1, 1]);
1354        s.tick(0.0);
1355        let before = s.stats.reclaims;
1356        // no bytes at all: both connections must be reclaimed after the timeout
1357        let acts = s.tick(5.0);
1358        assert!(s.stats.reclaims > before);
1359        assert!(acts.iter().any(|a| matches!(a, Action::Cancel { .. })));
1360        assert!(s.coverage_holds());
1361        assert!(s.liveness_holds());
1362    }
1363
1364    #[test]
1365    fn suspend_source_reclaims_and_reassigns() {
1366        let mut s = Scheduler::new(100_000, vec![src(1e5), src(1e5)], &[1, 1]);
1367        s.tick(0.0);
1368        s.suspend_source(0, 10.0);
1369        // Reclaimed bytes are now unassigned. They are NOT reassigned instantly:
1370        // the surviving connection is still streaming its own range, and taking
1371        // work from it would violate nothing but achieve nothing either. Work
1372        // conservation only requires that no connection sit IDLE while work
1373        // remains -- so the reassignment happens when conn 1 next goes idle.
1374        assert!(s.coverage_holds());
1375        assert!(s.unassigned.total() > 0);
1376
1377        let mut now = 0.2;
1378        let mut served_by_1 = false;
1379        for _ in 0..20_000 {
1380            let acts = s.tick(now);
1381            if acts
1382                .iter()
1383                .any(|a| matches!(a, Action::Request { conn, .. } if s.conns[*conn].source == 1))
1384            {
1385                served_by_1 = true;
1386            }
1387            s.on_bytes(1, 1000, now, 0.01);
1388            now += 0.01;
1389            assert!(s.coverage_holds());
1390            assert!(s.liveness_holds());
1391            if s.is_complete() {
1392                break;
1393            }
1394        }
1395        assert!(
1396            served_by_1,
1397            "surviving source never picked up the reclaimed work"
1398        );
1399        assert!(s.is_complete(), "held {} of 100000", s.bytes_held());
1400    }
1401
1402    #[test]
1403    fn greedy_matches_exhaustive_small() {
1404        // rho/gamma chosen so the optimum is interior
1405        let rho = [2.2e6, 1.1e6, 0.7e6];
1406        let gam = [0.55e6, 0.45e6, 0.35e6];
1407        let cap = 5.0e6;
1408        for budget in 1..10usize {
1409            let n = greedy_concurrency(&rho, &gam, cap, budget);
1410            let g = |n: &[usize]| -> f64 {
1411                let s: f64 = (0..3).map(|i| rho[i].min(n[i] as f64 * gam[i])).sum();
1412                s.min(cap)
1413            };
1414            let mut best = 0.0f64;
1415            for a in 0..=budget {
1416                for b in 0..=budget {
1417                    for c in 0..=budget {
1418                        if a + b + c <= budget {
1419                            best = best.max(g(&[a, b, c]));
1420                        }
1421                    }
1422                }
1423            }
1424            assert!(
1425                (g(&n) - best).abs() < 1.0,
1426                "budget {budget}: greedy {} vs {}",
1427                g(&n),
1428                best
1429            );
1430        }
1431    }
1432
1433    #[test]
1434    fn saturation_stops_allocation() {
1435        // one source, rho = 2*gamma: two connections saturate it
1436        let n = greedy_concurrency(&[2.0e6], &[1.0e6], 1e9, 10);
1437        assert_eq!(
1438            n[0], 2,
1439            "allocated {n:?}, expected exactly the saturation point"
1440        );
1441    }
1442    /// The detector must make the SCHEDULER act sooner, not merely grade sooner.
1443    ///
1444    /// A connection collapsing to 3% of its rate must be chosen as a repair
1445    /// victim well before the stall timeout would have reclaimed it. Without
1446    /// health-ranked victim selection the scheduler waits for the projected ETA
1447    /// to drift, which is the fixed detection cost measured at 0.25-0.9 s.
1448    #[test]
1449    fn collapsed_connection_becomes_a_repair_victim_before_the_stall_timeout() {
1450        const S: u64 = 40_000_000;
1451        let mut sc = Scheduler::new(S, vec![src(4e6), src(4e6)], &[1, 1]).with_stall_timeout(10.0);
1452        sc.tick(0.0);
1453        let mut now = 0.0;
1454        // Both healthy for a while.
1455        for _ in 0..12 {
1456            now += 0.1;
1457            sc.on_bytes(0, 400_000, now, 0.1);
1458            sc.on_bytes(1, 400_000, now, 0.1);
1459            sc.tick(now);
1460        }
1461        assert_eq!(sc.conn_health(0), crate::detect::Health::Healthy);
1462
1463        // Connection 0 collapses; connection 1 keeps its rate.
1464        let mut flagged_at = None;
1465        for _ in 0..8 {
1466            now += 0.1;
1467            sc.on_bytes(0, 12_000, now, 0.1);
1468            sc.on_bytes(1, 400_000, now, 0.1);
1469            sc.tick(now);
1470            if flagged_at.is_none() && sc.conn_health(0).is_suspect_or_worse() {
1471                flagged_at = Some(now);
1472            }
1473        }
1474        let t = flagged_at.expect("collapse must be graded");
1475        assert!(
1476            t < 1.2 + 10.0,
1477            "must be flagged well before the 10 s stall timeout, was {t}"
1478        );
1479        // And the healthy connection must never be the one downgraded.
1480        assert_eq!(
1481            sc.conn_health(1),
1482            crate::detect::Health::Healthy,
1483            "the connection holding its rate must stay Healthy"
1484        );
1485        assert!(sc.coverage_holds() && sc.liveness_holds());
1486    }
1487    /// The repair deadband must never fall below what a repair costs.
1488    ///
1489    /// `theta = scale*sqrt(delta*T_rem/n)` has the right shape but is unbounded
1490    /// below, and it approaches zero from two directions that both make repair a
1491    /// worse idea: `T_rem` shrinks as the transfer ends, `n` grows with
1492    /// concurrency. Measured on the shared-bottleneck harness, theta reached
1493    /// 0.061-0.081 s against a delta of 0.12 s — so the scheduler was spending a
1494    /// 0.12 s setup to recover a 0.06 s divergence, dozens of times per transfer.
1495    #[test]
1496    fn the_repair_deadband_never_drops_below_one_setup_cost() {
1497        const S: u64 = 8_000_000;
1498        const D: f64 = 0.12;
1499        let mk = |n: usize| {
1500            let sources = vec![Source {
1501                gamma_est: 1.4e6 / n as f64,
1502                delta_est: D,
1503                ..Default::default()
1504            }];
1505            Scheduler::new(S, sources, &[n])
1506        };
1507        // Sweep concurrency and progress: both drive theta down.
1508        for &n in &[1usize, 2, 4, 8, 16, 64] {
1509            let mut sc = mk(n);
1510            sc.tick(0.0);
1511            let mut now = 0.0;
1512            // Deliver most of the object, so T_rem — and with it the unfloored
1513            // band — becomes small.
1514            for _ in 0..60 {
1515                now += 0.05;
1516                for j in 0..n {
1517                    if sc.conn_range(j).is_some() {
1518                        sc.on_bytes(j, 100_000 / n as u64, now, 0.05);
1519                    }
1520                }
1521                sc.tick(now);
1522                let th = sc.theta_now(now);
1523                assert!(
1524                    th >= D - 1e-12,
1525                    "theta {th} fell below delta {D} at n={n}, progress {}/{S}: \
1526                     the scheduler would pay a full setup to recover a smaller divergence",
1527                    sc.bytes_held()
1528                );
1529            }
1530        }
1531    }
1532
1533    /// A stable unequal split settles after ONE equalisation; a collapse still
1534    /// gets answered.
1535    ///
1536    /// These two assertions are one test on purpose. Suppressing spurious repair is
1537    /// trivial in isolation — never repair — and that would be a regression, not a
1538    /// fix: the mechanism exists for the mirror that dies mid-transfer. The
1539    /// property worth pinning is the DISCRIMINATION between the two cases.
1540    ///
1541    /// # What this test does NOT cover
1542    ///
1543    /// It does not reproduce the repair storm, and no test in this crate can. The
1544    /// storm was a feedback loop between the scheduler and the transport: a repair
1545    /// shrank the victim's range, the victim's socket kept streaming the span
1546    /// anyway, the duplicate traffic slowed the honest connections, and that
1547    /// slowdown re-diverged the finish times into another repair. The core cannot
1548    /// see any of that — it has no sockets — so it cannot close the loop. Feeding
1549    /// it a stable unequal split, as here, correctly produces exactly one repair
1550    /// (equalising a persistent 60/40 asymmetry IS profitable) and then stops.
1551    ///
1552    /// The loop itself is tested where it lives, against a served-byte count at the
1553    /// origin: `hydra-net/tests/shrink_e2e.rs`.
1554    #[test]
1555    fn a_stable_unequal_split_settles_and_a_collapse_is_still_answered() {
1556        const S: u64 = 40_000_000;
1557        let src4 = || Source {
1558            gamma_est: 2e6,
1559            delta_est: 0.12,
1560            ..Default::default()
1561        };
1562
1563        // --- stationary: two connections at persistently unequal but stable shares.
1564        // This is what flows sharing one bottleneck look like (share ~ 1/RTT), and
1565        // no repair can change it — the asymmetry is a property of the path.
1566        let mut sc = Scheduler::new(S, vec![src4(), src4()], &[1, 1]);
1567        sc.tick(0.0);
1568        let mut now = 0.0;
1569        for k in 0..60 {
1570            now += 0.1;
1571            // 60/40 split, with a little jitter, conserving the aggregate.
1572            let wobble = if k % 3 == 0 { 12_000 } else { -8_000 };
1573            sc.on_bytes(0, (240_000i64 + wobble) as u64, now, 0.1);
1574            sc.on_bytes(1, (160_000i64 - wobble) as u64, now, 0.1);
1575            sc.tick(now);
1576        }
1577        // One equalisation is correct here and the scheduler must then SETTLE: the
1578        // 60/40 share ratio is a property of the path, so re-equalising cannot
1579        // improve it and every further repair is a pure setup cost. 60 ticks over
1580        // 6 s of simulated transfer would be ample room for a storm.
1581        let stationary_repairs = sc.stats.repairs;
1582        assert!(
1583            stationary_repairs <= 1,
1584            "a stable unequal split provoked {stationary_repairs} repairs over 60 \
1585             ticks; one equalisation is profitable, repeated ones only pay setups"
1586        );
1587
1588        // --- collapse: connection 0 drops to 2% and stays there.
1589        let mut sc = Scheduler::new(S, vec![src4(), src4()], &[1, 1]);
1590        sc.tick(0.0);
1591        let mut now = 0.0;
1592        for _ in 0..20 {
1593            now += 0.1;
1594            sc.on_bytes(0, 200_000, now, 0.1);
1595            sc.on_bytes(1, 200_000, now, 0.1);
1596            sc.tick(now);
1597        }
1598        let before = sc.stats.repairs;
1599        for _ in 0..40 {
1600            now += 0.1;
1601            sc.on_bytes(0, 4_000, now, 0.1);
1602            sc.on_bytes(1, 200_000, now, 0.1);
1603            sc.tick(now);
1604        }
1605        assert!(
1606            sc.stats.repairs > before,
1607            "a connection collapsing to 2% of its rate produced no repair: the \
1608             profitability test is suppressing the case repair exists for"
1609        );
1610        assert!(sc.coverage_holds() && sc.liveness_holds());
1611    }
1612
1613    /// A sole source must never be suspended past a caller's patience.
1614    ///
1615    /// Exponential backoff is right when work can go somewhere else. With one source
1616    /// it is a self-inflicted outage: nothing can move until the suspension expires,
1617    /// and a transport whose watchdog fails on silence cannot distinguish that from
1618    /// the source being gone.
1619    ///
1620    /// The numbers that made this real: `stall_timeout` 4.0s gives the transport a
1621    /// no-progress deadline of `4 * (4.0 + delta)` = 16.2s, while five consecutive
1622    /// stalls suspended the sole source for `min(4.0 * 2^3, 30)` = 30s. Measured on a
1623    /// 121.7 MiB GitHub release asset, 4 of 8 multi-connection runs aborted with a
1624    /// digest mismatch — three holding 126.9-127.0 MB of 127.6 MB, killed during a
1625    /// deliberate backoff over the final half-megabyte.
1626    #[test]
1627    fn a_sole_source_is_never_suspended_longer_than_its_stall_timeout() {
1628        const S: u64 = 8_000_000;
1629        let st = 4.0;
1630        let mut sc = Scheduler::new(S, vec![src(4e6)], &[4]).with_stall_timeout(st);
1631        sc.tick(0.0);
1632
1633        // Drive it through many consecutive stalls, which is what escalates backoff.
1634        let mut now = 0.0;
1635        let mut worst_suspension = 0.0f64;
1636        for _ in 0..12 {
1637            now += st * 1.5;
1638            sc.tick(now);
1639            if let Some(until) = sc.all_sources_suspended_until(now) {
1640                worst_suspension = worst_suspension.max(until - now);
1641            }
1642        }
1643        assert!(
1644            worst_suspension <= st.max(1.0) + 1e-9,
1645            "sole source suspended for {worst_suspension:.1}s against a {st:.1}s stall \
1646             timeout: a caller's no-progress watchdog will kill the transfer during a \
1647             pause the scheduler chose"
1648        );
1649    }
1650
1651    /// Ramping concurrency must find work WAITING, not have to steal it.
1652    ///
1653    /// With the ramp enabled the transfer starts with one connection active. If the
1654    /// initial split gives that connection the whole object, every connection
1655    /// admitted afterwards finds the unassigned set empty and its only route to
1656    /// work is a steal — paying a repair to undo a split that should not have been
1657    /// made. Measured cost of that mistake on a live 3.15 MB transfer: ~21 s
1658    /// against 6.3 s for fixed concurrency, with several runs reported as failures
1659    /// despite delivering byte-exact files.
1660    ///
1661    /// The invariant: while the active limit is below the connection budget, some
1662    /// work stays unassigned, and raising the limit produces `Request` actions
1663    /// rather than repairs.
1664    #[test]
1665    fn a_ramping_transfer_finds_unassigned_work_instead_of_stealing() {
1666        const S: u64 = 40_000_000;
1667        let sources = vec![Source {
1668            gamma_est: 2e6,
1669            delta_est: 0.05,
1670            ..Default::default()
1671        }];
1672        let mut sc = Scheduler::new(S, sources, &[8]).with_active_limit(1);
1673        let acts = sc.tick(0.0);
1674        assert_eq!(
1675            acts.iter()
1676                .filter(|a| matches!(a, Action::Request { .. }))
1677                .count(),
1678            1,
1679            "only the active connection may be given work"
1680        );
1681        assert!(
1682            !sc.unassigned_is_empty(),
1683            "the whole object was handed to one connection: connections admitted \
1684             later can only steal, which costs a repair each"
1685        );
1686
1687        // Deliver some bytes, then admit more connections as the ramp would.
1688        let mut now = 0.0;
1689        for _ in 0..5 {
1690            now += 0.1;
1691            sc.on_bytes(0, 200_000, now, 0.1);
1692            sc.tick(now);
1693        }
1694        let repairs_before = sc.stats.repairs;
1695        sc.set_active_limit(4);
1696        now += 0.1;
1697        let acts = sc.tick(now);
1698        let reqs = acts
1699            .iter()
1700            .filter(|a| matches!(a, Action::Request { .. }))
1701            .count();
1702        assert!(
1703            reqs >= 3,
1704            "admitting 3 connections produced {reqs} requests: they are not being \
1705             given the reserved work"
1706        );
1707        assert_eq!(
1708            sc.stats.repairs, repairs_before,
1709            "admitting a connection must not cost a repair"
1710        );
1711        assert!(sc.coverage_holds() && sc.liveness_holds());
1712    }
1713
1714    /// Every range shrink must be ANNOUNCED, not just performed.
1715    ///
1716    /// Regression test for the repair storm. The scheduler used to move
1717    /// `conns[victim].range` and emit nothing, so the transport's fetch loop —
1718    /// which tests `off < hi` against the bound it captured at request time —
1719    /// went on pulling the span that had just been handed to another connection.
1720    /// Both connections then fetched the same bytes over the same bottleneck, the
1721    /// resulting slowdown read as fresh divergence, and that triggered further
1722    /// repairs: measured at 32-49 repairs on a stationary 5.3 MB transfer whose
1723    /// correct repair count is zero, for ~2.2x the fluid optimum.
1724    ///
1725    /// The invariant is therefore stronger than "a repair happened": for every
1726    /// repair counted, the victim whose far end moved must appear in a `Shrink`
1727    /// carrying the new bound. A caller cannot honour what it is not told.
1728    #[test]
1729    fn every_repair_announces_the_victims_new_far_end() {
1730        const S: u64 = 40_000_000;
1731        let mut sc = Scheduler::new(S, vec![src(4e6), src(4e6)], &[1, 1]).with_stall_timeout(10.0);
1732        sc.tick(0.0);
1733        let mut now = 0.0;
1734        for _ in 0..12 {
1735            now += 0.1;
1736            sc.on_bytes(0, 400_000, now, 0.1);
1737            sc.on_bytes(1, 400_000, now, 0.1);
1738            sc.tick(now);
1739        }
1740
1741        // Collapse connection 0 so a divergence repair becomes correct to make.
1742        let mut shrinks: Vec<(usize, u64)> = Vec::new();
1743        let mut repairs_before = sc.stats.repairs;
1744        let mut saw_repair = false;
1745        for _ in 0..25 {
1746            now += 0.1;
1747            sc.on_bytes(0, 4_000, now, 0.1);
1748            sc.on_bytes(1, 400_000, now, 0.1);
1749            // Snapshot each victim's far end before the tick that may move it.
1750            let before: Vec<Option<u64>> = (0..sc.n_conns())
1751                .map(|j| sc.conn_range(j).map(|(_, _, hi)| hi))
1752                .collect();
1753            let acts = sc.tick(now);
1754            for a in &acts {
1755                if let Action::Shrink { conn, hi } = a {
1756                    shrinks.push((*conn, *hi));
1757                    // The announced bound must be the one actually installed, and
1758                    // it must be a genuine reduction — never a raise, which would
1759                    // hand out bytes another connection may already hold.
1760                    assert_eq!(
1761                        sc.conn_range(*conn).map(|(_, _, h)| h),
1762                        Some(*hi),
1763                        "announced bound must match the installed one"
1764                    );
1765                    if let Some(Some(b)) = before.get(*conn) {
1766                        assert!(*hi <= *b, "a shrink must lower the far end: {b} -> {hi}");
1767                    }
1768                }
1769            }
1770            if sc.stats.repairs > repairs_before {
1771                saw_repair = true;
1772                assert!(
1773                    !shrinks.is_empty(),
1774                    "a repair was counted with no Shrink announced: the victim's \
1775                     socket would keep streaming the stolen span"
1776                );
1777                repairs_before = sc.stats.repairs;
1778            }
1779        }
1780        assert!(saw_repair, "the scenario must produce at least one repair");
1781        assert!(sc.coverage_holds() && sc.liveness_holds());
1782    }
1783
1784    /// The initial split must respect `mark_done`.
1785    ///
1786    /// Regression test: an earlier version partitioned `[0, size)` arithmetically
1787    /// and never consulted the unassigned set, so `mark_done` was silently
1788    /// ignored. That broke `--range` (fetched from offset 0 instead of the
1789    /// requested interval) and `--continue` (re-fetched bytes already on disk).
1790    #[test]
1791    fn initial_split_never_requests_bytes_marked_done() {
1792        let size = 100_000u64;
1793        let mut s = Scheduler::new(size, vec![src(1e6), src(1e6)], &[1, 1]);
1794        // Range mode: only [90_000, 90_512) is wanted.
1795        s.mark_done(0, 90_000);
1796        s.mark_done(90_512, size);
1797        let acts = s.tick(0.0);
1798        assert!(
1799            !acts.is_empty(),
1800            "the wanted interval must still be requested"
1801        );
1802        for a in &acts {
1803            if let Action::Request { range, .. } = a {
1804                assert!(
1805                    range.lo >= 90_000 && range.hi <= 90_512,
1806                    "requested {range:?} outside the wanted interval"
1807                );
1808            }
1809        }
1810        assert!(s.coverage_holds());
1811    }
1812
1813    /// Overlapping `mark_done` calls must not inflate the held count.
1814    ///
1815    /// Regression test for a silent truncation. `mark_done` credited the width of
1816    /// the span it was given rather than the bytes it actually claimed, so two
1817    /// callers marking the same prefix — a `-c` resume replaying its sidecar, and
1818    /// the concurrency probe reporting the bytes it fetched, both of which start
1819    /// at offset 0 — pushed `held` past the object's real length. `is_complete()`
1820    /// tests exactly that counter, so the transfer stopped believing it was
1821    /// finished and left a zero-filled hole in the tail of a file it reported as
1822    /// a success: measured at 240 138 unwritten bytes on an 11 200 900-byte
1823    /// object whose gzip then refused to decompress.
1824    #[test]
1825    fn overlapping_mark_done_credits_each_byte_once() {
1826        let size = 100_000u64;
1827        let mut s = Scheduler::new(size, vec![src(1e6)], &[1]);
1828        s.mark_done(0, 30_000); // a resume record
1829        s.mark_done(0, 10_000); // the probe, re-reporting part of the same prefix
1830        assert_eq!(
1831            s.bytes_held(),
1832            30_000,
1833            "the overlap must be credited once, not twice"
1834        );
1835        assert!(!s.is_complete(), "70 000 bytes are still missing");
1836
1837        // Marking every byte, in overlapping pieces, is completion — and exactly
1838        // completion, never more.
1839        s.mark_done(20_000, size);
1840        s.mark_done(0, size);
1841        assert_eq!(s.bytes_held(), size);
1842        assert!(s.is_complete());
1843    }
1844
1845    /// After the probe's ranges are marked, `held_ranges` must describe them.
1846    ///
1847    /// This is what the pre-transfer checkpoint writes into the sidecar, so that a
1848    /// ^C during or shortly after the concurrency probe does not discard bytes the
1849    /// probe already fetched at true offsets. The periodic checkpoint inside the
1850    /// transfer only fires after 2 seconds, which an early interrupt beats.
1851    #[test]
1852    fn held_ranges_reports_probe_bytes_before_any_transfer() {
1853        let size = 11_200_900u64;
1854        let mut s = Scheduler::new(size, vec![Source::default()], &[1]);
1855        // Nothing fetched yet: nothing to checkpoint, and an empty record must not
1856        // be written as though it were progress.
1857        assert!(s.held_ranges().is_empty());
1858
1859        // The probe fetched a 3 MiB prefix into the real output.
1860        s.mark_done(0, 3 << 20);
1861        assert_eq!(s.held_ranges(), vec![(0, 3 << 20)]);
1862        assert_eq!(s.bytes_held(), 3 << 20);
1863
1864        // A second, disjoint probe range is reported as its own span rather than
1865        // merged into a count: a byte count cannot describe a hole, which is why
1866        // the sidecar stores ranges.
1867        s.mark_done(5 << 20, 6 << 20);
1868        assert_eq!(s.held_ranges(), vec![(0, 3 << 20), (5 << 20, 6 << 20)]);
1869
1870        // Adjacent spans DO coalesce, so the record stays compact across a long run.
1871        s.mark_done(3 << 20, 5 << 20);
1872        assert_eq!(s.held_ranges(), vec![(0, 6 << 20)]);
1873    }
1874
1875    /// Resume: bytes already on disk must never be re-requested.
1876    #[test]
1877    fn resume_does_not_refetch_held_prefix() {
1878        let size = 64_000u64;
1879        let mut s = Scheduler::new(size, vec![src(1e6)], &[2]);
1880        s.mark_done(0, 48_000); // three quarters already fetched
1881        let acts = s.tick(0.0);
1882        for a in &acts {
1883            if let Action::Request { range, .. } = a {
1884                assert!(
1885                    range.lo >= 48_000,
1886                    "re-requested a held byte at {}",
1887                    range.lo
1888                );
1889            }
1890        }
1891        assert_eq!(
1892            s.bytes_held(),
1893            48_000,
1894            "held count must include the resumed prefix"
1895        );
1896        assert!(s.coverage_holds());
1897    }
1898}