use core::{num::NonZeroU64, time::Duration};
use std::{
ffi::OsString,
path::{Path, PathBuf},
time::Instant,
};
use tributary_proto::{Epoch, Location, ScopeId};
use super::Coalescer;
use crate::{
event::{Event, EventKind},
options::{Debounce, DebounceConfig},
subscription::Subscription,
};
type Ev = Event<OsString, ()>;
fn sub(id: u64) -> Subscription {
Subscription::for_test(ScopeId::new(NonZeroU64::new(id).expect("nonzero id")))
}
fn key(path: &str) -> Vec<OsString> {
Path::new(path)
.components()
.map(|c| c.as_os_str().to_os_string())
.collect()
}
fn ev(s: Subscription, path: &str, kind: EventKind<OsString>, epoch: u64) -> Ev {
Event::synthetic(s, key(path), Location::new(), kind, Epoch::new(epoch))
}
fn created(s: Subscription, path: &str, epoch: u64) -> Ev {
ev(s, path, EventKind::Created, epoch)
}
fn modified(s: Subscription, path: &str, epoch: u64) -> Ev {
ev(s, path, EventKind::Modified, epoch)
}
fn removed(s: Subscription, path: &str, epoch: u64) -> Ev {
ev(s, path, EventKind::Removed, epoch)
}
fn moved(s: Subscription, path: &str, from: &str, epoch: u64) -> Ev {
ev(s, path, EventKind::Moved { from: key(from) }, epoch)
}
fn is_moved(ev: &Ev) -> bool {
ev.move_from().is_some()
}
fn move_from_path(ev: &Ev) -> PathBuf {
PathBuf::from_iter(ev.move_from().expect("a move source"))
}
fn rescan(s: Subscription, path: &str, epoch: u64) -> Ev {
ev(s, path, EventKind::Rescan, epoch)
}
fn config() -> DebounceConfig {
DebounceConfig::new()
.with_quiet_window(Duration::from_millis(10))
.with_max_hold(Duration::from_millis(100))
}
struct Clock {
origin: Instant,
}
impl Clock {
fn new() -> Self {
Self {
origin: Instant::now(),
}
}
fn at(&self, ms: u64) -> Instant {
self.origin + Duration::from_millis(ms)
}
}
fn drain(coalescer: &mut Coalescer<OsString, ()>, now: Instant) -> Vec<Ev> {
let mut out = Vec::new();
coalescer.drain_ready(now, &mut out);
out
}
#[test]
fn created_then_modified_stays_created() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(created(s, "/a/f", 1), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/a/f", 2), clk.at(1)).is_none());
assert!(
drain(&mut c, clk.at(5)).is_empty(),
"held during the window"
);
let out = drain(&mut c, clk.at(11));
assert_eq!(out.len(), 1, "the burst collapses to a single event");
assert!(
out[0].kind().is_created(),
"a created-then-modified stays Created"
);
assert_eq!(out[0].path(), PathBuf::from("/a/f"));
}
#[test]
fn modified_coalesces() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
for (n, epoch) in [1, 2, 3, 4].into_iter().enumerate() {
assert!(
c.admit(modified(s, "/a/f", epoch), clk.at(n as u64))
.is_none()
);
}
let out = drain(&mut c, clk.at(20));
assert_eq!(out.len(), 1, "four Modifieds coalesce to one");
assert!(out[0].kind().is_modified());
}
#[test]
fn created_then_removed_annihilates() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(created(s, "/a/tmp", 1), clk.at(0)).is_none());
assert!(c.admit(removed(s, "/a/tmp", 2), clk.at(1)).is_none());
assert!(
drain(&mut c, clk.at(50)).is_empty(),
"the transient annihilates"
);
assert_eq!(c.next_deadline(), None, "no entry lingers");
}
#[test]
fn modified_then_removed_is_removed() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/a/f", 1), clk.at(0)).is_none());
assert!(c.admit(removed(s, "/a/f", 2), clk.at(1)).is_none());
let out = drain(&mut c, clk.at(20));
assert_eq!(out.len(), 1);
assert!(
out[0].kind().is_removed(),
"modified-then-removed nets to Removed"
);
}
#[test]
fn removed_then_created_is_modified() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(removed(s, "/a/f", 1), clk.at(0)).is_none());
assert!(c.admit(created(s, "/a/f", 2), clk.at(1)).is_none());
let out = drain(&mut c, clk.at(20));
assert_eq!(out.len(), 1);
assert!(
out[0].kind().is_modified(),
"removed-then-created churn nets to a synthetic Modified"
);
assert_eq!(out[0].path(), PathBuf::from("/a/f"));
assert_eq!(
out[0].change_id(),
None,
"the synthesized Modified carries no change id"
);
}
#[test]
fn moved_is_atomic_and_flushes() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/a/src", 1), clk.at(0)).is_none());
assert!(c.admit(created(s, "/a/dst", 2), clk.at(1)).is_none());
assert!(
c.admit(moved(s, "/a/dst", "/a/src", 3), clk.at(2))
.is_none()
);
let out = drain(&mut c, clk.at(2));
assert_eq!(
out.len(),
3,
"both buffered endpoints flush plus the Moved emits"
);
let moved_events: Vec<_> = out.iter().filter(|e| is_moved(e)).collect();
assert_eq!(moved_events.len(), 1, "the Moved emits exactly once, whole");
let m = moved_events[0];
assert_eq!(m.path(), PathBuf::from("/a/dst"), "the rename destination");
assert_eq!(
move_from_path(m),
PathBuf::from("/a/src"),
"the rename source is intact — the Moved was not split"
);
assert_eq!(
c.next_deadline(),
None,
"nothing lingers after the atomic flush"
);
}
#[test]
fn moved_emits_undelayed_not_after_a_settle_window() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config())); let s = sub(1);
assert!(
c.admit(moved(s, "/a/dst", "/a/src", 1), clk.at(0))
.is_none()
);
assert_eq!(
c.next_deadline(),
Some(clk.at(0)),
"a Moved is due immediately (its ready instant), not at now + quiet_window"
);
let out = drain(&mut c, clk.at(0));
assert_eq!(out.len(), 1, "the undelayed Moved is due at once");
assert!(is_moved(&out[0]));
assert_eq!(c.next_deadline(), None, "nothing lingers");
}
#[test]
fn debounced_moved_flushes_subscription_buffer_preserving_epoch_order() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/a/other", 1), clk.at(0)).is_none());
assert!(
c.admit(moved(s, "/a/dst", "/a/src", 2), clk.at(1))
.is_none()
);
let out = drain(&mut c, clk.at(1));
assert_eq!(
out.len(),
2,
"the unrelated buffered entry is flushed alongside the immediate Moved"
);
assert!(
!is_moved(&out[0]),
"the flushed older-epoch buffered entry emits first"
);
assert_eq!(out[0].path(), PathBuf::from("/a/other"));
assert_eq!(out[0].epoch(), Epoch::new(1), "the older buffered epoch");
assert!(
is_moved(&out[1]),
"the immediate Moved emits after the flush"
);
assert_eq!(out[1].epoch(), Epoch::new(2), "the newer Moved epoch");
assert!(
out.windows(2).all(|w| w[0].epoch() <= w[1].epoch()),
"a debounced Moved never delivers an older buffered entry's epoch after itself"
);
assert_eq!(
c.next_deadline(),
None,
"the whole subscription was flushed"
);
}
#[test]
fn rescan_flushes_and_bypasses() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/a/one", 1), clk.at(0)).is_none());
assert!(c.admit(created(s, "/a/two", 2), clk.at(1)).is_none());
assert!(c.admit(rescan(s, "/a", 9), clk.at(2)).is_none());
let out = drain(&mut c, clk.at(2));
assert_eq!(
out.len(),
3,
"both buffered entries flush plus the Rescan emits"
);
let rescans: Vec<_> = out.iter().filter(|e| e.is_rescan()).collect();
assert_eq!(rescans.len(), 1, "exactly one Rescan");
assert_eq!(
rescans[0].epoch(),
Epoch::new(9),
"the Rescan's upstream umbrella epoch stamp is preserved unchanged"
);
let last = out.last().expect("non-empty");
assert!(
last.is_rescan(),
"the Rescan bypasses to the end of the flush"
);
for e in &out {
assert!(
e.epoch() <= Epoch::new(9),
"no flushed entry carries an epoch dominating the Rescan"
);
}
assert_eq!(
c.next_deadline(),
None,
"the Rescan drained everything for the sub"
);
}
#[test]
fn rescan_only_flushes_its_own_subscription() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let (s1, s2) = (sub(1), sub(2));
assert!(c.admit(modified(s1, "/a/f", 1), clk.at(0)).is_none());
assert!(c.admit(modified(s2, "/b/f", 1), clk.at(0)).is_none());
assert!(c.admit(rescan(s1, "/a", 5), clk.at(1)).is_none());
let out = drain(&mut c, clk.at(1));
assert_eq!(out.len(), 2, "s1's flushed burst plus its Rescan");
assert!(
out.iter().all(|e| e.subscription() == s1),
"only s1 is touched"
);
let out2 = drain(&mut c, clk.at(20));
assert_eq!(
out2.len(),
1,
"s2's burst is untouched and settles normally"
);
assert_eq!(out2[0].subscription(), s2);
}
#[test]
fn a_non_lifecycle_kind_flushes_and_emits_never_coalesced() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/a/f", 1), clk.at(0)).is_none());
assert!(
drain(&mut c, clk.at(0)).is_empty(),
"a lifecycle kind is buffered (enters coalesce), not immediately emitted"
);
assert!(
c.admit(moved(s, "/a/dst", "/a/src", 2), clk.at(1))
.is_none()
);
let out = drain(&mut c, clk.at(1));
assert_eq!(
out.len(),
2,
"the buffered lifecycle entry and the non-lifecycle kind BOTH emit — neither coalesced away"
);
assert!(
out[0].kind().is_modified() && !is_moved(&out[0]),
"the buffered lifecycle Modified is flushed FIRST (older-epoch, ahead of the immediate emit)"
);
assert!(
is_moved(&out[1]),
"the non-lifecycle kind emits immediately AFTER the flushed entry"
);
assert!(
out[0].epoch() < out[1].epoch(),
"epochs stay monotone: the flushed buffered entry precedes the immediate emit (design §8)"
);
assert!(
c.next_deadline().is_none(),
"nothing lingers buffered — the non-lifecycle kind was not held for a settle window"
);
}
#[test]
fn max_hold_forces_emission() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config())); let s = sub(1);
let mut t = 0;
while t <= 130 {
assert!(c.admit(modified(s, "/a/f", t / 5 + 1), clk.at(t)).is_none());
if t < 100 {
assert!(
drain(&mut c, clk.at(t)).is_empty(),
"still held before the max_hold cap at t={t}"
);
}
t += 5;
}
let out = drain(&mut c, clk.at(100));
assert_eq!(
out.len(),
1,
"the bounded hold forces one emission at the cap"
);
assert!(out[0].kind().is_modified());
}
#[test]
fn coalesced_pair_emits_with_the_newest_stamp() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(created(s, "/a/f", 2), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/a/f", 3), clk.at(1)).is_none());
assert!(c.admit(modified(s, "/a/f", 4), clk.at(2)).is_none());
let out = drain(&mut c, clk.at(20));
assert_eq!(out.len(), 1);
assert_eq!(
out[0].epoch(),
Epoch::new(4),
"the coalesced event keeps the newest observation's umbrella stamp"
);
assert!(
out[0].kind().is_created(),
"…while still reporting the collapsed kind"
);
}
#[test]
fn become_modified_keeps_the_newest_stamp() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(removed(s, "/a/f", 5), clk.at(0)).is_none());
assert!(c.admit(created(s, "/a/f", 7), clk.at(1)).is_none());
let out = drain(&mut c, clk.at(20));
assert_eq!(out.len(), 1);
assert!(out[0].kind().is_modified());
assert_eq!(
out[0].epoch(),
Epoch::new(7),
"the synthetic Modified carries the newest stamp"
);
}
#[test]
fn post_rescan_emission_never_carries_a_dominated_epoch() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(rescan(s, "/a", 10), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/a/f", 11), clk.at(1)).is_none());
assert!(c.admit(modified(s, "/a/f", 12), clk.at(2)).is_none());
let rescan_out = drain(&mut c, clk.at(2));
assert_eq!(rescan_out.len(), 1, "the Rescan emits undelayed");
assert_eq!(rescan_out[0].epoch(), Epoch::new(10));
let burst_out = drain(&mut c, clk.at(20));
assert_eq!(burst_out.len(), 1, "the post-Rescan burst settles");
assert!(
burst_out[0].epoch() >= Epoch::new(10),
"the post-Rescan emission is NOT dominated by the Rescan"
);
assert_eq!(
burst_out[0].epoch(),
Epoch::new(12),
"…and carries the newest stamp"
);
}
#[test]
fn next_deadline_is_the_earliest_pending() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert_eq!(c.next_deadline(), None, "empty: no deadline");
assert!(c.admit(modified(s, "/a/f", 1), clk.at(0)).is_none());
assert_eq!(
c.next_deadline(),
Some(clk.at(10)),
"one buffered entry: due at now + quiet_window"
);
assert!(c.admit(rescan(s, "/b", 3), clk.at(1)).is_none());
assert_eq!(
c.next_deadline(),
Some(clk.at(1)),
"a ready item pulls the deadline to its (earlier) ready instant"
);
}
#[test]
fn flush_all_drains_everything_for_stream_close() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/a/f", 1), clk.at(0)).is_none());
assert!(c.admit(created(s, "/b/g", 2), clk.at(0)).is_none());
let mut out = Vec::new();
c.flush_all(&mut out);
assert_eq!(
out.len(),
2,
"every still-settling entry is force-emitted on close"
);
assert_eq!(c.next_deadline(), None, "the coalescer is left empty");
}
#[test]
fn drop_subscription_discards_only_that_subscriptions_entries() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let (s1, s2) = (sub(1), sub(2));
assert!(c.admit(modified(s1, "/a/f", 1), clk.at(0)).is_none());
assert!(c.admit(rescan(s1, "/a", 2), clk.at(0)).is_none());
assert!(c.admit(modified(s1, "/a/h", 3), clk.at(0)).is_none());
assert!(c.admit(modified(s2, "/b/f", 4), clk.at(0)).is_none());
assert!(
c.next_deadline().is_some(),
"entries are pending before the drop"
);
c.drop_subscription(s1);
let out = drain(&mut c, clk.at(1000));
assert_eq!(out.len(), 1, "only s2's entry survives the drop of s1");
assert_eq!(
out[0].subscription(),
s2,
"the survivor belongs to the un-dropped subscription"
);
assert_eq!(out[0].path(), Path::new("/b/f"));
assert_eq!(
c.next_deadline(),
None,
"no s1 entry lingers in the buffer or ready queue after the drop"
);
}
#[test]
fn off_override_passes_through_while_inherit_sibling_settles() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config())); let (raw, settled) = (sub(1), sub(2));
c.set_policy(raw, Debounce::Off);
assert!(c.admit(modified(settled, "/s/f", 1), clk.at(0)).is_none());
assert!(c.admit(modified(raw, "/r/a", 1), clk.at(0)).is_none());
assert!(c.admit(modified(raw, "/r/a", 2), clk.at(1)).is_none());
assert!(c.admit(created(raw, "/r/b", 3), clk.at(1)).is_none());
assert_eq!(
c.next_deadline(),
Some(clk.at(0)),
"a pass-through event is ready the instant it is admitted"
);
let out = drain(&mut c, clk.at(1));
assert_eq!(out.len(), 3, "every raw event emits — none collapsed");
assert!(
out.iter().all(|e| e.subscription() == raw),
"only the Off subscription's events ride through"
);
assert_eq!(
(out[0].epoch(), out[1].epoch(), out[2].epoch()),
(Epoch::new(1), Epoch::new(2), Epoch::new(3)),
"pass-through preserves per-subscription admission (= epoch) order"
);
assert!(
drain(&mut c, clk.at(5)).is_empty(),
"the settling sibling is still held"
);
let out = drain(&mut c, clk.at(11));
assert_eq!(out.len(), 1, "the sibling's burst settles normally");
assert_eq!(out[0].subscription(), settled);
}
#[test]
fn custom_override_settles_under_its_own_windows() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config())); let (custom, inherit) = (sub(1), sub(2));
c.set_policy(
custom,
Debounce::Custom(config().with_quiet_window(Duration::from_millis(40))),
);
assert!(c.admit(modified(custom, "/c/f", 1), clk.at(0)).is_none());
assert!(c.admit(modified(inherit, "/i/f", 1), clk.at(0)).is_none());
let out = drain(&mut c, clk.at(11));
assert_eq!(out.len(), 1, "only the inheriting entry is due at 10ms");
assert_eq!(out[0].subscription(), inherit);
assert!(
drain(&mut c, clk.at(39)).is_empty(),
"the custom entry still settles under its longer window"
);
let out = drain(&mut c, clk.at(41));
assert_eq!(out.len(), 1, "the custom entry emits at its own deadline");
assert_eq!(out[0].subscription(), custom);
}
#[test]
fn custom_override_enables_settling_when_global_is_off() {
let clk = Clock::new();
let mut c = Coalescer::new(None);
let (custom, inherit) = (sub(1), sub(2));
c.set_policy(custom, Debounce::Custom(config()));
assert!(c.admit(modified(custom, "/c/f", 1), clk.at(0)).is_none());
assert!(c.admit(modified(custom, "/c/f", 2), clk.at(1)).is_none());
assert!(c.admit(modified(inherit, "/i/f", 1), clk.at(1)).is_none());
let out = drain(&mut c, clk.at(1));
assert_eq!(out.len(), 1, "inherit-of-nothing rides through undelayed");
assert_eq!(out[0].subscription(), inherit);
let out = drain(&mut c, clk.at(20));
assert_eq!(out.len(), 1, "the custom burst settled to one emission");
assert_eq!(out[0].subscription(), custom);
assert_eq!(out[0].epoch(), Epoch::new(2), "carrying the newest stamp");
}
#[test]
fn set_policy_inherit_removes_the_override() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
c.set_policy(s, Debounce::Off);
assert!(c.admit(modified(s, "/a/f", 1), clk.at(0)).is_none());
assert_eq!(
drain(&mut c, clk.at(0)).len(),
1,
"the Off override passes through"
);
c.set_policy(s, Debounce::Inherit);
assert!(!c.has_policy(s), "Inherit removes the override entry");
assert!(c.admit(modified(s, "/a/g", 2), clk.at(1)).is_none());
assert!(
drain(&mut c, clk.at(1)).is_empty(),
"back under the global default: the event settles"
);
assert_eq!(drain(&mut c, clk.at(20)).len(), 1);
}
#[test]
fn per_sub_cap_sheds_and_counter_zeroes_after_the_purge() {
let clk = Clock::new();
let mut c = Coalescer::new(None); let s = sub(1);
c.set_policy(s, Debounce::Custom(config().with_max_buffered(2)));
assert!(c.admit(modified(s, "/k0", 1), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/k1", 2), clk.at(0)).is_none());
assert_eq!(
c.per_sub_len.get(&s).copied(),
Some(2),
"two fresh entries counted"
);
assert_eq!(
c.admit(modified(s, "/k2", 3), clk.at(0)),
Some(s),
"the third fresh entry overflows the per-sub cap and sheds the subscription"
);
c.drop_subscription(s);
assert!(
!c.per_sub_len.contains_key(&s),
"the purge zeroes the fresh-entry counter"
);
assert!(c.buffer.is_empty(), "…and frees the buffered entries");
assert!(c.admit(modified(s, "/k3", 4), clk.at(1)).is_none());
assert!(c.admit(modified(s, "/k4", 5), clk.at(1)).is_none());
assert_eq!(c.admit(modified(s, "/k5", 6), clk.at(1)), Some(s));
}
#[test]
fn per_sub_cap_exempts_collapses() {
let clk = Clock::new();
let mut c = Coalescer::new(None);
let s = sub(1);
c.set_policy(s, Debounce::Custom(config().with_max_buffered(2)));
assert!(c.admit(modified(s, "/k0", 1), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/k1", 2), clk.at(0)).is_none());
assert!(
c.admit(modified(s, "/k0", 3), clk.at(0)).is_none(),
"a collapse onto a buffered entry is admitted at the cap"
);
assert_eq!(
c.per_sub_len.get(&s).copied(),
Some(2),
"a collapse never grows the fresh-entry count"
);
}
#[test]
fn per_sub_counter_tracks_every_removal_path() {
let clk = Clock::new();
let mut c = Coalescer::new(None);
let s = sub(1);
c.set_policy(s, Debounce::Custom(config().with_max_buffered(2)));
assert!(c.admit(created(s, "/a", 1), clk.at(0)).is_none());
assert!(c.admit(removed(s, "/a", 2), clk.at(0)).is_none());
assert!(
!c.per_sub_len.contains_key(&s),
"the annihilated transient freed its counted slot"
);
assert!(c.admit(modified(s, "/b", 3), clk.at(0)).is_none());
assert_eq!(c.per_sub_len.get(&s).copied(), Some(1));
assert_eq!(drain(&mut c, clk.at(20)).len(), 1);
assert!(
!c.per_sub_len.contains_key(&s),
"the drained entry decremented its count"
);
assert!(c.admit(modified(s, "/c", 4), clk.at(21)).is_none());
assert!(c.admit(modified(s, "/d", 5), clk.at(21)).is_none());
assert!(c.admit(rescan(s, "/", 6), clk.at(21)).is_none());
assert!(
!c.per_sub_len.contains_key(&s),
"the Rescan flush zeroed the count"
);
assert_eq!(drain(&mut c, clk.at(21)).len(), 3);
assert!(c.admit(modified(s, "/e", 7), clk.at(22)).is_none());
let mut out = Vec::new();
c.flush_all(&mut out);
assert_eq!(out.len(), 1);
assert!(
c.per_sub_len.is_empty(),
"the teardown flush cleared the counter map"
);
}
#[test]
fn forget_clears_the_policy_drop_retains_it() {
let clk = Clock::new();
let mut c = Coalescer::new(None);
let s = sub(1);
c.set_policy(s, Debounce::Custom(config()));
assert!(c.admit(modified(s, "/a/f", 1), clk.at(0)).is_none());
c.drop_subscription(s);
assert!(
c.has_policy(s),
"drop_subscription keeps the policy — the subscription is still live"
);
assert!(c.admit(modified(s, "/a/g", 2), clk.at(1)).is_none());
assert!(
drain(&mut c, clk.at(1)).is_empty(),
"the retained policy still buffers"
);
assert_eq!(drain(&mut c, clk.at(20)).len(), 1);
c.forget_subscription(s);
assert!(!c.has_policy(s), "forget_subscription retires the policy");
assert!(c.admit(modified(s, "/a/h", 3), clk.at(21)).is_none());
assert_eq!(
drain(&mut c, clk.at(21)).len(),
1,
"without the policy the subscription inherits the disabled default"
);
}
#[test]
fn structural_cap_defaults_when_override_only() {
let clk = Clock::new();
let mut c = Coalescer::new(None);
let s = sub(1);
c.set_policy(s, Debounce::Custom(config().with_max_buffered(usize::MAX)));
for i in 0..DebounceConfig::DEFAULT_MAX_BUFFERED {
assert!(
c.admit(modified(s, &format!("/k{i}"), i as u64 + 1), clk.at(0))
.is_none(),
"admission {i} sits under the structural bound"
);
}
assert_eq!(
c.admit(modified(s, "/overflow", u64::MAX), clk.at(0)),
Some(s),
"the coalescer-wide structural bound sheds past DEFAULT_MAX_BUFFERED"
);
assert_eq!(c.buffer.len(), DebounceConfig::DEFAULT_MAX_BUFFERED);
}
#[test]
fn drain_ready_emits_buffered_in_epoch_order_not_path_order() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/z", 1), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/a", 2), clk.at(1)).is_none());
let out = drain(&mut c, clk.at(20));
assert_eq!(
out.len(),
2,
"both distinct paths emit (no cross-path collapse)"
);
assert_eq!(
out[0].path(),
PathBuf::from("/z"),
"the earlier-admitted lower-epoch path emits first — NOT the lexically-first /a"
);
assert_eq!(out[0].epoch(), Epoch::new(1));
assert_eq!(
out[1].path(),
PathBuf::from("/a"),
"the later-admitted higher-epoch path emits second"
);
assert_eq!(out[1].epoch(), Epoch::new(2));
assert!(
out.windows(2).all(|w| w[0].epoch() <= w[1].epoch()),
"a subscription's buffered epochs never emit backwards"
);
}
#[test]
fn flush_all_emits_buffered_in_epoch_order_not_path_order() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/z", 1), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/a", 2), clk.at(1)).is_none());
let mut out = Vec::new();
c.flush_all(&mut out);
assert_eq!(out.len(), 2);
assert_eq!(
out[0].path(),
PathBuf::from("/z"),
"lower-epoch tail entry first"
);
assert_eq!(out[0].epoch(), Epoch::new(1));
assert_eq!(
out[1].path(),
PathBuf::from("/a"),
"higher-epoch tail entry second"
);
assert_eq!(out[1].epoch(), Epoch::new(2));
assert!(
out.windows(2).all(|w| w[0].epoch() <= w[1].epoch()),
"the teardown flush never delivers a subscription's epochs out of order"
);
}
#[test]
fn rescan_flush_emits_buffered_in_epoch_order_not_path_order() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/z", 1), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/a", 2), clk.at(1)).is_none());
assert!(c.admit(rescan(s, "/root", 3), clk.at(2)).is_none());
let out = drain(&mut c, clk.at(2));
assert_eq!(out.len(), 3, "both flushed entries plus the Rescan");
assert_eq!(
out[0].path(),
PathBuf::from("/z"),
"lower-epoch buffered entry flushed first"
);
assert_eq!(out[0].epoch(), Epoch::new(1));
assert_eq!(
out[1].path(),
PathBuf::from("/a"),
"higher-epoch buffered entry flushed second"
);
assert_eq!(out[1].epoch(), Epoch::new(2));
assert!(
out[2].is_rescan(),
"the Rescan bypasses to the end of the flush"
);
assert_eq!(out[2].epoch(), Epoch::new(3));
assert!(
out.windows(2).all(|w| w[0].epoch() <= w[1].epoch()),
"flushed epochs stay monotone: 1, 2, then the Rescan's 3"
);
}
#[test]
fn moved_flush_emits_buffered_in_epoch_order_not_path_order() {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
assert!(c.admit(modified(s, "/z", 1), clk.at(0)).is_none());
assert!(c.admit(modified(s, "/a", 2), clk.at(1)).is_none());
assert!(c.admit(moved(s, "/dst", "/src", 3), clk.at(2)).is_none());
let out = drain(&mut c, clk.at(2));
assert_eq!(out.len(), 3, "both flushed entries plus the Moved");
assert_eq!(
out[0].path(),
PathBuf::from("/z"),
"lower-epoch buffered entry flushed first"
);
assert_eq!(out[0].epoch(), Epoch::new(1));
assert_eq!(
out[1].path(),
PathBuf::from("/a"),
"higher-epoch buffered entry flushed second"
);
assert_eq!(out[1].epoch(), Epoch::new(2));
assert!(is_moved(&out[2]), "the Moved emits whole after the flush");
assert_eq!(out[2].epoch(), Epoch::new(3));
assert!(
out.windows(2).all(|w| w[0].epoch() <= w[1].epoch()),
"flushed epochs stay monotone: 1, 2, then the Moved's 3"
);
}
mod proptests {
use super::*;
use proptest::prelude::*;
#[derive(Debug, Clone)]
struct Step {
kind: u8,
path: u8,
epoch_delta: u16,
time_delta: u16,
}
fn step_strategy() -> impl Strategy<Value = Step> {
(0u8..5, 0u8..4, 0u16..3, 0u16..30).prop_map(|(kind, path, epoch_delta, time_delta)| Step {
kind,
path,
epoch_delta,
time_delta,
})
}
fn event_for(s: Subscription, step: &Step, epoch: u64) -> Ev {
let path = format!("/root/p{}", step.path);
match step.kind {
0 => created(s, &path, epoch),
1 => modified(s, &path, epoch),
2 => removed(s, &path, epoch),
3 => moved(s, &path, "/root/src", epoch),
_ => rescan(s, &path, epoch),
}
}
const CASES: u32 = if cfg!(miri) { 4 } else { 200 };
proptest! {
#![proptest_config(ProptestConfig { cases: CASES, failure_persistence: None, ..ProptestConfig::default() })]
#[test]
fn no_admitted_event_is_silently_lost(steps in prop::collection::vec(step_strategy(), 1..40)) {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
let mut epoch = 0u64;
let mut admitted = 0usize;
let mut emitted = Vec::new();
let mut t = 0u64;
for step in &steps {
epoch += u64::from(step.epoch_delta); t += u64::from(step.time_delta);
assert!(c.admit(event_for(s, step, epoch), clk.at(t)).is_none());
admitted += 1;
c.drain_ready(clk.at(t), &mut emitted);
}
c.flush_all(&mut emitted);
for e in &emitted {
prop_assert_eq!(e.subscription(), s);
}
let admitted_atomic = steps.iter().filter(|st| st.kind >= 3).count();
let emitted_atomic = emitted.iter().filter(|e| is_moved(e) || e.is_rescan()).count();
prop_assert_eq!(
emitted_atomic,
admitted_atomic,
"every Moved/Rescan is emitted whole, none coalesced or dropped"
);
prop_assert_eq!(c.next_deadline(), None);
let _ = admitted;
}
#[test]
fn determinism(steps in prop::collection::vec(step_strategy(), 1..40)) {
fn run(steps: &[Step]) -> Vec<(PathBuf, &'static str, Epoch)> {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
let mut epoch = 0u64;
let mut t = 0u64;
let mut out = Vec::new();
for step in steps {
epoch += u64::from(step.epoch_delta);
t += u64::from(step.time_delta);
assert!(c.admit(event_for(s, step, epoch), clk.at(t)).is_none());
c.drain_ready(clk.at(t), &mut out);
}
c.flush_all(&mut out);
out
.into_iter()
.map(|e| (e.path().to_path_buf(), e.kind().as_str(), e.epoch()))
.collect()
}
prop_assert_eq!(run(&steps), run(&steps));
}
#[test]
fn no_post_immediate_dominated_epoch(steps in prop::collection::vec(step_strategy(), 1..40)) {
let clk = Clock::new();
let mut c = Coalescer::new(Some(config()));
let s = sub(1);
let mut epoch = 0u64;
let mut t = 0u64;
let mut emitted = Vec::new();
for step in &steps {
epoch += u64::from(step.epoch_delta);
t += u64::from(step.time_delta);
assert!(c.admit(event_for(s, step, epoch), clk.at(t)).is_none());
c.drain_ready(clk.at(t), &mut emitted);
}
c.flush_all(&mut emitted);
let mut immediate_hw: Option<Epoch> = None;
for e in &emitted {
if let Some(r) = immediate_hw {
prop_assert!(
e.epoch() >= r,
"an emission after an immediate one is dominated by it: {:?} < {:?}",
e.epoch(),
r
);
}
if e.is_rescan() || is_moved(e) {
immediate_hw = Some(immediate_hw.map_or(e.epoch(), |r| r.max(e.epoch())));
}
}
}
}
}
#[cfg(feature = "tokio")]
mod tokio_timer {
use super::*;
use agnostic_lite::{LocalRuntimeLite, RuntimeLite};
type Rt = agnostic_lite::tokio::TokioRuntime;
#[tokio::test(start_paused = true)]
async fn burst_coalesces_and_rescan_jumps_the_queue() {
let cfg = config(); let mut c = Coalescer::new(Some(cfg));
let s = sub(1);
let start = Rt::now();
for epoch in 1..=3 {
assert!(c.admit(modified(s, "/a/f", epoch), start.into()).is_none());
}
let mut out = Vec::new();
c.drain_ready(Rt::now().into(), &mut out);
assert!(out.is_empty(), "the burst is still settling");
assert!(c.admit(rescan(s, "/a", 9), Rt::now().into()).is_none());
let deadline = c.next_deadline().expect("the ready Rescan sets a deadline");
Rt::sleep_until(deadline.into()).await;
c.drain_ready(Rt::now().into(), &mut out);
assert!(
Rt::now().duration_since(start) < cfg.quiet_window(),
"the Rescan jumped the queue: drained before the burst's settle window elapsed"
);
assert_eq!(out.len(), 2, "the coalesced burst plus the Rescan");
assert!(out[0].kind().is_modified(), "the flushed, coalesced burst");
assert_eq!(out[0].epoch(), Epoch::new(3), "…carrying the newest stamp");
assert!(
out[1].is_rescan(),
"the Rescan, jumped ahead of the burst's own deadline"
);
assert_eq!(
out[1].epoch(),
Epoch::new(9),
"its umbrella stamp preserved"
);
assert_eq!(c.next_deadline(), None, "everything drained");
}
}
#[test]
fn buffered_entry_cap_bounds_high_cardinality_bursts() {
let now = Instant::now();
let mut coalescer = Coalescer::new(Some(
crate::options::DebounceConfig::new().with_max_buffered(64),
));
let s = sub(1);
let mut overflows = 0usize;
for i in 0..10_000u32 {
let outcome = coalescer.admit(created(s, &format!("/k{i}"), u64::from(i) + 1), now);
assert!(
coalescer.buffer.len() <= 64,
"the buffer NEVER exceeds the cap (got {} at admission {i})",
coalescer.buffer.len()
);
if let Some(overflowed) = outcome {
assert_eq!(overflowed, s, "the shed names the admitting subscription");
overflows += 1;
}
}
assert_eq!(
overflows,
10_000 - 64,
"every admission past the cap signalled the shed — none was silently dropped"
);
assert!(
coalescer.admit(modified(s, "/k0", 20_000), now).is_none(),
"a collapse onto an existing entry is exempt at the cap"
);
assert_eq!(coalescer.buffer.len(), 64, "still exactly at the cap");
}