Skip to main content

cortex/models/
historical_runs.rs

1#![allow(clippy::extra_unused_lifetimes)]
2use chrono::prelude::*;
3use diesel::result::Error;
4use diesel::*;
5use serde::Serialize;
6use std::collections::HashSet;
7
8// use super::messages::*;
9// use super::tasks::Task;
10// use crate::helpers::TaskStatus;
11use crate::backend::progress_report;
12use crate::concerns::CortexInsertable;
13use crate::helpers::TaskStatus;
14use crate::models::{Corpus, Service};
15use crate::schema::historical_runs;
16
17#[derive(Identifiable, Queryable, Associations, Clone, Debug, PartialEq, Eq, QueryableByName)]
18#[diesel(table_name = historical_runs)]
19#[diesel(belongs_to(Corpus, foreign_key = corpus_id))]
20#[diesel(belongs_to(Service, foreign_key = service_id))]
21/// Historical `(Corpus, Service)` run records
22pub struct HistoricalRun {
23  /// id of the historical run
24  pub id: i32,
25  /// id of the service owning this task
26  pub service_id: i32,
27  /// id of the corpus hosting this task
28  pub corpus_id: i32,
29  /// total tasks in run
30  pub total: i32,
31  /// invalid tasks in run
32  pub invalid: i32,
33  /// fatal results in run
34  pub fatal: i32,
35  /// error results in run
36  pub error: i32,
37  /// warning results in run
38  pub warning: i32,
39  /// results with no notable problems in run
40  pub no_problem: i32,
41  /// tasks still in progress at end of run
42  pub in_progress: i32,
43  /// start timestamp of run
44  pub start_time: NaiveDateTime,
45  /// end timestamp of run, i.e. timestamp of next run initiation
46  pub end_time: Option<NaiveDateTime>,
47  /// owner who initiated the run
48  pub owner: String,
49  /// description of the purpose of this run
50  pub description: String,
51  /// Stable external handle (UUIDv7, DB-generated) for referencing this specific run independently
52  /// of its (corpus, service, start_time) coordinates. Immutable once assigned (Arm 3 / D8).
53  pub public_id: uuid::Uuid,
54}
55
56#[derive(Debug, Serialize, Clone, Default)]
57/// A JSON-friendly data structure, used for the frontend reports
58pub struct RunMetadata {
59  /// total tasks in run
60  pub total: i32,
61  /// invalid tasks in run
62  pub invalid: i32,
63  /// fatak tasks in run
64  pub fatal: i32,
65  /// error tasks in run
66  pub error: i32,
67  /// warning tasks in run
68  pub warning: i32,
69  /// no_problem tasks in run
70  pub no_problem: i32,
71  /// in_progress tasks in run
72  pub in_progress: i32,
73  /// start time of run, formatted for a report
74  pub start_time: String,
75  /// end time of run, formatted for a report
76  pub end_time: String,
77  /// initiator of the run
78  pub owner: String,
79  /// description of the run
80  pub description: String,
81}
82impl RunMetadata {
83  /// f32 type cast for the run frequency fields
84  pub fn field_f32(&self, field: &str) -> f32 {
85    let field_i32 = match field {
86      "invalid" => self.invalid,
87      "total" => self.total,
88      "fatal" => self.fatal,
89      "error" => self.error,
90      "warning" => self.warning,
91      "no_problem" => self.no_problem,
92      "in_progress" => self.in_progress,
93      // An unknown field is a programming error (callers pass fixed keys), but this feeds the
94      // **public** `/history` chart — degrade to 0 rather than `panic!` on a request path
95      // (robustness: no panic where a `Result`/default will do).
96      _ => 0,
97    };
98    field_i32 as f32
99  }
100}
101
102#[derive(Debug, Serialize, Clone)]
103/// A JSON-friendly data structure, used for vega-lite Stack figures
104/// https://vega.github.io/vega-lite/docs/stack.html
105pub struct RunMetadataStack {
106  /// unique per-run sequence key in this chart series (prevents Vega-Lite from collapsing
107  /// runs that share the same displayed timestamp bucket into a 200%+ stacked bar)
108  pub run_id: usize,
109  /// true when this run still had unfinished tasks (`in_progress > 0`, including paused/blocked
110  /// tasks folded from `total - terminal`) — lets the chart toggle intermediate runs on/off
111  pub has_in_progress: bool,
112  /// type of messages
113  pub severity: String,
114  /// raw severity index
115  pub severity_numeric: i32,
116  /// percent to total
117  pub percent: f32,
118  /// total number of jobs
119  pub total: i32,
120  /// start time of run, formatted for a report
121  pub start_time: String,
122  /// end time of run, formatted for a report
123  pub end_time: String,
124  /// initiator of the run
125  pub owner: String,
126  /// description of the run
127  pub description: String,
128}
129impl RunMetadataStack {
130  /// Transforms to a vega-lite Stack -near representation.
131  ///
132  /// Every included run receives a distinct `run_id` so the chart always plots one 100% column per
133  /// run even when two runs start in the same minute (or same second, or an open run overlaps a
134  /// closed run). Previously this only deduplicated exact second-precision `start_time` strings on
135  /// closed runs while Vega bucketed x by `yearmonthdatehoursminutes`, causing same-minute runs
136  /// (and open+closed collisions) to sum into a 200% bar.
137  ///
138  /// Any gap between `total` and `fatal + error + warning + no_problem + in_progress` (caused by
139  /// `Blocked` / paused tasks that older `mark_completed` snapshots omitted from `in_progress`) is
140  /// folded into `in_progress` so paused/partial historical runs still sum to 100% rather than
141  /// rendering as short stubs, and are flagged via `has_in_progress` for the intermediate-run
142  /// toggle.
143  pub fn transform(runs_meta: &[RunMetadata]) -> Vec<RunMetadataStack> {
144    let mut runs_meta_vega = Vec::new();
145    let mut run_id: usize = 0;
146    for run in runs_meta.iter() {
147      // skip extension runs from Vega report, too noisy
148      // Tip: rename the "description" field if you want the run included
149      if run.description == "extending corpus with more entries" {
150        continue;
151      }
152      let total = run.field_f32("total");
153      // A run with no valid tasks (total 0 — all-invalid, or an open run before any completion) has
154      // no success-rate to plot, and `field / 0.0` yields NaN/Inf which `serde_json` cannot encode.
155      // Critically, that failure is on the WHOLE array — one such run would blank the *entire*
156      // chart (the serialized payload falls back to empty) — so skip it rather than poison
157      // the series.
158      if total <= 0.0 {
159        continue;
160      }
161      let terminal = run.fatal + run.error + run.warning + run.no_problem;
162      let unaccounted = (run.total - terminal - run.in_progress).max(0);
163      let effective_in_progress = run.in_progress + unaccounted;
164      let has_in_progress = effective_in_progress > 0;
165      for field in ["fatal", "error", "warning", "no_problem", "in_progress"].iter() {
166        let count = if *field == "in_progress" {
167          effective_in_progress as f32
168        } else {
169          run.field_f32(field)
170        };
171        runs_meta_vega.push(RunMetadataStack {
172          run_id,
173          has_in_progress,
174          severity: (*field).to_string(),
175          severity_numeric: TaskStatus::from_key(field).unwrap().raw(),
176          percent: (100.0 * count) / total,
177          total: run.total,
178          start_time: run.start_time.clone(),
179          end_time: run.end_time.clone(),
180          owner: run.owner.clone(),
181          description: run.description.clone(),
182        })
183      }
184      run_id += 1;
185    }
186    runs_meta_vega
187  }
188}
189
190#[derive(Insertable, Debug, Clone)]
191#[diesel(table_name = historical_runs)]
192/// A new task, to be inserted into `CorTeX`
193pub struct NewHistoricalRun {
194  /// id of the service owning this task
195  pub service_id: i32,
196  /// id of the corpus hosting this task
197  pub corpus_id: i32,
198  /// description of the purpose of this run
199  pub description: String,
200  /// owner who initiated the run
201  pub owner: String,
202}
203
204impl CortexInsertable for NewHistoricalRun {
205  fn create(&self, connection: &mut PgConnection) -> Result<usize, Error> {
206    insert_into(historical_runs::table)
207      .values(self)
208      .execute(connection)
209  }
210}
211
212impl HistoricalRun {
213  /// Obtain all historical runs for a given `(Corpus, Service)` pair
214  pub fn find_by(
215    corpus: &Corpus,
216    service: &Service,
217    connection: &mut PgConnection,
218  ) -> Result<Vec<HistoricalRun>, Error> {
219    use crate::schema::historical_runs::dsl::{corpus_id, service_id, start_time};
220    let runs: Vec<HistoricalRun> = historical_runs::table
221      .filter(corpus_id.eq(corpus.id))
222      .filter(service_id.eq(service.id))
223      .order(start_time.desc())
224      .get_results(connection)?;
225    Ok(runs)
226  }
227
228  /// The most recent historical runs across **all** corpora/services, newest first — the
229  /// system-wide run-management overview. Capped at `limit`.
230  pub fn recent_all(
231    connection: &mut PgConnection,
232    limit: i64,
233  ) -> Result<Vec<HistoricalRun>, Error> {
234    Self::recent_filtered(connection, None, None, None, limit)
235  }
236
237  /// The most recent historical runs, newest first, optionally narrowed to a `corpus_id`,
238  /// `service_id`, and/or exact `owner` — the filter-driven run-management overview. Capped at
239  /// `limit`. Any combination of filters may be `None` (no constraint on that field).
240  pub fn recent_filtered(
241    connection: &mut PgConnection,
242    corpus: Option<i32>,
243    service: Option<i32>,
244    owner: Option<&str>,
245    limit: i64,
246  ) -> Result<Vec<HistoricalRun>, Error> {
247    use crate::schema::historical_runs::dsl;
248    let mut query = dsl::historical_runs.into_boxed();
249    if let Some(corpus) = corpus {
250      query = query.filter(dsl::corpus_id.eq(corpus));
251    }
252    if let Some(service) = service {
253      query = query.filter(dsl::service_id.eq(service));
254    }
255    if let Some(owner) = owner {
256      query = query.filter(dsl::owner.eq(owner.to_string()));
257    }
258    query
259      .order(dsl::start_time.desc())
260      .limit(limit)
261      .get_results(connection)
262  }
263
264  /// Obtain a currently ongoing run entry for a  `(Corpus, Service)` pair, if any
265  pub fn find_current(
266    corpus: &Corpus,
267    service: &Service,
268    connection: &mut PgConnection,
269  ) -> Result<Option<HistoricalRun>, Error> {
270    use crate::schema::historical_runs::dsl::{corpus_id, end_time, service_id};
271    historical_runs::table
272      .filter(corpus_id.eq(corpus.id))
273      .filter(service_id.eq(service.id))
274      .filter(end_time.is_null())
275      .first(connection)
276      .optional()
277  }
278
279  /// Mark this historical run as completed: freeze its live tallies and set `end_time`, as an
280  /// **atomic compare-and-set** (`WHERE id = ? AND end_time IS NULL`). Exactly one caller can ever
281  /// close a given run — even under duplicate finalize passes (a re-tried last task that lands
282  /// twice) or, hypothetically, concurrent writers — because the open-row predicate lives in the
283  /// UPDATE itself, not in a separate read. Returns `true` iff **this** call performed the close
284  /// (the UPDATE matched the still-open row); `false` if the run was already closed (a no-op). That
285  /// `true` is the safe edge to hang any run-completion side effect on: it can never double-fire.
286  pub fn mark_completed(&self, connection: &mut PgConnection) -> Result<bool, Error> {
287    use diesel::dsl::now;
288    // Fast path: a run we already know is closed needs no tally recompute. The atomic UPDATE below
289    // is the real guard — this only skips wasted work in the already-closed case.
290    if self.end_time.is_some() {
291      return Ok(false);
292    }
293    // Freeze the current statistics, then close — but the `end_time IS NULL` filter means a racing
294    // (or duplicate) close matches zero rows and is a clean no-op, never a re-mark.
295    let t = live_tally_fields(connection, self.corpus_id, self.service_id);
296    let rows = update(
297      historical_runs::table
298        .filter(historical_runs::id.eq(self.id))
299        .filter(historical_runs::end_time.is_null()),
300    )
301    .set((
302      historical_runs::end_time.eq(now),
303      historical_runs::total.eq(t.total),
304      historical_runs::in_progress.eq(t.in_progress),
305      historical_runs::invalid.eq(t.invalid),
306      historical_runs::no_problem.eq(t.no_problem),
307      historical_runs::warning.eq(t.warning),
308      historical_runs::error.eq(t.error),
309      historical_runs::fatal.eq(t.fatal),
310    ))
311    .execute(connection)?;
312    Ok(rows == 1)
313  }
314
315  /// **Run-completion-on-drain.** Close the open historical run for a `(corpus, service)` pair the
316  /// moment its work is exhausted — every task has reached a terminal severity, with nothing left
317  /// `TODO`, in-flight (`Queued`), or `Blocked` on a prerequisite. Freezes the run's tallies and
318  /// sets `end_time` (via [`Self::mark_completed`]), so a finished run stops reading as "ongoing"
319  /// *immediately*, instead of only when the next rerun supersedes it (the lazy
320  /// [`mark_new_run`](crate::backend::mark_new_run) path that left a run "ongoing" until the very
321  /// minute the next run started). Returns `true` iff a run was actually closed.
322  ///
323  /// Idempotent and safe to call repeatedly from the dispatcher's finalize loop: a no-op when work
324  /// still remains, when there is no open run (already closed, or never started), or for the
325  /// bookkeeping services `init` (1) / `import` (2) — those are not user-facing conversion runs and
326  /// are skipped.
327  pub fn complete_if_drained(
328    corpus: i32,
329    service: i32,
330    connection: &mut PgConnection,
331  ) -> Result<bool, Error> {
332    use crate::schema::historical_runs::dsl::{corpus_id, end_time, service_id};
333    use crate::schema::tasks;
334    // `init` (1) / `import` (2) are bookkeeping services, not conversion runs — no run to close.
335    if service <= 2 {
336      return Ok(false);
337    }
338    // Unfinished = anything OUTSIDE the terminal severity band [-5, -1]: `TODO` (0) and `Queued`
339    // (> 0) still to run, plus `Blocked` (< -5) gated on a prerequisite service. While any of these
340    // remain the run can still produce a result, so it is NOT drained. (Mirror of the raw status
341    // mapping in `TaskStatus::from_raw`.)
342    let unfinished: i64 = tasks::table
343      .filter(tasks::corpus_id.eq(corpus))
344      .filter(tasks::service_id.eq(service))
345      .filter(tasks::status.ge(0).or(tasks::status.lt(-5)))
346      .count()
347      .get_result(connection)?;
348    if unfinished > 0 {
349      return Ok(false);
350    }
351    // Drained: freeze + close the pair's open run, if one is still open.
352    let open: Option<HistoricalRun> = historical_runs::table
353      .filter(corpus_id.eq(corpus))
354      .filter(service_id.eq(service))
355      .filter(end_time.is_null())
356      .first(connection)
357      .optional()?;
358    // `mark_completed` is the atomic compare-and-set: it returns `true` only if THIS call closed
359    // the run, so a duplicate drain pass (or a racing writer) that finds the row already closed
360    // propagates as `false` here — never a second completion.
361    match open {
362      Some(run) => run.mark_completed(connection),
363      None => Ok(false),
364    }
365  }
366
367  /// Returns this run with its per-severity tallies reflecting **live** task state *when the run is
368  /// still open* (`end_time` is `None`). A run only freezes its tallies at [`Self::mark_completed`]
369  /// (i.e. when the next run supersedes it), so an open run's stored tallies are all zero;
370  /// overlaying the current progress makes the in-progress run show its real state across the
371  /// run-management surfaces — the "live + historical run state" north star — instead of a
372  /// misleading row of zeros (most visible on the *current* run and the dashboard's "last run").
373  /// A completed run is returned unchanged: its frozen snapshot is authoritative and this is a
374  /// no-op (no extra query). Cost is one grouped `progress_report` per *open* run only.
375  #[must_use]
376  pub fn with_live_tallies(mut self, connection: &mut PgConnection) -> HistoricalRun {
377    if self.end_time.is_none() {
378      let t = live_tally_fields(connection, self.corpus_id, self.service_id);
379      self.total = t.total;
380      self.no_problem = t.no_problem;
381      self.warning = t.warning;
382      self.error = t.error;
383      self.fatal = t.fatal;
384      self.invalid = t.invalid;
385      self.in_progress = t.in_progress;
386    }
387    self
388  }
389
390  /// Overlays live tallies onto every **open** run in `runs` using a **single** batched query,
391  /// replacing the per-open-run [`with_live_tallies`](Self::with_live_tallies) N+1 that made the
392  /// system-wide run overview cost one `progress_report` per open run (O(open runs) — a real drag
393  /// when many corpora convert at once). Completed runs keep their frozen tallies untouched. Use
394  /// this for any **multi-`(corpus, service)`** run list; a single-pair list (≤1 open run) can
395  /// keep `with_live_tallies`.
396  #[must_use]
397  pub fn overlay_live_tallies(
398    mut runs: Vec<HistoricalRun>,
399    connection: &mut PgConnection,
400  ) -> Vec<HistoricalRun> {
401    let pairs: Vec<(i32, i32)> = runs
402      .iter()
403      .filter(|run| run.end_time.is_none())
404      .map(|run| (run.corpus_id, run.service_id))
405      .collect::<HashSet<_>>()
406      .into_iter()
407      .collect();
408    if pairs.is_empty() {
409      return runs; // no open runs → nothing live to overlay
410    }
411    let tallies = live_tally_fields_batch(connection, &pairs);
412    for run in runs.iter_mut().filter(|run| run.end_time.is_none()) {
413      if let Some(t) = tallies.get(&(run.corpus_id, run.service_id)) {
414        run.total = t.total;
415        run.no_problem = t.no_problem;
416        run.warning = t.warning;
417        run.error = t.error;
418        run.fatal = t.fatal;
419        run.invalid = t.invalid;
420        run.in_progress = t.in_progress;
421      }
422    }
423    runs
424  }
425}
426
427/// The per-severity tallies of a `(corpus, service)` at a point in time.
428#[derive(Default)]
429struct RunTallies {
430  total: i32,
431  no_problem: i32,
432  warning: i32,
433  error: i32,
434  fatal: i32,
435  invalid: i32,
436  in_progress: i32,
437}
438
439/// Computes the live per-severity tallies for a `(corpus, service)` from the **current** task
440/// status distribution — the single source of truth shared by [`HistoricalRun::mark_completed`]
441/// (which freezes it) and [`HistoricalRun::with_live_tallies`] (which overlays it on an open run),
442/// so the in-progress numbers are identical to what gets frozen at completion. `in_progress` folds
443/// every unfinished task (`todo` + `queued` + `blocked`, including paused runs) so that
444/// `no_problem + warning + error + fatal + in_progress == total` always holds; `total` excludes
445/// invalids (as `progress_report` does).
446fn live_tally_fields(connection: &mut PgConnection, corpus_id: i32, service_id: i32) -> RunTallies {
447  let report = progress_report(connection, corpus_id, service_id);
448  let get = |key: &str| *report.get(key).unwrap_or(&0.0);
449  RunTallies {
450    total: get("total") as i32,
451    no_problem: get("no_problem") as i32,
452    warning: get("warning") as i32,
453    error: get("error") as i32,
454    fatal: get("fatal") as i32,
455    invalid: get("invalid") as i32,
456    in_progress: (get("queued") + get("todo") + get("blocked")) as i32,
457  }
458}
459
460/// Live tallies for **several** `(corpus, service)` pairs in **one** grouped query — the batched
461/// twin of [`live_tally_fields`], so overlaying live progress onto a list of open runs costs one DB
462/// round-trip instead of one per run (the N+1 that made the system-wide run overview O(open runs);
463/// see [`HistoricalRun::overlay_live_tallies`]). The `ANY` filters may select cross pairs that were
464/// not requested; those are dropped via `wanted`, so the result is exact. Folds the status
465/// distribution exactly as [`live_tally_fields`]/`progress_report` do (total excludes invalids;
466/// `in_progress` = all unfinished `todo` + `queued` + `blocked` tasks).
467fn live_tally_fields_batch(
468  connection: &mut PgConnection,
469  pairs: &[(i32, i32)],
470) -> std::collections::HashMap<(i32, i32), RunTallies> {
471  use crate::schema::tasks::dsl::{corpus_id, service_id, status, tasks};
472  use diesel::dsl::sql;
473  use diesel::sql_types::BigInt;
474  let mut out: std::collections::HashMap<(i32, i32), RunTallies> = std::collections::HashMap::new();
475  if pairs.is_empty() {
476    return out;
477  }
478  let wanted: HashSet<(i32, i32)> = pairs.iter().copied().collect();
479  let corpus_ids: Vec<i32> = wanted.iter().map(|(corpus, _)| *corpus).collect();
480  let service_ids: Vec<i32> = wanted.iter().map(|(_, service)| *service).collect();
481  // Raw `count(*)` (as `progress_report` does) sidesteps Diesel's aggregate/group-by type check
482  // while staying parameterized everywhere else.
483  let rows: Vec<(i32, i32, i32, i64)> = tasks
484    .select((corpus_id, service_id, status, sql::<BigInt>("count(*)")))
485    .filter(corpus_id.eq_any(&corpus_ids))
486    .filter(service_id.eq_any(&service_ids))
487    .group_by((corpus_id, service_id, status))
488    .load(connection)
489    .unwrap_or_default();
490  for (corpus, service, raw_status, count) in rows {
491    if !wanted.contains(&(corpus, service)) {
492      continue; // an over-selected cross pair (ANY × ANY) we did not ask for
493    }
494    let count = count as i32;
495    let tally = out.entry((corpus, service)).or_default();
496    let task_status = TaskStatus::from_raw(raw_status);
497    if task_status != TaskStatus::Invalid {
498      tally.total += count; // total excludes only invalids (matches progress_report)
499    }
500    match task_status {
501      TaskStatus::NoProblem => tally.no_problem += count,
502      TaskStatus::Warning => tally.warning += count,
503      TaskStatus::Error => tally.error += count,
504      TaskStatus::Fatal => tally.fatal += count,
505      TaskStatus::Invalid => tally.invalid += count,
506      // unfinished work: TODO (0), any positive lease mark (Queued), and Blocked (< -5, e.g.
507      // paused) all fold into in_progress so terminal + in_progress == total always holds.
508      TaskStatus::TODO | TaskStatus::Blocked(_) => tally.in_progress += count,
509      _ if raw_status > TaskStatus::TODO.raw() => tally.in_progress += count,
510      _ => {},
511    }
512  }
513  out
514}
515
516impl From<HistoricalRun> for RunMetadata {
517  fn from(run: HistoricalRun) -> RunMetadata {
518    let HistoricalRun {
519      total,
520      warning,
521      error,
522      no_problem,
523      invalid,
524      fatal,
525      start_time,
526      end_time,
527      description,
528      in_progress,
529      owner,
530      ..
531    } = run;
532    RunMetadata {
533      total,
534      invalid,
535      fatal,
536      warning,
537      error,
538      no_problem,
539      in_progress,
540      // Full RFC-3339 UTC timestamp, NOT date-only. The `/runs` Vega chart keys each bar by
541      // `run_id` with a localized `start_time` label (upgrading colliding same-minute runs to
542      // second precision + ordinal suffix so two runs never stack into a 200% bar).
543      // Seconds-precision RFC-3339 matches RunDto's `iso_utc` rendering (zone-unambiguous).
544      start_time: start_time
545        .and_utc()
546        .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
547      end_time: match end_time {
548        Some(etime) => etime
549          .and_utc()
550          .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
551        None => String::new(),
552      },
553      owner,
554      description,
555    }
556  }
557}
558
559#[cfg(test)]
560mod tests {
561  use super::{RunMetadata, RunMetadataStack};
562
563  /// A zero-total run (all-invalid, or an open run before any completion) must not blank the whole
564  /// history chart: it is skipped (no `field / 0.0` NaN/Inf percents, which would fail `serde_json`
565  /// on the *whole array* and empty the series), while runs with valid tasks still chart.
566  #[test]
567  fn transform_skips_zero_total_runs_so_one_doesnt_blank_the_chart() {
568    let zero_total = RunMetadata {
569      invalid: 5, // all-invalid → total 0 (the total excludes invalids)
570      start_time: "2026-01-01 00:00:00".to_string(),
571      end_time: "2026-01-01 01:00:00".to_string(),
572      ..Default::default()
573    };
574    let real = RunMetadata {
575      total: 4,
576      warning: 1,
577      no_problem: 3,
578      start_time: "2026-01-02 00:00:00".to_string(),
579      end_time: "2026-01-02 01:00:00".to_string(),
580      ..Default::default()
581    };
582    let stack = RunMetadataStack::transform(&[zero_total, real]);
583    assert!(!stack.is_empty(), "the valid run still charts");
584    assert!(
585      stack.iter().all(|row| row.percent.is_finite()),
586      "no NaN/Inf percents — a zero-total run is skipped, never divided by zero"
587    );
588    assert!(
589      serde_json::to_string(&stack).is_ok(),
590      "the series serializes — the bug was serde failing on a NaN and blanking the chart"
591    );
592  }
593
594  /// Two runs starting in the same minute (or even the same second, including an open run paired
595  /// with a closed run) must each receive a distinct `run_id` and sum to 100% independently — so
596  /// the chart never merges them into a 200% stacked column.
597  #[test]
598  fn transform_assigns_distinct_run_ids_to_same_minute_and_same_second_runs() {
599    let runs = vec![
600      // Open run sharing the exact same second as the closed run below.
601      RunMetadata {
602        total: 100,
603        no_problem: 80,
604        warning: 15,
605        error: 4,
606        fatal: 1,
607        start_time: "2026-11-20T14:05:42Z".to_string(),
608        end_time: String::new(),
609        description: "open run".to_string(),
610        ..Default::default()
611      },
612      // Closed run at the exact same second.
613      RunMetadata {
614        total: 100,
615        no_problem: 75,
616        warning: 15,
617        error: 5,
618        fatal: 5,
619        start_time: "2026-11-20T14:05:42Z".to_string(),
620        end_time: "2026-11-20T14:05:42Z".to_string(),
621        description: "same-second closed run".to_string(),
622        ..Default::default()
623      },
624      // Earlier closed run in the exact same minute (different seconds).
625      RunMetadata {
626        total: 100,
627        no_problem: 70,
628        warning: 20,
629        error: 8,
630        fatal: 2,
631        start_time: "2026-11-20T14:05:10Z".to_string(),
632        end_time: "2026-11-20T14:05:42Z".to_string(),
633        description: "same-minute earlier run".to_string(),
634        ..Default::default()
635      },
636    ];
637    let stack = RunMetadataStack::transform(&runs);
638    assert_eq!(
639      stack.len(),
640      15,
641      "3 runs × 5 severities = 15 rows (none silently dropped)"
642    );
643    for id in 0..3usize {
644      let run_rows: Vec<_> = stack.iter().filter(|row| row.run_id == id).collect();
645      assert_eq!(run_rows.len(), 5, "run_id {id} has all 5 severity rows");
646      let sum: f32 = run_rows.iter().map(|row| row.percent).sum();
647      assert!(
648        (sum - 100.0).abs() < 1e-4,
649        "run_id {id} percentages sum to 100% (got {sum})"
650      );
651    }
652  }
653
654  /// A frozen run whose `total` exceeds `fatal + error + warning + no_problem + in_progress`
655  /// (e.g. a paused run whose `Blocked` tasks were counted in `total` but omitted from
656  /// `in_progress`, leaving only a ~10% stub bar) must fold the unaccounted remainder into
657  /// `in_progress` so its bar still totals 100% and `has_in_progress` marks it intermediate.
658  #[test]
659  fn transform_folds_unaccounted_blocked_tasks_into_in_progress() {
660    let paused_frozen = RunMetadata {
661      total: 1000,
662      no_problem: 70,
663      warning: 20,
664      error: 8,
665      fatal: 2,
666      in_progress: 0, // 900 Blocked tasks were omitted from in_progress when frozen
667      start_time: "2026-10-04T12:00:00Z".to_string(),
668      end_time: "2026-10-05T12:00:00Z".to_string(),
669      description: "paused run".to_string(),
670      ..Default::default()
671    };
672    let finished = RunMetadata {
673      total: 1000,
674      no_problem: 800,
675      warning: 150,
676      error: 40,
677      fatal: 10,
678      in_progress: 0,
679      start_time: "2026-10-06T12:00:00Z".to_string(),
680      end_time: "2026-10-07T12:00:00Z".to_string(),
681      description: "finished run".to_string(),
682      ..Default::default()
683    };
684    let stack = RunMetadataStack::transform(&[paused_frozen, finished]);
685
686    let paused_rows: Vec<_> = stack.iter().filter(|r| r.run_id == 0).collect();
687    assert!(
688      paused_rows.iter().all(|r| r.has_in_progress),
689      "paused run with unaccounted tasks is flagged as intermediate"
690    );
691    let paused_in_progress = paused_rows
692      .iter()
693      .find(|r| r.severity == "in_progress")
694      .unwrap();
695    assert!(
696      (paused_in_progress.percent - 90.0).abs() < 1e-4,
697      "900 unaccounted tasks fold into 90% in_progress (got {})",
698      paused_in_progress.percent
699    );
700    let paused_sum: f32 = paused_rows.iter().map(|r| r.percent).sum();
701    assert!(
702      (paused_sum - 100.0).abs() < 1e-4,
703      "paused run bar totals 100% instead of a 10% stub (got {paused_sum})"
704    );
705
706    let finished_rows: Vec<_> = stack.iter().filter(|r| r.run_id == 1).collect();
707    assert!(
708      finished_rows.iter().all(|r| !r.has_in_progress),
709      "fully completed run is not flagged as intermediate"
710    );
711  }
712}