runnerd-core 0.1.3

Config, domain logic and API types shared by runnerd and its clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
//! The history's search, sorts, timeline and compare (ADR 0135): the store's SQL gives the pages, lanes and pairs
//! `api` defines, over generated histories with ties, unknown keys, record notes and restarts; each response is of
//! one moment; and a history an older runnerd wrote reads the same.

use std::path::Path;

use rusqlite::{Connection, params};

use super::{keep_since, user_version};
use crate::api::{
    self, BarEnd, Baseline, FigureKind, GapKind, JobComparison, JobList, JobQuery, JobSort,
    JobSummary, RecordFilter, RecordMark, SlotTimeline, SortOrder, Span, StepMatch,
};
use crate::store::{Store, VERSION};
use crate::testdir::TestDir;

/// The schema at version 21, as runnerd 0.0.23 to 0.1.0 created it.
const SCHEMA_21: &str = include_str!("schema-21.sql");

/// The schema at version 22, before observation sessions.
const SCHEMA_22: &str = include_str!("schema-22.sql");

/// 2026-10-23T01:00:00Z, in seconds.
const T0: u64 = 1_792_717_200;

/// A small random number generator with a fixed seed, so a failing history is the same on every run.
struct Rng(u64);

impl Rng {
    fn next(&mut self, below: u64) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0 % below
    }

    fn pick<'item, T>(&mut self, items: &'item [T]) -> &'item T {
        &items[usize::try_from(self.next(items.len() as u64)).unwrap()]
    }
}

/// A job row as the history holds it, times in ms.
#[derive(Clone)]
struct Row {
    id: u64,
    repository: &'static str,
    workflow: Option<&'static str>,
    name: &'static str,
    branch: Option<&'static str>,
    state: &'static str,
    conclusion: Option<&'static str>,
    queued_at: u64,
    started_at: Option<u64>,
    finished_at: Option<u64>,
    memory_peak: Option<u64>,
    /// `profile`, `slot`, container start and removal (ms).
    runner: Option<(&'static str, usize, u64, Option<u64>)>,
}

fn insert(db: &Connection, row: &Row) {
    let runner = row.runner.map(|_| format!("r{}", row.id));
    db.execute(
        "INSERT INTO jobs (id, repository, run_id, run_attempt, workflow, name, branch, labels, state, conclusion, \
         runner, queued_at, started_at, finished_at, memory_peak) \
         VALUES (?1, ?2, ?1, 1, ?3, ?4, ?5, '[\"self-hosted\"]', ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
        params![
            row.id,
            row.repository,
            row.workflow,
            row.name,
            row.branch,
            row.state,
            row.conclusion,
            runner,
            row.queued_at,
            row.started_at,
            row.finished_at,
            row.memory_peak
        ],
    )
    .unwrap();
    if let (Some(name), Some((profile, slot, started, removed))) = (runner, row.runner) {
        db.execute(
            "INSERT INTO runners (name, repository, profile, slot, container, started_at, removed_at) \
             VALUES (?1, ?2, ?3, ?4, ?1, ?5, ?6)",
            params![name, row.repository, profile, slot, started, removed],
        )
        .unwrap();
    }
}

/// A name longer than a list shows, of characters of 1 to 4 bytes.
fn long_name() -> &'static str {
    static NAME: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    NAME.get_or_init(|| "a\u{e9}\u{20ac}\u{1d11e}".repeat(api::JOB_TEXT_MAX))
}

/// `count` jobs with many equal and unknown keys, odd names and every record note, times with milliseconds.
fn generated(seed: u64, count: u64) -> Vec<Row> {
    let mut rng = Rng(seed);
    (1..=count)
        .map(|id| {
            let state = *rng.pick(&[
                "completed",
                "completed",
                "running",
                "queued",
                "lost",
                "elsewhere",
            ]);
            let queued_at = (T0 + rng.next(4) * 10) * 1000 + rng.next(1000);
            let started_at = match state {
                "queued" => None,
                "elsewhere" if rng.next(2) == 0 => None,
                _ => Some(queued_at + rng.next(3) * 5000 + rng.next(1000)),
            };
            let finished_at = match (state, started_at) {
                ("running" | "queued", _) => None,
                ("lost", _) if rng.next(2) == 0 => None,
                (_, Some(started)) => Some(started + rng.next(3) * 7000 + rng.next(1000)),
                (_, None) => Some(queued_at + 1000),
            };
            Row {
                id,
                repository: rng.pick(&["o/a", "o/b"]),
                workflow: *rng.pick(&[Some("CI"), None, Some("Re%lease")]),
                name: rng.pick(&[
                    "build",
                    "b_uild",
                    "baulk",
                    "engel",
                    "be\0fore NEEDLE",
                    long_name(),
                ]),
                branch: *rng.pick(&[Some("main"), None, Some("feat/A")]),
                state,
                conclusion: (state == "completed").then(|| *rng.pick(&["success", "failure"])),
                queued_at,
                started_at,
                finished_at,
                memory_peak: (rng.next(3) > 0).then(|| rng.next(3) << 30),
                runner: started_at.filter(|_| state != "elsewhere").map(|started| {
                    (
                        *rng.pick(&["jvm", "node"]),
                        1 + usize::try_from(rng.next(2)).unwrap(),
                        started,
                        finished_at.map(|at| at + 500),
                    )
                }),
            }
        })
        .collect()
}

