From 8b02390a6100b2bbce742a00f1c8d4532b1afcfb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 17:03:49 -0800 Subject: [PATCH] Tests: placed document tests wait on handshakes instead of timers The render crate's placed-document tests decided results by wall-clock time: - The gate that holds the background worker opened by itself after 10 s, so a test that forgot to open it still passed. It is now a mutex and a condition variable with no time limit, opened when the guard that shut_gate returns is dropped (also when the test fails). - settle polled busy() every 5 ms for up to 10 s. It now waits on placed_document::wait_idle, which a condition variable signals when the last pending bitmap is finished. - The self-placing document test asserted that drawing took under 10 s. It now asserts how deep the drawing went (at least 2 levels, at most MAX_DEPTH), read from a test-only counter kept by the depth guard. --- crates/render/src/placed_document.rs | 46 +++++++++++++++++-- crates/render/src/tests/placed_document.rs | 52 +++++++++++++--------- 2 files changed, 74 insertions(+), 24 deletions(-) diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index 9ad5b687bb..702933e95f 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -28,7 +28,7 @@ use std::cell::Cell; use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; use vectorcraft_doc::placed_document::MAX_DEPTH; use vectorcraft_doc::{ImageBlob, Node, PlacedDocument}; @@ -69,6 +69,8 @@ struct Bitmaps { static BITMAPS: LazyLock> = LazyLock::new(Default::default); /// Bitmaps being made. static PENDING: LazyLock>> = LazyLock::new(Default::default); +/// Signaled, under [`PENDING`]'s lock, when the last bitmap being made stops being pending. +static IDLE: Condvar = Condvar::new(); /// Bitmaps that could not be made (neither the file nor a preview could be read): not asked for /// again. static FAILED: LazyLock>> = LazyLock::new(Default::default); @@ -123,6 +125,24 @@ pub fn busy() -> bool { !lock(&PENDING).is_empty() } +/// Bitmap `key` stops being pending; when none is left, [`IDLE`] is signaled. +fn finish(key: &BitmapKey) { + let mut pending = lock(&PENDING); + pending.remove(key); + if pending.is_empty() { + IDLE.notify_all(); + } +} + +/// Wait until no bitmap is being made ([`busy`] is false). +#[cfg(test)] +pub(crate) fn wait_idle() { + let mut pending = lock(&PENDING); + while !pending.is_empty() { + pending = IDLE.wait(pending).unwrap_or_else(PoisonError::into_inner); + } +} + /// Is a bitmap of file `key` being made? #[cfg(test)] pub(crate) fn pending_for(key: &str) -> bool { @@ -237,12 +257,32 @@ thread_local! { static DEPTH: Cell = const { Cell::new(0) }; } +#[cfg(test)] +thread_local! { + /// The deepest this thread has drawn inside placed documents since [`reset_deepest`]. + static DEEPEST: Cell = const { Cell::new(0) }; +} + +/// Start counting how deep this thread draws inside placed documents ([`deepest`]). +#[cfg(test)] +pub(crate) fn reset_deepest() { + DEEPEST.with(|d| d.set(0)); +} + +/// The deepest this thread has drawn inside placed documents since [`reset_deepest`]. +#[cfg(test)] +pub(crate) fn deepest() -> usize { + DEEPEST.with(Cell::get) +} + /// While alive: drawing inside a placed document, one level deeper. struct Inside; impl Inside { fn enter() -> Self { DEPTH.with(|d| d.set(d.get() + 1)); + #[cfg(test)] + DEEPEST.with(|d| d.set(d.get().max(depth()))); Inside } } @@ -323,7 +363,7 @@ fn run(r: &mut Renderer, mut job: Job) { lock(&FAILED).insert(job.key.clone()); } } - lock(&PENDING).remove(&job.key); + finish(&job.key); }; match scope { Some(scoped) => scoped(&mut body), @@ -356,7 +396,7 @@ mod workers { let key = job.key.clone(); if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::run(&mut r, *job))).is_err() { super::lock(&super::FAILED).insert(key.clone()); - super::lock(&super::PENDING).remove(&key); + super::finish(&key); } } }); diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 9d11cd6eaf..6d4713930c 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -85,31 +85,43 @@ fn placed_node(id: u64, key: &str, width: f64, height: f64, xf: Affine) -> Node /// Held shut, [`gated_blue_page`] makes the background worker wait before reading a file, so a /// frame drawn meanwhile shows the placeholders whatever the scheduler does (#5152: a fast worker /// could finish between scheduling a bitmap and the frame looking it up again). -static GATE_SHUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static GATE_SHUT: std::sync::Mutex = std::sync::Mutex::new(false); +/// Signaled when the gate opens. +static GATE_OPENED: std::sync::Condvar = std::sync::Condvar::new(); /// The thread drawing while the gate is shut: it never waits (a file read there is drawn exactly). static GATE_HOLDER: std::sync::Mutex> = std::sync::Mutex::new(None); -/// [`blue_page`] once the gate opens (at most 10 s), except on the thread that shut it. Every test -/// here registers it: the first registration stays, so all of them must agree (open, it is +/// [`blue_page`] once the gate opens, except on the thread that shut it. Every test here +/// registers it: the first registration stays, so all of them must agree (open, it is /// `blue_page`). fn gated_blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> { let here = std::thread::current().id(); let holder = *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let t = std::time::Instant::now(); - while holder != Some(here) && GATE_SHUT.load(std::sync::atomic::Ordering::SeqCst) && t.elapsed().as_secs() < 10 { - std::thread::sleep(std::time::Duration::from_millis(1)); + if holder != Some(here) { + let mut shut = GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + while *shut { + shut = GATE_OPENED.wait(shut).unwrap_or_else(std::sync::PoisonError::into_inner); + } } blue_page(p, bytes) } -/// Shut the gate for the calling thread's frames. -fn shut_gate() { - *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::thread::current().id()); - GATE_SHUT.store(true, std::sync::atomic::Ordering::SeqCst); +/// The gate shut by [`shut_gate`]; dropping it opens the gate, also when the test fails while it +/// is shut. +struct Gate; + +impl Drop for Gate { + fn drop(&mut self) { + *GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = false; + GATE_OPENED.notify_all(); + } } -fn open_gate() { - GATE_SHUT.store(false, std::sync::atomic::Ordering::SeqCst); +/// Shut the gate for the calling thread's frames, until the [`Gate`] is dropped. +fn shut_gate() -> Gate { + *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::thread::current().id()); + *GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true; + Gate } /// Held by the tests that draw placed documents from bitmaps, which share the bitmaps, their @@ -129,12 +141,9 @@ fn render(d: &Document, progressive: bool) -> Rendered { Renderer::new().render(d, 100, 100, Affine::IDENTITY, &opts) } -/// Wait for the background bitmaps (at most 10 s). +/// Wait for the background bitmaps. fn settle() { - let t = std::time::Instant::now(); - while placed_document::busy() && t.elapsed().as_secs() < 10 { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + placed_document::wait_idle(); assert!(!placed_document::busy(), "bitmaps still coming"); } @@ -433,9 +442,9 @@ fn a_ready_bitmap_draws_again_where_its_file_shows() { let mut r = Renderer::new(); let generation = placed_document::generation(); // The first frame shows the placeholders: the worker waits until it is drawn. - shut_gate(); + let gate = shut_gate(); let before = r.render(&d, 100, 100, Affine::IDENTITY, &opts); - open_gate(); + drop(gate); settle(); let made = placed_document::made_between(generation, placed_document::generation()).expect("known"); let files = |keys: &[&str]| keys.iter().map(|k| k.to_string()).collect::>(); @@ -532,9 +541,10 @@ fn a_placed_document_kept_as_its_preview_draws_the_preview() { fn a_document_that_places_itself_draws_a_few_levels_deep_then_stops() { let _serial = serial(); let d = doc_with("loop-1", b"loop"); - let t = std::time::Instant::now(); + placed_document::reset_deepest(); let r = render(&d, false); - assert!(t.elapsed().as_secs() < 10); + let deepest = placed_document::deepest(); + assert!((2..=vectorcraft_doc::placed_document::MAX_DEPTH).contains(&deepest), "drawn {deepest} levels deep"); assert_eq!(&r.pixel(50, 30)[..3], &[0, 0, 255]); // On screen too. render(&d, true);