second-brain-api 0.13.4

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
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
//! Holds seq minting until the wall clock can be trusted. A Pi without an
//! RTC boots on a saved, older time until NTP syncs, and a restored card
//! boots at roughly its image time; seqs minted then could repeat.

use std::any::Any;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use chrono::{DateTime, Utc};
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::sqlite_store::clock::{ClockUntrusted, HLC_CEILING_MICROS, WallClock};

use crate::health::Health;

pub const READING_FILE: &str = "clock-reading";
const TICK_OPEN: Duration = Duration::from_secs(60);
const TICK_CLOSED: Duration = Duration::from_secs(1);
const REEVALUATE_EVERY: Duration = Duration::from_secs(1);
/// Smaller backward moves are NTP step corrections, which the HLC absorbs
/// by counting up from its last seq.
const BACKWARD_STEP_MICROS: i64 = 1_000_000;
const DAY_MICROS: i64 = 86_400 * 1_000_000;
const PEER_AHEAD_SYNCED_MICROS: i64 = DAY_MICROS;
const PEER_AHEAD_UNSYNCED_MICROS: i64 = 365 * DAY_MICROS;
const BASIS_AHEAD_MICROS: i64 = 60 * 1_000_000;

pub trait TimeSignals: Send + Sync + std::panic::RefUnwindSafe {
    fn now_micros(&self) -> i64;
    fn ntp_synced(&self) -> bool;
    fn rtc_secs(&self) -> Option<i64>;
}

pub struct SystemSignals;

impl TimeSignals for SystemSignals {
    fn now_micros(&self) -> i64 {
        system_micros()
    }

    #[cfg(target_os = "linux")]
    fn ntp_synced(&self) -> bool {
        kernel_synced() || Path::new("/run/systemd/timesync/synchronized").exists()
    }

    #[cfg(not(target_os = "linux"))]
    fn ntp_synced(&self) -> bool {
        false
    }

    #[cfg(target_os = "linux")]
    fn rtc_secs(&self) -> Option<i64> {
        std::fs::read_to_string("/sys/class/rtc/rtc0/since_epoch")
            .ok()?
            .trim()
            .parse()
            .ok()
    }

    #[cfg(not(target_os = "linux"))]
    fn rtc_secs(&self) -> Option<i64> {
        None
    }
}

#[cfg(target_os = "linux")]
fn kernel_synced() -> bool {
    let mut tx: libc::timex = unsafe { std::mem::zeroed() };
    let state = unsafe { libc::adjtimex(&mut tx) };
    state != -1 && state != libc::TIME_ERROR && tx.status & libc::STA_UNSYNC == 0
}

fn system_micros() -> i64 {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(since) => since.as_micros() as i64,
        Err(before) => -(before.duration().as_micros() as i64),
    }
}

struct TrustedSystemTime;

impl TimeSignals for TrustedSystemTime {
    fn now_micros(&self) -> i64 {
        system_micros()
    }

    fn ntp_synced(&self) -> bool {
        true
    }

    fn rtc_secs(&self) -> Option<i64> {
        None
    }
}

/// The opening rule used when neither NTP nor a peer vouches for the clock.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Fallback {
    /// A batteryless or missing RTC never passes, so a Pi waits for NTP.
    Rtc,
    /// Every Mac has a battery RTC, so its clock alone is enough.
    WallClock,
}

