powercut 0.1.1

Prove an acknowledged write survives a power cut or process crash, in cargo test. A database-agnostic crash-injection harness that derives the durable set from the fsyncs that actually happened.
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
//! What came back, and how sure we are about it.
//!
//! The type that matters most here is [`Finding`], and the variant that
//! matters most is [`Finding::NotMeasured`]. A check that could not be
//! performed must never render as a pass — that is the whole reason this
//! module has four outcomes instead of two.

use std::fmt;

use crate::capture::{CapturedFile, Tier};
use crate::witness::Coverage;

/// What kind of thing went wrong, so a ratchet can tell *new* breakage from
/// breakage it already knows about.
///
/// ```
/// # use powercut::ViolationKind;
/// assert_eq!(ViolationKind::LostData.as_str(), "lost-data");
/// ```
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ViolationKind {
    /// Something the ack promised is simply absent.
    LostData,
    /// Something the ack promised came back with a different value.
    Divergent,
    /// State that existed **before** the workload ran is missing, so the
    /// captured copy is not a usable store and nothing else in the report is a
    /// durability measurement.
    Baseline,
}

impl ViolationKind {
    /// A short, stable, lowercase label. Baseline files contain these, so they
    /// are part of the public contract.
    ///
    /// ```
    /// # use powercut::ViolationKind;
    /// assert_eq!(ViolationKind::Baseline.as_str(), "baseline");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            ViolationKind::LostData => "lost-data",
            ViolationKind::Divergent => "divergent",
            ViolationKind::Baseline => "baseline",
        }
    }

    /// Parse a label written by [`Self::as_str`].
    ///
    /// ```
    /// # use powercut::ViolationKind;
    /// assert_eq!(ViolationKind::parse("divergent"), Some(ViolationKind::Divergent));
    /// assert_eq!(ViolationKind::parse("nonsense"), None);
    /// ```
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "lost-data" => Some(ViolationKind::LostData),
            "divergent" => Some(ViolationKind::Divergent),
            "baseline" => Some(ViolationKind::Baseline),
            _ => None,
        }
    }
}

/// One way the acked promise failed to survive.
///
/// ```
/// # use powercut::{Violation, ViolationKind};
/// let v = Violation::lost("row id=7 the API acked is absent");
/// assert_eq!(v.kind, ViolationKind::LostData);
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Violation {
    /// What kind of failure this is.
    pub kind: ViolationKind,
    /// The human-readable detail, written for whoever reads the failure.
    pub detail: String,
}

impl Violation {
    /// Something the ack promised is gone.
    ///
    /// ```
    /// # use powercut::Violation;
    /// assert!(Violation::lost("order 42 is absent").detail.contains("42"));
    /// ```
    #[must_use]
    pub fn lost(detail: impl Into<String>) -> Self {
        Self {
            kind: ViolationKind::LostData,
            detail: detail.into(),
        }
    }

    /// Something the ack promised came back different.
    ///
    /// ```
    /// # use powercut::{Violation, ViolationKind};
    /// assert_eq!(Violation::divergent("balance is 9, acked 10").kind, ViolationKind::Divergent);
    /// ```
    #[must_use]
    pub fn divergent(detail: impl Into<String>) -> Self {
        Self {
            kind: ViolationKind::Divergent,
            detail: detail.into(),
        }
    }

    /// Pre-workload state is missing, so this run measured nothing.
    ///
    /// ```
    /// # use powercut::{Violation, ViolationKind};
    /// let v = Violation::baseline("the schema itself is absent from the copy");
    /// assert_eq!(v.kind, ViolationKind::Baseline);
    /// ```
    #[must_use]
    pub fn baseline(detail: impl Into<String>) -> Self {
        Self {
            kind: ViolationKind::Baseline,
            detail: detail.into(),
        }
    }
}

impl fmt::Display for Violation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let prefix = match self.kind {
            ViolationKind::LostData => "LOST",
            ViolationKind::Divergent => "DIVERGENT",
            ViolationKind::Baseline => "HARNESS/BASELINE",
        };
        write!(f, "{prefix}: {}", self.detail)
    }
}

/// A small helper for writing checkers that put the baseline check first.
///
/// The ordering is the point. If the captured copy lost state that existed
/// *before* the workload, then every later assertion fails for a reason that
/// has nothing to do with durability — and a report that says "data loss" in
/// that situation is a false accusation.
///
/// ```
/// use powercut::{Checker, ViolationKind};
///
/// let mut c = Checker::new();
/// c.baseline("schema present", true, true);
/// c.survives("row 7", Some(42_i64), None);
/// let violations = c.finish();
///
/// assert_eq!(violations.len(), 1);
/// assert_eq!(violations[0].kind, ViolationKind::LostData);
/// ```
#[derive(Debug, Default)]
pub struct Checker {
    baseline: Vec<Violation>,
    rest: Vec<Violation>,
}

