cbh_model 0.2.2

Implementation crate for cargo-bench-history - do not reference directly
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
//! Comparability: deciding which runs may be compared to each other, and how the
//! storage is partitioned so that only comparable runs share a series.
//!
//! The guiding rule (see the *Comparability & storage partitioning* section of
//! `DESIGN.md`) is to partition only by what makes results *fundamentally*
//! incomparable. The project selects the enclosing store, so results from two
//! projects never meet. Inside a project, a [`DiscriminantSet`] is engine, target
//! triple, and machine key. Everything else is recorded as metadata so its effect
//! stays visible in the timeline.

use std::cmp::Ordering;
use std::fmt;

use serde::{Deserialize, Serialize};

use super::constants::{OBJECTS_SEGMENT, STORAGE_VERSION};
use super::identifiers::{MachineKey, TargetTriple};

/// A benchmark engine: the measurement tool whose output a series accumulates.
///
/// Serializes to (and deserializes from) its stable lowercase
/// [identifier](Self::as_str) — `criterion`, `callgrind`, `alloc_tracker`,
/// `all_the_time` — so a [`DiscriminantSet`] flattened into a JSON report keeps
/// that exact wire name.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Engine {
    /// Criterion wall-clock benchmarks: noisy, with confidence intervals on every point.
    Criterion,
    /// Callgrind (via Gungraun) instruction counts: simulated and low-noise, yet
    /// still machine-dependent (microarchitecture-specific library dispatch moves
    /// the counts), so its history is partitioned by machine key like every engine.
    /// It reports single simulated figures rather than interval estimates.
    Callgrind,
    /// `alloc_tracker` allocation counts and bytes: not deterministic — warmup and
    /// buffer-resize allocations jitter the per-iteration figure, which is amortized
    /// over a Criterion-chosen iteration count. A confidence interval is present
    /// only when the operation was measured over several spans.
    AllocTracker,
    /// `all_the_time` processor-time measurements: noisy. A confidence interval is
    /// present only when the operation was measured over several spans.
    AllTheTime,
}

/// Whether an engine can attach confidence-interval bounds to parsed metrics.
///
/// This is the production contract for interval availability. Adapters may omit
/// bounds only in the cases described here; analysis treats any present interval
/// as a suppression-only veto, never as evidence that creates a finding.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum IntervalSupport {
    /// Every persisted point carries confidence-interval bounds.
    ///
    /// The engine always estimates a point from a statistical sample that includes
    /// interval bounds, so every metric parsed from its normal output can carry
    /// those bounds into analysis.
    Always,
    /// Only multi-span measurements carry confidence-interval bounds.
    ///
    /// A single measured span has a point estimate but no between-span dispersion
    /// to bound; once several spans are present, the producer can estimate interval
    /// bounds and the adapter preserves them.
    MultiSpanOnly,
    /// Persisted points never carry confidence-interval bounds.
    ///
    /// The engine reports one simulated or observed value per metric rather than a
    /// statistical interval estimate.
    Never,
}

impl Engine {
    /// Every supported engine, in a stable order used to inject the combined
    /// benchmark environment and to harvest each engine's output tree after the
    /// single `cargo bench` invocation.
    pub const ALL: [Self; 4] = [
        Self::Callgrind,
        Self::Criterion,
        Self::AllocTracker,
        Self::AllTheTime,
    ];

