powercut 0.1.0

Prove your acknowledged write survives the power cut, in cargo test. A DB-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
//! Who certifies durability: the [`DurabilityWitness`] trait and the
//! zero-dependency [`SyncJournal`] that implements it.
//!
//! The rule this module exists to enforce: **a path enters the durable set
//! only after a `sync` that returned `Ok`.** Never because a test author
//! listed it, never because the code "should" have synced it.

use std::fs::{File, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

/// A monotonic ordering point, handed out by a [`SyncJournal`] on every
/// successful sync.
///
/// It is a sequence number, not a clock: it says *what happened before what*,
/// which is all a crash model needs, and it never goes backwards when the
/// system clock does.
///
/// ```
/// # use powercut::{Barrier, SyncJournal, SyncKind};
/// let journal = SyncJournal::complete();
/// let first = journal.record("a.db", SyncKind::File, None);
/// let second = journal.record("b.db", SyncKind::File, None);
/// assert!(first < second);
/// assert_eq!(Barrier::new(0), Barrier::new(0));
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Barrier(u64);

impl Barrier {
    /// Build a barrier from a raw sequence number.
    ///
    /// You need this only when implementing [`DurabilityWitness`] by hand;
    /// [`SyncJournal`] hands out its own.
    ///
    /// ```
    /// # use powercut::Barrier;
    /// assert_eq!(Barrier::new(7).seq(), 7);
    /// ```
    #[must_use]
    pub const fn new(seq: u64) -> Self {
        Self(seq)
    }

    /// The raw sequence number.
    ///
    /// ```
    /// # use powercut::Barrier;
    /// assert_eq!(Barrier::new(42).seq(), 42);
    /// ```
    #[must_use]
    pub const fn seq(self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for Barrier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "#{}", self.0)
    }
}

/// Which flavour of sync was performed.
///
/// The distinction matters when you read a report: a [`SyncKind::Data`] sync
/// (`fdatasync`) makes the file's *contents* durable but may leave its size
/// or timestamps in the page cache, and a [`SyncKind::Directory`] sync makes
/// a newly created *name* durable without touching the file's bytes.
///
/// ```
/// # use powercut::SyncKind;
/// assert_eq!(SyncKind::File.as_str(), "file");
/// ```
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum SyncKind {
    /// `File::sync_all` — contents **and** metadata.
    ///
    /// On macOS this is `fcntl(F_FULLFSYNC)`, a real device-cache flush; on
    /// Linux `fsync(2)`; on Windows `FlushFileBuffers`. See the crate-root
    /// section *The durability primitive* for what that does and does not buy.
    File,
    /// `File::sync_data` — contents only (`fdatasync` on Linux).
    Data,
    /// `fsync` of a *directory*, which is what makes a newly created file's
    /// **name** durable on Unix. Unavailable on Windows.
    Directory,
}

impl SyncKind {
    /// A short, stable, lowercase label for reports.
    ///
    /// ```
    /// # use powercut::SyncKind;
    /// assert_eq!(SyncKind::Directory.as_str(), "directory");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            SyncKind::File => "file",
            SyncKind::Data => "data",
            SyncKind::Directory => "directory",
        }
    }
}

