flm_core/progress/
estimate.rs1use std::collections::{BTreeMap, HashMap};
5use std::time::Duration;
6
7use super::kind::SharedText;
8use super::sheet::{RowId, RowSnapshot, RowState, Snapshot};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
16pub struct KindDurations {
17 #[serde(default, skip_serializing_if = "Option::is_none", with = "seconds")]
20 pub per_unit: Option<Duration>,
21 #[serde(default, skip_serializing_if = "Option::is_none", with = "seconds")]
23 pub per_row: Option<Duration>,
24}
25
26#[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 pub fn new() -> Expected {
60 Expected::default()
61 }
62
63 pub fn insert(&mut self, kind: impl Into<SharedText>, durations: KindDurations) {
65 self.kinds.insert(kind.into(), durations);
66 }
67
68 pub fn get(&self, kind: &str) -> Option<&KindDurations> {
70 self.kinds.get(kind)
71 }
72
73 pub fn iter(&self) -> impl Iterator<Item = (&str, &KindDurations)> {
76 self.kinds.iter().map(|(kind, durations)| (kind.as_str(), durations))
77 }
78
79 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
93pub 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
138pub 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
204struct Tree<'a> {
206 rows: &'a [RowSnapshot],
207 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 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 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
285const RUNNING_AT_MOST: f64 = 0.95;
288
289fn took(row: &RowSnapshot) -> Option<f64> {
291 let (started, ended) = (row.started?, row.ended?);
292 Some(ended.checked_sub(started)?.as_secs_f64())
293}
294
295fn 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
310fn duration(seconds: f64) -> Option<Duration> {
312 Duration::try_from_secs_f64(seconds).ok()
313}
314
315mod 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}