    /// The stable lowercase identifier used in storage paths and config keys.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Criterion => "criterion",
            Self::Callgrind => "callgrind",
            Self::AllocTracker => "alloc_tracker",
            Self::AllTheTime => "all_the_time",
        }
    }

    /// Parses an [`Engine`] from its stable identifier, case-insensitively.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        match name.to_ascii_lowercase().as_str() {
            "criterion" => Some(Self::Criterion),
            "callgrind" => Some(Self::Callgrind),
            "alloc_tracker" => Some(Self::AllocTracker),
            "all_the_time" => Some(Self::AllTheTime),
            _ => None,
        }
    }

    /// Whether metrics parsed from this engine carry confidence intervals.
    ///
    /// Criterion stores an interval with every statistical estimate. Callgrind
    /// stores low-noise simulated counts as single figures. `alloc_tracker` and
    /// `all_the_time` store interval bounds only when the producer measured several
    /// spans for the operation.
    #[must_use]
    pub fn interval_support(self) -> IntervalSupport {
        match self {
            Self::Criterion => IntervalSupport::Always,
            Self::Callgrind => IntervalSupport::Never,
            Self::AllocTracker | Self::AllTheTime => IntervalSupport::MultiSpanOnly,
        }
    }
}

/// Orders engines by their stable [identifier](Self::as_str), so a
/// [`DiscriminantSet`] sorts identically whether its engine is compared as an
/// `Engine` or as the serialized string that used to stand in for it.
impl Ord for Engine {
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_str().cmp(other.as_str())
    }
}

impl PartialOrd for Engine {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for Engine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The set of factors that must match for two runs in a project to share a series.
///
/// A discriminant set is `engine / target_triple / machine`. Within a single
/// project all runs that share a discriminant set are comparable; runs in
/// different sets (a different engine, target triple, or machine key) never share
/// a series. It is both the value `run` writes under and the value `analyze` reads
/// back (parsed from a storage key), so the same type drives both sides.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct DiscriminantSet {
    /// The benchmark engine whose output the series accumulates.
    pub engine: Engine,
    /// Resolved target triple the run was recorded under.
    pub target_triple: TargetTriple,
    /// Machine key: a stable hardware fingerprint (or an explicit override). Every
    /// engine is machine-keyed.
    pub machine_key: MachineKey,
}

impl DiscriminantSet {
    /// Creates a discriminant set, sanitizing the path-forming components.
    ///
    /// `target_triple` and `machine_key` are sanitized so that every segment is a
    /// single, well-formed path component: any character that is not ASCII
    /// alphanumeric, `-`, `_`, or `.` is replaced with `_`, and a segment that
    /// would otherwise be empty or consist only of dots becomes `_`. This keeps a
    /// stray `/` (or other surprising input) from silently splitting a storage key
    /// into the wrong number of segments.
    #[must_use]
    pub fn new(engine: Engine, target_triple: &TargetTriple, machine_key: &MachineKey) -> Self {
        Self {
            engine,
            target_triple: TargetTriple::from(sanitize_segment(target_triple.as_str())),
            machine_key: MachineKey::from(sanitize_segment(machine_key.as_str())),
        }
    }

    /// The storage prefix that all runs in this series share, within `project`.
    ///
    /// Layout:
    /// `{STORAGE_VERSION}/{project}/{OBJECTS_SEGMENT}/{engine}/{target_triple}/{machine}/`.
    /// The fixed `objects` segment separates the data subtree from a project's
    /// metadata siblings (e.g. the cache-invalidation marker); below this prefix the
    /// history is organized by commit (see [`clean_key`] and [`dirty_key`]) so
    /// `analyze` can resolve a series from git topology.
    ///
    /// The trailing separator is part of the contract: storage listings match on a
    /// plain string prefix, so without it a listing of this partition would also
    /// return a sibling partition whose machine key merely *starts with* this one
    /// (`ci` picking up `ci-pool`), silently mixing two independent data sets.
    ///
    /// [`clean_key`]: Self::clean_key
    /// [`dirty_key`]: Self::dirty_key
    #[must_use]
    pub fn partition_prefix(&self, project: &str) -> String {
        let project = sanitize_segment(project);
        let engine = self.engine.as_str();
        let triple = &self.target_triple;
        let machine_key = &self.machine_key;
        format!("{STORAGE_VERSION}/{project}/{OBJECTS_SEGMENT}/{engine}/{triple}/{machine_key}/")
    }