impl Checker {
    /// An empty checker.
    ///
    /// ```
    /// # use powercut::Checker;
    /// assert!(Checker::new().finish().is_empty());
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Assert something that was true **before** the workload ran. A failure
    /// here means the harness, not the store, is the problem.
    ///
    /// ```
    /// # use powercut::{Checker, ViolationKind};
    /// let mut c = Checker::new();
    /// c.baseline("table count", 1_usize, 0_usize);
    /// assert_eq!(c.finish()[0].kind, ViolationKind::Baseline);
    /// ```
    pub fn baseline<T>(&mut self, what: &str, expected: T, actual: T)
    where
        T: PartialEq + fmt::Debug,
    {
        if expected != actual {
            self.baseline.push(Violation::baseline(format!(
                "{what}: the captured copy has {actual:?}, but this was already true \
                 BEFORE the workload ran (expected {expected:?}). The copy is not a usable \
                 store, so nothing else in this report is a durability measurement."
            )));
        }
    }

    /// Assert something the workload's ack promised.
    ///
    /// A missing value is reported as [`ViolationKind::LostData`], a different
    /// value as [`ViolationKind::Divergent`] — a distinction that matters,
    /// because losing a row and reading a stale row are different bugs.
    ///
    /// ```
    /// # use powercut::{Checker, ViolationKind};
    /// let mut c = Checker::new();
    /// c.survives("balance", 10_i64, 9_i64);
    /// assert_eq!(c.finish()[0].kind, ViolationKind::Divergent);
    /// ```
    pub fn survives<T>(&mut self, what: &str, expected: T, actual: T)
    where
        T: PartialEq + fmt::Debug + IsAbsent,
    {
        if expected == actual {
            return;
        }
        let detail = format!("{what}: acked {expected:?}, the durable set has {actual:?}");
        self.rest.push(if actual.is_absent() {
            Violation::lost(detail)
        } else {
            Violation::divergent(detail)
        });
    }

    /// Record a violation you built yourself.
    ///
    /// ```
    /// # use powercut::{Checker, Violation};
    /// let mut c = Checker::new();
    /// c.push(Violation::lost("the WAL replayed but the row is not in it"));
    /// assert_eq!(c.finish().len(), 1);
    /// ```
    pub fn push(&mut self, violation: Violation) {
        if violation.kind == ViolationKind::Baseline {
            self.baseline.push(violation);
        } else {
            self.rest.push(violation);
        }
    }

    /// Every violation, baseline failures first.
    ///
    /// ```
    /// # use powercut::{Checker, ViolationKind};
    /// let mut c = Checker::new();
    /// c.survives("row", 1_i64, 0_i64);
    /// c.baseline("schema", true, false);
    /// assert_eq!(c.finish()[0].kind, ViolationKind::Baseline);
    /// ```
    #[must_use]
    pub fn finish(mut self) -> Vec<Violation> {
        self.baseline.append(&mut self.rest);
        self.baseline
    }
}

/// Lets [`Checker::survives`] tell "absent" apart from "different".
///
/// The blanket rule is that only `None` counts as absent; implement it for
/// your own type if it has its own notion of emptiness.
///
/// ```
/// # use powercut::IsAbsent;
/// assert!(None::<i64>.is_absent());
/// assert!(!Some(0_i64).is_absent());
/// assert!(!7_i64.is_absent());
/// ```
pub trait IsAbsent {
    /// `true` when this value represents "nothing came back".
    ///
    /// This is what lets [`Checker::survives`] say *lost* rather than
    /// *different*. A row that is gone and a row that came back stale are
    /// different bugs, and a report that conflates them sends somebody to the
    /// wrong part of their write path.
    ///
    /// ```
    /// use powercut::{Checker, IsAbsent, ViolationKind};
    ///
    /// /// A read-back type with its own notion of emptiness.
    /// #[derive(Debug, PartialEq)]
    /// struct Rows(Vec<i64>);
    ///
    /// impl IsAbsent for Rows {
    ///     fn is_absent(&self) -> bool {
    ///         self.0.is_empty()
    ///     }
    /// }
    ///
    /// let mut c = Checker::new();
    /// c.survives("orders", Rows(vec![7]), Rows(vec![]));       // absent
    /// c.survives("balance", Rows(vec![100]), Rows(vec![99]));  // present, wrong
    /// let violations = c.finish();
    ///
    /// assert_eq!(violations[0].kind, ViolationKind::LostData);
    /// assert_eq!(violations[1].kind, ViolationKind::Divergent);
    /// ```
    fn is_absent(&self) -> bool;
}