/// A note for each kind of record, on some of the jobs.
fn notes(db: &Connection, count: u64) {
    for id in (1..=count).step_by(3) {
        let sql = match id % 5 {
            0 => "INSERT INTO records (job, created_at, bytes) VALUES (?1, 1000, 10)",
            1 => {
                "INSERT INTO records (job, created_at, bytes, removed_at, removed_by) VALUES (?1, 1, 1, 2, 'age')"
            }
            2 => "INSERT INTO records (job, skipped) VALUES (?1, 'too little free disk')",
            3 => {
                "INSERT INTO records (job, removed_at, removed_by, gone_at) VALUES (?1, 2, 'user', 3)"
            }
            // Found gone from Docker: removed outside runnerd.
            _ => {
                "INSERT INTO records (job, created_at, bytes, gone_at) VALUES (?1, 1000, 10, 3000)"
            }
        };
        db.execute(sql, [id]).unwrap();
    }
}

/// Every page of `query`, following each `next`, reopening the store after every other page.
async fn store_pages(path: &Path, query: &JobQuery) -> Vec<JobList> {
    let mut store = Store::open(path).unwrap();
    let mut query = query.clone();
    let mut pages = Vec::new();
    loop {
        let list = store.jobs(query.clone()).await.unwrap();
        let next = list.page.next;
        pages.push(list);
        if pages.len() % 2 == 0 {
            drop(store);
            store = Store::open(path).unwrap();
        }
        match next {
            Some(next) => query.before = Some(next),
            None => return pages,
        }
    }
}

/// The same pages as `api` defines them over the jobs the store reads.
fn core_pages(query: &JobQuery, jobs: &[JobSummary]) -> Vec<JobList> {
    let mut query = query.clone();
    let mut pages = Vec::new();
    loop {
        let list: JobList = query.page(jobs).unwrap();
        let next = list.page.next;
        pages.push(list);
        match next {
            Some(next) => query.before = Some(next),
            None => return pages,
        }
    }
}

/// Every job of the history, as its own page reads it: its text whole.
async fn every_job(store: &Store) -> Vec<JobSummary> {
    let query = JobQuery {
        limit: Some(api::JOBS_PAGE_MAX),
        ..JobQuery::default()
    };
    let mut jobs = Vec::new();
    for listed in store.jobs(query).await.unwrap().page.jobs {
        jobs.push(store.job(listed.id).await.unwrap().unwrap().summary);
    }
    jobs
}

#[tokio::test]
async fn the_historys_pages_are_the_ones_core_defines_for_every_search_sort_and_filter_across_restarts()
 {
    const COUNT: u64 = 90;
    let dir = TestDir::new("lens-pages");
    let path = dir.0.join("runnerd.db");
    drop(Store::open(&path).unwrap());
    for seed in [7, 1_000_003] {
        let db = Connection::open(&path).unwrap();
        db.execute_batch("DELETE FROM jobs; DELETE FROM runners; DELETE FROM records;")
            .unwrap();
        for row in generated(seed, COUNT) {
            insert(&db, &row);
        }
        notes(&db, COUNT);
        drop(db);
        let store = Store::open(&path).unwrap();
        let jobs = every_job(&store).await;
        assert_eq!(jobs.len() as u64, COUNT);
        for job in &jobs {
            let note = store.job(job.id).await.unwrap().unwrap().record;
            assert_eq!(
                job.record_mark,
                note.as_ref().map(RecordMark::of),
                "job {}'s mark is its note's state",
                job.id
            );
        }
        drop(store);
        let filters = [
            JobQuery::default(),
            JobQuery {
                q: Some("b_u".to_owned()),
                ..JobQuery::default()
            },
            JobQuery {
                q: Some("E%L".to_owned()),
                ..JobQuery::default()
            },
            JobQuery {
                q: Some("needle".to_owned()),
                ..JobQuery::default()
            },
            JobQuery {
                q: Some("feat/a".to_owned()),
                repository: Some("o/a".to_owned()),
                ..JobQuery::default()
            },
            JobQuery {
                branch: Some("main".to_owned()),
                record: Some(RecordFilter::Any),
                ..JobQuery::default()
            },
            JobQuery {
                record: Some(RecordFilter::Skipped),
                ..JobQuery::default()
            },
            JobQuery {
                state: Some(api::JobState::Completed),
                since: Some(T0 + 10),
                until: Some(T0 + 30),
                ..JobQuery::default()
            },
        ];
        let sorts = [
            None,
            Some(JobSort::Queued),
            Some(JobSort::Wait),
            Some(JobSort::Run),
            Some(JobSort::Memory),
        ];
        for filter in &filters {
            for sort in sorts {
                for order in [None, Some(SortOrder::Asc)] {
                    for limit in [1, 4, 500] {
                        let query = JobQuery {
                            sort,
                            order: sort.and(order),
                            limit: Some(limit),
                            ..filter.clone()
                        };
                        let expected = core_pages(&query, &jobs);
                        let mut read = store_pages(&path, &query).await;
                        // A restart counts the time no runnerd ran into an open job's wait.
                        for job in read.iter_mut().flat_map(|page| &mut page.page.jobs) {
                            job.timeline.unseen = 0;
                        }
                        assert_eq!(read, expected, "{query:?}");
                    }
                }
            }
        }
    }
}

