use super::*;
#[test]
fn stage2_disclosure_scope_has_no_deadline_or_sticky_read_failure() {
let root = tempfile::tempdir().unwrap();
let _scope = enter_disclosure_if_absent();
assert!(current().is_none());
assert!(request_deadline(None).is_none());
let id = capture().unwrap().id;
{
let _nested = enter_disclosure_if_absent();
assert_eq!(capture().unwrap().id, id);
}
let _error = failure(&root.path().join("absent"), "read_blocked", "test failure");
assert!(prior_failure().is_none());
let context = capture();
rayon::join(
|| {
with_budget(context.clone(), || {
note_large_read_skip(&root.path().join("large.txt"))
})
},
|| {},
);
let response = with_skip_disclosure(|| {
finish_response(Response::success(
"native",
serde_json::json!({"complete":true}),
))
});
assert!(response.success);
assert_eq!(response.data["complete"], false);
assert_eq!(response.data["skipped_files"].as_array().unwrap().len(), 1);
}
#[test]
fn stage2_skip_disclosure_is_sorted_bounded_deduplicated_and_non_failing() {
let root = tempfile::tempdir().unwrap();
let readable = root.path().join("readable.txt");
std::fs::write(&readable, b"still readable").unwrap();
let response = with_budget(Some(Budget::after(Duration::from_secs(30))), || {
for at in (0..23).rev() {
let path = root.path().join(format!("large-{at:02}.txt"));
note_large_read_skip(&path);
note_large_read_skip(&path);
}
assert_eq!(read(&readable, None).unwrap(), b"still readable");
with_skip_disclosure(|| {
finish_response(Response::success(
"skips",
serde_json::json!({"complete":true,"text":"results"}),
))
})
});
assert!(response.success);
assert_eq!(response.data["complete"], false);
let skips = response.data["skipped_files"].as_array().unwrap();
assert_eq!(skips.len(), 20);
assert!(skips[0]["file"].as_str().unwrap().ends_with("large-00.txt"));
assert!(skips[19]["file"]
.as_str()
.unwrap()
.ends_with("large-19.txt"));
assert_eq!(response.data["skipped_files_remaining"], 3);
assert!(response.data["text"]
.as_str()
.unwrap()
.contains("shown 20 of 23 files (cap) ยท narrow: path"));
}
use std::sync::mpsc::{channel, Receiver, Sender};
struct HelperGate {
reached: Sender<()>,
release: Receiver<()>,
finished: Sender<()>,
}
static HELPER_GATES: LazyLock<Mutex<HashMap<PathBuf, HelperGate>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
static RUNNING_GATES: LazyLock<Mutex<HashMap<PathBuf, HelperGate>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
#[cfg(unix)]
pub struct HelperStall {
path: PathBuf,
gates: &'static Mutex<HashMap<PathBuf, HelperGate>>,
pub reached: Receiver<()>,
release: Sender<()>,
finished: Receiver<()>,
}
#[cfg(unix)]
impl Drop for HelperStall {
fn drop(&mut self) {
self.gates.lock().unwrap().remove(&self.path);
if self.release.send(()).is_ok() {
let _ = self.finished.recv_timeout(IO_BUDGET);
}
}
}
#[cfg(unix)]
pub fn stall_helper(path: &Path) -> HelperStall {
stall_helper_at(path, &HELPER_GATES)
}
#[cfg(unix)]
pub fn stall_running_helper(path: &Path) -> HelperStall {
stall_helper_at(path, &RUNNING_GATES)
}
#[cfg(unix)]
fn stall_helper_at(
path: &Path,
gates: &'static Mutex<HashMap<PathBuf, HelperGate>>,
) -> HelperStall {
let (reached, reached_rx) = channel();
let (release, release_rx) = channel();
let (finished, finished_rx) = channel();
gates.lock().unwrap().insert(
path.to_path_buf(),
HelperGate {
reached,
release: release_rx,
finished,
},
);
HelperStall {
path: path.to_path_buf(),
gates,
reached: reached_rx,
release,
finished: finished_rx,
}
}
static BLOCKED_DIRECTORIES: LazyLock<Mutex<HashMap<PathBuf, Arc<AtomicUsize>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
pub(super) fn before_helper(path: &Path) {
wait_at_gate(path, &HELPER_GATES);
}
pub(super) fn after_helper_start(path: &Path) {
wait_at_gate(path, &RUNNING_GATES);
}
fn wait_at_gate(path: &Path, gates: &Mutex<HashMap<PathBuf, HelperGate>>) {
let gate = gates.lock().unwrap().remove(path);
if let Some(gate) = gate {
let _ = gate.reached.send(());
let _ = gate.release.recv();
let _ = gate.finished.send(());
}
}
pub(super) fn before_directory_probe(path: &Path) -> io::Result<()> {
wait_at_gate(path, &RUNNING_GATES);
if let Some(fired) = BLOCKED_DIRECTORIES.lock().unwrap().get(path) {
fired.fetch_add(1, Ordering::Relaxed);
return Err(failure(
path,
"read_blocked",
"injected stalled directory enumeration",
));
}
Ok(())
}
#[cfg(unix)]
#[test]
fn walk_filter_stall_names_directory_being_read() {
let dir = tempfile::tempdir().unwrap();
let child = dir.path().join("child");
std::fs::create_dir(&child).unwrap();
let stall = stall_running_helper(&child);
let budget =
Budget::after(Duration::from_secs(5)).with_access_budget(Duration::from_millis(200));
let child_in_walk = child.clone();
let error = with_budget(Some(budget), || {
run(dir.path(), None, move |_| {
probe_directory(&child_in_walk, None)
})
})
.unwrap_err();
stall.reached.recv_timeout(Duration::from_secs(1)).unwrap();
assert!(
error
.to_string()
.contains(&format!("read_blocked: {}:", child.display())),
"{error}"
);
}
pub struct BlockDirectory(PathBuf, pub Arc<AtomicUsize>);
impl BlockDirectory {
pub fn new(path: &Path) -> Self {
let fired = Arc::new(AtomicUsize::new(0));
BLOCKED_DIRECTORIES
.lock()
.unwrap()
.insert(path.to_path_buf(), Arc::clone(&fired));
Self(path.to_path_buf(), fired)
}
}
impl Drop for BlockDirectory {
fn drop(&mut self) {
BLOCKED_DIRECTORIES.lock().unwrap().remove(&self.0);
}
}
#[cfg(unix)]
#[test]
fn walk_read_block_and_time_budget_report_both_gaps() {
let dir = tempfile::tempdir().unwrap();
let keep = dir.path().join("keep.rs");
let child = dir.path().join("child");
std::fs::write(&keep, "fn keep() {}\n").unwrap();
std::fs::create_dir(&child).unwrap();
let blocked = BlockDirectory::new(&child);
let after_error = dir.path().join("after-directory-error");
let stall = stall_running_helper(&after_error);
let kept = keep.clone();
let blocked_child = child.clone();
let budget = Budget::after(Duration::from_secs(5)).with_access_budget(Duration::from_secs(2));
let response = with_budget(Some(budget), || {
let (files, completion) = run_walk(
dir.path(),
Some(Instant::now() + Duration::from_millis(300)),
Vec::<PathBuf>::new(),
move |_, progress| {
progress.update(|files| files.push(kept.clone()));
let error = probe_directory(&blocked_child, None).unwrap_err();
assert!(error.to_string().contains("read_blocked"));
after_helper_start(&after_error);
Ok(vec![kept])
},
);
assert!(completion.incomplete);
assert!(completion.time_limit);
finish_response(Response::success(
"walk-both-gaps",
serde_json::json!({
"complete": true, "files": files,
}),
))
});
stall.reached.recv_timeout(Duration::from_secs(1)).unwrap();
assert_eq!(blocked.1.load(Ordering::Relaxed), 1);
assert!(response.success, "{:?}", response.data);
assert_eq!(response.data["complete"], false);
assert_eq!(response.data["files"], serde_json::json!([keep]));
let gaps = response.data["gaps"].as_array().unwrap();
assert_eq!(gaps.len(), 2);
assert_eq!(
gaps[0],
"Directory walk reached its time budget; only examined entries are reported."
);
let named_gap = format!("read_blocked: {}:", child.display());
assert!(gaps[1].as_str().unwrap().starts_with(&named_gap));
let text = response.data["text"].as_str().unwrap();
assert!(text.lines().any(|line| line
== "Directory walk reached its time budget; only examined entries are reported."));
assert!(text.contains(&named_gap));
}
#[test]
fn walk_directory_probes_reuse_the_owned_helper() {
let dir = tempfile::tempdir().unwrap();
let child = dir.path().join("child");
std::fs::create_dir(&child).unwrap();
let budget =
Budget::after(Duration::from_secs(5)).with_access_budget(Duration::from_millis(200));
with_budget(Some(budget.clone()), || {
let (_, completion) = run_walk(dir.path(), None, 0usize, move |_, progress| {
probe_directory(&child, None)?;
progress.update(|count| *count += 1);
Ok(1)
});
assert!(!completion.incomplete);
});
assert_eq!(
budget.measurements().0,
1,
"a walk must not queue a nested helper"
);
}
#[test]
fn helper_health_does_not_start_an_unused_pool() {
let helpers = OnceLock::new();
let health = helper_health_from(&helpers);
assert_eq!(health["status"], "not_started");
assert_eq!(health["pool_size"], IO_POOL_SIZE);
assert_eq!(health["thread_cap"], MAX_IO_THREADS);
assert_eq!(health["live"], 0);
assert!(helpers.get().is_none(), "health started the helper factory");
}
#[test]
fn helper_health_does_not_wait_for_the_state_lock() {
let pool = Limiter::new(1);
let state = pool.state.lock().unwrap();
let reader = pool.clone();
let (tx, rx) = channel();
let thread = std::thread::spawn(move || tx.send(reader.health()).unwrap());
let health = rx.recv_timeout(Duration::from_secs(1));
drop(state);
thread.join().unwrap();
let health = health.expect("health waited for the helper state lock");
assert_eq!(health["status"], "unavailable");
assert_eq!(health["reason"], "state_busy");
assert!(
health.get("live").is_none(),
"unavailable counts are unknown"
);
assert_eq!(pool.health()["status"], "ready");
}
#[test]
fn metadata_and_canonicalize_do_not_enumerate_an_ancestor() {
let dir = tempfile::tempdir().unwrap();
let ancestor = std::fs::canonicalize(dir.path()).unwrap();
let root = ancestor.join("project");
std::fs::create_dir(&root).unwrap();
let blocked = BlockDirectory::new(&ancestor);
assert!(
with_budget(Some(Budget::after(IO_BUDGET)), || metadata(&root))
.unwrap()
.is_dir()
);
let resolved = with_budget(Some(Budget::after(IO_BUDGET)), || canonicalize(&root)).unwrap();
assert_eq!(resolved, std::fs::canonicalize(&root).unwrap());
assert_eq!(blocked.1.load(Ordering::Relaxed), 0);
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn sibling_metadata_reuses_traversal_without_granting_listing_access() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
assert!(local_filesystem(&root).unwrap());
let paths: Vec<_> = (0..8).map(|n| root.join(format!("file-{n}"))).collect();
for path in &paths {
std::fs::write(path, "sibling").unwrap();
}
let blocked = BlockDirectory::new(&root);
let budget = Budget::after(IO_BUDGET);
with_budget(Some(budget.clone()), || {
for path in &paths {
assert!(metadata(path).unwrap().is_file());
}
assert_eq!(budget.measurements(), (1, 1), "one cold stat helper");
assert_eq!(blocked.1.load(Ordering::Relaxed), 0);
let error = read(&paths[0], None).unwrap_err();
assert!(error.to_string().contains("read_blocked"), "{error}");
assert_eq!(blocked.1.load(Ordering::Relaxed), 1);
assert_eq!(
budget.measurements(),
(2, 2),
"reading still probes the parent"
);
});
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn canonicalize_warms_sibling_traversal_shared_only_within_the_request() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
assert!(local_filesystem(&root).unwrap());
let first = root.join("first");
let second = root.join("second");
std::fs::write(&first, "first").unwrap();
std::fs::write(&second, "second").unwrap();
let blocked = BlockDirectory::new(&root);
let budget = Budget::after(IO_BUDGET);
with_budget(Some(budget.clone()), || {
assert_eq!(canonicalize(&first).unwrap(), first);
assert_eq!(canonicalize(&second).unwrap(), second);
let worker_budget = budget.clone();
let worker_path = second.clone();
std::thread::spawn(move || {
with_budget(Some(worker_budget), || {
assert!(metadata(&worker_path).unwrap().is_file());
});
})
.join()
.unwrap();
assert_eq!(budget.measurements(), (1, 1));
});
assert!(!cached_traversal(&root), "no evidence outside the request");
let fresh_budget = Budget::after(IO_BUDGET);
with_budget(Some(fresh_budget.clone()), || {
assert!(metadata(&second).unwrap().is_file());
assert_eq!(
fresh_budget.measurements(),
(1, 1),
"a new request probes again"
);
});
assert_eq!(blocked.1.load(Ordering::Relaxed), 0);
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn directory_probed_on_another_thread_answers_child_metadata() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
assert!(local_filesystem(&root).unwrap());
let file = root.join("file");
std::fs::write(&file, "contents").unwrap();
let budget = Budget::after(IO_BUDGET);
let worker_budget = budget.clone();
let worker_root = root.clone();
std::thread::spawn(move || {
with_budget(Some(worker_budget), || {
probe_directory(&worker_root, None).unwrap();
});
})
.join()
.unwrap();
assert_eq!(budget.measurements(), (1, 1), "one directory probe");
with_budget(Some(budget.clone()), || {
assert!(metadata(&file).unwrap().is_file());
assert!(canonicalize(&root).is_ok());
assert!(probe_target(&root).is_ok());
});
assert_eq!(
budget.measurements(),
(1, 1),
"the request's finished directory probe must be reused on every thread"
);
let fresh_budget = Budget::after(IO_BUDGET);
with_budget(Some(fresh_budget.clone()), || {
assert!(metadata(&file).unwrap().is_file());
});
assert_eq!(fresh_budget.measurements(), (1, 1));
}
#[test]
fn failed_stats_do_not_warm_traversal() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("missing");
let budget = Budget::after(IO_BUDGET);
with_budget(Some(budget.clone()), || {
assert_eq!(metadata(&path).unwrap_err().kind(), io::ErrorKind::NotFound);
assert_eq!(
canonicalize(&path).unwrap_err().kind(),
io::ErrorKind::NotFound
);
assert!(!cached_traversal(dir.path()));
assert_eq!(budget.measurements(), (2, 2));
std::fs::write(&path, "now present").unwrap();
assert!(metadata(&path).unwrap().is_file());
assert_eq!(budget.measurements(), (3, 3));
});
}
#[test]
fn traversal_does_not_answer_an_explicit_directory_access_probe() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
let path = root.join("file");
std::fs::write(&path, "contents").unwrap();
let blocked = BlockDirectory::new(&root);
with_budget(Some(Budget::after(IO_BUDGET)), || {
assert!(metadata(&path).unwrap().is_file());
let error = probe_target(&root).unwrap_err();
assert!(error.to_string().contains("read_blocked"), "{error}");
assert_eq!(blocked.1.load(Ordering::Relaxed), 1);
});
}
#[test]
fn timed_out_traversal_does_not_publish_late_success() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
let path = root.join("file");
std::fs::write(&path, "contents").unwrap();
let budget = Budget::after(Duration::from_millis(250));
let caller_budget = budget.clone();
let (started_tx, started_rx) = channel();
let (release_tx, release_rx) = channel();
let (finished_tx, finished_rx) = channel();
struct Finished(Sender<()>);
impl Drop for Finished {
fn drop(&mut self) {
let _ = self.0.send(());
}
}
let caller = std::thread::spawn(move || {
with_budget(Some(caller_budget), || {
run_traversal(&path, move |path| {
let result = std::fs::metadata(path)?;
started_tx.send(()).unwrap();
let _ = release_rx.recv();
Ok((result, Finished(finished_tx)))
})
.err()
.unwrap()
})
});
let started = started_rx.recv_timeout(IO_BUDGET);
let error = caller.join().unwrap();
release_tx.send(()).unwrap();
finished_rx.recv_timeout(IO_BUDGET).unwrap();
started.expect("the stat must finish before holding its result past the deadline");
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
assert_eq!(timeout_code(&error), "read_blocked");
with_budget(Some(budget), || assert!(!cached_traversal(&root)));
}
#[cfg(unix)]
#[test]
fn traversal_keeps_symlink_stats_isolated() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
let file = root.join("file");
let link = root.join("link");
std::fs::write(&file, "contents").unwrap();
std::os::unix::fs::symlink(&file, &link).unwrap();
let budget = Budget::after(IO_BUDGET);
with_budget(Some(budget.clone()), || {
assert!(metadata(&file).unwrap().is_file());
assert!(metadata(&link).unwrap().is_file());
assert_eq!(canonicalize(&link).unwrap(), file);
assert_eq!(budget.measurements(), (3, 3));
});
}
#[test]
fn explicit_directory_probe_still_observes_blocked_access() {
let dir = tempfile::tempdir().unwrap();
let blocked = BlockDirectory::new(dir.path());
let error = with_budget(Some(Budget::after(IO_BUDGET)), || {
probe_directory(dir.path(), None)
})
.unwrap_err();
assert!(error.to_string().contains("read_blocked"));
assert_eq!(blocked.1.load(Ordering::Relaxed), 1);
}
#[test]
fn unscheduled_helper_is_queue_timeout_and_never_runs_late() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("unscheduled");
let (reached_tx, reached_rx) = channel();
let (release_tx, release_rx) = channel();
let (finished_tx, finished_rx) = channel();
HELPER_GATES.lock().unwrap().insert(
path.clone(),
HelperGate {
reached: reached_tx,
release: release_rx,
finished: finished_tx,
},
);
let fired = Arc::new(AtomicUsize::new(0));
let work_fired = Arc::clone(&fired);
let (dropped_tx, dropped_rx) = channel();
struct Dropped(Sender<()>);
impl Drop for Dropped {
fn drop(&mut self) {
let _ = self.0.send(());
}
}
let dropped = Dropped(dropped_tx);
let caller = std::thread::spawn(move || {
run_with_limiter(
&path,
Some(Instant::now() + Duration::from_millis(80)),
Limiter::new(1),
move |_| {
let _dropped = dropped;
work_fired.fetch_add(1, Ordering::Relaxed);
Ok(())
},
)
});
let reached = reached_rx.recv_timeout(IO_BUDGET);
let error = caller.join().unwrap().unwrap_err();
release_tx.send(()).unwrap();
finished_rx.recv_timeout(IO_BUDGET).unwrap();
dropped_rx.recv_timeout(IO_BUDGET).unwrap();
reached.expect("the helper must reach the scheduling gate");
assert!(
error.to_string().contains("read_io_queue_timeout"),
"{error}"
);
assert!(!error.to_string().contains("read_blocked"), "{error}");
assert_eq!(
fired.load(Ordering::Relaxed),
0,
"expired work must not start after release"
);
}
#[test]
fn saturated_limiter_is_queue_timeout_and_does_not_start_work() {
let limiter = Limiter::new(1);
let _permit = limiter.acquire(Instant::now() + IO_BUDGET).unwrap();
let fired = Arc::new(AtomicUsize::new(0));
let work_fired = Arc::clone(&fired);
let error = run_with_limiter(
Path::new("queued"),
Some(Instant::now() + Duration::from_millis(80)),
limiter,
move |_| {
work_fired.fetch_add(1, Ordering::Relaxed);
Ok(())
},
)
.unwrap_err();
assert!(
error.to_string().contains("read_io_queue_timeout"),
"{error}"
);
assert!(!error.to_string().contains("read_blocked"), "{error}");
assert_eq!(fired.load(Ordering::Relaxed), 0);
let cached_error = ProbeError::from(&error).error();
let response = access_error("queued", Path::new("queued"), cached_error);
assert_eq!(
response.data["code"], "read_io_queue_timeout",
"{response:?}"
);
}
#[cfg(unix)]
#[test]
fn queued_time_does_not_consume_running_access_budget() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("queued-then-healthy");
let gate = stall_helper(&path);
let (started_tx, started_rx) = channel();
let (release_tx, release_rx) = channel();
let (result_tx, result_rx) = channel();
let caller = std::thread::spawn(move || {
result_tx
.send(with_budget(
Some(Budget::after(Duration::from_secs(30))),
|| {
run_with_timeout(
&path,
None,
Limiter::new(1),
Duration::from_secs(6),
None,
move |_| {
started_tx.send(()).unwrap();
let _ = release_rx.recv();
Ok(42)
},
)
},
))
.unwrap();
});
gate.reached.recv_timeout(IO_BUDGET).unwrap();
assert!(result_rx.recv_timeout(Duration::from_secs(3)).is_err());
drop(gate);
let started = started_rx.recv_timeout(IO_BUDGET);
let early = result_rx.recv_timeout(Duration::from_secs(4));
let _ = release_tx.send(());
caller.join().unwrap();
let result = early.unwrap_or_else(|_| result_rx.recv_timeout(IO_BUDGET).unwrap());
assert!(
started.is_ok(),
"the filesystem operation must actually start: {started:?}; run_with_timeout returned {result:?}"
);
assert_eq!(
result.unwrap(),
42,
"queueing must not exhaust the access cap"
);
}
#[test]
fn running_access_keeps_shorter_request_deadline() {
let (started_tx, started_rx) = channel();
let (release_tx, release_rx) = channel();
let (finished_tx, finished_rx) = channel();
let caller = std::thread::spawn(move || {
with_budget(Some(Budget::after(Duration::from_millis(80))), || {
run_with_timeout(
Path::new("running-past-request"),
None,
Limiter::new(1),
Duration::from_secs(1),
None,
move |_| {
let _ = started_tx.send(());
let _ = release_rx.recv();
let _ = finished_tx.send(());
Ok(())
},
)
})
});
let started = started_rx.recv_timeout(IO_BUDGET);
let error = caller.join().unwrap().unwrap_err();
let _ = release_tx.send(());
finished_rx.recv_timeout(IO_BUDGET).unwrap();
started.expect("the filesystem operation must actually start");
assert_eq!(timeout_code(&error), "read_blocked");
let message = error.to_string();
let duration = message
.split_once("within ")
.unwrap()
.1
.split_once(" s")
.unwrap()
.0
.parse::<f64>()
.unwrap();
assert!((0.0..=0.080).contains(&duration), "{error}");
}
#[cfg(unix)]
#[test]
fn queued_time_without_request_budget_does_not_consume_running_access_budget() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("queued-without-request-budget");
let gate = stall_helper(&path);
let (started_tx, started_rx) = channel();
let (release_tx, release_rx) = channel();
let (result_tx, result_rx) = channel();
let caller = std::thread::spawn(move || {
assert!(current().is_none(), "this call must have no request budget");
result_tx
.send(run_with_timeout(
&path,
None,
Limiter::new(1),
Duration::from_secs(1),
None,
move |_| {
started_tx.send(()).unwrap();
let _ = release_rx.recv();
Ok(42)
},
))
.unwrap();
});
gate.reached.recv_timeout(IO_BUDGET).unwrap();
assert!(result_rx.recv_timeout(Duration::from_millis(750)).is_err());
drop(gate);
let started = started_rx.recv_timeout(IO_BUDGET);
let early = result_rx.recv_timeout(Duration::from_millis(500));
let _ = release_tx.send(());
caller.join().unwrap();
started.expect("the filesystem operation must actually start");
let result = early.unwrap_or_else(|_| result_rx.recv_timeout(IO_BUDGET).unwrap());
assert_eq!(result.unwrap(), 42, "queueing is not a request deadline");
}
#[cfg(unix)]
#[test]
fn shared_probe_waiter_follows_queued_then_running_owner() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().to_path_buf();
let queued = stall_helper(&path);
let running = stall_running_helper(&path);
let budget = Budget::after(Duration::from_secs(20));
let owner_path = path.clone();
let owner_budget = budget.clone();
let owner = std::thread::spawn(move || {
with_budget(Some(owner_budget), || probe_directory(&owner_path, None))
});
queued.reached.recv_timeout(IO_BUDGET).unwrap();
let (waiting_tx, waiting_rx) = channel();
let (result_tx, result_rx) = channel();
let waiter_budget = budget.clone();
let waiter = std::thread::spawn(move || {
with_budget(Some(waiter_budget), || {
waiting_tx.send(()).unwrap();
result_tx.send(probe_directory(&path, None)).unwrap();
});
});
waiting_rx.recv_timeout(IO_BUDGET).unwrap();
assert!(result_rx.recv_timeout(Duration::from_millis(3750)).is_err());
drop(queued);
running.reached.recv_timeout(IO_BUDGET).unwrap();
let early = result_rx.recv_timeout(Duration::from_millis(2500));
drop(running);
let owner_result = owner.join().unwrap();
waiter.join().unwrap();
let result = early.unwrap_or_else(|_| result_rx.recv_timeout(IO_BUDGET).unwrap());
result.expect("a shared waiter must receive the healthy owner's result");
owner_result.unwrap();
assert_eq!(budget.measurements(), (1, 1), "the probe must be shared");
assert!(!budget.failed.load(Ordering::Acquire));
}
#[cfg(unix)]
#[test]
fn shared_probe_waiter_keeps_shorter_request_deadline_after_owner_starts() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().to_path_buf();
let queued = stall_helper(&path);
let running = stall_running_helper(&path);
let budget = Budget::after(Duration::from_secs(10));
let owner_path = path.clone();
let owner_budget = budget.clone();
let owner = std::thread::spawn(move || {
with_budget(Some(owner_budget), || probe_directory(&owner_path, None))
});
queued.reached.recv_timeout(IO_BUDGET).unwrap();
let (waiting_tx, waiting_rx) = channel();
let (result_tx, result_rx) = channel();
let waiter = std::thread::spawn(move || {
with_budget(Some(budget), || {
let at = Instant::now() + Duration::from_millis(500);
waiting_tx.send(at).unwrap();
result_tx.send(probe_directory(&path, Some(at))).unwrap();
});
});
let at = waiting_rx.recv_timeout(IO_BUDGET).unwrap();
assert!(result_rx.recv_timeout(Duration::from_millis(100)).is_err());
drop(queued);
running.reached.recv_timeout(IO_BUDGET).unwrap();
let result = result_rx.recv_timeout(Duration::from_secs(2));
let finished = Instant::now();
drop(running);
let _ = owner.join().unwrap();
waiter.join().unwrap();
let error = result.unwrap().unwrap_err();
assert_eq!(timeout_code(&error), "read_io_queue_timeout", "{error}");
assert!(finished >= at, "the waiter must not expire early");
assert!(finished < at + Duration::from_secs(1));
}
#[cfg(all(unix, any(target_os = "macos", target_os = "linux")))]
#[test]
fn shared_probe_waiters_preserve_owner_queue_and_access_timeout_codes() {
for running in [false, true] {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().to_path_buf();
let gate = if running {
stall_running_helper(&path)
} else {
stall_helper(&path)
};
let budget =
Budget::after(Duration::from_secs(5)).with_access_budget(Duration::from_millis(200));
let owner_path = path.clone();
let owner_budget = budget.clone();
let (owner_tx, owner_rx) = channel();
let owner = std::thread::spawn(move || {
let result = with_budget(Some(owner_budget), || probe_directory(&owner_path, None));
owner_tx.send(result).unwrap();
});
gate.reached.recv_timeout(IO_BUDGET).unwrap();
let (result_tx, result_rx) = channel();
let waiter = std::thread::spawn(move || {
with_budget(Some(budget), || {
result_tx.send(probe_directory(&path, None)).unwrap();
});
});
let result = result_rx
.recv_timeout(Duration::from_secs(30))
.expect("the shared-probe waiter must observe its deadline");
let owner_result = owner_rx
.recv_timeout(Duration::from_secs(30))
.expect("the shared-probe owner must observe its deadline");
drop(gate);
owner.join().unwrap();
waiter.join().unwrap();
let owner_error = owner_result.unwrap_err();
let waiter_error = result.unwrap_err();
let expected = if running {
"read_blocked"
} else {
"read_io_queue_timeout"
};
assert_eq!(timeout_code(&owner_error), expected, "{owner_error}");
assert_eq!(timeout_code(&waiter_error), expected, "{waiter_error}");
}
}
#[test]
fn running_helper_timeout_has_only_native_platform_hint() {
let (release_tx, release_rx) = channel();
let (started_tx, started_rx) = channel();
let (finished_tx, finished_rx) = channel();
let caller = std::thread::spawn(move || {
run_with_limiter(Path::new("running"), None, Limiter::new(1), move |_| {
started_tx.send(()).unwrap();
let _ = release_rx.recv();
finished_tx.send(()).unwrap();
Ok(())
})
});
let started = started_rx.recv_timeout(IO_BUDGET);
let error = caller.join().unwrap().unwrap_err();
release_tx.send(()).unwrap();
finished_rx.recv_timeout(IO_BUDGET).unwrap();
started.expect("the helper must start its operation");
assert!(error.to_string().contains("read_blocked"), "{error}");
let message = error.to_string();
let (prefix, duration_and_hint) = message.split_once("within ").unwrap();
assert_eq!(prefix, "read_blocked: running: OS access did not finish ");
let (duration, hint) = duration_and_hint.split_once(" s").unwrap();
assert!(duration.parse::<f64>().unwrap() > 0.0);
let expected_hint = if cfg!(target_os = "macos") {
"; on macOS, check ck-aft access in Privacy & Security, then retry"
} else {
""
};
assert_eq!(hint, expected_hint);
}
#[cfg(all(unix, any(target_os = "macos", target_os = "linux")))]
#[test]
fn mutation_admission_keeps_the_running_access_cap() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("running-mutation-check");
let gate = stall_running_helper(&path);
let budget =
Budget::after(Duration::from_secs(25)).with_access_budget(Duration::from_millis(200));
let started = Instant::now();
let error = with_budget(Some(budget), || {
let _mutation = enter_mutation();
run(&path, None, |_| Ok(()))
})
.unwrap_err();
let elapsed = started.elapsed();
drop(gate);
assert_eq!(timeout_code(&error), "read_blocked", "{error}");
assert!(elapsed < Duration::from_secs(5), "{elapsed:?}");
}
#[cfg(all(unix, any(target_os = "macos", target_os = "linux")))]
#[test]
fn read_admission_keeps_the_queue_cap_outside_mutations() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("queued-read");
let gate = stall_helper(&path);
let budget =
Budget::after(Duration::from_secs(25)).with_access_budget(Duration::from_millis(200));
let started = Instant::now();
let error = with_budget(Some(budget), || run(&path, None, |_| Ok(()))).unwrap_err();
let elapsed = started.elapsed();
drop(gate);
assert_eq!(timeout_code(&error), "read_io_queue_timeout", "{error}");
assert!(elapsed < Duration::from_secs(5), "{elapsed:?}");
}
#[test]
fn audit1432_walk_gap_precedes_the_entire_skipped_files_block() {
with_budget(Some(Budget::after(Duration::from_secs(30))), || {
let budget = current().unwrap();
budget.walk_partial.store(true, Ordering::Release);
budget
.walk_time_limit_reached
.store(true, Ordering::Release);
for at in 0..23 {
note_large_read_skip(Path::new(&format!("large-{at:02}.log")));
}
let response = with_skip_disclosure(|| {
finish_response(Response::success(
"walk-and-skips",
serde_json::json!({"text":"rows"}),
))
});
let text = response.data["text"].as_str().unwrap();
assert!(
text.find(WALK_PARTIAL_GAP).unwrap()
< text
.find(crate::large_read_counts::WHOLE_READ_SKIP_REASON)
.unwrap(),
"{text}"
);
assert!(
text.ends_with("shown 20 of 23 files (cap) ยท narrow: path"),
"{text}"
);
});
}