impl Fallback {
    fn for_target() -> Self {
        if cfg!(target_os = "linux") {
            Fallback::Rtc
        } else {
            Fallback::WallClock
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GateStatus {
    pub open: bool,
    pub synced: bool,
    pub now_micros: i64,
}

impl GateStatus {
    pub fn basis_ahead(&self, basis_micros: i64) -> bool {
        self.synced && basis_micros > self.now_micros.saturating_add(BASIS_AHEAD_MICROS)
    }
}

type Observer = Box<dyn Fn(&GateStatus) + Send + Sync>;

struct GateState {
    open: bool,
    /// The highest reading seen since the gate last opened.
    high: i64,
    persisted: i64,
    evaluated_at: Option<Instant>,
    changed: bool,
    closures: u64,
}

pub struct ClockGate {
    signals: Arc<dyn TimeSignals>,
    build_secs: i64,
    fallback: Fallback,
    reading_path: Option<PathBuf>,
    state: Mutex<GateState>,
    changed: Condvar,
    persisting: Mutex<()>,
    observers: Mutex<Vec<Observer>>,
}

impl ClockGate {
    /// Closed until an opening rule holds; `build_secs` is the binary's build
    /// time, a lower bound on real time.
    pub fn new(data_dir: &Path, signals: Arc<dyn TimeSignals>, build_secs: i64) -> Arc<Self> {
        Self::build(
            Some(data_dir.join(READING_FILE)),
            signals,
            build_secs,
            Fallback::for_target(),
            false,
        )
    }

    pub fn system(data_dir: &Path) -> Arc<Self> {
        Self::new(data_dir, Arc::new(SystemSignals), build_epoch())
    }

    pub fn open_for_tests() -> Arc<Self> {
        Self::build(
            None,
            Arc::new(TrustedSystemTime),
            0,
            Fallback::for_target(),
            true,
        )
    }

    fn build(
        reading_path: Option<PathBuf>,
        signals: Arc<dyn TimeSignals>,
        build_secs: i64,
        fallback: Fallback,
        open: bool,
    ) -> Arc<Self> {
        let persisted = reading_path.as_deref().map_or(0, load_reading);
        let high = signals.now_micros();
        Arc::new(Self {
            signals,
            build_secs,
            fallback,
            reading_path,
            state: Mutex::new(GateState {
                open,
                high,
                persisted,
                evaluated_at: None,
                changed: false,
                closures: 0,
            }),
            changed: Condvar::new(),
            persisting: Mutex::new(()),
            observers: Mutex::new(Vec::new()),
        })
    }

    /// Re-evaluates the opening rules when closed, at most once a second.
    pub fn is_open(&self) -> bool {
        self.reading().is_some()
    }

    /// How many times the gate has gone from open to closed. A unit of work
    /// that failed while this moved failed on writes the gate held, so it is
    /// still pending.
    pub fn closures(&self) -> u64 {
        self.lock().closures
    }

    pub fn synced(&self) -> bool {
        self.signals.ntp_synced()
    }

    pub fn wall_micros(&self) -> i64 {
        self.signals.now_micros().min(HLC_CEILING_MICROS)
    }

    /// For a handshake with a peer that reported its own clock synchronised;
    /// the caller has already bounded the peer's time.
    pub fn open_by_peer(&self) {
        let now = self.signals.now_micros();
        let mut state = self.lock();
        if !state.open {
            tracing::info!("clock gate opened by a synchronised sync peer");
            self.set_open(&mut state, now);
        }
    }

    pub fn check_peer_time(&self, peer_micros: i64) -> Result<(), String> {
        if peer_micros > HLC_CEILING_MICROS {
            return Err(format!(
                "peer time {} is past the clock ceiling {}",
                show(peer_micros),
                show(HLC_CEILING_MICROS)
            ));
        }
        let (base, allowed, span, against) = if self.synced() {
            (
                self.signals.now_micros(),
                PEER_AHEAD_SYNCED_MICROS,
                "a day",
                "this device's synchronised clock",
            )
        } else {
            (
                self.lock()
                    .persisted
                    .max(self.build_secs.saturating_mul(1_000_000)),
                PEER_AHEAD_UNSYNCED_MICROS,
                "a year",
                "this device's last trusted clock reading",
            )
        };
        if peer_micros > base.saturating_add(allowed) {
            return Err(format!(
                "peer time {} is more than {span} ahead of {against} ({})",
                show(peer_micros),
                show(base)
            ));
        }
        Ok(())
    }

    /// Saves the reading while open, re-evaluates while closed, then tells
    /// every observer where the gate stands.
    pub fn tick(&self) {
        if !self.lock().open {
            self.evaluate();
        }
        if let Some(reading) = self.reading() {
            self.persist(reading);
        }
        let status = GateStatus {
            open: self.lock().open,
            synced: self.synced(),
            now_micros: self.signals.now_micros(),
        };
        for observer in self.observers().iter() {
            observer(&status);
        }
    }

    /// Ticks every minute while open and every second while closed, and at
    /// once whenever the gate opens or closes.
    pub fn spawn_ticker(self: &Arc<Self>) {
        let gate = self.clone();
        let spawned = std::thread::Builder::new()
            .name("clock-gate".to_string())
            .spawn(move || {
                loop {
                    gate.tick();
                    gate.wait_for_change();
                }
            });
        if let Err(e) = spawned {
            tracing::error!("cannot start the clock gate ticker: {e}");
        }
    }

    /// Observers run on the ticking thread, never inside a store write.
    pub fn observe(&self, observer: impl Fn(&GateStatus) + Send + Sync + 'static) {
        self.observers().push(Box::new(observer));
    }

    fn reading(&self) -> Option<i64> {
        {
            let mut state = self.lock();
            if state.open {
                let now = self.signals.now_micros();
                return self.observe_open(&mut state, now);
            }
            if state
                .evaluated_at
                .is_some_and(|at| at.elapsed() < REEVALUATE_EVERY)
            {
                return None;
            }
        }
        if !self.evaluate() {
            return None;
        }
        let mut state = self.lock();
        if !state.open {
            return None;
        }
        let now = self.signals.now_micros();
        self.observe_open(&mut state, now)
    }

    fn observe_open(&self, state: &mut GateState, now: i64) -> Option<i64> {
        if now < state.high - BACKWARD_STEP_MICROS {
            tracing::warn!(
                "the wall clock stepped back from {} to {}; holding writes until it is trusted again",
                show(state.high),
                show(now)
            );
            state.open = false;
            state.evaluated_at = None;
            state.closures += 1;
            self.mark_changed(state);
            return None;
        }
        state.high = state.high.max(now);
        Some(now.min(HLC_CEILING_MICROS))
    }

    fn evaluate(&self) -> bool {
        let synced = self.signals.ntp_synced();
        let rtc = match self.fallback {
            Fallback::Rtc => self.signals.rtc_secs(),
            Fallback::WallClock => None,
        };
        let now = self.signals.now_micros();
        let mut state = self.lock();
        state.evaluated_at = Some(Instant::now());
        if state.open {
            return true;
        }
        let opens = synced
            || match self.fallback {
                Fallback::Rtc => {
                    rtc.is_some_and(|secs| secs >= self.build_secs) && now >= state.persisted
                }
                Fallback::WallClock => {
                    now >= state.persisted && now >= self.build_secs.saturating_mul(1_000_000)
                }
            };
        if opens {
            tracing::info!(
                "clock gate opened ({})",
                if synced {
                    "time is synchronised"
                } else {
                    "the clock is past the last trusted reading"
                }
            );
            self.set_open(&mut state, now);
        }
        opens
    }

    fn set_open(&self, state: &mut GateState, now: i64) {
        state.open = true;
        state.high = now;
        self.mark_changed(state);
    }

    fn mark_changed(&self, state: &mut GateState) {
        state.changed = true;
        self.changed.notify_all();
    }

    fn persist(&self, reading: i64) {
        let Some(path) = &self.reading_path else {
            return;
        };
        let _serial = relock(self.persisting.lock());
        if reading <= self.lock().persisted {
            return;
        }
        match write_reading(path, reading) {
            Ok(()) => {
                let mut state = self.lock();
                state.persisted = state.persisted.max(reading);
            }
            Err(e) => tracing::warn!("cannot save the clock reading to {}: {e}", path.display()),
        }
    }

    fn wait_for_change(&self) {
        let state = self.lock();
        let timeout = if state.open { TICK_OPEN } else { TICK_CLOSED };
        let (mut state, _) = relock(
            self.changed
                .wait_timeout_while(state, timeout, |state| !state.changed),
        );
        state.changed = false;
    }

    fn lock(&self) -> MutexGuard<'_, GateState> {
        relock(self.state.lock())
    }

    fn observers(&self) -> MutexGuard<'_, Vec<Observer>> {
        relock(self.observers.lock())
    }
}

impl WallClock for ClockGate {
    fn now_micros(&self) -> Option<i64> {
        self.reading()
    }
}

/// Reports the gate, and a store basis running ahead of synchronised time,
/// to `/health` on every tick.
pub fn report_to(clock: &ClockGate, health: Arc<Health>, sqlite: Arc<SqliteStore>) {
    let hold = Mutex::new(HoldTimer::default());
    clock.observe(move |status| {
        let now = Utc::now();
        let held_for = relock(hold.lock()).observe(status.open, Instant::now());
        health.clock_gate(held_for, now);
        if !status.synced {
            health.clock_basis_ahead(false, now);
            return;
        }
        match sqlite.clock_state() {
            Ok(state) => health.clock_basis_ahead(status.basis_ahead(state.basis), now),
            Err(e) => tracing::warn!("cannot read the store's clock state: {e:#}"),
        }
    });
}

#[derive(Default)]
struct HoldTimer {
    closed_at: Option<Instant>,
}

impl HoldTimer {
    fn observe(&mut self, open: bool, now: Instant) -> Option<Duration> {
        if open {
            self.closed_at = None;
            return None;
        }
        let closed_at = *self.closed_at.get_or_insert(now);
        Some(now.saturating_duration_since(closed_at))
    }
}

/// True for `ClockUntrusted` itself or an `anyhow::Error` carrying it
/// anywhere in its chain.
pub fn is_untrusted(error: &dyn Any) -> bool {
    if error.is::<ClockUntrusted>() {
        return true;
    }
    error
        .downcast_ref::<anyhow::Error>()
        .is_some_and(|e| e.chain().any(|cause| cause.is::<ClockUntrusted>()))
}

fn build_epoch() -> i64 {
    env!("SB_BUILD_EPOCH").parse().unwrap_or(0)
}

fn load_reading(path: &Path) -> i64 {
    match std::fs::read_to_string(path) {
        Ok(text) => match text.trim().parse::<i64>() {
            Ok(micros) => micros.min(HLC_CEILING_MICROS),
            Err(e) => {
                tracing::warn!("ignoring the clock reading in {}: {e}", path.display());
                0
            }
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
        Err(e) => {
            tracing::warn!("cannot read the clock reading in {}: {e}", path.display());
            0
        }
    }
}

fn write_reading(path: &Path, micros: i64) -> std::io::Result<()> {
    let tmp = path.with_extension("tmp");
    let mut file = std::fs::File::create(&tmp)?;
    file.write_all(micros.to_string().as_bytes())?;
    file.sync_all()?;
    drop(file);
    std::fs::rename(&tmp, path)
}

fn show(micros: i64) -> String {
    DateTime::<Utc>::from_timestamp_micros(micros)
        .map_or_else(|| format!("{micros} µs"), |at| at.to_rfc3339())
}

fn relock<G>(result: Result<G, std::sync::PoisonError<G>>) -> G {
    match result {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};

    use super::*;

    const BUILD_SECS: i64 = 1_790_000_000;
    const T0: i64 = (BUILD_SECS + 86_400) * 1_000_000;
    const SECOND: i64 = 1_000_000;

    #[derive(Default)]
    struct FakeSignals {
        now: AtomicI64,
        synced: AtomicBool,
        rtc: Mutex<Option<i64>>,
    }

    impl FakeSignals {
        fn at(now: i64) -> Arc<Self> {
            let fake = Arc::new(Self::default());
            fake.set_now(now);
            fake
        }

        fn set_now(&self, now: i64) {
            self.now.store(now, Ordering::SeqCst);
        }

        fn set_synced(&self, synced: bool) {
            self.synced.store(synced, Ordering::SeqCst);
        }

        fn set_rtc(&self, secs: Option<i64>) {
            *self.rtc.lock().unwrap() = secs;
        }
    }

    impl TimeSignals for FakeSignals {
        fn now_micros(&self) -> i64 {
            self.now.load(Ordering::SeqCst)
        }

        fn ntp_synced(&self) -> bool {
            self.synced.load(Ordering::SeqCst)
        }

        fn rtc_secs(&self) -> Option<i64> {
            *self.rtc.lock().unwrap()
        }
    }

    fn gate(dir: &Path, fake: &Arc<FakeSignals>, fallback: Fallback) -> Arc<ClockGate> {
        ClockGate::build(
            Some(dir.join(READING_FILE)),
            fake.clone(),
            BUILD_SECS,
            fallback,
            false,
        )
    }

    fn saved(dir: &Path) -> Option<i64> {
        std::fs::read_to_string(dir.join(READING_FILE))
            .ok()
            .map(|s| s.trim().parse().unwrap())
    }

    fn mints(gate: &ClockGate) -> Option<i64> {
        WallClock::now_micros(gate)
    }

    #[test]
    fn without_any_signal_the_gate_stays_closed_and_mints_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(T0);
        for fallback in [Fallback::Rtc, Fallback::WallClock] {
            let gate = gate(dir.path(), &fake, fallback);
            if fallback == Fallback::WallClock {
                fake.set_now(BUILD_SECS * SECOND - SECOND);
            }
            gate.tick();
            assert!(!gate.is_open(), "{fallback:?}");
            assert_eq!(mints(&gate), None);
            assert_eq!(saved(dir.path()), None, "a closed gate saves nothing");
        }
    }

    #[test]
    fn ntp_sync_opens_the_gate() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(T0);
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        gate.tick();
        assert!(!gate.is_open());
        fake.set_synced(true);
        gate.tick();
        assert!(gate.is_open());
        assert!(gate.synced());
        assert_eq!(mints(&gate), Some(T0));
    }