    /// The object key for the canonical (clean working tree) result at `commit`.
    ///
    /// Layout: `{prefix}{commit}/clean.json`, where `{prefix}` is
    /// [`partition_prefix`] and already ends in a separator. A clean run is keyed
    /// solely by its commit, so it is deterministic: a second clean run of the same
    /// commit maps to the same key and collides, which the write-once storage
    /// detects so `run` can refuse the duplicate unless an overwrite is explicitly
    /// requested.
    ///
    /// `commit` is sanitized so the directory name always forms a single segment.
    ///
    /// [`partition_prefix`]: Self::partition_prefix
    #[must_use]
    pub fn clean_key(&self, project: &str, commit: &str) -> String {
        let prefix = self.partition_prefix(project);
        let commit = sanitize_segment(commit);
        format!("{prefix}{commit}/clean.json")
    }

    /// The object key for a dirty (uncommitted-changes) snapshot at `commit`,
    /// observed at `observation_unix`.
    ///
    /// Layout: `{prefix}{commit}/dirty-{observation_unix}.json`, where `{prefix}`
    /// is [`partition_prefix`] and already ends in a separator. Because a dirty
    /// snapshot does not correspond to committed code, it is distinguished by its
    /// observation time rather than by the commit alone, so multiple dirty
    /// snapshots on the same base commit coexist; only two snapshots sharing an
    /// observation second collide.
    ///
    /// `commit` is sanitized so the directory name always forms a single segment.
    ///
    /// [`partition_prefix`]: Self::partition_prefix
    #[must_use]
    pub fn dirty_key(&self, project: &str, commit: &str, observation_unix: i64) -> String {
        let prefix = self.partition_prefix(project);
        let commit = sanitize_segment(commit);
        format!("{prefix}{commit}/dirty-{observation_unix}.json")
    }

    /// The blessing sidecar key for this set's commit directory, issued at
    /// `issued_unix`.
    ///
    /// Layout: `{prefix}{commit}/bless-{issued_unix}.json`, where `{prefix}` is
    /// [`partition_prefix`] and already ends in a separator. `commit` is sanitized
    /// so the directory name always forms a single segment.
    ///
    /// [`partition_prefix`]: Self::partition_prefix
    #[must_use]
    pub fn bless_key(&self, project: &str, commit: &str, issued_unix: i64) -> String {
        let prefix = self.partition_prefix(project);
        let commit = sanitize_segment(commit);
        format!("{prefix}{commit}/bless-{issued_unix}.json")
    }

    /// The storage prefix shared by every object recorded at `commit` in this
    /// partition (`{prefix}{commit}/`, where `{prefix}` is [`partition_prefix`] and
    /// already ends in a separator), used to enumerate a commit directory.
    ///
    /// `commit` is sanitized so the directory name always forms a single segment.
    ///
    /// [`partition_prefix`]: Self::partition_prefix
    #[must_use]
    pub fn commit_prefix(&self, project: &str, commit: &str) -> String {
        let prefix = self.partition_prefix(project);
        let commit = sanitize_segment(commit);
        format!("{prefix}{commit}/")
    }
}

impl fmt::Display for DiscriminantSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}/{}/{}",
            self.engine, self.target_triple, self.machine_key
        )
    }
}

/// Which kind of object a storage key names, decoded from its file segment.
///
/// A commit directory holds three kinds of object, distinguished by file name:
/// the canonical clean run (`clean.json`), zero or more dirty snapshots
/// (`dirty-<observation_unix>.json`), and zero or more blessing sidecars
/// (`bless-<issued_unix>.json`). Recovering this typed classification once
/// (rather than re-testing string prefixes at each use site) keeps the three
/// cases exhaustive and parses each embedded timestamp a single time.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ObjectKind {
    /// The canonical clean-working-tree run (`clean.json`).
    Clean,
    /// A dirty (uncommitted-tree) snapshot, distinguished by its observation second.
    Dirty {
        /// The Unix second at which the snapshot was observed, from the file name.
        observation_unix: i64,
    },
    /// A blessing sidecar, distinguished by the second it was issued.
    Bless {
        /// The Unix second at which the blessing was issued, from the file name.
        issued_unix: i64,
    },
}

