Merge pull request #9839 from dotCooCoo/fix/plugins-tests-without-timing

Plug-ins: loader, registry and dialog tests wait on handshakes instead of spin counts
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-27 21:36:45 -08:00
commit 990637f30d
3 files changed
+123 -80

No files matched your search

+22 -4
View File
@@ -170,6 +170,8 @@ impl Manifest {
let mut shown = BTreeSet::new();
for (name, p) in &self.params {
let met = p.ui.visible_when.iter().all(|(other, allowed)| {
#[cfg(test)]
tests::count_check();
shown.contains(other.as_str())
&& match values.get(other) {
Some(v) => allowed.contains(v),
@@ -219,6 +221,19 @@ mod tests {
use super::*;
thread_local! {
/// The conditions [`Manifest::visible`] may still check on this thread before the test fails.
static CHECKS_LEFT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
}
/// Counts one condition [`Manifest::visible`] checks, and fails the test once it checked more
/// than it was allowed, so a check that would run forever ends the test instead.
pub(super) fn count_check() {
let left = CHECKS_LEFT.with(|n| n.get());
assert!(left > 0, "more conditions were checked than the test allows");
CHECKS_LEFT.with(|n| n.set(left - 1));
}
const RICH: &str = r#"{"id":"org.example.hatch","name":"Hatch","kind":"effect","params":{
"pattern":{"type":"choice","options":["lines","crosshatch","dots"],"default":"lines",
"label":"Pattern","group":"Fill","help":"How the shape is filled."},
@@ -290,7 +305,8 @@ mod tests {
/// Conditions that each name several earlier parameters are checked once per parameter, not
/// once per path through them: 256 checkboxes, each shown while the 8 before it are checked,
/// would otherwise take longer than the age of the universe on every frame of the dialog.
/// would otherwise take longer than the age of the universe on every frame of the dialog. The
/// test counts the conditions checked, so it ends however slow the machine is.
#[test]
fn overlapping_conditions_are_checked_once_per_parameter() {
let params: Vec<String> = (0..256)
@@ -300,9 +316,11 @@ mod tests {
})
.collect();
let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap();
let (done, finished) = std::sync::mpsc::channel();
std::thread::spawn(move || done.send(m.visible(&Map::new()).len()));
let shown = finished.recv_timeout(std::time::Duration::from_secs(10)).expect("the check took more than 10 s");
// Each parameter names at most `MAX_CONDITIONS` others, so checking each condition once
// stays within this.
CHECKS_LEFT.with(|n| n.set(256 * MAX_CONDITIONS));
let shown = m.visible(&Map::new()).len();
CHECKS_LEFT.with(|n| n.set(usize::MAX));
assert_eq!(shown, 256, "every checkbox is checked, so every parameter is shown");
// Unchecking the first hides the rest: each names it or one it hides.
let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap();
+50 -43
View File
@@ -351,6 +351,16 @@ impl<T: Send + 'static> Loads<T> {
out
}
/// Tests: waits for the next outcome a worker sends and records it → its job (`None`: the
/// channel the outcomes come on was closed).
#[cfg(test)]
pub(crate) fn record_next(&mut self) -> Option<usize> {
let done = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv().ok()?;
let i = done.0;
self.record(done);
Some(i)
}
fn record(&mut self, (i, r, took): Done<T>) {
let r = if took >= self.deadline { Err(self.too_long()) } else { r };
// An outcome that comes after the job failed past its deadline is dropped.
@@ -488,26 +498,11 @@ mod tests {
})
}
/// Polls `loads` until `done` says so, at most a million times.
fn poll_until(loads: &mut Loads<u32>, mut done: impl FnMut(&mut Loads<u32>) -> bool) -> bool {
(0..1_000_000).any(|_| {
std::thread::yield_now();
loads.poll();
done(loads)
})
}
/// What `rx` receives, looked for 100 million times at most, so a worker that never sends fails the
/// test instead of holding it. The test fails at once when every sender is gone.
fn recv_soon<V>(rx: &Receiver<V>) -> V {
for _ in 0..100_000_000 {
match rx.try_recv() {
Ok(v) => return v,
Err(mpsc::TryRecvError::Disconnected) => panic!("every sender ended without sending"),
Err(mpsc::TryRecvError::Empty) => std::thread::yield_now(),
}
}
panic!("nothing was received");
/// The channel `loads`' workers send their outcomes on, taken out of `loads` so that the test
/// still receives them once `loads` is dropped. A worker sends its outcome after it stopped
/// counting its thread as stuck, so receiving it shows that the count went down.
fn take_results(loads: &mut Loads<u32>) -> Receiver<Done<u32>> {
std::mem::replace(&mut *loads.results.lock().unwrap(), mpsc::channel().1)
}
/// The outcomes come back in the order of the jobs when they finish in the reverse order.
@@ -527,15 +522,13 @@ mod tests {
// return, and dropping `loads` does not wait on them while the test clock stands still.
let release = go;
for _ in 0..3 {
recv_soon(&starts);
starts.recv().unwrap();
}
// Each job is let go only once the one after it has finished.
let mut finished = Vec::new();
for v in (0..3).rev() {
release[v].send(()).unwrap();
let done = recv_soon(&loads.results.lock().unwrap());
finished.push(done.0);
loads.record(done);
finished.extend(loads.record_next());
}
assert_eq!(finished, vec![2, 1, 0], "they finished in reverse");
assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::<Vec<_>>(), vec![0, 1, 2]);
@@ -561,10 +554,16 @@ mod tests {
let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))];
let (ms, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
assert_eq!(recv_soon(&starts), 0);
assert_eq!(starts.recv().unwrap(), 0);
assert!(!loads.poll(), "the first job is still running and the second waits for a worker");
ms.store(10_000, Ordering::SeqCst);
let done = poll_until(&mut loads, |l| l.outcomes.iter().all(Option::is_some));
// The first job fails at its deadline. Unless the second job failed with it, for want of a
// worker, the worker started in place of the stuck one sends the second job's outcome.
loads.poll();
if loads.outcomes[1].is_none() {
loads.record_next();
}
let done = loads.poll();
go.send(()).unwrap();
assert!(done, "the job after the one that hangs never got its outcome");
let out = loads.wait();
@@ -582,10 +581,12 @@ mod tests {
let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))];
let (ms, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
assert_eq!(recv_soon(&starts), 0);
assert_eq!(starts.recv().unwrap(), 0);
ms.store(10_000, Ordering::SeqCst);
loads.poll();
assert_eq!(recv_soon(&starts), 1, "a worker took the place of the stuck one");
// The second job fails at once when no worker is left to take it; otherwise one starts it.
assert!(loads.outcomes[1].is_none(), "no worker took the place of the stuck one: {:?}", loads.outcomes[1]);
assert_eq!(starts.recv(), Ok(1), "a worker took the place of the stuck one");
ms.store(20_000, Ordering::SeqCst);
let done = loads.poll();
go0.send(()).unwrap();
@@ -624,11 +625,18 @@ mod tests {
.collect();
let (_, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded");
let loaded = [loads.record_next(), loads.record_next()];
assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded");
let early = ran.load(Ordering::SeqCst);
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
assert_eq!(early, 2, "the third job waited for the first outcomes to be taken");
assert!(!poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() > 0), "taken but not released");
// The worker starts the third job only once the limit passes it.
loads.poll();
let (may_start, started) = {
let s = loads.pool.lock();
(s.limit > 2, s.started[2].is_some())
};
assert!(!may_start && !started, "taken but not released");
assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes");
loads.release(2);
assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]);
@@ -641,13 +649,14 @@ mod tests {
let jobs: Vec<Job<u32>> = (0..3).map(|v| Job::new(None, move || Ok(v))).collect();
let (_, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded");
let loaded = [loads.record_next(), loads.record_next()];
assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded");
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
let (done, rest) = mpsc::channel();
std::thread::spawn(move || {
let _ = done.send(loads.wait());
});
assert_eq!(recv_soon(&rest), vec![Ok(2)]);
assert_eq!(rest.recv(), Ok(vec![Ok(2)]));
}
/// When no worker can take the jobs left, because the only one is stuck past its deadline and
@@ -659,7 +668,7 @@ mod tests {
let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))];
let (ms, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
recv_soon(&starts);
starts.recv().unwrap();
loads.refuse_threads = true;
ms.store(10_000, Ordering::SeqCst);
let done = loads.poll();
@@ -687,18 +696,17 @@ mod tests {
let (go, held_until) = mpsc::channel();
let (ms, clock) = manual();
let mut first = make(vec![held(0, started, held_until)], clock);
recv_soon(&starts);
starts.recv().unwrap();
ms.store(10_000, Ordering::SeqCst);
assert!(first.poll(), "the stuck job failed at its deadline");
let results = take_results(&mut first);
drop(first);
let (_, clock) = manual();
let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait();
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]);
go.send(()).unwrap();
assert!((0..1_000_000).any(|_| {
std::thread::yield_now();
stuck.load(Ordering::SeqCst) == 0
}));
assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned");
assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck");
assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]);
}
@@ -713,15 +721,14 @@ mod tests {
let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock);
loads.stuck_threads = stuck;
loads.begin();
recv_soon(&starts);
starts.recv().unwrap();
ms.store(10_000, Ordering::SeqCst);
let results = take_results(&mut loads);
drop(loads);
assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts");
go.send(()).unwrap();
assert!((0..1_000_000).any(|_| {
std::thread::yield_now();
stuck.load(Ordering::SeqCst) == 0
}));
assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned");
assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck");
}
/// The launch marker names an item while its job runs, and stops naming it when the job
+51 -33
View File
@@ -65,6 +65,14 @@ pub fn approved(plugin: &Plugin) -> bool {
!m.asks_permissions() || granted(&m.id).is_some_and(|g| g.covers(&m.id, plugin.hash(), &m.permissions()))
}
/// Tests: what runs before an install waits for the plug-ins, given the plug-in's id.
#[cfg(test)]
type InstallHook = Arc<dyn Fn(&str) + Send + Sync>;
/// Tests: runs right before [`install`] waits for the plug-ins' write lock.
#[cfg(test)]
static BEFORE_INSTALL_LOCK: Mutex<Option<InstallHook>> = Mutex::new(None);
/// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists
/// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and
/// the plug-in installed under its id, the grants and the revision stay as they were.
@@ -72,6 +80,13 @@ pub fn install(plugin: Plugin) -> Result<Arc<Plugin>> {
// The revision moves while the write lock is held, so a cache that reads the new revision and
// then the plug-ins finds the new plug-in among them. The approval is checked while it is held
// too.
#[cfg(test)]
{
let hook = BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()).clone();
if let Some(hook) = hook {
hook(plugin.id());
}
}
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
if !approved(&plugin) {
return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", ")));
@@ -718,15 +733,24 @@ mod tests {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let plugin = Plugin::load(include_bytes!("../tests/fixtures/desaturate.wasm"), Limits::default()).unwrap();
let id = plugin.id().to_string();
let (waits, install_waits) = std::sync::mpsc::channel();
let ours = id.clone();
*BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &str| {
if p == ours {
let _ = waits.send(());
}
}));
let held = PLUGINS.read().unwrap_or_else(|e| e.into_inner());
let before = revision();
let installing = std::thread::spawn(move || install(plugin));
let moved = (0..1_000_000).any(|_| {
std::thread::yield_now();
revision() != before
});
// The install has done everything it does before it waits for the set, which the test holds.
let reached = install_waits.recv();
let moved = revision() != before;
drop(held);
installing.join().unwrap().unwrap();
let installed = installing.join();
*BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = None;
installed.unwrap().unwrap();
assert!(reached.is_ok(), "the install never asked for the set");
assert!(!moved, "the revision changed while the install waited for the set");
assert!(revision() > before && remove(&id));
}
@@ -1117,46 +1141,40 @@ mod tests {
let first = dir.join("a.wasm");
let (go, a_waits) = std::sync::mpsc::channel::<()>();
let a_waits = Mutex::new(a_waits);
let seen = std::sync::Arc::new(Mutex::new(Vec::new()));
let (reached, a_reached) = std::sync::mpsc::channel::<()>();
let held = first.clone();
let saw = seen.clone();
let _hook = Hooked::set(move |p| {
saw.lock().unwrap_or_else(|e| e.into_inner()).push(p.to_path_buf());
if p == held {
let _ = reached.send(());
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
}
});
// Two workers, so the other files load while the first one waits.
let loading = std::thread::spawn({
let dir = dir.clone();
move || {
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2))?;
load.start();
while !load.done() {
load.wait();
load.install_ready(|_| false);
}
Ok::<_, Error>(load.finish())
}
});
// The other two files load on the other worker while the first one waits: their loads have
// started (the hook saw them) and ended (the launch marker list no longer has them).
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
load.start();
// Bound after `load`, so a failing assertion lets the first file go before dropping `load`
// waits for it.
let go = go;
a_reached.recv().unwrap();
// The other two files load on the other worker while the first one waits: their outcomes
// come in, and the launch marker no longer names them.
let others = [load.loads.record_next(), load.loads.record_next()];
let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm")));
let finished = |p: &std::path::Path| {
let named = |p: &std::path::Path| {
let item = crate::safe_mode::Item::file(p.display().to_string());
seen.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|s| s == p) && !crate::safe_mode::still_loading().iter().any(|i| i.same(&item))
crate::safe_mode::still_loading().iter().any(|i| i.same(&item))
};
// Looked at a bounded number of times, and given up when the load ends first.
let reached = (0..10_000_000).any(|_| {
std::thread::yield_now();
loading.is_finished() || (seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2]))
});
assert!(reached && !loading.is_finished(), "the load ended, or the other files didn't load, while the first one waited");
assert!(ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded");
assert!(others == [Some(1), Some(2)] && !named(&all[1]) && !named(&all[2]), "the other files didn't load meanwhile: {others:?}");
let early = load.install_ready(|_| false);
assert!(!load.done(), "the load ended while the first file waited");
assert!(early.is_empty() && ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded");
go.send(()).unwrap();
let r = loading.join().unwrap();
while !load.done() {
load.wait();
load.install_ready(|_| false);
}
let r = load.finish();
std::fs::remove_dir_all(&dir).unwrap();
let r = r.unwrap();
assert_eq!(r.loaded, ids.to_vec(), "{r:?}");
let serials: Vec<u64> = ids.iter().map(|id| get(id).unwrap().serial()).collect();
assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}");