    #[test]
    fn a_synced_peer_opens_the_gate() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(T0);
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        gate.tick();
        gate.open_by_peer();
        assert!(gate.is_open());
        assert!(!gate.synced());
        assert_eq!(mints(&gate), Some(T0));
    }

    #[test]
    fn an_rtc_at_or_after_the_build_opens_once_the_clock_passes_the_saved_reading() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(READING_FILE),
            (T0 + 10 * SECOND).to_string(),
        )
        .unwrap();
        let fake = FakeSignals::at(T0);

        fake.set_rtc(Some(BUILD_SECS - 1));
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        fake.set_now(T0 + 20 * SECOND);
        gate.tick();
        assert!(!gate.is_open(), "an RTC before the build time");

        fake.set_rtc(None);
        gate.tick();
        assert!(!gate.is_open(), "no RTC");

        fake.set_rtc(Some(BUILD_SECS));
        fake.set_now(T0);
        gate.tick();
        assert!(!gate.is_open(), "the clock is behind the saved reading");

        fake.set_now(T0 + 10 * SECOND);
        gate.tick();
        assert!(gate.is_open());
    }

    #[test]
    fn without_the_rtc_rule_the_clock_opens_past_both_the_reading_and_the_build() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(READING_FILE), T0.to_string()).unwrap();
        let fake = FakeSignals::at(T0 - SECOND);
        fake.set_rtc(Some(BUILD_SECS + 1));
        let gate = gate(dir.path(), &fake, Fallback::WallClock);
        gate.tick();
        assert!(!gate.is_open(), "behind the saved reading");

        let fresh = tempfile::tempdir().unwrap();
        let early = gate_at(fresh.path(), BUILD_SECS * SECOND - SECOND);
        early.tick();
        assert!(!early.is_open(), "behind the build time");

        fake.set_now(T0);
        gate.tick();
        assert!(gate.is_open());
    }

    fn gate_at(dir: &Path, now: i64) -> Arc<ClockGate> {
        gate(dir, &FakeSignals::at(now), Fallback::WallClock)
    }

    #[test]
    fn a_backward_step_while_open_closes_the_gate() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(T0);
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        gate.open_by_peer();
        fake.set_now(T0 + 30 * SECOND);
        assert_eq!(mints(&gate), Some(T0 + 30 * SECOND));

        fake.set_now(T0 + 30 * SECOND - SECOND / 2);
        assert!(gate.is_open(), "a sub-second correction keeps it open");

        fake.set_now(T0 + 10 * SECOND);
        assert_eq!(mints(&gate), None);
        assert!(!gate.is_open());
        gate.tick();
        assert!(
            !gate.is_open(),
            "the peer's opening does not outlast a step"
        );

        fake.set_synced(true);
        gate.tick();
        assert!(gate.is_open());
    }

    #[test]
    fn peer_time_is_bounded_by_a_day_when_synced_and_a_year_when_not() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(T0);
        fake.set_synced(true);
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        assert_eq!(gate.check_peer_time(T0 + DAY_MICROS), Ok(()));
        let err = gate.check_peer_time(T0 + DAY_MICROS + 1).unwrap_err();
        assert!(err.contains("more than a day ahead"), "{err}");

        fake.set_synced(false);
        let build = BUILD_SECS * SECOND;
        assert_eq!(gate.check_peer_time(build + 365 * DAY_MICROS), Ok(()));
        assert!(gate.check_peer_time(build + 365 * DAY_MICROS + 1).is_err());

        let saved_dir = tempfile::tempdir().unwrap();
        let reading = T0 + 100 * DAY_MICROS;
        std::fs::write(saved_dir.path().join(READING_FILE), reading.to_string()).unwrap();
        let unsynced = gate_at(saved_dir.path(), T0);
        assert_eq!(unsynced.check_peer_time(reading + 365 * DAY_MICROS), Ok(()));
        let err = unsynced
            .check_peer_time(reading + 365 * DAY_MICROS + 1)
            .unwrap_err();
        assert!(err.contains("more than a year ahead"), "{err}");
    }

    #[test]
    fn peer_time_past_the_ceiling_is_rejected_whatever_the_own_clock_reads() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(HLC_CEILING_MICROS);
        fake.set_synced(true);
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        assert_eq!(gate.check_peer_time(HLC_CEILING_MICROS), Ok(()));
        let err = gate.check_peer_time(HLC_CEILING_MICROS + 1).unwrap_err();
        assert!(err.contains("ceiling"), "{err}");
    }

    #[test]
    fn the_saved_reading_only_rises_and_is_capped_at_the_ceiling() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(T0);
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        gate.open_by_peer();
        gate.tick();
        assert_eq!(saved(dir.path()), Some(T0));

        fake.set_now(T0 - SECOND / 2);
        gate.tick();
        assert!(gate.is_open());
        assert_eq!(saved(dir.path()), Some(T0));

        fake.set_now(T0 + 5 * SECOND);
        gate.tick();
        assert_eq!(saved(dir.path()), Some(T0 + 5 * SECOND));

        let restarted = gate_at(dir.path(), T0);
        restarted.open_by_peer();
        restarted.tick();
        assert_eq!(saved(dir.path()), Some(T0 + 5 * SECOND));

        fake.set_now(HLC_CEILING_MICROS + DAY_MICROS);
        gate.tick();
        assert_eq!(mints(&gate), Some(HLC_CEILING_MICROS));
        assert_eq!(gate.wall_micros(), HLC_CEILING_MICROS);
        assert_eq!(saved(dir.path()), Some(HLC_CEILING_MICROS));
        assert!(!dir.path().join("clock-reading.tmp").exists());
    }

    #[test]
    fn observers_hear_the_gate_on_every_tick() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(T0);
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        let heard = Arc::new(Mutex::new(Vec::new()));
        let sink = heard.clone();
        gate.observe(move |status| sink.lock().unwrap().push(*status));
        gate.tick();
        fake.set_synced(true);
        gate.tick();
        let heard = heard.lock().unwrap();
        assert_eq!(
            *heard,
            [
                GateStatus {
                    open: false,
                    synced: false,
                    now_micros: T0
                },
                GateStatus {
                    open: true,
                    synced: true,
                    now_micros: T0
                },
            ]
        );
    }

    #[test]
    fn the_ticker_reports_a_closing_without_waiting_out_its_minute() {
        let dir = tempfile::tempdir().unwrap();
        let fake = FakeSignals::at(T0);
        let gate = gate(dir.path(), &fake, Fallback::Rtc);
        gate.open_by_peer();
        let (tx, rx) = std::sync::mpsc::channel();
        gate.observe(move |status| {
            let _ = tx.send(status.open);
        });
        gate.spawn_ticker();
        assert_eq!(rx.recv_timeout(Duration::from_secs(10)), Ok(true));
        fake.set_now(T0 - 10 * SECOND);
        assert_eq!(mints(&gate), None);
        let closed = std::iter::from_fn(|| rx.recv_timeout(Duration::from_secs(10)).ok())
            .find(|open| !*open);
        assert_eq!(closed, Some(false));
    }

    #[test]
    fn the_hold_counts_from_the_first_closed_tick_and_restarts_on_reopening() {
        let start = Instant::now();
        let at = |secs: u64| start + Duration::from_secs(secs);
        let mut hold = HoldTimer::default();
        assert_eq!(hold.observe(false, at(0)), Some(Duration::ZERO));
        assert_eq!(hold.observe(false, at(90)), Some(Duration::from_secs(90)));
        assert_eq!(hold.observe(true, at(120)), None);
        assert_eq!(hold.observe(false, at(180)), Some(Duration::ZERO));
        assert_eq!(hold.observe(false, at(240)), Some(Duration::from_secs(60)));
    }

    #[test]
    fn a_basis_is_ahead_only_past_a_minute_of_synchronised_time() {
        let synced = GateStatus {
            open: true,
            synced: true,
            now_micros: T0,
        };
        assert!(!synced.basis_ahead(T0 + 60 * SECOND));
        assert!(synced.basis_ahead(T0 + 60 * SECOND + 1));
        let unsynced = GateStatus {
            synced: false,
            ..synced
        };
        assert!(!unsynced.basis_ahead(T0 + DAY_MICROS));
    }

    #[test]
    fn untrusted_is_found_through_context_and_nowhere_else() {
        let wrapped = anyhow::Error::new(ClockUntrusted).context("storing a memory");
        assert!(is_untrusted(&wrapped));
        assert!(is_untrusted(&ClockUntrusted));
        assert!(!is_untrusted(&anyhow::anyhow!("database is locked")));
        assert!(!is_untrusted(&"wall clock not yet trusted".to_string()));
    }

    #[test]
    fn the_test_gate_is_open_and_saves_nothing() {
        let gate = ClockGate::open_for_tests();
        assert!(gate.is_open());
        assert!(mints(&gate).is_some());
        gate.tick();
        assert!(gate.reading_path.is_none());
    }
}