impl ObjectKind {
    /// Decodes the file segment of a storage key into its object kind, returning
    /// `None` when the segment is not one of the three recognized object files.
    fn from_file_segment(file: &str) -> Option<Self> {
        if file == "clean.json" {
            return Some(Self::Clean);
        }
        if let Some(seconds) = file
            .strip_prefix("dirty-")
            .and_then(|rest| rest.strip_suffix(".json"))
        {
            return seconds
                .parse()
                .ok()
                .map(|observation_unix| Self::Dirty { observation_unix });
        }
        if let Some(seconds) = file
            .strip_prefix("bless-")
            .and_then(|rest| rest.strip_suffix(".json"))
        {
            return seconds
                .parse()
                .ok()
                .map(|issued_unix| Self::Bless { issued_unix });
        }
        None
    }
}

/// The components a storage key decomposes into.
///
/// A storage key references one of three kinds of object in a commit directory:
/// a clean run (`clean.json`), a dirty snapshot (`dirty-<unix>.json`), or a
/// blessing sidecar (`bless-<unix>.json`). The [`kind`](Self::kind) field, an
/// [`ObjectKind`], captures which; [`is_clean`](Self::is_clean),
/// [`is_dirty`](Self::is_dirty), and [`is_bless`](Self::is_bless) classify it.
///
/// This is the inverse of the key-construction methods above ([`clean_key`],
/// [`dirty_key`], [`bless_key`]): [`parse_key`] recovers this decomposition from a
/// stored object's key so `analyze` can group objects into comparable series.
///
/// [`clean_key`]: DiscriminantSet::clean_key
/// [`dirty_key`]: DiscriminantSet::dirty_key
/// [`bless_key`]: DiscriminantSet::bless_key
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StorageKey {
    /// The (sanitized) project segment.
    pub project: String,
    /// The discriminant set the key belongs to.
    pub set: DiscriminantSet,
    /// The commit directory segment (full commit ID, or `unknown`).
    pub commit: String,
    /// Which kind of object the key names, decoded from its file segment.
    pub kind: ObjectKind,
}

impl StorageKey {
    /// Whether the key names a clean (committed-tree) run.
    #[must_use]
    pub fn is_clean(&self) -> bool {
        matches!(self.kind, ObjectKind::Clean)
    }

    /// Whether the key names a dirty (uncommitted-tree) snapshot.
    #[must_use]
    pub fn is_dirty(&self) -> bool {
        matches!(self.kind, ObjectKind::Dirty { .. })
    }

    /// Whether the key names a blessing sidecar rather than a stored run.
    #[must_use]
    pub fn is_bless(&self) -> bool {
        matches!(self.kind, ObjectKind::Bless { .. })
    }

    /// The blessing sidecar key for this set's commit directory, issued at
    /// `issued_unix`.
    #[must_use]
    pub fn bless_key(&self, issued_unix: i64) -> String {
        self.set.bless_key(&self.project, &self.commit, issued_unix)
    }
}

/// Parses a storage object key into its components.
///
/// Keys have the form
/// `{STORAGE_VERSION}/{project}/{OBJECTS_SEGMENT}/{engine}/{triple}/{machine_key}/{commit}/{file}`
/// — exactly eight non-empty segments, with the fixed `objects` segment directly
/// under the project. Any key that does not match that shape exactly (wrong
/// version, missing `objects` segment, too few or too many segments, or an empty
/// segment), names an engine the tool has no adapter for, or whose file segment is
/// not one of the three recognized object files, is ignored (returns `None`)
/// rather than misattributed — so a per-project metadata sibling such as the
/// cache-invalidation marker is skipped.
#[must_use]
pub fn parse_key(key: &str) -> Option<StorageKey> {
    let parts: Vec<&str> = key.split('/').collect();
    let [
        version,
        project,
        objects,
        engine,
        target_triple,
        machine_key,
        commit,
        file,
    ] = parts.as_slice()
    else {
        return None;
    };
    if *version != STORAGE_VERSION || *objects != OBJECTS_SEGMENT {
        return None;
    }
    if parts.iter().any(|segment| segment.is_empty()) {
        return None;
    }
    let engine = Engine::from_name(engine)?;
    let kind = ObjectKind::from_file_segment(file)?;
    Some(StorageKey {
        project: (*project).to_owned(),
        set: DiscriminantSet {
            engine,
            target_triple: TargetTriple::from(*target_triple),
            machine_key: MachineKey::from(*machine_key),
        },
        commit: (*commit).to_owned(),
        kind,
    })
}