impl<T> IsAbsent for Option<T> {
    fn is_absent(&self) -> bool {
        self.is_none()
    }
}

impl<T> IsAbsent for Vec<T> {
    fn is_absent(&self) -> bool {
        self.is_empty()
    }
}

macro_rules! not_absent {
    ($($t:ty),*) => {$(
        impl IsAbsent for $t {
            fn is_absent(&self) -> bool { false }
        }
    )*};
}
not_absent!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, bool, String, &str);

/// The four-valued outcome. Two of these are not "pass" and not "fail".
///
/// ```
/// # use powercut::Verdict;
/// assert!(!Verdict::NotMeasured.is_pass());
/// assert!(Verdict::NotMeasured.severity() < Verdict::Lost.severity());
/// ```
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Verdict {
    /// Everything the ack promised came back from the durable set.
    Survived,
    /// The check could not be performed soundly. **Not a pass.**
    NotMeasured,
    /// The durable set was missing or diverged from what was acked.
    Lost,
    /// The harness itself is broken, so the red proves nothing about the store.
    HarnessBroken,
}

impl Verdict {
    /// A short, stable label. Baseline files contain these.
    ///
    /// ```
    /// # use powercut::Verdict;
    /// assert_eq!(Verdict::HarnessBroken.as_str(), "harness-broken");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Verdict::Survived => "survived",
            Verdict::NotMeasured => "not-measured",
            Verdict::Lost => "lost",
            Verdict::HarnessBroken => "harness-broken",
        }
    }

    /// Parse a label written by [`Self::as_str`].
    ///
    /// ```
    /// # use powercut::Verdict;
    /// assert_eq!(Verdict::parse("lost"), Some(Verdict::Lost));
    /// assert_eq!(Verdict::parse("green"), None);
    /// ```
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "survived" => Some(Verdict::Survived),
            "not-measured" => Some(Verdict::NotMeasured),
            "lost" => Some(Verdict::Lost),
            "harness-broken" => Some(Verdict::HarnessBroken),
            _ => None,
        }
    }

    /// Only [`Verdict::Survived`] is a pass. In particular
    /// [`Verdict::NotMeasured`] is not.
    ///
    /// ```
    /// # use powercut::Verdict;
    /// assert!(Verdict::Survived.is_pass());
    /// assert!(!Verdict::NotMeasured.is_pass());
    /// ```
    #[must_use]
    pub fn is_pass(self) -> bool {
        matches!(self, Verdict::Survived)
    }

    /// Ranking used by the CI ratchet: lower is better.
    ///
    /// ```
    /// # use powercut::Verdict;
    /// assert!(Verdict::Survived.severity() < Verdict::HarnessBroken.severity());
    /// ```
    #[must_use]
    pub const fn severity(self) -> u8 {
        match self {
            Verdict::Survived => 0,
            Verdict::NotMeasured => 1,
            Verdict::Lost => 2,
            Verdict::HarnessBroken => 3,
        }
    }
}

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

/// The outcome with its evidence attached.
///
/// ```
/// # use powercut::{Finding, Verdict};
/// let f = Finding::NotMeasured { why: "the engine syncs where we cannot see".into() };
/// assert_eq!(f.verdict(), Verdict::NotMeasured);
/// ```
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Finding {
    /// The durable set honoured the ack.
    Survived,
    /// The durable set did not honour the ack, and coverage was complete
    /// enough for that to mean something.
    Lost {
        /// What was missing or different.
        violations: Vec<Violation>,
    },
    /// **Never a silent pass, never a false accusation.** The check ran but
    /// its result is not sound — most often because the witness admitted it
    /// cannot see all of the store's sync activity, so an unobserved sync
    /// might have saved the data.
    NotMeasured {
        /// Why this could not be measured, in one sentence.
        why: String,
    },
    /// The harness is broken: the captured copy was not a usable store, or the
    /// teeth control — the run that *must* pass — did not.
    HarnessBroken {
        /// What is wrong with the harness.
        why: String,
        /// The violations that proved it.
        violations: Vec<Violation>,
    },
}

impl Finding {
    /// The matching [`Verdict`].
    ///
    /// ```
    /// # use powercut::{Finding, Verdict};
    /// assert_eq!(Finding::Survived.verdict(), Verdict::Survived);
    /// ```
    #[must_use]
    pub fn verdict(&self) -> Verdict {
        match self {
            Finding::Survived => Verdict::Survived,
            Finding::Lost { .. } => Verdict::Lost,
            Finding::NotMeasured { .. } => Verdict::NotMeasured,
            Finding::HarnessBroken { .. } => Verdict::HarnessBroken,
        }
    }