#[tokio::test]
async fn a_page_is_read_in_one_snapshot_while_jobs_are_pruned() {
    let dir = TestDir::new("lens-snapshot");
    let path = dir.0.join("runnerd.db");
    let store = Store::open(&path).unwrap();
    let db = Connection::open(&path).unwrap();
    for row in generated(3, 50) {
        insert(&db, &row);
    }
    drop(db);
    // Pruning deletes old jobs, a batch at a time. Here the first half goes and comes back, again and again.
    let writer = path.clone();
    let pruner = tokio::task::spawn_blocking(move || {
        let db = Connection::open(&writer).unwrap();
        db.execute_batch("CREATE TEMP TABLE first AS SELECT * FROM jobs WHERE id <= 25")
            .unwrap();
        for _ in 0..300 {
            db.execute_batch(
                "DELETE FROM jobs WHERE id <= 25; INSERT INTO jobs SELECT * FROM first;",
            )
            .unwrap();
        }
    });
    let mut reads = 0;
    while !pruner.is_finished() {
        let list = store
            .jobs(JobQuery {
                limit: Some(50),
                sort: Some(JobSort::Queued),
                ..JobQuery::default()
            })
            .await
            .unwrap();
        let count = list.page.jobs.len();
        assert!(
            count == 25 || count == 50,
            "a page holds the jobs of one moment, not {count}"
        );
        reads += 1;
    }
    pruner.await.unwrap();
    assert!(reads > 0, "the jobs were read while they were pruned");
}

/// A daemon's session from `from` to its last stored host sample at `to`, in seconds.
fn session(db: &Connection, from: u64, to: u64) {
    db.execute(
        "INSERT INTO sessions (started_at, sampled_at) VALUES (?1, ?2)",
        [from * 1000, to * 1000],
    )
    .unwrap();
}

/// A host sample every 2 s from `from` to `to`, in seconds.
fn watched(db: &Connection, from: u64, to: u64) {
    for at in (from..=to).step_by(2) {
        db.execute(
            "INSERT INTO host_samples (at, cpu, memory) VALUES (?1, 0, 0)",
            [at * 1000],
        )
        .unwrap();
    }
}

#[tokio::test]
async fn a_timeline_is_the_one_core_lays_out_from_the_jobs_overlapping_its_window() {
    let dir = TestDir::new("lens-timeline");
    let path = dir.0.join("runnerd.db");
    drop(Store::open(&path).unwrap());
    let db = Connection::open(&path).unwrap();
    let rows = generated(11, 80);
    for row in &rows {
        insert(&db, row);
    }
    keep_since(&path, 0);
    watched(&db, T0, T0 + 12);
    session(&db, T0, T0 + 12);
    // A restart: no sample from T0 + 12 to T0 + 20.
    watched(&db, T0 + 20, T0 + 40);
    session(&db, T0 + 20, T0 + 40);
    drop(db);
    let store = Store::open(&path).unwrap();
    let jobs = every_job(&store).await;
    for window in [
        Span {
            from: T0,
            to: T0 + 25,
        },
        Span {
            from: T0 + 12,
            to: T0 + 15,
        },
        Span {
            from: T0 + 30,
            to: T0 + 3600,
        },
    ] {
        let read = store.timeline(window).await.unwrap();
        let laid = SlotTimeline::of(&jobs, window, read.observed.clone(), read.history_from);
        let bars = |timeline: &SlotTimeline| {
            let lanes: Vec<(String, usize, Vec<u64>)> = timeline
                .lanes
                .iter()
                .map(|lane| {
                    (
                        lane.profile.clone(),
                        lane.slot,
                        lane.bars.iter().map(|bar| bar.job).collect::<Vec<u64>>(),
                    )
                })
                .filter(|lane| !lane.2.is_empty())
                .collect();
            (lanes, timeline.unassigned.clone())
        };
        assert_eq!(bars(&read), bars(&laid), "{window:?}");
    }
    let read = store
        .timeline(Span {
            from: T0,
            to: T0 + 25,
        })
        .await
        .unwrap();
    assert_eq!(
        read.observed,
        [
            Span {
                from: T0,
                to: T0 + 12
            },
            Span {
                from: T0 + 20,
                to: T0 + 24
            }
        ],
        "the restart is a gap"
    );
}