/// Canonicalizes a single path segment: lowercases ASCII letters, replaces every
/// character that is not safe with `_`, and maps an otherwise-empty or all-dots
/// result to `_`.
///
/// "Safe" is the conservative set `[A-Za-z0-9._-]`, which is valid both as a
/// filesystem path component (for local storage) and as an Azure blob name part.
/// Mangling rather than rejecting means the tool never refuses a run merely
/// because its project, triple, or machine key contains an awkward character.
///
/// Letters are folded to lower case so a segment's identity is case-insensitive:
/// a discriminant set, project, or commit differing only in letter case resolves
/// to the same storage key, and so blessing, pruning, and analysis never split on
/// case alone.
#[must_use]
pub fn sanitize_segment(raw: &str) -> String {
    let mangled: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
                c.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect();
    if mangled.is_empty() || mangled.chars().all(|c| c == '.') {
        return "_".to_owned();
    }
    mangled
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn every_engine_partitions_by_machine_key() {
        // Every engine is machine-keyed: even the low-noise simulated counts differ
        // by microarchitecture, so a machine key always appears in the partition.
        let set = DiscriminantSet::new(
            Engine::AllocTracker,
            &TargetTriple::from("x86_64-pc-windows-msvc"),
            &MachineKey::from("abc123"),
        );
        assert_eq!(
            set.partition_prefix("folo"),
            "v1/folo/objects/alloc_tracker/x86_64-pc-windows-msvc/abc123/"
        );
    }

    #[test]
    fn all_the_time_partitions_by_machine_key() {
        // Processor time depends on the machine, so `all_the_time` carries a
        // machine fingerprint.
        let set = DiscriminantSet::new(
            Engine::AllTheTime,
            &TargetTriple::from("x86_64-pc-windows-msvc"),
            &MachineKey::from("abc123"),
        );
        assert_eq!(
            set.partition_prefix("folo"),
            "v1/folo/objects/all_the_time/x86_64-pc-windows-msvc/abc123/"
        );
    }

    #[test]
    fn machine_key_appears_in_partition() {
        let set = DiscriminantSet::new(
            Engine::Criterion,
            &TargetTriple::from("x86_64-pc-windows-msvc"),
            &MachineKey::from("abc123"),
        );
        assert_eq!(
            set.partition_prefix("folo"),
            "v1/folo/objects/criterion/x86_64-pc-windows-msvc/abc123/"
        );
    }

    #[test]
    fn partition_prefix_does_not_match_a_sibling_machine_key() {
        // Storage listings match on a plain string prefix, so a partition prefix
        // that stopped at the machine key would also return every sibling key that
        // merely starts with it. The trailing separator keeps the two independent
        // data sets apart.
        let triple = TargetTriple::from("x86_64-pc-windows-msvc");
        let ci = DiscriminantSet::new(Engine::Criterion, &triple, &MachineKey::from("ci"));
        let pool = DiscriminantSet::new(Engine::Criterion, &triple, &MachineKey::from("ci-pool"));

        assert!(
            !pool
                .clean_key("folo", "abc123")
                .starts_with(&ci.partition_prefix("folo")),
            "{} must not fall under {}",
            pool.clean_key("folo", "abc123"),
            ci.partition_prefix("folo")
        );
        assert!(
            ci.clean_key("folo", "abc123")
                .starts_with(&ci.partition_prefix("folo"))
        );
    }

    #[test]
    fn display_formats_engine_triple_and_machine_key() {
        let set = DiscriminantSet::new(
            Engine::Criterion,
            &TargetTriple::from("x86_64-pc-windows-msvc"),
            &MachineKey::from("abc123"),
        );
        assert_eq!(set.to_string(), "criterion/x86_64-pc-windows-msvc/abc123");
    }

    #[test]
    fn clean_key_is_named_by_commit() {
        let set = DiscriminantSet::new(
            Engine::Callgrind,
            &TargetTriple::from("x86_64-unknown-linux-gnu"),
            &MachineKey::from("abc123"),
        );
        assert_eq!(
            set.clean_key("folo", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"),
            "v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/abc123/\
             deadbeefdeadbeefdeadbeefdeadbeefdeadbeef/clean.json"
        );
    }

    #[test]
    fn dirty_key_is_named_by_commit_and_observation_time() {
        let set = DiscriminantSet::new(
            Engine::Callgrind,
            &TargetTriple::from("x86_64-unknown-linux-gnu"),
            &MachineKey::from("abc123"),
        );
        assert_eq!(
            set.dirty_key(
                "folo",
                "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
                1_700_000_000
            ),
            "v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/abc123/\
             deadbeefdeadbeefdeadbeefdeadbeefdeadbeef/dirty-1700000000.json"
        );
    }

    #[test]
    fn bless_key_targets_the_commit_directory() {
        let set = DiscriminantSet::new(
            Engine::Callgrind,
            &TargetTriple::from("x86_64-unknown-linux-gnu"),
            &MachineKey::from("m1"),
        );
        assert_eq!(
            set.bless_key("folo", "abc123", 1_700_000_000),
            "v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/abc123/bless-1700000000.json"
        );
    }

    #[test]
    fn commit_prefix_enumerates_one_commit_directory() {
        let set = DiscriminantSet::new(
            Engine::Callgrind,
            &TargetTriple::from("x86_64-unknown-linux-gnu"),
            &MachineKey::from("m1"),
        );
        assert_eq!(
            set.commit_prefix("folo", "dead/beef"),
            "v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/dead_beef/"
        );
    }

    #[test]
    fn engine_display_matches_as_str() {
        assert_eq!(Engine::Criterion.to_string(), "criterion");
        assert_eq!(Engine::Callgrind.to_string(), "callgrind");
        assert_eq!(Engine::AllocTracker.to_string(), "alloc_tracker");
        assert_eq!(Engine::AllTheTime.to_string(), "all_the_time");
    }

    #[test]
    fn engine_from_name_roundtrips() {
        for engine in Engine::ALL {
            assert_eq!(Engine::from_name(engine.as_str()), Some(engine));
        }
        assert_eq!(Engine::from_name("dhat"), None);
    }

    #[test]
    fn engine_from_name_is_case_insensitive() {
        assert_eq!(Engine::from_name("Callgrind"), Some(Engine::Callgrind));
        assert_eq!(Engine::from_name("ALL_THE_TIME"), Some(Engine::AllTheTime));
    }

    #[test]
    fn interval_support_is_declared_for_every_engine() {
        for engine in Engine::ALL {
            let expected = match engine {
                Engine::Criterion => IntervalSupport::Always,
                Engine::Callgrind => IntervalSupport::Never,
                Engine::AllocTracker | Engine::AllTheTime => IntervalSupport::MultiSpanOnly,
            };

            assert_eq!(engine.interval_support(), expected);
        }
    }

    #[test]
    fn sanitize_segment_keeps_safe_characters() {
        assert_eq!(
            sanitize_segment("x86_64-unknown-linux-gnu"),
            "x86_64-unknown-linux-gnu"
        );
        assert_eq!(sanitize_segment("my.project-1"), "my.project-1");
    }

    #[test]
    fn sanitize_segment_folds_case() {
        assert_eq!(sanitize_segment("Team-App"), "team-app");
        assert_eq!(
            sanitize_segment("X86_64-PC-Windows-MSVC"),
            "x86_64-pc-windows-msvc"
        );
    }

    #[test]
    fn sanitize_segment_replaces_separators_and_specials() {
        assert_eq!(sanitize_segment("team/app"), "team_app");
        assert_eq!(sanitize_segment(r"team\app"), "team_app");
        assert_eq!(sanitize_segment("weird:name"), "weird_name");
        assert_eq!(sanitize_segment("with space"), "with_space");
        assert_eq!(sanitize_segment("café"), "caf_");
    }

    #[test]
    fn sanitize_segment_maps_empty_and_dot_only_to_underscore() {
        assert_eq!(sanitize_segment(""), "_");
        assert_eq!(sanitize_segment("."), "_");
        assert_eq!(sanitize_segment(".."), "_");
    }

    #[test]
    fn new_sanitizes_partition_components() {
        let set = DiscriminantSet::new(
            Engine::Criterion,
            &TargetTriple::from("weird/triple"),
            &MachineKey::from("machine/one"),
        );
        assert_eq!(
            set.partition_prefix("team/app"),
            "v1/team_app/objects/criterion/weird_triple/machine_one/"
        );
        // The partition prefix has exactly the six canonical segments and ends in
        // the separator that keeps a listing inside this partition.
        let prefix = set.partition_prefix("team/app");
        assert!(prefix.ends_with('/'), "{prefix}");
        assert_eq!(prefix.trim_end_matches('/').split('/').count(), 6);
    }

    #[test]
    fn clean_key_sanitizes_the_commit() {
        let set = DiscriminantSet::new(
            Engine::Callgrind,
            &TargetTriple::from("x86_64-unknown-linux-gnu"),
            &MachineKey::from("m1"),
        );
        let object = set.clean_key("folo", "dead/beef");
        assert_eq!(
            object,
            "v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/dead_beef/clean.json"
        );
        // Exactly the eight canonical key segments survive sanitization.
        assert_eq!(object.split('/').count(), 8);
    }

    #[test]
    fn dirty_key_sanitizes_the_commit() {
        let set = DiscriminantSet::new(
            Engine::Callgrind,
            &TargetTriple::from("x86_64-unknown-linux-gnu"),
            &MachineKey::from("m1"),
        );
        let object = set.dirty_key("folo", "dead/beef", 1_700_000_000);
        assert_eq!(
            object,
            "v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/dead_beef/dirty-1700000000.json"
        );
        // Exactly the eight canonical key segments survive sanitization.
        assert_eq!(object.split('/').count(), 8);
    }

    #[test]
    fn parse_key_decomposes_a_clean_key() {
        let parsed =
            parse_key("v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/abc123/clean.json")
                .unwrap();
        assert_eq!(parsed.project, "folo");
        assert_eq!(parsed.set.engine, Engine::Callgrind);
        assert_eq!(parsed.set.target_triple, "x86_64-unknown-linux-gnu");
        assert_eq!(parsed.set.machine_key, "m1");
        assert_eq!(parsed.commit, "abc123");
        assert!(parsed.is_clean());
        assert!(!parsed.is_dirty());
        assert!(!parsed.is_bless());
    }

    #[test]
    fn parse_key_recognizes_a_dirty_snapshot() {
        let parsed = parse_key(
            "v1/folo/objects/criterion/x86_64-pc-windows-msvc/m1/abc123/dirty-1700000000.json",
        )
        .unwrap();
        assert!(parsed.is_dirty());
        assert!(!parsed.is_clean());
        assert_eq!(
            parsed.kind,
            ObjectKind::Dirty {
                observation_unix: 1_700_000_000
            }
        );
        assert_eq!(parsed.set.target_triple, "x86_64-pc-windows-msvc");
        assert_eq!(parsed.set.machine_key, "m1");
    }

    #[test]
    fn parse_key_recognizes_a_blessing_sidecar() {
        let parsed = parse_key(
            "v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/abc123/bless-1700000000.json",
        )
        .unwrap();
        assert!(parsed.is_bless());
        assert!(!parsed.is_dirty());
        assert!(!parsed.is_clean());
        assert_eq!(
            parsed.kind,
            ObjectKind::Bless {
                issued_unix: 1_700_000_000
            }
        );
        assert_eq!(parsed.commit, "abc123");
    }

    #[test]
    fn bless_key_targets_the_sets_commit_directory() {
        let parsed =
            parse_key("v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/abc123/clean.json")
                .unwrap();
        assert_eq!(
            parsed.bless_key(1_700_000_000),
            "v1/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/abc123/bless-1700000000.json"
        );
    }

    #[test]
    fn parse_key_rejects_malformed_keys() {
        // Wrong (unrecognized) storage version, even with an otherwise valid shape.
        assert!(parse_key("v2/folo/objects/callgrind/t/m/c/f.json").is_none());
        // Missing the fixed `objects` segment (the pre-objects v1 shape).
        assert!(parse_key("v1/folo/callgrind/t/m/c/f.json").is_none());
        // A different literal in the objects position.
        assert!(parse_key("v1/folo/data/callgrind/t/m/c/f.json").is_none());
        // Structurally malformed keys at the recognized version.
        assert!(parse_key("v1/folo/objects/callgrind/t/m/f.json").is_none());
        assert!(parse_key("v1/folo/objects/callgrind/t/m/c/sub/f.json").is_none());
        assert!(parse_key("v1/folo/objects/callgrind/t//c/f.json").is_none());
        assert!(parse_key("v1/folo/objects/callgrind/t/m/c/").is_none());
        // A structurally valid key naming an engine the tool has no adapter for.
        assert!(parse_key("v1/folo/objects/dhat/t/m/c/clean.json").is_none());
        // A structurally valid key whose file segment is not a known object.
        assert!(parse_key("v1/folo/objects/callgrind/t/m/c/notes.json").is_none());
        // Keys that are valid in every respect except one guarded segment, so the
        // version and `objects` guards are each exercised in isolation (a real
        // engine and object file would otherwise let a mutated guard slip through).
        assert!(
            parse_key("v2/folo/objects/callgrind/x86_64-unknown-linux-gnu/m1/abc123/clean.json")
                .is_none()
        );
        assert!(
            parse_key("v1/folo/data/callgrind/x86_64-unknown-linux-gnu/m1/abc123/clean.json")
                .is_none()
        );
    }

    #[test]
    fn engine_orders_by_identifier() {
        // Ordering follows `as_str`, so a `DiscriminantSet` sorts identically
        // whether its engine is compared as an `Engine` or as its serialized name.
        let mut by_engine = Engine::ALL.to_vec();
        by_engine.sort();
        let ordered_names: Vec<&str> = by_engine.iter().map(|engine| engine.as_str()).collect();
        let mut by_name = Engine::ALL.map(Engine::as_str).to_vec();
        by_name.sort_unstable();
        assert_eq!(ordered_names, by_name);
        assert!(Engine::Callgrind < Engine::Criterion);
        assert_eq!(
            Engine::Callgrind.partial_cmp(&Engine::Criterion),
            Some(Ordering::Less)
        );
    }

    #[test]
    fn engine_serde_matches_as_str() {
        // The serialized wire form must equal `as_str`, so a flattened
        // `DiscriminantSet` keeps the exact engine name in JSON reports.
        for engine in Engine::ALL {
            let json = serde_json::to_string(&engine).unwrap();
            assert_eq!(json, format!("\"{}\"", engine.as_str()));
            assert_eq!(
                serde_json::from_str::<Engine>(&json).unwrap(),
                engine,
                "engine {engine} must round-trip through its wire form"
            );
        }
    }
}