    /// The violations behind this finding, if any.
    ///
    /// ```
    /// # use powercut::Finding;
    /// assert!(Finding::Survived.violations().is_empty());
    /// ```
    #[must_use]
    pub fn violations(&self) -> &[Violation] {
        match self {
            Finding::Lost { violations } | Finding::HarnessBroken { violations, .. } => violations,
            Finding::Survived | Finding::NotMeasured { .. } => &[],
        }
    }
}

/// The result of one case: one store, one tier, one checker.
///
/// A `Report` is written to be **self-adjudicating**. Every failure prints the
/// full manifest, every warrant, the notes the capture made, and — when the
/// tier is [`Tier::PowerCut`] — whether the data was present in the tier-1
/// byte copy taken at the same instant. That last line is usually the answer:
/// *present at tier 1, absent at tier 2* means the write reached the
/// filesystem and no further, which is a missing fsync, not a lost write.
///
/// ```
/// use powercut::{Checker, ScratchDir, Scenario, SyncJournal, Tier, Verdict};
///
/// let store = ScratchDir::new("doc-report").unwrap();
/// let journal = SyncJournal::complete();
///
/// let report = Scenario::new(store.path(), journal.clone())
///     .label("no-fsync-at-all")
///     .tier(Tier::PowerCut)
///     .ack(|| std::fs::write(store.path().join("app.log"), b"acked").unwrap())
///     .unwrap()
///     .check(|crash, ()| {
///         let mut c = Checker::new();
///         let survived = std::fs::read(crash.dir().join("app.log")).ok();
///         c.survives("app.log", Some(b"acked".to_vec()), survived);
///         c.finish()
///     });
///
/// assert_eq!(report.verdict(), Verdict::Lost);
/// assert!(report.reached_filesystem() == Some(true));
/// ```
#[derive(Debug)]
pub struct Report {
    pub(crate) label: String,
    pub(crate) tier: Tier,
    pub(crate) finding: Finding,
    pub(crate) coverage: Coverage,
    pub(crate) manifest: Vec<CapturedFile>,
    pub(crate) manifest_text: String,
    pub(crate) notes: Vec<String>,
    pub(crate) reference_violations: Option<Vec<Violation>>,
    pub(crate) control_violations: Option<Vec<Violation>>,
    pub(crate) used_assumption: bool,
}

impl Report {
    /// The case name. Baseline files are keyed on it, so keep it stable.
    ///
    /// ```
    /// use powercut::{ScratchDir, Scenario, SyncJournal};
    ///
    /// let store = ScratchDir::new("doc-report-label").unwrap();
    ///
    /// let named = Scenario::new(store.path(), SyncJournal::complete())
    ///     .label("myengine/durable-ack")
    ///     .ack(|| ())
    ///     .unwrap()
    ///     .check(|_crash, ()| Vec::new());
    /// assert_eq!(named.label(), "myengine/durable-ack");
    ///
    /// // Unlabelled, a case falls back to the store directory's name — which
    /// // for a scratch directory changes every run, and is exactly the kind of
    /// // unstable key a committed baseline must not be built on.
    /// let unnamed = Scenario::new(store.path(), SyncJournal::complete())
    ///     .ack(|| ())
    ///     .unwrap()
    ///     .check(|_crash, ()| Vec::new());
    /// assert!(unnamed.label().starts_with("powercut-doc-report-label-"));
    /// ```
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Which tier was measured.
    ///
    /// ```
    /// use powercut::{Checker, CrashState, ScratchDir, Scenario, SyncJournal, Tier, Verdict};
    ///
    /// let store = ScratchDir::new("doc-report-tier").unwrap();
    /// let db = store.path().join("app.log");
    /// let check = |crash: &CrashState, _: &()| {
    ///     let mut c = Checker::new();
    ///     c.survives(
    ///         "app.log",
    ///         Some(b"acked".to_vec()),
    ///         std::fs::read(crash.dir().join("app.log")).ok(),
    ///     );
    ///     c.finish()
    /// };
    ///
    /// // One never-fsynced write, measured at each tier. The tier is the
    /// // difference between the two verdicts, and `tier()` is how a report
    /// // says which question it answered.
    /// let crash = Scenario::new(store.path(), SyncJournal::complete())
    ///     .tier(Tier::ProcessCrash)
    ///     .ack(|| std::fs::write(&db, b"acked").unwrap())
    ///     .unwrap()
    ///     .check(check);
    /// assert_eq!(crash.tier(), Tier::ProcessCrash);
    /// assert_eq!(crash.verdict(), Verdict::Survived);
    ///
    /// let cut = Scenario::new(store.path(), SyncJournal::complete())
    ///     .tier(Tier::PowerCut)
    ///     .ack(|| std::fs::write(&db, b"acked").unwrap())
    ///     .unwrap()
    ///     .check(check);
    /// assert_eq!(cut.tier(), Tier::PowerCut);
    /// assert_eq!(cut.verdict(), Verdict::Lost);
    /// ```
    #[must_use]
    pub fn tier(&self) -> Tier {
        self.tier
    }

