From 5c4e3d5bf827051ec88c61934e3c41703af24194 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 12:19:09 -0700 Subject: [PATCH 1/4] fix(render): a document put aside keeps no pictures that were still being drawn (M8) --- crates/engine/src/render_service.rs | 68 ++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs index 21edca10..02caf93d 100644 --- a/crates/engine/src/render_service.rs +++ b/crates/engine/src/render_service.rs @@ -22,6 +22,7 @@ use anicraft_render::{RenderStats, View, render}; use rayon::prelude::*; use std::collections::{HashMap, HashSet, VecDeque}; use std::hash::{Hash, Hasher}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::thread::JoinHandle; use web_time::Instant; @@ -434,6 +435,9 @@ struct Shared { raster: Mutex, wake: Condvar, cache: Mutex, + /// Counts [`RenderService::forget_pictures`] calls: a batch the worker took before one of + /// them is of a document no longer shown, and its pictures are dropped, not cached. + forgets: AtomicU64, notify: Option>, } @@ -454,7 +458,7 @@ impl RenderService { /// Starts the worker. `notify` runs on the worker after each finished batch (the UI passes /// "request a repaint"). If no thread can be spawned, requests render synchronously. pub fn new(cache_bytes: usize, notify: Option>) -> RenderService { - let shared = Arc::new(Shared { queue: Mutex::new(Queue::default()), raster: Mutex::new(RasterSlot::default()), wake: Condvar::new(), cache: Mutex::new(FrameCache::new(cache_bytes)), notify }); + let shared = Arc::new(Shared { queue: Mutex::new(Queue::default()), raster: Mutex::new(RasterSlot::default()), wake: Condvar::new(), cache: Mutex::new(FrameCache::new(cache_bytes)), forgets: AtomicU64::new(0), notify }); let s = shared.clone(); let worker = std::thread::Builder::new().name("anicraft-render".into()).spawn(move || worker_loop(&s)).ok(); RenderService { shared, worker } @@ -607,9 +611,20 @@ impl RenderService { !q.busy.is_empty() || !q.urgent.is_empty() || !q.prefetch.is_empty() } - /// Forgets every finished picture, in memory and on the GPU: an editor showing another - /// document calls it, so the one put aside keeps no pictures (ADR 0112). + /// Forgets every picture, in memory and on the GPU: an editor showing another document + /// calls it, so the one put aside keeps no pictures (ADR 0112). That includes the ones still + /// to come: queued jobs are dropped, and a batch the worker is drawing is thrown away when + /// it finishes, instead of landing in the cache after it was emptied. pub fn forget_pictures(&self) { + { + let mut q = self.queue(); + q.urgent.clear(); + q.prefetch.clear(); + // Under the queue's lock, where the worker reads it as it takes a batch; and before + // the cache is emptied, so a batch that still sees the old count is cached before + // the emptying, never after. + self.shared.forgets.fetch_add(1, Ordering::SeqCst); + } self.cache().clear(); } @@ -650,7 +665,7 @@ impl Drop for RenderService { fn worker_loop(s: &Shared) { loop { // Take a whole batch: urgent first, topped up with prefetch work. - let jobs: Vec = { + let (jobs, forgets): (Vec, u64) = { let mut q = s.queue.lock().unwrap_or_else(PoisonError::into_inner); loop { if q.shutdown { @@ -665,7 +680,7 @@ fn worker_loop(s: &Shared) { for j in &batch { q.busy.insert(j.key); } - break batch; + break (batch, s.forgets.load(Ordering::SeqCst)); } q = s.wake.wait(q).unwrap_or_else(PoisonError::into_inner); } @@ -678,8 +693,11 @@ fn worker_loop(s: &Shared) { let imgs = render_batch_by(&todo, &slot); { let mut cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner); - for img in imgs { - cache.insert(Arc::new(img)); + // Pictures asked for before `forget_pictures` show a document put aside since. + if s.forgets.load(Ordering::SeqCst) == forgets { + for img in imgs { + cache.insert(Arc::new(img)); + } } } { @@ -705,6 +723,42 @@ mod tests { make_job(state, doc, frame, view, None) } + /// ADR 0112: the document put aside keeps no pictures, also when the worker was still + /// drawing some, or had some queued, as the other document was shown. (They used to land + /// in the cache after it was emptied and stay until something evicted them.) + #[test] + fn pictures_still_being_drawn_are_forgotten_too() { + use std::sync::mpsc::channel; + let doc = sample::demo(); + let svc = RenderService::new(64 << 20, None); + // A stand-in rasterizer that says when it starts a picture and waits to be let go. + let (started, starts) = channel::<()>(); + let (go, gate) = channel::<()>(); + let (started, gate) = (Mutex::new(started), Mutex::new(gate)); + let held: Rasterizer = Arc::new(move |_: &DisplayList, v: &View| { + let _ = started.lock().unwrap_or_else(PoisonError::into_inner).send(()); + let _ = gate.lock().unwrap_or_else(PoisonError::into_inner).recv(); + Ok((Raster::Premul8(vec![0; v.width as usize * v.height as usize * 4]), RenderStats::default())) + }); + svc.set_rasterizer(Some(held)); + let view = View { transform: Affine::scale(0.25, 0.25), width: 32, height: 18, background: None }; + let (drawing, queued) = (svc.job(1, &doc, 3, view, None), svc.job(1, &doc, 4, view, None)); + assert!(svc.request(drawing.clone()).is_none()); + starts.recv().unwrap(); // the worker is drawing the first picture + svc.prefetch(vec![queued.clone()]); + svc.forget_pictures(); + // Let the worker finish whatever it still draws; nothing more is started. + drop(go); + while svc.busy() { + std::thread::yield_now(); + } + assert_eq!(svc.cache_stats().0, 0, "the picture that was being drawn is not kept"); + assert!(starts.try_recv().is_err(), "and the queued one is never drawn"); + // The service still draws what is asked for afterwards. + assert!(svc.request(queued.clone()).is_none()); + assert!(svc.wait_for(queued.key, 60_000).is_some()); + } + #[test] fn worker_matches_synchronous_render() { let doc = sample::demo(); From 26c54d7471822a60526edc64f4362f2bee2fffb9 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 12:19:09 -0700 Subject: [PATCH 2/4] test(engine): the command fuzz is one test per start, spread over the runner's threads (M8) --- crates/engine/src/tests.rs | 131 +++++++++++++++++++++++++++---------- 1 file changed, 97 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4b791968..d58567d1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -580,8 +580,28 @@ fn save_load_round_trip() { } /// Adversarial params for every command: must return Ok or Err, never panic. -#[test] -fn panic_hunt_every_command() { +/// +/// One test per starting session, so the test runner spreads them over its threads: each start +/// is a pass over every command that leaves thousands of undo steps behind, and the 17 of them +/// one after another were four fifths of the whole workspace's test time. +mod panic_hunt_every_command { + macro_rules! from { + ($($start:ident),* $(,)?) => { + pub(super) const STARTS: &[&str] = &[$(stringify!($start)),*]; + $( + #[test] + fn $start() { + super::panic_hunt(stringify!($start)); + } + )* + }; + } + from!(empty, sample, sounds, parented_arm, motion_path, raw_shapes, armature, shape_armature, mixed_armature, warped, two_layers_selected, inside_a_symbol, several_keyframes, library_folders, button, group_in_a_group, eases); +} + +/// [`panic_hunt_every_command`] from the start named `only`. Every start is built each time: +/// the hostile parameters name what is in them (bones, pins, folders), whichever one is fuzzed. +fn panic_hunt(only: &str) { let mut hostile: Vec = vec![ Value::Null, json!({}), @@ -1010,42 +1030,85 @@ Exec=evil", "data_home": "relative/share", "refresh": false}), json!({"parent": u64::MAX, "layer": limbs.get(1), "keep": false, "sx": 0, "sy": 0}), json!({"parent": null, "layers": [u64::MAX, 0], "frame": 4_000_000_000u64}), ]); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), arm, on_path, raw, rig, shaped, mixed, warped, layered, in_symbol, keyed, library, button, grouped, eased] { - let mut s = start; - for spec in commands().iter().filter(|c| !skip(c.id)) { - for p in &hostile { - let _ = s.execute(spec.id, p); - } - // and with a selection present - let _ = s.execute("edit.select_all", &json!({})); - for p in &hostile { - let _ = s.execute(spec.id, p); - } + let starts = [ + ("empty", Session::default()), + ("sample", Session::new(sample::demo())), + ("sounds", Session::new(with_sound)), + ("parented_arm", arm), + ("motion_path", on_path), + ("raw_shapes", raw), + ("armature", rig), + ("shape_armature", shaped), + ("mixed_armature", mixed), + ("warped", warped), + ("two_layers_selected", layered), + ("inside_a_symbol", in_symbol), + ("several_keyframes", keyed), + ("library_folders", library), + ("button", button), + ("group_in_a_group", grouped), + ("eases", eased), + ]; + // A start added here without a test of its own would never be fuzzed. + assert_eq!(starts.iter().map(|(name, _)| *name).collect::>(), panic_hunt_every_command::STARTS); + for (name, start) in starts { + if name == only { + hunt_from(name, start, &hostile, skip); } - // The document must still evaluate and render, and so must what the stage shows. - for f in [0, 1, 5, 47, 1000] { - let _ = anicraft_render::render_frame(&s.doc, f, 0.1); - } - s.hit_area = Some((anicraft_doc::Rgba::WHITE, 0.4)); - let pic = s.stage_picture(); - // ...and every button's hit area draws, under a pointer that goes over and presses. - let mut ns = anicraft_doc::player::NoScripts; - let st = anicraft_doc::player::start(&s.doc, &mut ns).state; - let p = anicraft_geom::Vec2::new(640.0, 400.0); - let st = anicraft_doc::player::input(&s.doc, &st, &[anicraft_doc::player::Event::Move(p), anicraft_doc::player::Event::Down(p), anicraft_doc::player::Event::Up(p)], &mut ns).state; - let _ = anicraft_render::render(&anicraft_doc::player::hit_overlay(&s.doc, &st, anicraft_doc::Rgba::WHITE, 0.4), &anicraft_render::View { transform: anicraft_geom::Affine::scale(0.1, 0.1), width: 128, height: 72, background: None }); - let _ = anicraft_render::render_frame(&pic.doc, pic.frame, 0.1); - // ...and its sounds lay out and mix. - let voices = anicraft_doc::sound::voices(&s.doc, 8000); - let mut out = vec![0.0; 2 * 4096]; - anicraft_doc::audio::mix(&voices, 8000, Default::default(), 0, &mut out); - // ...and its Library tree stays whole: nothing a load would have to repair. - let mut loaded = s.doc.clone(); - loaded.sanitize(); - assert_eq!(loaded.library_tree, s.doc.library_tree); } } +/// One pass of [`panic_hunt_every_command`]: every command with every hostile parameter set, +/// from `start`, then what the stage, the player and the mixer make of the document left over. +fn hunt_from(name: &str, start: Session, hostile: &[Value], skip: impl Fn(&str) -> bool) { + /// Says where the hunt was when it panicked (the panic itself names only a line). + struct At<'a>(&'a str, std::cell::Cell<(&'static str, usize)>); + impl Drop for At<'_> { + fn drop(&mut self) { + if std::thread::panicking() { + let (command, param) = self.1.get(); + eprintln!("panic hunt: start “{}”, command {command}, hostile parameter set {param}", self.0); + } + } + } + let at = At(name, std::cell::Cell::new(("", 0))); + let mut s = start; + for spec in commands().iter().filter(|c| !skip(c.id)) { + for (i, p) in hostile.iter().enumerate() { + at.1.set((spec.id, i)); + let _ = s.execute(spec.id, p); + } + // and with a selection present + let _ = s.execute("edit.select_all", &json!({})); + for (i, p) in hostile.iter().enumerate() { + at.1.set((spec.id, i)); + let _ = s.execute(spec.id, p); + } + } + at.1.set(("(the document left over)", 0)); + // The document must still evaluate and render, and so must what the stage shows. + for f in [0, 1, 5, 47, 1000] { + let _ = anicraft_render::render_frame(&s.doc, f, 0.1); + } + s.hit_area = Some((anicraft_doc::Rgba::WHITE, 0.4)); + let pic = s.stage_picture(); + // ...and every button's hit area draws, under a pointer that goes over and presses. + let mut ns = anicraft_doc::player::NoScripts; + let st = anicraft_doc::player::start(&s.doc, &mut ns).state; + let p = anicraft_geom::Vec2::new(640.0, 400.0); + let st = anicraft_doc::player::input(&s.doc, &st, &[anicraft_doc::player::Event::Move(p), anicraft_doc::player::Event::Down(p), anicraft_doc::player::Event::Up(p)], &mut ns).state; + let _ = anicraft_render::render(&anicraft_doc::player::hit_overlay(&s.doc, &st, anicraft_doc::Rgba::WHITE, 0.4), &anicraft_render::View { transform: anicraft_geom::Affine::scale(0.1, 0.1), width: 128, height: 72, background: None }); + let _ = anicraft_render::render_frame(&pic.doc, pic.frame, 0.1); + // ...and its sounds lay out and mix. + let voices = anicraft_doc::sound::voices(&s.doc, 8000); + let mut out = vec![0.0; 2 * 4096]; + anicraft_doc::audio::mix(&voices, 8000, Default::default(), 0, &mut out); + // ...and its Library tree stays whole: nothing a load would have to repair. + let mut loaded = s.doc.clone(); + loaded.sanitize(); + assert_eq!(loaded.library_tree, s.doc.library_tree, "start “{name}”"); +} + #[test] fn file_commands_reject_bad_params() { let mut s = Session::default(); From 654e4efbe4cead03f69a7bf2bcdaee5ac1cbcc60 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 12:20:39 -0700 Subject: [PATCH 3/4] test: polling deadlines are a minute, not two seconds; the stroke test skips work it never read (M8) --- crates/cli/src/control/tests.rs | 3 ++- crates/render/src/stroke.rs | 4 ++-- src/gpu_stage.rs | 5 +++-- src/remote.rs | 2 +- src/tabs_tests.rs | 3 ++- 5 files changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/cli/src/control/tests.rs b/crates/cli/src/control/tests.rs index afc967f4..c073dbdd 100644 --- a/crates/cli/src/control/tests.rs +++ b/crates/cli/src/control/tests.rs @@ -328,7 +328,8 @@ fn dropping_the_server_frees_the_port() { let port = server.port; assert!(TcpListener::bind(("127.0.0.1", port)).is_err(), "the port is taken while the server lives"); drop(server); - let freed = (0..200).any(|_| { + // (Up to a minute: the listening thread ends when it next runs, late on a busy machine.) + let freed = (0..6000).any(|_| { std::thread::sleep(Duration::from_millis(10)); TcpListener::bind(("127.0.0.1", port)).is_ok() }); diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 5b6c9c6e..f6407481 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -931,9 +931,9 @@ mod tests { assert!(apart < 1.0 / 255.0, "{what}, {how}: {apart}"); // 3. Against the truth: each pixel sampled 16 × 16 times against the pieces. // (Checked for the plain styles; a sample grid is good to a sixteenth.) - let (pieces, _) = piece_loops(&lines, hw, &outline, profile.as_ref(), None, false); - let before = coverage(&pieces, FillRule::NonZero); if how == "round" || how == "dashes whose round caps overlap" { + let (pieces, _) = piece_loops(&lines, hw, &outline, profile.as_ref(), None, false); + let before = coverage(&pieces, FillRule::NonZero); for y in (0..300).step_by(7) { for x in 0..400 { let c = drawn[y * 400 + x]; diff --git a/src/gpu_stage.rs b/src/gpu_stage.rs index 74215b39..177d59e9 100644 --- a/src/gpu_stage.rs +++ b/src/gpu_stage.rs @@ -589,10 +589,11 @@ mod imp { ) } - /// Frames until the start thread has answered (bounded). + /// Frames until the start thread has answered (bounded: a minute, which only a start + /// thread that never answers reaches; a busy machine can take seconds to run it). fn settle(m: &mut Imp, svc: &RenderService, ctx: &egui::Context, now: f64, size: (u32, u32)) -> Vec { let mut out = Vec::new(); - for _ in 0..400 { + for _ in 0..12_000 { out.extend(m.sync(true, svc, ctx, now, size)); if m.starting.is_none() { break; diff --git a/src/remote.rs b/src/remote.rs index 83554d9a..f6c07b3d 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -193,7 +193,7 @@ mod tests { assert!(!file.exists(), "the token file goes when the window closes"); assert_eq!(super::port(&app), None); // The port is free again: the same run can open another window on it (ADR 0092). - let freed = (0..200).any(|_| { + let freed = (0..6000).any(|_| { std::thread::sleep(std::time::Duration::from_millis(10)); std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() }); diff --git a/src/tabs_tests.rs b/src/tabs_tests.rs index ddd1613e..e736de90 100644 --- a/src/tabs_tests.rs +++ b/src/tabs_tests.rs @@ -390,8 +390,9 @@ fn autosave_and_recovery_cover_every_open_document() { let dir = std::env::temp_dir().join(format!("anicraft-tabs-recovery-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); + // (A minute: a deadline for a save thread on a busy machine, not a time that is checked.) let wait = |saver_ids: &[String]| { - for _ in 0..200 { + for _ in 0..6000 { if saver_ids.iter().all(|id| recovery::document_path(&dir, id).exists()) { return; } From 740cf824c60c8151c97c6b50aafc88edb0fed228 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:04:05 -0700 Subject: [PATCH 4/4] docs: the reliability pass in the changelog and roadmap (M8) --- CHANGELOG.md | 14 ++++++++++++++ docs/roadmap.md | 3 +-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e8f79bb..7c652936 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +* **Reliability pass on the tests** (M8, roadmap P-056). + * **Fixed: a document put aside could keep pictures.** Showing another document (a new tab, + New, Open) empties the stage's picture cache, but pictures the render thread was still + drawing, or had queued, landed in it afterwards and stayed until something evicted them. + They are now dropped, and queued ones are never drawn. This was the flaky test + `a_document_that_is_not_shown_keeps_no_pictures`, and the only test that failed in + repeated runs of the whole suite (once in 8 runs before the fix, none in 11 after). + * **The test suite takes less than half the time**: 141 s of test time on 4 threads against + 305 s. The command fuzz (`panic_hunt_every_command`) was 268 s in one test, four fifths of + the suite; it is now one test per starting document, 17 of them, that the runner spreads + over its threads. It does the same work. + * Tests that wait for another thread (a save, a freed port, a GPU start) give it a minute + instead of two seconds before failing; none of them asserts a time. + * **The roadmap is now a guideline, with a parity matrix** (M8, ADR 0125). Docs only. `docs/parity.md` compares AniCraft with the reference app feature by feature (done, partial, missing, won't do), checked against the code and the guide. `docs/roadmap.md` replaces the diff --git a/docs/roadmap.md b/docs/roadmap.md index 427deb4a..76deeb6e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -34,7 +34,7 @@ an ADR. *Lane* names the part of the code an item mostly touches. Two items in * lanes** with no entry under *Needs* can be built and merged in parallel; two in the **same lane** are better done one after the other, because they meet in the same files. The ids are stable: an item keeps its id when the order changes, a new item takes the next free number -wherever it is placed (P-056 is in the first tier), and a finished item leaves the table for +wherever it is placed (P-056 was in the first tier), and a finished item leaves the table for the changelog. ## Backlog @@ -59,7 +59,6 @@ the changelog. | P-014 | Pen pressure on every desktop: Linux Wayland (outside PR [#320](https://github.com/storytold/anicraft/issues/320)), reports from tablets ([#290](https://github.com/storytold/anicraft/issues/290)) | Tools | M | a tablet to test with | platform | | P-015 | Verified by hand on real machines: the Mac checklist of [ADR 0062](adr/0062-test-movie-window-and-macos-document-opening.md), a hybrid-GPU laptop, passes with Narrator, VoiceOver and Orca ([ADR 0064](adr/0064-accessibility-second-pass.md)), launcher icons on Fedora ([#348](https://github.com/storytold/anicraft/issues/348)) | Accessibility, platforms | M | the machines; the person | platform | | P-016 | The guide tells the truth: "Coming from Animate" still lists shipped features as missing; close the issues the appendix marks delivered (the lead does that) | (docs) | S | | docs | -| P-056 | The test `a_document_that_is_not_shown_keeps_no_pictures` (`src/tabs_tests.rs`) passes every time: on `main` it fails about two runs in three on Windows, alone or in the full run, so a red `cargo test` says nothing | (robustness) | S | | shell | ### Next: the parity gaps artists meet every day