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);
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
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Fallback {
Rtc,
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,
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 {
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()),
})
}
pub fn is_open(&self) -> bool {
self.reading().is_some()
}
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)
}
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(())
}
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);
}
}
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}");
}
}
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()
}
}
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))
}
}
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());
}
}