    /// The outcome with its evidence.
    ///
    /// [`Report::verdict`] says *what* happened in one word; this says *why*,
    /// and carries the violations a failure message is built from.
    ///
    /// ```
    /// use powercut::{Checker, Finding, ScratchDir, Scenario, SyncJournal, ViolationKind};
    ///
    /// let store = ScratchDir::new("doc-report-finding").unwrap();
    /// let db = store.path().join("app.log");
    ///
    /// let report = Scenario::new(store.path(), SyncJournal::complete())
    ///     .label("no-fsync")
    ///     .ack(|| std::fs::write(&db, b"balance=100").unwrap())
    ///     .unwrap()
    ///     .check(|crash, ()| {
    ///         let mut c = Checker::new();
    ///         c.survives(
    ///             "balance",
    ///             Some(b"balance=100".to_vec()),
    ///             std::fs::read(crash.dir().join("app.log")).ok(),
    ///         );
    ///         c.finish()
    ///     });
    ///
    /// // `Finding` is `#[non_exhaustive]`, so match with a wildcard arm.
    /// match report.finding() {
    ///     Finding::Lost { violations } => {
    ///         assert_eq!(violations[0].kind, ViolationKind::LostData);
    ///         assert!(violations[0].detail.contains("balance"));
    ///     }
    ///     other => panic!("expected a loss, got {other:?}"),
    /// }
    /// ```
    #[must_use]
    pub fn finding(&self) -> &Finding {
        &self.finding
    }

    /// The outcome as a plain, matchable value.
    ///
    /// ```
    /// use powercut::{Checker, CrashState, ScratchDir, Scenario, SyncJournal, Verdict};
    ///
    /// let check = |crash: &CrashState, _: &()| {
    ///     let mut c = Checker::new();
    ///     c.survives(
    ///         "app.log",
    ///         Some(b"acked".to_vec()),
    ///         std::fs::read(crash.dir().join("app.log")).ok(),
    ///     );
    ///     c.finish()
    /// };
    ///
    /// // Written and fsynced: the durable set honours the ack.
    /// let store = ScratchDir::new("doc-report-verdict").unwrap();
    /// let journal = SyncJournal::complete();
    /// let db = store.path().join("app.log");
    /// let synced = Scenario::new(store.path(), journal.clone())
    ///     .ack(|| {
    ///         std::fs::write(&db, b"acked").unwrap();
    ///         journal.sync_path(&db).unwrap();
    ///     })
    ///     .unwrap()
    ///     .check(check);
    /// assert_eq!(synced.verdict(), Verdict::Survived);
    /// assert!(synced.verdict().is_pass());
    ///
    /// // Delete that one `sync_path` line and the same workload goes red. The
    /// // durable set is derived from the syncs that happened, so the
    /// // derivation is the mutation test.
    /// let store = ScratchDir::new("doc-report-verdict-unsynced").unwrap();
    /// let db = store.path().join("app.log");
    /// let unsynced = Scenario::new(store.path(), SyncJournal::complete())
    ///     .ack(|| std::fs::write(&db, b"acked").unwrap())
    ///     .unwrap()
    ///     .check(check);
    /// assert_eq!(unsynced.verdict(), Verdict::Lost);
    /// assert!(!unsynced.verdict().is_pass());
    /// ```
    #[must_use]
    pub fn verdict(&self) -> Verdict {
        self.finding.verdict()
    }

