Skip to main content

grit_lib/progress/
estimate.rs

1//! One overall completion estimate across the phases of a fetch or clone.
2//!
3//! A clone runs as a sequence of phases — transfer the pack, index it, resolve
4//! its deltas, check out files — each with its own unit and total.
5//! [`OverallEstimator`] follows the same [`ProgressPhase`] events a sink sees
6//! and turns them into a single fraction and a time-left estimate: phases that
7//! are under way are projected from their own measured pace, and phases that
8//! have not started are sized from what is already known (the pack's object
9//! and delta counts) at typical [`PhaseRates`].
10//!
11//! The estimator never reads the clock; every call takes the time elapsed
12//! since the operation began.
13
14use std::time::Duration;
15
16use super::{ProgressPhase, ProgressUnit, ReceivedObjects};
17
18/// Typical throughput used to size phases that have not started yet.
19///
20/// Phases already under way are projected from their own measured pace, so
21/// these only shape the estimate until each phase begins.
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct PhaseRates {
24    /// Objects indexed per second.
25    pub indexing: f64,
26    /// Deltas resolved per second.
27    pub resolving: f64,
28    /// Files checked out per second.
29    pub checkout: f64,
30}
31
32impl Default for PhaseRates {
33    /// Rates measured from `grit clone` of large public repositories on a
34    /// current laptop.
35    fn default() -> Self {
36        Self {
37            indexing: 250_000.0,
38            resolving: 300_000.0,
39            checkout: 10_000.0,
40        }
41    }
42}
43
44/// Share of deltas assumed in a pack whose delta count is not known yet.
45const ASSUMED_DELTA_SHARE: f64 = 0.7;
46/// Work-tree files assumed per pack object before checkout reports its total.
47const ASSUMED_FILES_PER_OBJECT: f64 = 0.015;
48/// Below this share of a phase done, its measured pace is too noisy to trust
49/// over the typical rate.
50const TRUST_MEASURED_AFTER: f64 = 0.1;
51/// The fraction reported while any phase is still ahead.
52const MAX_UNFINISHED_FRACTION: f64 = 0.99;
53
54/// A snapshot of overall progress.
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct OverallEstimate {
57    /// Share of the whole operation done, from `0.0` to `1.0`. It never goes
58    /// down between calls, and stays below `1.0` until every phase finished.
59    pub fraction: f64,
60    /// Estimated time until the operation finishes.
61    pub remaining: Duration,
62}
63
64/// The phases of a clone, in the order they run.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
66enum Stage {
67    Transfer,
68    Indexing,
69    Resolving,
70    Checkout,
71}
72
73const STAGES: [Stage; 4] = [
74    Stage::Transfer,
75    Stage::Indexing,
76    Stage::Resolving,
77    Stage::Checkout,
78];
79
80impl Stage {
81    fn of(phase: ProgressPhase) -> Option<Self> {
82        match phase {
83            ProgressPhase::ReceivingObjects
84            | ProgressPhase::SendingObjects
85            | ProgressPhase::EnumeratingObjects
86            | ProgressPhase::CopyingObjects
87            | ProgressPhase::CompressingObjects
88            | ProgressPhase::WritingObjects => Some(Self::Transfer),
89            ProgressPhase::IndexingObjects => Some(Self::Indexing),
90            ProgressPhase::ResolvingDeltas => Some(Self::Resolving),
91            ProgressPhase::CheckingOutFiles => Some(Self::Checkout),
92            // Shown by its own display; the estimate covers the fetch after it.
93            ProgressPhase::TransferringBundle => None,
94            // Not part of a clone.
95            ProgressPhase::StagingFiles => None,
96        }
97    }
98}
99
100#[derive(Debug, Clone, Copy)]
101struct Active {
102    stage: Stage,
103    /// Total for the phase in its own unit; `None` for a byte-counted receive.
104    total: Option<u64>,
105    current: u64,
106    started: Duration,
107}
108
109/// Combines per-phase progress into one overall estimate.
110///
111/// Phases under way are projected from their own measured pace; phases not
112/// yet started are sized from the pack's object and delta counts at typical
113/// [`PhaseRates`]. The estimator never reads the clock: every call takes the
114/// time elapsed since the operation began.
115///
116/// ```rust
117/// use std::time::Duration;
118/// use grit_lib::progress::{OverallEstimator, ProgressPhase, ProgressUnit, ReceivedObjects};
119///
120/// let secs = Duration::from_secs;
121/// let mut est = OverallEstimator::new(true);
122/// est.start(ProgressPhase::ReceivingObjects, ProgressUnit::Bytes, None, secs(1));
123/// est.received_objects(ReceivedObjects { received: 500, total: 1_000, deltas: 300 }, secs(3));
124/// let now = est.estimate(secs(3)).unwrap();
125/// assert!(now.fraction > 0.3 && now.fraction < 0.7);
126/// ```
127#[derive(Debug, Clone)]
128pub struct OverallEstimator {
129    rates: PhaseRates,
130    checkout: bool,
131    objects: Option<u64>,
132    deltas: Option<u64>,
133    files: Option<u64>,
134    received: Option<ReceivedObjects>,
135    active: Option<Active>,
136    /// The furthest stage that has finished.
137    finished: Option<Stage>,
138    best: f64,
139}
140
141impl OverallEstimator {
142    /// Create an estimator with the default [`PhaseRates`].
143    ///
144    /// # Parameters
145    ///
146    /// - `checkout`: whether a work-tree checkout follows the transfer (true
147    ///   for a non-bare clone, false for a fetch).
148    #[must_use]
149    pub fn new(checkout: bool) -> Self {
150        Self {
151            rates: PhaseRates::default(),
152            checkout,
153            objects: None,
154            deltas: None,
155            files: None,
156            received: None,
157            active: None,
158            finished: None,
159            best: 0.0,
160        }
161    }
162
163    /// Use `rates` to size phases that have not started.
164    #[must_use]
165    pub fn with_rates(mut self, rates: PhaseRates) -> Self {
166        self.rates = rates;
167        self
168    }
169
170    /// A phase began at `at`, counting `unit`s towards `total` when known.
171    ///
172    /// Starting a phase ends the previous one.
173    pub fn start(
174        &mut self,
175        phase: ProgressPhase,
176        unit: ProgressUnit,
177        total: Option<u64>,
178        at: Duration,
179    ) {
180        self.finish(at);
181        let Some(stage) = Stage::of(phase) else {
182            return;
183        };
184        let total = total.filter(|_| unit != ProgressUnit::Bytes);
185        match stage {
186            Stage::Transfer | Stage::Indexing => {
187                if total.is_some() {
188                    self.objects = total;
189                }
190            }
191            Stage::Resolving => self.deltas = total,
192            Stage::Checkout => self.files = total,
193        }
194        self.active = Some(Active {
195            stage,
196            total,
197            current: 0,
198            started: at,
199        });
200    }
201
202    /// The current phase reached `current` units.
203    pub fn set(&mut self, current: u64) {
204        if let Some(active) = &mut self.active {
205            active.current = current;
206        }
207    }
208
209    /// The current phase advanced by `units`.
210    pub fn inc(&mut self, units: u64) {
211        if let Some(active) = &mut self.active {
212            active.current = active.current.saturating_add(units);
213        }
214    }
215
216    /// The pack being received now holds `counts` objects.
217    ///
218    /// Sizes the later phases: the pack's object total drives indexing, and
219    /// the share of deltas seen so far projects how many will need resolving.
220    pub fn received_objects(&mut self, counts: ReceivedObjects, _at: Duration) {
221        self.objects = Some(counts.total);
222        if counts.received > 0 {
223            let share = counts.deltas as f64 / counts.received as f64;
224            self.deltas = Some((share * counts.total as f64).round() as u64);
225        }
226        self.received = Some(counts);
227    }
228
229    /// The current phase finished at `at`.
230    pub fn finish(&mut self, _at: Duration) {
231        if let Some(active) = self.active.take() {
232            self.finished = self.finished.max(Some(active.stage));
233        }
234    }
235
236    /// Overall progress at `at`, or `None` while there is not enough to go on
237    /// (before the transfer has reported any objects).
238    pub fn estimate(&mut self, at: Duration) -> Option<OverallEstimate> {
239        let remaining = self.remaining_secs(at)?;
240        let elapsed = at.as_secs_f64();
241        let all_done = self.active.is_none() && self.finished == Some(self.last_stage());
242        let raw = if all_done {
243            1.0
244        } else if elapsed + remaining <= 0.0 {
245            0.0
246        } else {
247            (elapsed / (elapsed + remaining)).min(MAX_UNFINISHED_FRACTION)
248        };
249        self.best = self.best.max(raw);
250        Some(OverallEstimate {
251            fraction: self.best,
252            remaining: Duration::from_secs_f64(remaining.max(0.0)),
253        })
254    }
255
256    fn last_stage(&self) -> Stage {
257        if self.checkout {
258            Stage::Checkout
259        } else {
260            Stage::Resolving
261        }
262    }
263
264    fn remaining_secs(&self, at: Duration) -> Option<f64> {
265        let mut total = 0.0;
266        for stage in STAGES {
267            if stage > self.last_stage() || Some(stage) <= self.finished {
268                continue;
269            }
270            match self.active {
271                Some(active) if active.stage == stage => total += self.active_secs(active, at)?,
272                // Started later than this stage, so this one was skipped.
273                Some(active) if active.stage > stage => {}
274                _ => total += self.pending_secs(stage)?,
275            }
276        }
277        Some(total)
278    }
279
280    /// Seconds left in the phase under way.
281    fn active_secs(&self, active: Active, at: Duration) -> Option<f64> {
282        let elapsed = at.saturating_sub(active.started).as_secs_f64();
283        let (done, total) = match (active.stage, active.total) {
284            (_, Some(total)) => (active.current, total),
285            (Stage::Transfer, None) => {
286                let counts = self.received?;
287                (counts.received, counts.total)
288            }
289            (_, None) => return self.pending_secs(active.stage),
290        };
291        let left = total.saturating_sub(done) as f64;
292        if left == 0.0 {
293            return Some(0.0);
294        }
295        let share = if total == 0 {
296            1.0
297        } else {
298            done as f64 / total as f64
299        };
300        let typical = self.rate(active.stage).map(|rate| left / rate);
301        if share >= TRUST_MEASURED_AFTER || typical.is_none() {
302            if done == 0 {
303                return None;
304            }
305            return Some(elapsed * left / done as f64);
306        }
307        typical
308    }
309
310    /// Seconds a phase that has not started is expected to take.
311    fn pending_secs(&self, stage: Stage) -> Option<f64> {
312        let objects = self.objects? as f64;
313        let units = match stage {
314            // Nothing predicts how fast the network will be.
315            Stage::Transfer => return None,
316            Stage::Indexing => objects,
317            Stage::Resolving => self
318                .deltas
319                .map_or(objects * ASSUMED_DELTA_SHARE, |d| d as f64),
320            Stage::Checkout => self
321                .files
322                .map_or(objects * ASSUMED_FILES_PER_OBJECT, |f| f as f64),
323        };
324        Some(units / self.rate(stage)?)
325    }
326
327    fn rate(&self, stage: Stage) -> Option<f64> {
328        let rate = match stage {
329            Stage::Transfer => return None,
330            Stage::Indexing => self.rates.indexing,
331            Stage::Resolving => self.rates.resolving,
332            Stage::Checkout => self.rates.checkout,
333        };
334        (rate > 0.0).then_some(rate)
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    fn secs(s: f64) -> Duration {
343        Duration::from_secs_f64(s)
344    }
345
346    fn rates() -> PhaseRates {
347        PhaseRates {
348            indexing: 1_000.0,
349            resolving: 1_000.0,
350            checkout: 100.0,
351        }
352    }
353
354    fn receiving(est: &mut OverallEstimator, at: f64) {
355        est.start(
356            ProgressPhase::ReceivingObjects,
357            ProgressUnit::Bytes,
358            None,
359            secs(at),
360        );
361    }
362
363    #[test]
364    fn no_estimate_until_objects_are_counted() {
365        let mut est = OverallEstimator::new(true);
366        assert!(est.estimate(secs(1.0)).is_none());
367        receiving(&mut est, 1.0);
368        est.inc(4096);
369        assert!(
370            est.estimate(secs(2.0)).is_none(),
371            "bytes alone are not enough"
372        );
373    }
374
375    #[test]
376    fn receive_projects_its_pace_and_sizes_later_phases() {
377        let mut est = OverallEstimator::new(true).with_rates(rates());
378        receiving(&mut est, 0.0);
379        // Half of 2,000 objects in 4s; 60% deltas so far.
380        est.received_objects(
381            ReceivedObjects {
382                received: 1_000,
383                total: 2_000,
384                deltas: 600,
385            },
386            secs(4.0),
387        );
388        let e = est.estimate(secs(4.0)).unwrap();
389        // 4s more receiving + 2s indexing + 1.2s deltas + 0.3s checkout.
390        assert!(
391            (e.remaining.as_secs_f64() - 7.5).abs() < 1e-6,
392            "{:?}",
393            e.remaining
394        );
395        assert!((e.fraction - 4.0 / 11.5).abs() < 1e-6, "{}", e.fraction);
396    }
397
398    #[test]
399    fn active_phase_uses_measured_pace_once_trustworthy() {
400        let mut est = OverallEstimator::new(false).with_rates(rates());
401        est.start(
402            ProgressPhase::IndexingObjects,
403            ProgressUnit::Objects,
404            Some(1_000),
405            secs(10.0),
406        );
407        // Early on, the typical rate wins: 990 left at 1,000/s.
408        est.set(10);
409        let early = est.estimate(secs(10.5)).unwrap();
410        assert!((early.remaining.as_secs_f64() - (0.99 + 0.7)).abs() < 1e-6);
411        // At 50% after 2s, 2s more indexing at the measured pace.
412        est.set(500);
413        let later = est.estimate(secs(12.0)).unwrap();
414        assert!((later.remaining.as_secs_f64() - (2.0 + 0.7)).abs() < 1e-6);
415    }
416
417    #[test]
418    fn known_totals_replace_assumptions() {
419        let mut est = OverallEstimator::new(true).with_rates(rates());
420        est.start(
421            ProgressPhase::ResolvingDeltas,
422            ProgressUnit::Objects,
423            Some(0),
424            secs(1.0),
425        );
426        est.finish(secs(1.0));
427        est.start(
428            ProgressPhase::CheckingOutFiles,
429            ProgressUnit::Files,
430            Some(200),
431            secs(1.0),
432        );
433        // Earlier stages count as done; 200 files at 100/s.
434        let e = est.estimate(secs(1.0)).unwrap();
435        assert!((e.remaining.as_secs_f64() - 2.0).abs() < 1e-6);
436    }
437
438    #[test]
439    fn fraction_never_goes_backwards_and_reaches_one_when_done() {
440        let mut est = OverallEstimator::new(false).with_rates(rates());
441        receiving(&mut est, 0.0);
442        est.received_objects(
443            ReceivedObjects {
444                received: 900,
445                total: 1_000,
446                deltas: 0,
447            },
448            secs(9.0),
449        );
450        let high = est.estimate(secs(9.0)).unwrap().fraction;
451        // The last tenth stalls: the projection gets worse, the bar holds.
452        let stalled = est.estimate(secs(30.0)).unwrap().fraction;
453        assert!(stalled >= high);
454        est.start(
455            ProgressPhase::IndexingObjects,
456            ProgressUnit::Objects,
457            Some(1_000),
458            secs(30.0),
459        );
460        est.set(1_000);
461        est.start(
462            ProgressPhase::ResolvingDeltas,
463            ProgressUnit::Objects,
464            Some(0),
465            secs(31.0),
466        );
467        let unfinished = est.estimate(secs(31.0)).unwrap().fraction;
468        assert!(unfinished < 1.0);
469        est.finish(secs(31.0));
470        let done = est.estimate(secs(31.0)).unwrap();
471        assert_eq!(done.fraction, 1.0);
472        assert_eq!(done.remaining, Duration::ZERO);
473    }
474
475    #[test]
476    fn local_copy_with_known_total_is_estimated() {
477        let mut est = OverallEstimator::new(false).with_rates(rates());
478        est.start(
479            ProgressPhase::CopyingObjects,
480            ProgressUnit::Objects,
481            Some(100),
482            secs(0.0),
483        );
484        est.set(50);
485        let e = est.estimate(secs(1.0)).unwrap();
486        // 1s more copying + 0.1s indexing + 0.07s deltas.
487        assert!((e.remaining.as_secs_f64() - 1.17).abs() < 1e-6, "{e:?}");
488    }
489}