/// A finished job of `o/r` in `profile`'s `slot`, which ran from `from` to `to` (seconds); its runner was up a
/// second around it.
fn slot_job(id: u64, profile: &'static str, slot: usize, from: u64, to: Option<u64>) -> Row {
    Row {
        id,
        repository: "o/r",
        workflow: Some("CI"),
        name: "build",
        branch: Some("main"),
        state: if to.is_some() { "completed" } else { "running" },
        conclusion: to.map(|_| "success"),
        queued_at: (from - 1) * 1000,
        started_at: Some(from * 1000),
        finished_at: to.map(|to| to * 1000),
        memory_peak: None,
        runner: Some((
            profile,
            slot,
            (from - 1) * 1000,
            to.map(|to| (to + 1) * 1000),
        )),
    }
}

#[tokio::test]
async fn an_empty_historys_timeline_has_nothing_and_watched_nothing() {
    let dir = TestDir::new("lens-empty");
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let window = Span {
        from: T0,
        to: T0 + 100,
    };
    let empty = store.timeline(window).await.unwrap();
    assert_eq!(
        empty,
        SlotTimeline {
            since: T0,
            until: T0 + 100,
            history_from: empty.history_from,
            ..SlotTimeline::default()
        }
    );
}

/// Jobs of slots a reload took away, a lost and a waiting job, a warm runner, and samples around a restart, some
/// held.
fn slots_history(store: &Store, path: &Path) {
    let db = Connection::open(path).unwrap();
    let mut lost = slot_job(4, "jvm", 2, T0 + 150, None);
    lost.state = "lost";
    let mut waiting = slot_job(5, "jvm", 1, T0 + 170, None);
    (waiting.state, waiting.started_at, waiting.runner) = ("queued", None, None);
    for row in [
        slot_job(1, "jvm", 1, T0 + 90, Some(T0 + 120)),
        // A third slot a later reload took away, and a profile it removed.
        slot_job(2, "jvm", 3, T0 + 190, Some(T0 + 400)),
        slot_job(3, "retired", 1, T0 + 130, Some(T0 + 140)),
        lost,
        waiting,
    ] {
        insert(&db, &row);
    }
    // A warm runner up with no job.
    db.execute(
        "INSERT INTO runners (name, repository, profile, slot, container, started_at, purpose) \
         VALUES ('warm', 'o/r', 'jvm', 1, 'warm', ?1, 'warm')",
        [(T0 + 125) * 1000],
    )
    .unwrap();
    watched(&db, T0 + 100, T0 + 140);
    session(&db, T0 + 95, T0 + 140);
    watched(&db, T0 + 160, T0 + 180);
    // The latest session, as this daemon's is: it goes on past its last stored sample.
    session(&db, T0 + 158, T0 + 180);
    drop(db);
    keep_since(path, (T0 + 110) * 1000);
    // Samples not stored yet are watched time too.
    for at in (T0 + 182..T0 + 190).step_by(2) {
        store.host_sample(api::HostSample {
            at,
            cpu: 0,
            memory: 0,
        });
    }
}

#[tokio::test]
async fn a_job_whose_container_was_removed_before_github_ended_it_ends_at_the_removal() {
    let dir = TestDir::new("lens-killed");
    let path = dir.0.join("runnerd.db");
    drop(Store::open(&path).unwrap());
    let db = Connection::open(&path).unwrap();
    // `stop --force` removed job 1's container at T0 + 30; GitHub said it was cancelled at T0 + 316, two seconds
    // after job 2 started in the same slot.
    let mut killed = slot_job(1, "jvm", 1, T0 + 10, Some(T0 + 316));
    killed.runner = Some(("jvm", 1, (T0 + 9) * 1000, Some((T0 + 30) * 1000)));
    insert(&db, &killed);
    insert(&db, &slot_job(2, "jvm", 1, T0 + 314, Some(T0 + 400)));
    keep_since(&path, 0);
    drop(db);
    let store = Store::open(&path).unwrap();
    let jobs = every_job(&store).await;
    for window in [
        Span {
            from: T0,
            to: T0 + 500,
        },
        // After the removal, before GitHub's end: the killed job is no longer in it.
        Span {
            from: T0 + 100,
            to: T0 + 500,
        },
    ] {
        let read = store.timeline(window).await.unwrap();
        let laid = SlotTimeline::of(&jobs, window, read.observed.clone(), read.history_from);
        let ends = |timeline: &SlotTimeline| {
            timeline
                .lanes
                .iter()
                .flat_map(|lane| lane.bars.iter().map(|bar| (bar.job, bar.end)))
                .collect::<Vec<_>>()
        };
        assert_eq!(ends(&read), ends(&laid), "{window:?}");
        let killed = ends(&read).into_iter().find(|(job, _)| *job == 1);
        assert_eq!(
            killed.map(|(_, end)| end),
            (window.from < T0 + 30).then_some(BarEnd::At { at: T0 + 30 }),
            "{window:?}: the killed job's bar ends at its removal, before the next job starts"
        );
    }
}