    /// What the witness admitted it could see.
    ///
    /// This is the line that decides whether a red is a finding or an
    /// admission: under [`Coverage::Partial`] an unobserved sync might have
    /// saved the data, so the verdict is [`Verdict::NotMeasured`].
    ///
    /// ```
    /// use powercut::{Checker, Coverage, ScratchDir, Scenario, SyncJournal, Verdict};
    ///
    /// let store = ScratchDir::new("doc-report-coverage").unwrap();
    /// let db = store.path().join("app.db");
    ///
    /// // An FFI engine at its default settings syncs where we cannot see it.
    /// let journal = SyncJournal::partial("libsqlite3 syncs internally through libc");
    ///
    /// let report = Scenario::new(store.path(), journal)
    ///     .ack(|| std::fs::write(&db, b"row 42").unwrap())
    ///     .unwrap()
    ///     .check(|crash, ()| {
    ///         let mut c = Checker::new();
    ///         c.survives(
    ///             "row 42",
    ///             Some(b"row 42".to_vec()),
    ///             std::fs::read(crash.dir().join("app.db")).ok(),
    ///         );
    ///         c.finish()
    ///     });
    ///
    /// assert!(!report.coverage().is_complete());
    /// match report.coverage() {
    ///     Coverage::Partial { unobserved } => assert!(unobserved.contains("libsqlite3")),
    ///     other => panic!("expected partial coverage, got {other:?}"),
    /// }
    /// // The check failed, but the coverage says the failure is not attributable.
    /// assert_eq!(report.verdict(), Verdict::NotMeasured);
    /// ```
    #[must_use]
    pub fn coverage(&self) -> &Coverage {
        &self.coverage
    }

    /// The surviving files and their warrants.
    ///
    /// ```
    /// use powercut::{ScratchDir, Scenario, SyncJournal, Warrant};
    ///
    /// let store = ScratchDir::new("doc-report-manifest").unwrap();
    /// let journal = SyncJournal::complete();
    /// let db = store.path().join("certified");
    ///
    /// let report = Scenario::new(store.path(), journal.clone())
    ///     .ack(|| {
    ///         std::fs::write(&db, b"0123456789").unwrap();
    ///         journal.sync_path(&db).unwrap();
    ///         // Appended after the sync, and never re-synced: written, but
    ///         // never certified.
    ///         std::fs::write(&db, b"0123456789TAIL").unwrap();
    ///         std::fs::write(store.path().join("never-synced"), b"gone").unwrap();
    ///     })
    ///     .unwrap()
    ///     .check(|_crash, ()| Vec::new());
    ///
    /// // Only the fsynced file is here, and only up to its certified length.
    /// assert_eq!(report.manifest().len(), 1);
    /// let file = &report.manifest()[0];
    /// assert_eq!(file.path.as_os_str(), "certified");
    /// assert_eq!(file.bytes, 10);
    /// assert_eq!(file.truncated_from, Some(14));
    /// assert!(matches!(file.warrant, Warrant::Synced(_)));
    /// ```
    #[must_use]
    pub fn manifest(&self) -> &[CapturedFile] {
        &self.manifest
    }

    /// For a [`Tier::PowerCut`] run: did the same check pass against the
    /// tier-1 byte copy taken at the same instant?
    ///
    /// `Some(true)` with a `Lost` verdict is the classic missing-fsync
    /// signature. `Some(false)` means the data was not even on the filesystem,
    /// which is a different bug — or a wrong store path. `None` means the run
    /// was already tier 1.
    ///
    /// ```
    /// use powercut::{Checker, CrashState, ScratchDir, Scenario, SyncJournal, Tier, Verdict};
    ///
    /// let store = ScratchDir::new("doc-reached-filesystem").unwrap();
    /// let db = store.path().join("app.log");
    /// let check = |crash: &CrashState, _: &()| {
    ///     let mut c = Checker::new();
    ///     c.survives(
    ///         "app.log",
    ///         Some(b"acked".to_vec()),
    ///         std::fs::read(crash.dir().join("app.log")).ok(),
    ///     );
    ///     c.finish()
    /// };
    ///
    /// // The write reached the file; no fsync ever certified it.
    /// let missing_fsync = Scenario::new(store.path(), SyncJournal::complete())
    ///     .tier(Tier::PowerCut)
    ///     .ack(|| std::fs::write(&db, b"acked").unwrap())
    ///     .unwrap()
    ///     .check(check);
    /// assert_eq!(missing_fsync.verdict(), Verdict::Lost);
    /// assert_eq!(missing_fsync.reached_filesystem(), Some(true));
    ///
    /// // A tier-1 run has no second copy to compare itself against.
    /// let tier1 = Scenario::new(store.path(), SyncJournal::complete())
    ///     .tier(Tier::ProcessCrash)
    ///     .ack(|| ())
    ///     .unwrap()
    ///     .check(check);
    /// assert_eq!(tier1.reached_filesystem(), None);
    /// ```
    #[must_use]
    pub fn reached_filesystem(&self) -> Option<bool> {
        self.reference_violations.as_ref().map(|v| v.is_empty())
    }