/// One successful sync: *this path reached stable storage, at this length,
/// at this point in the ordering*.
///
/// A `SyncRecord` is only ever created after the underlying sync call
/// returned `Ok`. That is the whole contract — a journal that records
/// attempts rather than successes would make every downstream verdict a lie.
///
/// ```
/// # use powercut::{Barrier, SyncKind, SyncRecord};
/// let record = SyncRecord::new("/tmp/app.db", SyncKind::File, Barrier::new(1), Some(4096));
/// assert_eq!(record.durable_len, Some(4096));
/// assert_eq!(record.kind, SyncKind::File);
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SyncRecord {
    /// The synced path, canonicalised when the filesystem allowed it.
    pub path: PathBuf,
    /// Which sync call was made.
    pub kind: SyncKind,
    /// Where this sync sits in the ordering.
    pub at: Barrier,
    /// The file's length at the moment the sync returned `Ok`, when it could
    /// be observed. Bytes appended *after* this length are not durable, and
    /// [`Tier::PowerCut`](crate::Tier) truncates the captured copy to it.
    pub durable_len: Option<u64>,
    /// A byte-for-byte copy of the file's certified content, taken the instant
    /// the sync returned `Ok`.
    ///
    /// This is what makes tier 2 exact rather than optimistic. Without it, a
    /// capture has to read the file's *current* bytes, which silently credits
    /// any in-place overwrite made after the sync — and an in-place rewrite
    /// that was never re-synced is precisely what a checkpoint or a compaction
    /// does. [`SyncJournal`] always takes one; a hand-written witness may not,
    /// and the capture prints a note saying so.
    pub snapshot: Option<PathBuf>,
}

impl SyncRecord {
    /// Build a record. Call this only after a sync returned `Ok`.
    ///
    /// ```
    /// # use powercut::{Barrier, SyncKind, SyncRecord};
    /// let r = SyncRecord::new("data.log", SyncKind::Data, Barrier::new(3), None);
    /// assert_eq!(r.at.seq(), 3);
    /// ```
    #[must_use]
    pub fn new(
        path: impl Into<PathBuf>,
        kind: SyncKind,
        at: Barrier,
        durable_len: Option<u64>,
    ) -> Self {
        Self {
            path: path.into(),
            kind,
            at,
            durable_len,
            snapshot: None,
        }
    }

    /// Attach a content snapshot — a file holding exactly the bytes this sync
    /// certified. See [`SyncRecord::snapshot`].
    ///
    /// ```
    /// # use powercut::{Barrier, SyncKind, SyncRecord};
    /// let r = SyncRecord::new("app.db", SyncKind::File, Barrier::new(1), Some(9))
    ///     .with_snapshot("/tmp/snap/1");
    /// assert!(r.snapshot.is_some());
    /// ```
    #[must_use]
    pub fn with_snapshot(mut self, snapshot: impl Into<PathBuf>) -> Self {
        self.snapshot = Some(snapshot.into());
        self
    }
}

/// A path the harness is *told* to treat as durable without having observed a
/// sync for it.
///
/// This is the escape hatch for state that predates the measured window — a
/// base file that setup wrote, folded and closed long before the workload ran.
/// It **inflates** the durable set, so it can only ever turn a red into a
/// green. Every report prints it, loudly, for exactly that reason.
///
/// ```
/// # use powercut::AssumedDurable;
/// let a = AssumedDurable::new("base.db", "setup checkpointed and closed it before the workload");
/// assert_eq!(a.path.as_os_str(), "base.db");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AssumedDurable {
    /// The path being assumed durable.
    pub path: PathBuf,
    /// Why. This string is printed in every report that used the assumption.
    pub reason: String,
}

impl AssumedDurable {
    /// Build an assumption. The reason is mandatory on purpose.
    ///
    /// ```
    /// # use powercut::AssumedDurable;
    /// let a = AssumedDurable::new("base.db", "written and fsynced by setup");
    /// assert!(a.reason.contains("setup"));
    /// ```
    #[must_use]
    pub fn new(path: impl Into<PathBuf>, reason: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            reason: reason.into(),
        }
    }
}

/// How much of the store's sync activity this witness can actually see.
///
/// This is the single most important honesty knob in the crate, and it works
/// asymmetrically:
///
/// * Under [`Coverage::Partial`] the durable set is a **subset** of the truth.
///   A check that **passes** is therefore still sound — the data survived on
///   less than everything that was really durable.
/// * A check that **fails** under partial coverage proves nothing, because an
///   unobserved sync might have saved it. `powercut` reports that as
///   [`Finding::NotMeasured`](crate::Finding::NotMeasured), never as a loss.
///
/// That asymmetry is what stops the crate from libelling somebody's database.
///
/// ```
/// # use powercut::Coverage;
/// let c = Coverage::partial("libsqlite3 syncs through libc; we cannot see those calls");
/// assert!(!c.is_complete());
/// assert!(Coverage::Complete.is_complete());
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Coverage {
    /// Every sync that touches the store passes through this witness.
    ///
    /// Claim this only when it is structurally true — for example when the
    /// engine is configured to perform no syncs of its own and your code does
    /// all of them, or when the engine's storage backend is a type you wrapped.
    Complete,
    /// Some sync activity is invisible to this witness. The string says what.
    Partial {
        /// What is not observed, in one sentence, phrased for someone reading
        /// a failure report six months from now.
        unobserved: String,
    },
}