#[tokio::test]
async fn a_timeline_keeps_old_slots_real_ends_restarts_and_unknown_time_apart() {
    let dir = TestDir::new("lens-slots");
    let path = dir.0.join("runnerd.db");
    let store = Store::open(&path).unwrap();
    let window = Span {
        from: T0 + 100,
        to: T0 + 200,
    };
    slots_history(&store, &path);
    let timeline = store.timeline(window).await.unwrap();
    let lane = |profile: &str, slot: usize| {
        timeline
            .lanes
            .iter()
            .find(|lane| (lane.profile.as_str(), lane.slot) == (profile, slot))
            .unwrap()
    };
    assert_eq!(timeline.history_from, T0 + 110);
    assert_eq!(
        timeline.observed,
        [
            Span {
                from: T0 + 110,
                to: T0 + 140
            },
            Span {
                from: T0 + 160,
                to: T0 + 188
            },
        ],
        "watched from the history's start, around the restart, the held samples too"
    );
    let first = lane("jvm", 1);
    assert_eq!(
        (first.bars[0].started_at, first.bars[0].end),
        (Some(T0 + 90), BarEnd::At { at: T0 + 120 }),
        "a bar keeps its real ends"
    );
    assert_eq!(
        first
            .runners
            .iter()
            .map(|runner| (runner.name.as_str(), runner.end))
            .collect::<Vec<_>>(),
        [("r1", BarEnd::At { at: T0 + 121 }), ("warm", BarEnd::Open)]
    );
    assert_eq!(lane("jvm", 3).bars[0].end, BarEnd::At { at: T0 + 400 });
    assert_eq!(lane("retired", 1).bars.len(), 1);
    assert_eq!(lane("jvm", 2).bars[0].end_words(), Some("end unknown"));
    assert_eq!(
        timeline
            .unassigned
            .iter()
            .map(|bar| bar.job)
            .collect::<Vec<_>>(),
        [5]
    );
    let gaps: Vec<(u64, u64, GapKind)> = first
        .gaps(&timeline)
        .into_iter()
        .map(|gap| (gap.span.from - T0, gap.span.to - T0, gap.kind))
        .collect();
    assert_eq!(
        gaps,
        [
            (120, 140, GapKind::NoJob),
            (140, 160, GapKind::Unknown),
            (160, 188, GapKind::NoJob),
            (188, 200, GapKind::Unknown),
        ],
        "a warm runner is no job; unwatched time is unknown, never idle"
    );
}

#[tokio::test]
async fn a_restart_between_two_samples_is_unwatched_and_so_is_time_before_the_first_session() {
    let dir = TestDir::new("lens-sessions");
    let path = dir.0.join("runnerd.db");
    let store = Store::open(&path).unwrap();
    keep_since(&path, 0);
    let db = Connection::open(&path).unwrap();
    // Samples from before any session the history recorded.
    watched(&db, T0 - 20, T0 - 2);
    // A daemon stopped at T0 + 11 and the next started at T0 + 13: its samples are 2 s apart.
    watched(&db, T0, T0 + 10);
    session(&db, T0, T0 + 10);
    watched(&db, T0 + 12, T0 + 20);
    session(&db, T0 + 11, T0 + 20);
    drop(db);
    let timeline = store
        .timeline(Span {
            from: T0 - 20,
            to: T0 + 20,
        })
        .await
        .unwrap();
    assert_eq!(
        timeline.observed,
        [
            Span {
                from: T0,
                to: T0 + 10
            },
            Span {
                from: T0 + 12,
                to: T0 + 20
            }
        ],
        "a restart shorter than three intervals is still a gap"
    );
}

#[tokio::test]
async fn a_daemon_notes_its_session_and_each_host_sample_it_stores_in_it() {
    let dir = TestDir::new("lens-session-write");
    let path = dir.0.join("runnerd.db");
    let sessions = || -> Vec<(u64, Option<u64>)> {
        Connection::open(&path)
            .unwrap()
            .prepare("SELECT started_at, sampled_at FROM sessions ORDER BY id")
            .unwrap()
            .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
            .unwrap()
            .collect::<rusqlite::Result<_>>()
            .unwrap()
    };
    let store = Store::open(&path).unwrap();
    let at = crate::time::now_ms() / 1000;
    for second in [at, at + 2, at + 4] {
        store.host_sample(api::HostSample {
            at: second,
            cpu: 0,
            memory: 0,
        });
    }
    store.flush().await;
    let first = sessions();
    assert_eq!(first.len(), 1);
    assert_eq!(
        first[0].1,
        Some((at + 4) * 1000),
        "its latest stored sample"
    );
    drop(store);
    let reopened = Store::open(&path).unwrap();
    reopened.flush().await;
    let both = sessions();
    assert_eq!(
        (both.len(), both[1].1),
        (2, None),
        "a new session, no sample yet"
    );
}