    /// Everything worth reading, as text. This is what the assertions print.
    ///
    /// A failure is meant to be adjudicable from this string alone — which is
    /// also why `CONTRIBUTING.md` asks for it verbatim on an engine report.
    ///
    /// ```
    /// use powercut::{Checker, ScratchDir, Scenario, SyncJournal};
    ///
    /// let store = ScratchDir::new("doc-to-text").unwrap();
    /// let db = store.path().join("app.log");
    ///
    /// let report = Scenario::new(store.path(), SyncJournal::complete())
    ///     .label("myengine/no-fsync")
    ///     .ack(|| std::fs::write(&db, b"acked").unwrap())
    ///     .unwrap()
    ///     .check(|crash, ()| {
    ///         let mut c = Checker::new();
    ///         c.survives(
    ///             "app.log",
    ///             Some(b"acked".to_vec()),
    ///             std::fs::read(crash.dir().join("app.log")).ok(),
    ///         );
    ///         c.finish()
    ///     });
    ///
    /// let text = report.to_text();
    /// assert!(text.contains("myengine/no-fsync"));
    /// assert!(text.contains("=> lost"));
    /// assert!(text.contains("witness coverage: COMPLETE"));
    /// assert!(text.contains("surviving files at tier power-cut"));
    /// // The tier-1 comparison names the bug rather than leaving it to be guessed.
    /// assert!(text.contains("the missing thing is an fsync, not a write"));
    /// // And it says the red is not yet trustworthy, because nothing proved
    /// // the checker would have found the data even if it were durable.
    /// assert!(text.contains("teeth control: NOT RUN"));
    /// ```
    #[must_use]
    pub fn to_text(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!(
            "powercut: {} [tier {}] => {}\n",
            self.label,
            self.tier.as_str(),
            self.verdict()
        ));
        out.push_str(&format!("  tier models {}\n", self.tier.models()));
        match &self.coverage {
            Coverage::Complete => {
                out.push_str("  witness coverage: COMPLETE\n");
            }
            Coverage::Partial { unobserved } => {
                out.push_str(&format!("  witness coverage: PARTIAL — {unobserved}\n"));
            }
        }
        if self.used_assumption {
            out.push_str(
                "  !! this run used an ASSUMED-durable file. Assumptions only ever ENLARGE \
                 the durable set, so a pass here is weaker than a measured one.\n",
            );
        }
        // Only worth saying when something went wrong: on a pass the tier-1
        // copy always holds the data too, so the line would be pure noise.
        match self
            .reached_filesystem()
            .filter(|_| !self.verdict().is_pass())
        {
            Some(true) => out.push_str(
                "  asymmetry: the acked data IS present in the tier-1 byte copy taken at the \
                 same instant. It reached the filesystem and no further — the missing thing \
                 is an fsync, not a write.\n",
            ),
            Some(false) => out.push_str(
                "  asymmetry: the acked data is ALSO absent from the tier-1 byte copy, which \
                 keeps every byte that reached the filesystem. So the write never reached the \
                 filesystem at all — it is still in the engine's user-space buffers — or the \
                 store paths / checker are wrong. A teeth control tells those apart.\n",
            ),
            None => {}
        }
        if let Some(control) = &self.control_violations {
            if control.is_empty() {
                out.push_str(
                    "  teeth control: PASSED — with an explicit flush the same copy and the \
                     same checker do find the data, so the red above is about durability.\n",
                );
            } else {
                out.push_str("  teeth control: FAILED — see below.\n");
            }
        } else if self.verdict() == Verdict::Lost {
            out.push_str(
                "  teeth control: NOT RUN. Without one, a red cannot be distinguished from a \
                 broken harness. Add `.with_teeth_control(...)`.\n",
            );
        }
        out.push_str(&self.manifest_text);
        for note in &self.notes {
            out.push_str(&format!("  note: {note}\n"));
        }
        let violations = self.finding.violations();
        if !violations.is_empty() {
            out.push_str("  findings:\n");
            for v in violations {
                out.push_str(&format!("    {v}\n"));
            }
        }
        if let Finding::NotMeasured { why } = &self.finding {
            out.push_str(&format!("  NOT MEASURED: {why}\n"));
        }
        out
    }

    /// One markdown table row: `| label | tier | verdict | detail |`.
    ///
    /// ```
    /// use powercut::{to_markdown, Checker, ScratchDir, Scenario, SyncJournal};
    ///
    /// let store = ScratchDir::new("doc-markdown-row").unwrap();
    /// let journal = SyncJournal::complete();
    /// let db = store.path().join("app.log");
    ///
    /// let report = Scenario::new(store.path(), journal.clone())
    ///     .label("redb/default")
    ///     .ack(|| {
    ///         std::fs::write(&db, b"acked").unwrap();
    ///         journal.sync_path(&db).unwrap();
    ///     })
    ///     .unwrap()
    ///     .check(|crash, ()| {
    ///         let mut c = Checker::new();
    ///         c.survives(
    ///             "app.log",
    ///             Some(b"acked".to_vec()),
    ///             std::fs::read(crash.dir().join("app.log")).ok(),
    ///         );
    ///         c.finish()
    ///     });
    ///
    /// assert_eq!(
    ///     report.to_markdown_row(),
    ///     "| `redb/default` | power-cut | **survived** | — |",
    /// );
    ///
    /// // `to_markdown` wraps rows like this one in a table you can paste into
    /// // a README or a pull request.
    /// assert!(to_markdown(&[report]).contains("| `redb/default` |"));
    /// ```
    #[must_use]
    pub fn to_markdown_row(&self) -> String {
        let detail = match &self.finding {
            Finding::Survived => "—".to_string(),
            Finding::NotMeasured { why } => escape(why),
            Finding::Lost { violations } | Finding::HarnessBroken { violations, .. } => violations
                .iter()
                .map(|v| escape(&v.to_string()))
                .collect::<Vec<_>>()
                .join("; "),
        };
        format!(
            "| `{}` | {} | **{}** | {} |",
            self.label,
            self.tier.as_str(),
            self.verdict(),
            detail
        )
    }

    /// Panic unless the verdict is [`Verdict::Survived`], printing the whole
    /// self-adjudicating report.
    ///
    /// # Panics
    ///
    /// On any verdict other than `Survived` — including `NotMeasured`, which
    /// is the point: a check that could not run is not a pass.
    ///
    /// ```
    /// use powercut::{Checker, ScratchDir, Scenario, SyncJournal};
    ///
    /// let store = ScratchDir::new("doc-assert-survived").unwrap();
    /// let journal = SyncJournal::complete();
    /// let db = store.path().join("app.log");
    ///
    /// Scenario::new(store.path(), journal.clone())
    ///     .label("myengine/durable-ack")
    ///     .ack(|| {
    ///         std::fs::write(&db, b"balance=100").unwrap();
    ///         journal.sync_path(&db).unwrap();
    ///     })
    ///     .unwrap()
    ///     .check(|crash, ()| {
    ///         let mut c = Checker::new();
    ///         c.survives(
    ///             "balance",
    ///             Some(b"balance=100".to_vec()),
    ///             std::fs::read(crash.dir().join("app.log")).ok(),
    ///         );
    ///         c.finish()
    ///     })
    ///     .assert_survived();
    /// ```
    ///
    /// `NotMeasured` is where that matters. The check below could not be
    /// performed soundly, so it panics rather than passing quietly — never
    /// write `assert_ne!(verdict, Verdict::Lost)` in its place:
    ///
    /// ```should_panic
    /// use powercut::{Checker, ScratchDir, Scenario, SyncJournal};
    ///
    /// let store = ScratchDir::new("doc-assert-not-measured").unwrap();
    /// let db = store.path().join("app.db");
    ///
    /// Scenario::new(store.path(), SyncJournal::partial("the engine syncs through libc"))
    ///     .ack(|| std::fs::write(&db, b"row 42").unwrap())
    ///     .unwrap()
    ///     .check(|crash, ()| {
    ///         let mut c = Checker::new();
    ///         c.survives(
    ///             "row 42",
    ///             Some(b"row 42".to_vec()),
    ///             std::fs::read(crash.dir().join("app.db")).ok(),
    ///         );
    ///         c.finish()
    ///     })
    ///     .assert_survived();   // panics: NotMeasured is not a pass
    /// ```
    pub fn assert_survived(&self) {
        assert!(
            self.verdict().is_pass(),
            "\n{}\n{}",
            self.to_text(),
            self.control_detail()
        );
    }

    fn control_detail(&self) -> String {
        match &self.control_violations {
            Some(v) if !v.is_empty() => {
                let mut s = String::from(
                    "  the teeth control FAILED. With everything explicitly flushed the \
                     checker still could not find the data, so this run measured the harness, \
                     not the store:\n",
                );
                for violation in v {
                    s.push_str(&format!("    {violation}\n"));
                }
                s
            }
            _ => String::new(),
        }
    }
}

pub(crate) fn escape(s: &str) -> String {
    s.replace('|', "\\|").replace('\n', " ")
}