mod common;
use common::{
append_line, count_occurrences, mds_bin, most_debounce_windows, poll_tap_until,
record_run_flag, run_flag_line, spawn_watch_ready, write_atomic, ChildGuard, RunFlag,
StderrTap, WriteCadence, ORDER_MARKER_LINE, ORDER_MARKER_SOURCE,
};
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
const WINDOW: Duration = Duration::from_millis(200);
const CAP: Duration = Duration::from_secs(2);
const WRITE_FOR: Duration = Duration::from_secs(6);
const WRITE_PAUSE: Duration = Duration::from_millis(5);
const MAX_WRITES: u32 = 1_200;
const ALLOWANCE: usize = 1;
const TIMEOUT: Duration = Duration::from_secs(2);
const OUTPUT_POLL: Duration = Duration::from_millis(20);
fn spawn_ready(cmd: &mut Command) -> (ChildGuard, StderrTap) {
let (child, tap, stdout_tap) = spawn_watch_ready(cmd);
assert!(stdout_tap.is_none(), "this test never pipes stdout");
(ChildGuard(child), tap)
}
fn source(version: u32) -> String {
format!("---\nname: v{version}\n---\nHot {{{{name}}}}!\n")
}
fn output(version: u32) -> String {
format!("---\nname: v{version}\n---\nHot v{version}!\n")
}
fn wait_for_output(path: &Path, expected: &str, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
loop {
if std::fs::read_to_string(path).is_ok_and(|held| held == expected) {
return true;
}
if Instant::now() >= deadline {
return false;
}
std::thread::sleep(OUTPUT_POLL);
}
}
struct Stream {
cadence: WriteCadence,
rebuilt_before: Option<(u32, String)>,
}
fn write_stream(src: &Path, out: &Path, startup: &str) -> Stream {
let mut cadence = WriteCadence::with_capacity(MAX_WRITES as usize);
let mut rebuilt_before = None;
for version in 1..=MAX_WRITES {
if cadence.span() >= WRITE_FOR {
break;
}
if rebuilt_before.is_none() {
rebuilt_before = std::fs::read_to_string(out)
.ok()
.filter(|held| held != startup)
.map(|held| {
let line = held.lines().next_back().unwrap_or_default();
(version, line.to_owned())
});
}
cadence.time(|| write_atomic(src, source(version)));
std::thread::sleep(WRITE_PAUSE);
}
Stream {
cadence,
rebuilt_before,
}
}
fn claim_1(stream: &Stream) -> (bool, String) {
let writes = stream.cadence.writes();
let Some((version, line)) = &stream.rebuilt_before else {
return (
false,
format!("no rebuilt output read before any of the {writes} writes"),
);
};
let before = stream
.cadence
.first(usize::try_from(*version).expect("a write number fits usize"));
let quiet = before.pauses(WINDOW / 2);
let read = format!("{line:?} read before write {version} of {writes}");
if quiet == 0 {
(
true,
format!(
"claim 1 proven: {read}, no gap of {:?} or more by then ({before})",
WINDOW / 2
),
)
} else {
(
false,
format!(
"claim 1 not judged: {read}, after {quiet} gap(s) of {:?} or more in which a \
window could close quietly ({before})",
WINDOW / 2
),
)
}
}
#[test]
fn watch_debounce_cap_rebuilds_while_writes_never_stop() {
const TEST: &str = "watch_debounce_cap_rebuilds_while_writes_never_stop";
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hot.mds");
let out = dir.path().join("hot.md");
std::fs::write(&src, source(0)).unwrap();
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"200",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
let startup = output(0);
assert!(
wait_for_output(&out, &startup, TIMEOUT),
"the startup compile must publish version 0"
);
let stream = write_stream(&src, &out, &startup);
let writes = stream.cadence.writes();
let last = u32::try_from(writes).expect("at most MAX_WRITES writes");
let published = wait_for_output(&out, &output(last), CAP + TIMEOUT);
write_atomic(&src, ORDER_MARKER_SOURCE);
let anchored = poll_tap_until(&stderr_tap, TIMEOUT, |text| {
text.contains(ORDER_MARKER_LINE)
})
.is_ok();
let stderr = stderr_tap.finish_text(&mut child);
let rebuilds = count_occurrences(&stderr, "Recompiled ");
let pauses = stream.cadence.pauses(WINDOW / 2);
let most = most_debounce_windows(&stream.cadence, WINDOW, CAP) + ALLOWANCE;
let flag = if pauses == 0 {
RunFlag::Conclusive
} else {
RunFlag::Inconclusive
};
let judged = match flag {
RunFlag::Conclusive => format!("at most {most} allowed"),
RunFlag::Inconclusive => format!(
"at most {most} allowed, loosened by {pauses} gap(s) of {:?} or more",
WINDOW / 2
),
};
let (proven, seen) = claim_1(&stream);
assert!(
flag == RunFlag::Inconclusive || proven || stream.rebuilt_before.is_none(),
"a run without a pause proves claim 1 whenever it saw a rebuild: {seen}"
);
record_run_flag(
TEST,
flag,
&format!(
"{rebuilds} rebuild(s), {judged}; {seen}; {}",
stream.cadence
),
);
assert!(
stream.rebuilt_before.is_some(),
"a rebuild must be published while the writes go on — that is what the cap is \
for — but every read before a write found the startup output ({seen}; {}); \
stderr was:\n{stderr}",
stream.cadence
);
assert!(
published,
"the stream's final state, version {last}, must be published once it ends; the \
output holds {:?}; stderr was:\n{stderr}",
std::fs::read_to_string(&out).ok()
);
assert!(
anchored,
"the order marker's diagnostic must reach stderr within {TIMEOUT:?}, or the count \
below is not exact; stderr was:\n{stderr}"
);
assert!(
rebuilds >= 2,
"a rebuild during the stream and the one that published its final state make \
at least two `Recompiled` lines; got {rebuilds}; stderr was:\n{stderr}"
);
assert!(
rebuilds <= most,
"{} with {pauses} gap(s) of {:?} or more allow at most {most} rebuilds under a \
{WINDOW:?} quiet period capped at {CAP:?} — a window that never extended would \
close about once per window; got {rebuilds}; stderr was:\n{stderr}",
stream.cadence,
WINDOW / 2
);
}
fn at(t0: Instant, ms: u64) -> Instant {
t0 + Duration::from_millis(ms)
}
fn writes_every(t0: Instant, from: u64, every: u64, count: u64) -> Vec<(Instant, Instant)> {
(0..count)
.map(|k| {
let began = from + k * every;
(at(t0, began), at(t0, began + 1))
})
.collect()
}
#[test]
fn a_gap_runs_from_the_start_of_one_write_to_the_end_of_the_next() {
let t0 = Instant::now();
let cadence = WriteCadence::of(vec![
(at(t0, 0), at(t0, 1)),
(at(t0, 6), at(t0, 7)),
(at(t0, 120), at(t0, 121)),
]);
assert_eq!(cadence.writes(), 3);
assert_eq!(cadence.span(), Duration::from_millis(121));
assert_eq!(
cadence.gaps(),
[Duration::from_millis(7), Duration::from_millis(115)]
);
assert_eq!(
cadence.pauses(Duration::from_millis(115)),
1,
"a gap of exactly the threshold is a pause"
);
assert_eq!(cadence.pauses(Duration::from_millis(116)), 0);
assert_eq!(cadence.pauses(Duration::from_millis(7)), 2);
assert_eq!(WriteCadence::of(Vec::new()).span(), Duration::ZERO);
}
#[test]
fn the_first_writes_are_a_cadence_of_their_own() {
let t0 = Instant::now();
let cadence = WriteCadence::of(vec![
(at(t0, 0), at(t0, 1)),
(at(t0, 6), at(t0, 7)),
(at(t0, 120), at(t0, 121)),
]);
let first_two = cadence.first(2);
assert_eq!(first_two.writes(), 2);
assert_eq!(first_two.gaps(), [Duration::from_millis(7)]);
assert_eq!(
first_two.pauses(WINDOW / 2),
0,
"the pause comes after the second write"
);
assert_eq!(cadence.first(3).pauses(WINDOW / 2), 1);
assert_eq!(
cadence.first(10).writes(),
3,
"all of them when fewer were recorded"
);
assert_eq!(cadence.first(0).span(), Duration::ZERO);
}
#[test]
fn claim_1_is_proven_only_when_no_pause_came_before_the_read() {
let t0 = Instant::now();
let stream = |read_before: Option<u32>| {
let mut writes = writes_every(t0, 0, 5, 10);
writes.extend(writes_every(t0, 300, 5, 10));
Stream {
cadence: WriteCadence::of(writes),
rebuilt_before: read_before.map(|version| (version, "Hot v1!".to_owned())),
}
};
for (read_before, proven) in [(Some(5), true), (Some(10), true), (Some(11), false)] {
let (verdict, text) = claim_1(&stream(read_before));
assert_eq!(verdict, proven, "read before write {read_before:?}: {text}");
}
let (verdict, text) = claim_1(&stream(None));
assert!(
!verdict && text.starts_with("no rebuilt output"),
"no rebuild read: {text}"
);
}
#[test]
fn the_rebuild_bound_follows_the_measured_cadence() {
let t0 = Instant::now();
let dense = WriteCadence::of(writes_every(t0, 0, 5, 1_200));
assert_eq!(dense.span(), Duration::from_millis(5_996));
assert_eq!(dense.pauses(WINDOW / 2), 0);
assert_eq!(most_debounce_windows(&dense, WINDOW, CAP), 4);
let mut paused = writes_every(t0, 0, 5, 400);
paused.extend(writes_every(t0, 2_145, 5, 400));
paused.extend(writes_every(t0, 4_290, 5, 400));
let paused = WriteCadence::of(paused);
assert_eq!(paused.pauses(WINDOW / 2), 2);
assert_eq!(paused.span(), Duration::from_millis(6_286));
assert_eq!(most_debounce_windows(&paused, WINDOW, CAP), 6);
let burst = WriteCadence::of(writes_every(t0, 0, 30, 12));
let burst_window = Duration::from_millis(250);
assert_eq!(
most_debounce_windows(&burst, burst_window, Duration::from_millis(2_500)),
1
);
}
#[test]
fn a_run_flag_is_one_line_the_soak_can_count() {
let yes = run_flag_line("t", RunFlag::Conclusive, "4 rebuild(s)");
let no = run_flag_line("t", RunFlag::Inconclusive, "2 gap(s)");
assert_eq!(yes, "t: conclusive: 4 rebuild(s)");
assert_eq!(no, "t: inconclusive: 2 gap(s)");
assert!(
!no.contains(": conclusive: "),
"the soak's conclusive pattern must not match an inconclusive line"
);
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("flags.log");
append_line(&log, &yes).unwrap();
append_line(&log, &no).unwrap();
assert_eq!(
std::fs::read_to_string(&log).unwrap(),
format!("{yes}\n{no}\n")
);
assert!(append_line(dir.path(), &yes).is_err());
}
#[test]
fn flags_appended_at_once_stay_one_per_line() {
const WRITERS: usize = 8;
const FLAGS: usize = 200;
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("flags.log");
std::thread::scope(|scope| {
for writer in 0..WRITERS {
let log = &log;
scope.spawn(move || {
for flag in 0..FLAGS {
let line = run_flag_line(
&format!("writer_{writer}"),
RunFlag::Conclusive,
&format!("flag {flag}"),
);
append_line(log, &line).expect("append a flag");
}
});
}
});
let text = std::fs::read_to_string(&log).unwrap();
let lines: Vec<&str> = text.lines().collect();
let malformed: Vec<&str> = lines
.iter()
.copied()
.filter(|line| count_occurrences(line, ": conclusive: ") != 1)
.take(3)
.collect();
assert!(
malformed.is_empty() && lines.len() == WRITERS * FLAGS,
"{} lines for {} flags; first malformed: {malformed:?}",
lines.len(),
WRITERS * FLAGS
);
}