#[tokio::test]
async fn a_v22_history_reads_its_old_samples_as_unwatched_once_opened() {
    let dir = TestDir::new("lens-22");
    let path = dir.0.join("runnerd.db");
    let db = Connection::open(&path).unwrap();
    db.execute_batch(SCHEMA_22).unwrap();
    insert(&db, &slot_job(1, "jvm", 1, T0 + 10, Some(T0 + 20)));
    watched(&db, T0, T0 + 40);
    db.pragma_update(None, "user_version", 22).unwrap();
    drop(db);
    let store = Store::open(&path).unwrap();
    assert_eq!(user_version(&path), VERSION);
    keep_since(&path, 0);
    let timeline = store
        .timeline(Span {
            from: T0,
            to: T0 + 40,
        })
        .await
        .unwrap();
    assert_eq!(timeline.lanes[0].bars[0].job, 1);
    assert_eq!(
        timeline.observed,
        [],
        "no session vouches for samples a runnerd before sessions stored"
    );
}

/// A lane's gaps, in seconds from `T0`.
fn lane_gaps(timeline: &SlotTimeline, profile: &str, slot: usize) -> Vec<(u64, u64, GapKind)> {
    timeline
        .lanes
        .iter()
        .find(|lane| (lane.profile.as_str(), lane.slot) == (profile, slot))
        .unwrap()
        .gaps(timeline)
        .into_iter()
        .map(|gap| (gap.span.from - T0, gap.span.to - T0, gap.kind))
        .collect()
}

#[tokio::test]
async fn a_lane_with_a_bar_left_out_or_an_unknown_end_is_never_free() {
    let window = Span {
        from: T0,
        to: T0 + 100,
    };
    // A job running in jvm 1 since before the window, which the cap leaves out for the jobs queued after it.
    let dir = TestDir::new("lens-whole-cap");
    let path = dir.0.join("runnerd.db");
    let store = Store::open(&path).unwrap();
    keep_since(&path, 0);
    let db = Connection::open(&path).unwrap();
    insert(&db, &slot_job(1, "jvm", 1, T0 - 100, None));
    for id in 2..=api::TIMELINE_BARS_MAX as u64 + 1 {
        let mut waiting = slot_job(id, "jvm", 1, T0 + 1 + id % 90, None);
        (waiting.state, waiting.started_at, waiting.runner) = ("queued", None, None);
        insert(&db, &waiting);
    }
    watched(&db, T0, T0 + 100);
    session(&db, T0, T0 + 100);
    drop(db);
    let timeline = store.timeline(window).await.unwrap();
    assert!(timeline.cut_before.is_some(), "the cap left a bar out");
    assert_eq!(
        lane_gaps(&timeline, "jvm", 1),
        [(0, 100, GapKind::Unknown)],
        "its runner's lane, without its bar, is not free"
    );

    // Lost before the window with no end; its runner was removed at T0 + 50.
    let dir = TestDir::new("lens-whole-lost");
    let path = dir.0.join("runnerd.db");
    let store = Store::open(&path).unwrap();
    keep_since(&path, 0);
    let db = Connection::open(&path).unwrap();
    let mut lost = slot_job(1, "jvm", 1, T0 - 100, None);
    lost.state = "lost";
    lost.runner = Some(("jvm", 1, (T0 - 101) * 1000, Some((T0 + 50) * 1000)));
    insert(&db, &lost);
    watched(&db, T0, T0 + 100);
    session(&db, T0, T0 + 100);
    drop(db);
    let timeline = store.timeline(window).await.unwrap();
    assert_eq!(
        lane_gaps(&timeline, "jvm", 1),
        [(0, 50, GapKind::Unknown), (50, 100, GapKind::NoJob)],
        "it may have run until its runner went"
    );
}

#[tokio::test]
async fn a_timeline_past_its_cap_keeps_the_latest_and_says_from_when() {
    let dir = TestDir::new("lens-cap");
    let path = dir.0.join("runnerd.db");
    let store = Store::open(&path).unwrap();
    let db = Connection::open(&path).unwrap();
    let count = api::TIMELINE_BARS_MAX as u64 + 5;
    for id in 1..=count {
        insert(&db, &slot_job(id, "jvm", 1, T0 + id, Some(T0 + id + 1)));
    }
    drop(db);
    let timeline = store
        .timeline(Span {
            from: T0,
            to: T0 + 10_000,
        })
        .await
        .unwrap();
    assert_eq!(timeline.lanes[0].bars.len(), api::TIMELINE_BARS_MAX);
    assert_eq!(timeline.lanes[0].runners.len(), api::TIMELINE_BARS_MAX);
    assert_eq!(
        timeline.lanes[0].bars[0].job, 6,
        "the oldest five are left out"
    );
    assert_eq!(timeline.cut_before, Some(T0 + 5), "job 6 was queued then");
}