impl Coverage {
    /// Convenience constructor for [`Coverage::Partial`].
    ///
    /// ```
    /// # use powercut::Coverage;
    /// let c = Coverage::partial("the engine syncs internally through libc");
    /// assert!(matches!(c, Coverage::Partial { .. }));
    /// ```
    #[must_use]
    pub fn partial(unobserved: impl Into<String>) -> Self {
        Coverage::Partial {
            unobserved: unobserved.into(),
        }
    }

    /// `true` only for [`Coverage::Complete`].
    ///
    /// ```
    /// # use powercut::Coverage;
    /// assert!(Coverage::Complete.is_complete());
    /// ```
    #[must_use]
    pub fn is_complete(&self) -> bool {
        matches!(self, Coverage::Complete)
    }
}

/// Something that can tell `powercut` which bytes reached stable storage.
///
/// Implement this when your store already has its own durability bookkeeping
/// and you would rather hand it over than route syncs through
/// [`SyncJournal`]. Otherwise use `SyncJournal`, which implements this trait.
///
/// [`Self::coverage`] has no default implementation on purpose: forgetting it
/// would silently over-claim, and over-claiming is how a durability harness
/// starts accusing innocent databases.
///
/// ```
/// use powercut::{Barrier, Coverage, DurabilityWitness, SyncKind, SyncRecord};
///
/// /// A witness for a store that syncs exactly one file, once, at commit.
/// struct OneFile(std::path::PathBuf);
///
/// impl DurabilityWitness for OneFile {
///     fn synced(&self) -> Vec<SyncRecord> {
///         vec![SyncRecord::new(&self.0, SyncKind::File, Barrier::new(1), None)]
///     }
///     fn coverage(&self) -> Coverage {
///         Coverage::Complete
///     }
/// }
///
/// let w = OneFile("app.db".into());
/// assert_eq!(w.synced().len(), 1);
/// assert!(w.assumed().is_empty());
/// ```
pub trait DurabilityWitness {
    /// Every successful sync observed so far, in barrier order.
    fn synced(&self) -> Vec<SyncRecord>;

    /// How much of the store's sync activity this witness sees.
    fn coverage(&self) -> Coverage;

    /// Paths to treat as durable without having observed a sync. Defaults to
    /// none, which is the safe direction.
    fn assumed(&self) -> Vec<AssumedDurable> {
        Vec::new()
    }
}

impl<W: DurabilityWitness + ?Sized> DurabilityWitness for &W {
    fn synced(&self) -> Vec<SyncRecord> {
        (**self).synced()
    }
    fn coverage(&self) -> Coverage {
        (**self).coverage()
    }
    fn assumed(&self) -> Vec<AssumedDurable> {
        (**self).assumed()
    }
}

#[derive(Debug, Default)]
struct JournalInner {
    records: Vec<SyncRecord>,
    assumed: Vec<AssumedDurable>,
    /// Where certified content is stashed. Created on first successful sync so
    /// that a journal which never records anything costs nothing.
    snapshots: Option<crate::ScratchDir>,
}

