1#![allow(clippy::extra_unused_lifetimes)]
2use chrono::prelude::*;
3use diesel::result::Error;
4use diesel::*;
5use serde::Serialize;
6use std::collections::HashSet;
7
8use 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))]
21pub struct HistoricalRun {
23 pub id: i32,
25 pub service_id: i32,
27 pub corpus_id: i32,
29 pub total: i32,
31 pub invalid: i32,
33 pub fatal: i32,
35 pub error: i32,
37 pub warning: i32,
39 pub no_problem: i32,
41 pub in_progress: i32,
43 pub start_time: NaiveDateTime,
45 pub end_time: Option<NaiveDateTime>,
47 pub owner: String,
49 pub description: String,
51 pub public_id: uuid::Uuid,
54}
55
56#[derive(Debug, Serialize, Clone, Default)]
57pub struct RunMetadata {
59 pub total: i32,
61 pub invalid: i32,
63 pub fatal: i32,
65 pub error: i32,
67 pub warning: i32,
69 pub no_problem: i32,
71 pub in_progress: i32,
73 pub start_time: String,
75 pub end_time: String,
77 pub owner: String,
79 pub description: String,
81}
82impl RunMetadata {
83 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 _ => 0,
97 };
98 field_i32 as f32
99 }
100}
101
102#[derive(Debug, Serialize, Clone)]
103pub struct RunMetadataStack {
106 pub run_id: usize,
109 pub has_in_progress: bool,
112 pub severity: String,
114 pub severity_numeric: i32,
116 pub percent: f32,
118 pub total: i32,
120 pub start_time: String,
122 pub end_time: String,
124 pub owner: String,
126 pub description: String,
128}
129impl RunMetadataStack {
130 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 if run.description == "extending corpus with more entries" {
150 continue;
151 }
152 let total = run.field_f32("total");
153 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)]
192pub struct NewHistoricalRun {
194 pub service_id: i32,
196 pub corpus_id: i32,
198 pub description: String,
200 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 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 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 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 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 pub fn mark_completed(&self, connection: &mut PgConnection) -> Result<bool, Error> {
287 use diesel::dsl::now;
288 if self.end_time.is_some() {
291 return Ok(false);
292 }
293 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 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 if service <= 2 {
336 return Ok(false);
337 }
338 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 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 match open {
362 Some(run) => run.mark_completed(connection),
363 None => Ok(false),
364 }
365 }
366
367 #[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 #[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; }
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#[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
439fn 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
460fn 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 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; }
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; }
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 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 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 #[test]
567 fn transform_skips_zero_total_runs_so_one_doesnt_blank_the_chart() {
568 let zero_total = RunMetadata {
569 invalid: 5, 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 #[test]
598 fn transform_assigns_distinct_run_ids_to_same_minute_and_same_second_runs() {
599 let runs = vec![
600 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 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 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 #[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, 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}