/// Job `id`'s steps, in seconds: the set-up, a tests step of `tests` seconds, and two named `Run lint`.
fn steps(db: &Connection, id: u64, from: u64, tests: u64, renamed: bool) {
    let name = if renamed {
        "Run unit tests"
    } else {
        "Run tests"
    };
    for (number, name, start, end) in [
        (1, "Set up job", from, from + 2),
        (2, name, from + 2, from + 2 + tests),
        (3, "Run lint", from + 2 + tests, from + 4 + tests),
        (4, "Run lint", from + 4 + tests, from + 6 + tests),
    ] {
        db.execute(
            "INSERT INTO steps (job, number, name, status, conclusion, started_at, completed_at) \
             VALUES (?1, ?2, ?3, 'completed', 'success', ?4, ?5)",
            params![id, number, name, start * 1000, end * 1000],
        )
        .unwrap();
    }
}

/// Runs of job `build` on `main` (1, 2 and 5), a failed one, one on `dev` and a job of another name, each with a
/// tests step and two steps named `Run lint`; job 5's and job 2's tests steps sampled, job 1's samples pruned.
fn compare_history(path: &Path) {
    let db = Connection::open(path).unwrap();
    let mut failed = slot_job(3, "jvm", 1, T0 + 300, Some(T0 + 400));
    failed.conclusion = Some("failure");
    let mut other_branch = slot_job(4, "jvm", 1, T0 + 500, Some(T0 + 600));
    other_branch.branch = Some("dev");
    let mut other_name = slot_job(6, "jvm", 1, T0 + 700, Some(T0 + 800));
    other_name.name = "lint";
    for (row, tests) in [
        (slot_job(1, "jvm", 1, T0, Some(T0 + 100)), 60),
        (slot_job(2, "jvm", 1, T0 + 100, Some(T0 + 200)), 60),
        (failed, 60),
        (other_branch, 60),
        (slot_job(5, "jvm", 2, T0 + 1000, Some(T0 + 1100)), 80),
        (other_name, 60),
    ] {
        let from = row.started_at.unwrap() / 1000;
        insert(&db, &row);
        steps(&db, row.id, from, tests, false);
    }
    // Job 5's tests step sampled every 2 s; its baseline, job 2, sampled too, job 1 no longer.
    for (runner, from, to) in [("r5", T0 + 1002, T0 + 1082), ("r2", T0 + 102, T0 + 162)] {
        for at in (from + 2..=to).step_by(2) {
            db.execute(
                "INSERT INTO samples (runner, at, cpu, cpu_usage, memory, network_received, network_sent) \
                 VALUES (?1, ?2, 1000, 0, ?3, 0, 0)",
                params![runner, at * 1000, if runner == "r5" { 3u64 << 30 } else { 2 << 30 }],
            )
            .unwrap();
        }
    }
}

#[tokio::test]
async fn compare_reads_steps_bounded_and_cut_as_core_does() {
    let dir = TestDir::new("lens-compare-bounded");
    let path = dir.0.join("runnerd.db");
    let store = Store::open(&path).unwrap();
    compare_history(&path);
    let db = Connection::open(&path).unwrap();
    // Jobs 5 and 2 each gain 600 more steps, names of 2,000 bytes, one with a NUL in its first 800.
    for id in [5u64, 2] {
        for number in 5..605u32 {
            let lead = if number == 7 { "be\0fore" } else { "step" };
            let name = format!("{lead} {number:04} {}", "é".repeat(995));
            db.execute(
                "INSERT INTO steps (job, number, name, status, conclusion, started_at, completed_at) \
                 VALUES (?1, ?2, ?3, 'completed', 'success', NULL, NULL)",
                params![id, number, name],
            )
            .unwrap();
        }
    }
    let compared = store.compare(5, None).await.unwrap().unwrap();
    let history = [
        store.job(5).await.unwrap().unwrap(),
        store.job(2).await.unwrap().unwrap(),
    ];
    assert_eq!(history[0].steps.len(), 604, "the job keeps every step");
    let mut usages = Vec::new();
    for job in &history {
        let series = store
            .job_samples(job.summary.id, std::time::Duration::from_secs(2))
            .await
            .unwrap()
            .unwrap();
        usages.push(api::StepUsage::of(&series.samples, &job.steps));
    }
    let in_memory = JobComparison::in_history(5, None, &history, |job| {
        usages[usize::from(job.summary.id == 2)].clone()
    });
    assert_eq!(
        in_memory.as_ref(),
        Some(&compared),
        "the store cuts the steps as core does"
    );
    assert!(compared.steps_cut, "a comparison says it left steps out");
    assert!(
        compared.steps.len() < 200,
        "the names' bytes bound the steps read: {}",
        compared.steps.len()
    );
    assert!(
        compared.steps[6].name.starts_with("before 0007 "),
        "a NUL inside the bytes read is kept, then made plain: {:?}",
        compared.steps[6].name.get(..16)
    );
}