impl JournalInner {
    /// Copy `path`'s first `len` bytes somewhere safe and return where.
    ///
    /// Best effort: if the snapshot cannot be taken the record still stands —
    /// a missing snapshot degrades tier 2 to the optimistic reading and says
    /// so in the report, whereas dropping the record would silently shrink the
    /// durable set, which is far worse.
    fn snapshot(&mut self, seq: u64, path: &Path, len: Option<u64>) -> Option<PathBuf> {
        if self.snapshots.is_none() {
            self.snapshots = crate::ScratchDir::new("synced-content").ok();
        }
        let dir = self.snapshots.as_ref()?;
        let dst = dir.path().join(format!("{seq:012}"));
        crate::scratch::copy_file(path, &dst, len).ok()?;
        Some(dst)
    }
}

/// The cooperative witness: a cheap, cloneable, thread-safe journal of
/// successful syncs.
///
/// Every `sync_*` method here performs the real sync **and records it only if
/// the call returned `Ok`**. Route your store's durability through it and the
/// durable set derives itself:
///
/// > delete an fsync from your write path and a file drops out of the durable
/// > set, which turns the power-cut tier red. The derivation *is* the mutation
/// > test.
///
/// `SyncJournal` is `Clone` and shares one journal between clones, so you can
/// hand a clone to your store and keep one for the [`Scenario`](crate::Scenario).
///
/// ```
/// use powercut::{Coverage, DurabilityWitness, SyncJournal};
///
/// let dir = powercut::ScratchDir::new("doc-journal").unwrap();
/// let path = dir.path().join("app.log");
/// std::fs::write(&path, b"hello").unwrap();
///
/// let journal = SyncJournal::complete();
/// journal.sync_path(&path).unwrap();
///
/// assert_eq!(journal.synced().len(), 1);
/// assert_eq!(journal.synced()[0].durable_len, Some(5));
/// assert!(journal.coverage().is_complete());
/// ```
#[derive(Clone, Debug)]
pub struct SyncJournal {
    inner: Arc<Mutex<JournalInner>>,
    next: Arc<AtomicU64>,
    coverage: Coverage,
}

impl SyncJournal {
    /// A journal that claims to observe **every** sync touching the store.
    ///
    /// Only claim this when it is structurally true. See [`Coverage`].
    ///
    /// ```
    /// # use powercut::{DurabilityWitness, SyncJournal};
    /// assert!(SyncJournal::complete().coverage().is_complete());
    /// ```
    #[must_use]
    pub fn complete() -> Self {
        Self::with_coverage(Coverage::Complete)
    }

    /// A journal that admits some sync activity is invisible to it.
    ///
    /// Under this coverage a failed check is reported as
    /// [`Finding::NotMeasured`](crate::Finding::NotMeasured) rather than a loss.
    ///
    /// ```
    /// # use powercut::{DurabilityWitness, SyncJournal};
    /// let j = SyncJournal::partial("the engine also syncs internally via libc");
    /// assert!(!j.coverage().is_complete());
    /// ```
    #[must_use]
    pub fn partial(unobserved: impl Into<String>) -> Self {
        Self::with_coverage(Coverage::partial(unobserved))
    }

    /// A journal with an explicitly supplied [`Coverage`].
    ///
    /// ```
    /// # use powercut::{Coverage, DurabilityWitness, SyncJournal};
    /// let j = SyncJournal::with_coverage(Coverage::Complete);
    /// assert!(j.synced().is_empty());
    /// ```
    #[must_use]
    pub fn with_coverage(coverage: Coverage) -> Self {
        Self {
            inner: Arc::new(Mutex::new(JournalInner::default())),
            next: Arc::new(AtomicU64::new(1)),
            coverage,
        }
    }

    fn next_barrier(&self) -> Barrier {
        Barrier(self.next.fetch_add(1, Ordering::SeqCst))
    }

    fn push(&self, record: SyncRecord) {
        let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        guard.records.push(record);
    }

