Skip to main content

flm_core/progress/
estimate.rs

1//! The estimate of the overall percentage: the table of expected durations,
2//! [`measure`] and [`estimate`].
3
4use std::collections::{BTreeMap, HashMap};
5use std::time::Duration;
6
7use super::kind::SharedText;
8use super::sheet::{RowId, RowSnapshot, RowState, Snapshot};
9
10/// The expected durations of the rows of one kind, an entry of an
11/// [`Expected`] table.
12///
13/// In the serialized form, each duration is a number of seconds, and a
14/// duration that is not known is left out.
15#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
16pub struct KindDurations {
17    /// The duration of one unit of the count, for the rows of the kind that
18    /// have a count.
19    #[serde(default, skip_serializing_if = "Option::is_none", with = "seconds")]
20    pub per_unit: Option<Duration>,
21    /// The duration of a whole row of the kind.
22    #[serde(default, skip_serializing_if = "Option::is_none", with = "seconds")]
23    pub per_row: Option<Duration>,
24}
25
26/// The table of expected durations, by the name of a row's [`Kind`]: what
27/// [`estimate`] weighs the rows of a sheet with.
28///
29/// A host measures the table of a build with [`measure`], stores it, and lays
30/// it over a table of defaults with [`Expected::over`] for the next build. A
31/// table serializes as a map from the name of a kind to its
32/// [`KindDurations`]:
33///
34/// ```
35/// use std::time::Duration;
36/// use flm_core::progress::{Expected, KindDurations};
37///
38/// let mut defaults = Expected::new();
39/// defaults.insert(
40///     "flm.graphics.convert",
41///     KindDurations { per_unit: None, per_row: Some(Duration::from_millis(1500)) },
42/// );
43/// let measured = Expected::new();
44///
45/// let expected = measured.over(defaults);
46/// let durations = expected.get("flm.graphics.convert").unwrap();
47/// assert_eq!(durations.per_row, Some(Duration::from_millis(1500)));
48/// ```
49///
50/// [`Kind`]: super::Kind
51#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
52#[serde(transparent)]
53pub struct Expected {
54    kinds: BTreeMap<SharedText, KindDurations>,
55}
56
57impl Expected {
58    /// An empty table.
59    pub fn new() -> Expected {
60        Expected::default()
61    }
62
63    /// Sets the durations of the kind named `kind`, replacing those it had.
64    pub fn insert(&mut self, kind: impl Into<SharedText>, durations: KindDurations) {
65        self.kinds.insert(kind.into(), durations);
66    }
67
68    /// The durations of the kind named `kind`, if the table has any.
69    pub fn get(&self, kind: &str) -> Option<&KindDurations> {
70        self.kinds.get(kind)
71    }
72
73    /// The kinds of the table and their durations, in the order of their
74    /// names.
75    pub fn iter(&self) -> impl Iterator<Item = (&str, &KindDurations)> {
76        self.kinds.iter().map(|(kind, durations)| (kind.as_str(), durations))
77    }
78
79    /// The table that answers from `self` first, and from `base` for what
80    /// `self` lacks: a kind that `self` does not hold, or one of the two
81    /// durations of a kind that `self` does not know.
82    pub fn over(self, base: Expected) -> Expected {
83        let mut kinds = base.kinds;
84        for (kind, durations) in self.kinds {
85            let entry = kinds.entry(kind).or_default();
86            entry.per_unit = durations.per_unit.or(entry.per_unit);
87            entry.per_row = durations.per_row.or(entry.per_row);
88        }
89        Expected { kinds }
90    }
91}
92
93/// Measures the table of expected durations from the last snapshot of a build
94/// whose rows carry their times.
95///
96/// For each kind, over the rows of that kind that ended as
97/// [`RowState::Finished`] with both times: the duration of a whole row is the
98/// mean of their durations, and the duration of one unit is the sum of their
99/// durations divided by the sum of their totals, over those that have a count
100/// with a total above zero. A kind with no such row is not in the table.
101///
102/// The function keeps no memory and reads no clock.
103pub fn measure(snapshot: &Snapshot) -> Expected {
104    #[derive(Default)]
105    struct Sums {
106        rows: u32,
107        seconds: f64,
108        counted_seconds: f64,
109        units: f64,
110    }
111
112    let mut sums: BTreeMap<&SharedText, Sums> = BTreeMap::new();
113    for row in &snapshot.rows {
114        let Some(took) = took(row).filter(|_| row.state == RowState::Finished) else {
115            continue;
116        };
117        let sums = sums.entry(&row.kind).or_default();
118        sums.rows += 1;
119        sums.seconds += took;
120        if let Some(count) = row.count.filter(|count| count.total > 0) {
121            sums.counted_seconds += took;
122            sums.units += count.total as f64;
123        }
124    }
125
126    let kinds = sums
127        .into_iter()
128        .map(|(kind, sums)| {
129            let per_row = duration(sums.seconds / f64::from(sums.rows));
130            let per_unit =
131                if sums.units > 0.0 { duration(sums.counted_seconds / sums.units) } else { None };
132            (kind.clone(), KindDurations { per_unit, per_row })
133        })
134        .collect();
135    Expected { kinds }
136}
137
138/// Estimates the fraction done of a build, from 0 to 1: the fraction of the
139/// root row of `snapshot`, with its rows weighed by `expected`.
140///
141/// `now` is the host's time, from the same origin as the times the host's
142/// observer returned; the caller reads it. The function keeps no memory and
143/// reads no clock.
144///
145/// The fraction of a row:
146///
147/// | Row | Fraction |
148/// |---|---|
149/// | `Finished` or `Failed` | 1 |
150/// | `Pending` | 0 |
151/// | `NotRun` | left out of its parent's fraction |
152/// | `Running`, with a count | (done + the fractions of its running children) / total, at most 1 |
153/// | `Running`, no count, with children | the weighted average of its children's fractions |
154/// | `Running`, no count, no children | the time since it started / the duration of a whole row of its kind, at most 0.95; 0 when either is unknown |
155///
156/// A child of a counted row stands for one of the counted units. A count
157/// whose total is zero counts as no count.
158///
159/// The weight of a row, where its parent averages its children, is the first
160/// of:
161///
162/// 1. for a row that has ended with both times, the time it took;
163/// 2. for a row with a count, whose kind has a duration per unit, that
164///    duration times its total;
165/// 3. for a row whose kind has a duration for a whole row, that duration;
166/// 4. otherwise the median of the weights that the first three rules gave
167///    among its siblings, and 1 when they gave none.
168///
169/// A parent's own weight comes from these rules applied to it, never from the
170/// sum of its children, so a row declared late changes the fraction of its
171/// parent and the share of no other row.
172///
173/// Two consequences for a display:
174///
175/// - **The fraction can decrease** from one call to the next: the total of a
176///   row, known when it starts, replaces the duration of a whole row in its
177///   weight, and a row declared late lowers the fraction of its parent. A row
178///   declared in advance and then not run moves the fraction forward instead.
179///   A display keeps the highest value it has shown, and shows the whole only
180///   when the root row has finished.
181/// - **Under batches that run in parallel**, the fraction is representative
182///   of the work done, not a measure of the time left.
183pub fn estimate(snapshot: &Snapshot, expected: &Expected, now: Duration) -> f64 {
184    let Some(root) = snapshot.rows.iter().position(|row| row.parent.is_none()) else {
185        return 0.0;
186    };
187    let mut index: HashMap<RowId, usize> = HashMap::with_capacity(snapshot.rows.len());
188    for (at, row) in snapshot.rows.iter().enumerate() {
189        index.entry(row.id).or_insert(at);
190    }
191    let mut children: Vec<Vec<usize>> = vec![Vec::new(); snapshot.rows.len()];
192    for (at, row) in snapshot.rows.iter().enumerate() {
193        if row.state == RowState::NotRun || index.get(&row.id) != Some(&at) {
194            continue;
195        }
196        if let Some(&parent) = row.parent.and_then(|parent| index.get(&parent)) {
197            children[parent].push(at);
198        }
199    }
200    let tree = Tree { rows: &snapshot.rows, children: &children, expected, now };
201    tree.fraction(root).clamp(0.0, 1.0)
202}
203
204/// The rows of a snapshot with the children of each, for [`estimate`].
205struct Tree<'a> {
206    rows: &'a [RowSnapshot],
207    /// For each row, the positions of its children that are not `NotRun`.
208    children: &'a [Vec<usize>],
209    expected: &'a Expected,
210    now: Duration,
211}
212
213impl Tree<'_> {
214    fn fraction(&self, at: usize) -> f64 {
215        let row = &self.rows[at];
216        match row.state {
217            RowState::Finished | RowState::Failed => return 1.0,
218            RowState::Pending | RowState::NotRun => return 0.0,
219            RowState::Running => {}
220        }
221        let children = &self.children[at];
222        if let Some(count) = row.count.filter(|count| count.total > 0) {
223            let running: f64 = children
224                .iter()
225                .filter(|&&child| self.rows[child].state == RowState::Running)
226                .map(|&child| self.fraction(child))
227                .sum();
228            return ((count.done as f64 + running) / count.total as f64).min(1.0);
229        }
230        if !children.is_empty() {
231            return self.average(children);
232        }
233        let (Some(started), Some(per_row)) = (row.started, self.durations(row).per_row) else {
234            return 0.0;
235        };
236        if per_row.is_zero() {
237            return RUNNING_AT_MOST;
238        }
239        let elapsed = self.now.saturating_sub(started);
240        (elapsed.as_secs_f64() / per_row.as_secs_f64()).min(RUNNING_AT_MOST)
241    }
242
243    /// The average of the fractions of `children`, weighted by their weights.
244    fn average(&self, children: &[usize]) -> f64 {
245        let known: Vec<Option<f64>> = children.iter().map(|&child| self.weight(child)).collect();
246        let fallback = median(known.iter().flatten().copied().collect()).unwrap_or(1.0);
247        let mut weighted = 0.0;
248        let mut weights = 0.0;
249        for (&child, weight) in children.iter().zip(&known) {
250            let weight = weight.unwrap_or(fallback);
251            weighted += weight * self.fraction(child);
252            weights += weight;
253        }
254        if weights > 0.0 {
255            weighted / weights
256        } else {
257            let sum: f64 = children.iter().map(|&child| self.fraction(child)).sum();
258            sum / children.len() as f64
259        }
260    }
261
262    /// The weight of a row by the first three rules, in seconds; `None` when
263    /// none of them gives one.
264    fn weight(&self, at: usize) -> Option<f64> {
265        let row = &self.rows[at];
266        if matches!(row.state, RowState::Finished | RowState::Failed) {
267            if let Some(took) = took(row) {
268                return Some(took);
269            }
270        }
271        let durations = self.durations(row);
272        if let (Some(count), Some(per_unit)) =
273            (row.count.filter(|count| count.total > 0), durations.per_unit)
274        {
275            return Some(per_unit.as_secs_f64() * count.total as f64);
276        }
277        durations.per_row.map(|per_row| per_row.as_secs_f64())
278    }
279
280    fn durations(&self, row: &RowSnapshot) -> KindDurations {
281        self.expected.get(&row.kind).copied().unwrap_or_default()
282    }
283}
284
285/// The highest fraction of a running row that the time since it started
286/// gives.
287const RUNNING_AT_MOST: f64 = 0.95;
288
289/// The time a row took, in seconds, when it carries both times.
290fn took(row: &RowSnapshot) -> Option<f64> {
291    let (started, ended) = (row.started?, row.ended?);
292    Some(ended.checked_sub(started)?.as_secs_f64())
293}
294
295/// The median of `values`; the mean of the two middle values when their number
296/// is even.
297fn median(mut values: Vec<f64>) -> Option<f64> {
298    if values.is_empty() {
299        return None;
300    }
301    values.sort_by(f64::total_cmp);
302    let middle = values.len() / 2;
303    Some(if values.len() % 2 == 0 {
304        (values[middle - 1] + values[middle]) / 2.0
305    } else {
306        values[middle]
307    })
308}
309
310/// A duration of `seconds`, when it is one.
311fn duration(seconds: f64) -> Option<Duration> {
312    Duration::try_from_secs_f64(seconds).ok()
313}
314
315/// The serialized form of an optional duration: a number of seconds.
316mod seconds {
317    use std::time::Duration;
318
319    use serde::{Deserialize, Deserializer, Serializer};
320
321    pub(super) fn serialize<S: Serializer>(
322        value: &Option<Duration>,
323        serializer: S,
324    ) -> Result<S::Ok, S::Error> {
325        match value {
326            Some(duration) => serializer.serialize_f64(duration.as_secs_f64()),
327            None => serializer.serialize_none(),
328        }
329    }
330
331    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
332        deserializer: D,
333    ) -> Result<Option<Duration>, D::Error> {
334        Option::<f64>::deserialize(deserializer)?
335            .map(|seconds| {
336                Duration::try_from_secs_f64(seconds).map_err(|_| {
337                    serde::de::Error::custom(format!(
338                        "Invalid duration ‘{seconds}’ (a duration is a number of seconds, zero or above)"
339                    ))
340                })
341            })
342            .transpose()
343    }
344}