#[tokio::test]
async fn compare_picks_the_baseline_pairs_steps_by_name_and_samples_only_what_is_covered() {
    let dir = TestDir::new("lens-compare");
    let path = dir.0.join("runnerd.db");
    let store = Store::open(&path).unwrap();
    compare_history(&path);
    let compared = store.compare(5, None).await.unwrap().unwrap();
    assert!(
        matches!(
            compared.baseline,
            Baseline::Chosen {
                job: 2,
                asked: false,
                ..
            }
        ),
        "the latest earlier success on its branch: {:?}",
        compared.baseline
    );
    let usage = async |job: &api::Job| {
        let series = store
            .job_samples(job.summary.id, std::time::Duration::from_secs(2))
            .await
            .unwrap()
            .unwrap();
        api::StepUsage::of(&series.samples, &job.steps)
    };
    let history = [
        store.job(5).await.unwrap().unwrap(),
        store.job(2).await.unwrap().unwrap(),
    ];
    let usages = [usage(&history[0]).await, usage(&history[1]).await];
    let in_memory = JobComparison::in_history(5, None, &history, |job| {
        usages[usize::from(job.summary.id == 2)].clone()
    });
    assert_eq!(
        in_memory.as_ref(),
        Some(&compared),
        "core compares the history in memory, as the demo does, as the store does"
    );
    let tests = &compared.steps[1];
    assert_eq!(
        (tests.matched, tests.time.change_words()),
        (StepMatch::Matched, "+20s (+33%)".to_owned())
    );
    assert_eq!(
        tests
            .memory
            .map(|memory| (memory.sampled, memory.this, memory.baseline)),
        Some((true, Some(3 << 30), Some(2 << 30)))
    );
    assert_eq!(
        compared.steps[2..4]
            .iter()
            .map(|step| step.matched)
            .collect::<Vec<_>>(),
        [StepMatch::Ambiguous; 2]
    );
    assert!(
        compared
            .figures
            .iter()
            .any(|figure| figure.figure == FigureKind::Run && figure.change_words() == "same"),
        "{:?}",
        compared.figures
    );

    // Job 1, past sample retention: its step times compare, its steps' memory is not guessed.
    let asked = store.compare(5, Some(1)).await.unwrap().unwrap();
    assert!(matches!(
        asked.baseline,
        Baseline::Chosen {
            job: 1,
            asked: true,
            ..
        }
    ));
    assert_eq!(asked.steps[1].memory, None);
    assert_eq!(asked.steps[1].time.baseline, Some(60));

    let other = store.compare(5, Some(6)).await.unwrap().unwrap();
    assert_eq!(other.baseline, Baseline::Incompatible { job: 6 });
    assert_eq!(store.compare(5, Some(99)).await.unwrap(), None);
    assert_eq!(store.compare(99, None).await.unwrap(), None);
    let first = store.compare(1, None).await.unwrap().unwrap();
    assert_eq!(
        first.baseline,
        Baseline::Unavailable {
            reason: api::Unavailable::NoEarlierSuccess
        }
    );
    assert_eq!(
        JobComparison::baseline_of(
            &store.job(5).await.unwrap().unwrap().summary,
            &every_job(&store).await
        )
        .unwrap()
        .id,
        2,
        "core picks the same baseline from the same history"
    );
}

#[tokio::test]
async fn a_v21_history_is_searched_sorted_marked_and_laid_out_once_opened() {
    let dir = TestDir::new("lens-21");
    let path = dir.0.join("runnerd.db");
    let db = Connection::open(&path).unwrap();
    db.execute_batch(SCHEMA_21).unwrap();
    for row in [
        slot_job(1, "jvm", 1, T0, Some(T0 + 100)),
        slot_job(2, "jvm", 1, T0 + 200, Some(T0 + 250)),
    ] {
        insert(&db, &row);
        steps(&db, row.id, row.started_at.unwrap() / 1000, 30, row.id == 2);
    }
    db.execute(
        "INSERT INTO records (job, created_at, bytes) VALUES (1, 1000, 10)",
        [],
    )
    .unwrap();
    db.pragma_update(None, "user_version", 21).unwrap();
    drop(db);
    let store = Store::open(&path).unwrap();
    assert_eq!(user_version(&path), VERSION);
    let list = store
        .jobs(JobQuery {
            q: Some("BUILD".to_owned()),
            sort: Some(JobSort::Run),
            record: Some(RecordFilter::Kept),
            ..JobQuery::default()
        })
        .await
        .unwrap();
    assert_eq!(
        list.page
            .jobs
            .iter()
            .map(|job| (job.id, job.record_mark))
            .collect::<Vec<_>>(),
        [(1, Some(RecordMark::Kept))]
    );
    let timeline = store
        .timeline(Span {
            from: T0,
            to: T0 + 300,
        })
        .await
        .unwrap();
    assert_eq!(timeline.lanes[0].bars.len(), 2);
    let compared = store.compare(2, None).await.unwrap().unwrap();
    assert!(matches!(compared.baseline, Baseline::Chosen { job: 1, .. }));
    assert_eq!(
        compared
            .steps
            .iter()
            .filter(|step| matches!(step.matched, StepMatch::OnlyThis | StepMatch::OnlyBaseline))
            .count(),
        2,
        "a renamed step pairs with nothing"
    );
}