    /// Record a sync **you have already performed successfully**.
    ///
    /// Use this when the sync happens somewhere `powercut` cannot reach — an
    /// engine callback, another thread, a `WriteGuard::drop`. Calling it
    /// without a successful sync behind it is the one way to make this crate
    /// lie to you.
    ///
    /// ```
    /// # use powercut::{DurabilityWitness, SyncJournal, SyncKind};
    /// let journal = SyncJournal::complete();
    /// // ... your code called `file.sync_all()?` and it returned Ok ...
    /// let at = journal.record("app.db", SyncKind::File, Some(8192));
    /// assert_eq!(at.seq(), 1);
    /// assert_eq!(journal.synced()[0].durable_len, Some(8192));
    /// ```
    pub fn record(
        &self,
        path: impl AsRef<Path>,
        kind: SyncKind,
        durable_len: Option<u64>,
    ) -> Barrier {
        let at = self.next_barrier();
        let path = canonical(path.as_ref());
        let mut record = SyncRecord::new(path.clone(), kind, at, durable_len);
        if kind != SyncKind::Directory {
            let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
            if let Some(snapshot) = guard.snapshot(at.seq(), &path, durable_len) {
                record.snapshot = Some(snapshot);
            }
            guard.records.push(record);
            return at;
        }
        self.push(record);
        at
    }

    /// `file.sync_all()`, then record it — contents and metadata.
    ///
    /// `path` is what the record will name; it must be the path `file` was
    /// opened from. The durable length is read back from the file handle
    /// **after** the sync returned `Ok`.
    ///
    /// ```
    /// # use powercut::{DurabilityWitness, SyncJournal};
    /// let dir = powercut::ScratchDir::new("doc-sync-all").unwrap();
    /// let path = dir.path().join("wal");
    /// let file = std::fs::File::create(&path).unwrap();
    /// std::io::Write::write_all(&mut (&file), b"0123456789").unwrap();
    ///
    /// let journal = SyncJournal::complete();
    /// journal.sync_all(&file, &path).unwrap();
    /// assert_eq!(journal.synced()[0].durable_len, Some(10));
    /// ```
    pub fn sync_all(&self, file: &File, path: impl AsRef<Path>) -> io::Result<Barrier> {
        file.sync_all()?;
        let len = file.metadata().ok().map(|m| m.len());
        Ok(self.record(path, SyncKind::File, len))
    }

    /// `file.sync_data()`, then record it — contents only.
    ///
    /// ```
    /// # use powercut::{DurabilityWitness, SyncJournal, SyncKind};
    /// let dir = powercut::ScratchDir::new("doc-sync-data").unwrap();
    /// let path = dir.path().join("wal");
    /// let file = std::fs::File::create(&path).unwrap();
    /// let journal = SyncJournal::complete();
    /// journal.sync_data(&file, &path).unwrap();
    /// assert_eq!(journal.synced()[0].kind, SyncKind::Data);
    /// ```
    pub fn sync_data(&self, file: &File, path: impl AsRef<Path>) -> io::Result<Barrier> {
        file.sync_data()?;
        let len = file.metadata().ok().map(|m| m.len());
        Ok(self.record(path, SyncKind::Data, len))
    }

    /// Open `path`, `sync_all` it, close it, record it.
    ///
    /// This is the *durable-ack* primitive: the thing an application does
    /// after its engine says "committed" when it does not trust the engine to
    /// have made that commit durable. It opens read-write because
    /// `FlushFileBuffers` on Windows requires write access.
    ///
    /// ```
    /// # use powercut::{DurabilityWitness, SyncJournal};
    /// let dir = powercut::ScratchDir::new("doc-sync-path").unwrap();
    /// let path = dir.path().join("app.db");
    /// std::fs::write(&path, b"committed").unwrap();
    ///
    /// let journal = SyncJournal::complete();
    /// journal.sync_path(&path).unwrap();
    /// assert_eq!(journal.synced()[0].durable_len, Some(9));
    /// ```
    pub fn sync_path(&self, path: impl AsRef<Path>) -> io::Result<Barrier> {
        let path = path.as_ref();
        let file = OpenOptions::new().read(true).write(true).open(path)?;
        self.sync_all(&file, path)
    }

    /// Like [`Self::sync_path`], but a missing file is not an error.
    ///
    /// Stores create and delete sidecars (`-wal`, `-shm`, `.tmp`) as they
    /// please, so a durable-ack that hard-fails on a sidecar that happens not
    /// to exist right now is a flake generator. Returns `Ok(None)` when the
    /// path is absent.
    ///
    /// ```
    /// # use powercut::{DurabilityWitness, SyncJournal};
    /// let dir = powercut::ScratchDir::new("doc-sync-opt").unwrap();
    /// let journal = SyncJournal::complete();
    /// assert!(journal.sync_path_if_present(dir.path().join("nope")).unwrap().is_none());
    /// assert!(journal.synced().is_empty());
    /// ```
    pub fn sync_path_if_present(&self, path: impl AsRef<Path>) -> io::Result<Option<Barrier>> {
        match self.sync_path(path) {
            Ok(barrier) => Ok(Some(barrier)),
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// `fsync` a **directory**, which is what makes a newly created file's
    /// *name* durable on Unix.
    ///
    /// Returns `Ok(None)` on Windows, where a directory handle cannot be
    /// flushed portably and the concept does not apply the same way. Nothing
    /// is recorded in that case, because recording an unperformed sync is the
    /// one thing this type must never do.
    ///
    /// ```
    /// # use powercut::SyncJournal;
    /// let dir = powercut::ScratchDir::new("doc-sync-dir").unwrap();
    /// let journal = SyncJournal::complete();
    /// let barrier = journal.sync_dir(dir.path()).unwrap();
    /// #[cfg(unix)]
    /// assert!(barrier.is_some());
    /// #[cfg(windows)]
    /// assert!(barrier.is_none());
    /// ```
    pub fn sync_dir(&self, dir: impl AsRef<Path>) -> io::Result<Option<Barrier>> {
        let dir = dir.as_ref();
        #[cfg(unix)]
        {
            File::open(dir)?.sync_all()?;
            Ok(Some(self.record(dir, SyncKind::Directory, None)))
        }
        #[cfg(not(unix))]
        {
            let _ = dir;
            Ok(None)
        }
    }

    /// Declare a path durable without having observed a sync for it.
    ///
    /// See [`AssumedDurable`]. This can only turn a red into a green, so every
    /// report that used it says so in its own paragraph.
    ///
    /// ```
    /// # use powercut::{DurabilityWitness, SyncJournal};
    /// let journal = SyncJournal::complete();
    /// journal.assume("base.db", "setup wrote, checkpointed and closed it before the workload");
    /// assert_eq!(journal.assumed().len(), 1);
    /// ```
    pub fn assume(&self, path: impl AsRef<Path>, reason: impl Into<String>) {
        let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        guard
            .assumed
            .push(AssumedDurable::new(canonical(path.as_ref()), reason));
    }
}

impl DurabilityWitness for SyncJournal {
    fn synced(&self) -> Vec<SyncRecord> {
        let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        guard.records.clone()
    }

    fn coverage(&self) -> Coverage {
        self.coverage.clone()
    }

    fn assumed(&self) -> Vec<AssumedDurable> {
        let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        guard.assumed.clone()
    }
}

/// Canonicalise if the filesystem lets us; otherwise keep the path as given.
///
/// Canonicalisation matters because `/tmp` is a symlink to `/private/tmp` on
/// macOS, so a record naming one and a capture walking the other would never
/// match and the durable set would come out silently empty.
pub(crate) fn canonical(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_failed_sync_records_nothing() {
        let journal = SyncJournal::complete();
        let err = journal.sync_path("/definitely/not/a/real/path/app.db");
        assert!(err.is_err());
        assert!(
            journal.synced().is_empty(),
            "the journal must mean `this is on stable storage`, never `we tried`"
        );
    }

    #[test]
    fn barriers_are_monotonic_across_clones() {
        let journal = SyncJournal::complete();
        let clone = journal.clone();
        let a = journal.record("a", SyncKind::File, None);
        let b = clone.record("b", SyncKind::File, None);
        assert!(a < b);
        assert_eq!(journal.synced().len(), 2, "clones share one journal");
    }
}