From 3b629776d8bdfe0ee8d710fee00f81146340e4fd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 23 Nov 2026 04:43:29 +0000 Subject: [PATCH] Testing runtime runs background work inline: InstallSpec::jobs and Env::jobs_of Story trials have no host, so document-face and texture loads ran on default_jobs' threads and a fixture could settle before a face landed (StyleList::variants on Windows: rtl 52.0 vs 52.8, motion shapes change after the drive). InstallSpec::jobs sets where a context's background work runs while no host is installed; Env::jobs_of (host, else installed, else default_jobs) replaces the two copies in the face registry and the texture loader. testing::install_spec and the suite's language hosts use InlineJobs, so a load asked for in one pass lands in the next on every machine; the two per-story InlineJobs options go. --- crates/menu/src/ribbon/gallery/stories.rs | 9 ++----- crates/ui-contract/src/fonts/document.rs | 6 ++--- .../src/primitives/textures/loader.rs | 10 +++---- crates/ui-contract/src/runtime/env.rs | 23 ++++++++++++++-- crates/ui-contract/src/runtime/install.rs | 14 +++++++++- .../ui-contract/src/runtime/layout_memory.rs | 1 + .../ui-contract/src/testing/suite/variants.rs | 4 +-- crates/ui-contract/src/testing/windows.rs | 5 +++- crates/ui-contract/tests/it/fonts/document.rs | 26 +++++++++---------- .../ui-widgets/src/display/picture/stories.rs | 9 ++----- docs/contract-api.md | 3 ++- 11 files changed, 68 insertions(+), 42 deletions(-) diff --git a/crates/menu/src/ribbon/gallery/stories.rs b/crates/menu/src/ribbon/gallery/stories.rs index 0019a98a7..786f074e2 100644 --- a/crates/menu/src/ribbon/gallery/stories.rs +++ b/crates/menu/src/ribbon/gallery/stories.rs @@ -1,8 +1,5 @@ //! Stories of the in-ribbon gallery. -use std::sync::Arc; - -use craft_host::InlineJobs; use craft_ui::contract::Show as _; use craft_ui::list::{ThumbAspect, ThumbSize}; use craft_ui::primitives::textures::Revision; @@ -171,10 +168,8 @@ fn gallery_painted(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(Gallery<'static, usize>, covers = [], drive = Drive::Never)] fn gallery_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - // The source renders as a `Later` job: each tile shows the store's placeholder, then its picture. The jobs run - // inline, so the pictures land in the next frame and not whenever a thread ends: the suite's settled frames are - // the same on every run. - let options = ThumbnailOptions::new().jobs(Arc::new(InlineJobs)); + // The source renders as a `Later` job: each tile shows the store's placeholder, then its picture. + let options = ThumbnailOptions::new(); let thumbnails = Thumbnails::::in_context(ui.ctx(), "craft_menu.gallery.story", options); let source = FakeThumbSource::::new().later(true); let items: Vec> = (0..COUNT) diff --git a/crates/ui-contract/src/fonts/document.rs b/crates/ui-contract/src/fonts/document.rs index 3cf1ff52c..db18a925b 100644 --- a/crates/ui-contract/src/fonts/document.rs +++ b/crates/ui-contract/src/fonts/document.rs @@ -18,8 +18,8 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use craft_host::Wake; use craft_host::queue::{JobQueue, Priority, QueueOptions}; -use craft_host::{Wake, default_jobs}; use egui::epaint::text::{Blob, FontTweak, VariationCoords}; use egui::{Context, FontData}; @@ -198,13 +198,13 @@ enum Known { New, } -/// The queue of `ctx`'s catalog loads: made on first use on the host's `Jobs` (`default_jobs` without a host) and kept +/// The queue of `ctx`'s catalog loads: made on first use on the context's jobs (`Env::jobs_of`) and kept /// for the context's life, as `TextureLoader::in_context` keeps its own. fn queue_of(ctx: &Context, registry: &mut Registry) -> Arc>> { if let Some(queue) = ®istry.queue { return Arc::clone(&queue.queue); } - let jobs = Env::host_of(ctx).map_or_else(default_jobs, |host| Arc::clone(host.jobs_shared())); + let jobs = Env::jobs_of(ctx); let wake_ctx = ctx.clone(); let wake = Wake::new(move || repaint::request(&wake_ctx)); let lanes = QueueOptions::default_lanes(); diff --git a/crates/ui-contract/src/primitives/textures/loader.rs b/crates/ui-contract/src/primitives/textures/loader.rs index 8e05cf0ab..c00dfeb60 100644 --- a/crates/ui-contract/src/primitives/textures/loader.rs +++ b/crates/ui-contract/src/primitives/textures/loader.rs @@ -6,7 +6,7 @@ use crate::runtime::egui::{memory, pass, repaint}; use crate::runtime::env::Env; use crate::runtime::replay; use craft_host::queue::{Cancel, JobQueue, QueueOptions}; -use craft_host::{Jobs, Wake, default_jobs}; +use craft_host::{Jobs, Wake}; use egui::{Color32, ColorImage, Context}; use std::collections::HashMap; use std::fmt::Debug; @@ -23,9 +23,9 @@ pub struct LoaderOptions { pub store: TextureStoreOptions, /// Jobs running at once; 0 runs one job per frame on the UI thread (wasm32). pub lanes: usize, - /// Where the lanes run. `None`: the installed host's `Jobs`, or `craft_host::default_jobs()` when no host is - /// installed (threads on native targets, one job per frame on wasm32). Stories and tests pass a `ManualJobs` to - /// finish one job at a time. + /// Where the lanes run. `None`: the installed host's `Jobs`, else the jobs the runtime was installed with (inline + /// in tests and story trials), else `craft_host::default_jobs()` (threads on native targets, one job per frame on + /// wasm32). Stories and tests pass a `ManualJobs` to finish one job at a time. pub jobs: Option>, } @@ -188,7 +188,7 @@ impl TextureLoader { let (queue, lanes) = match known { Some(known) => known, None => { - let jobs = options.jobs.unwrap_or_else(|| Env::host_of(ctx).map_or_else(default_jobs, |host| Arc::clone(host.jobs_shared()))); + let jobs = options.jobs.unwrap_or_else(|| Env::jobs_of(ctx)); let wake = { let ctx = ctx.clone(); Wake::new(move || repaint::request(&ctx)) diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 7131b4c20..a6b6236cf 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -12,14 +12,14 @@ pub use shell::{BodyMode, PageBandRoom, RevealEdge, ShellCx, ShellRegions, SlotK pub use units::{ColumnSize, LengthUnits, PointSize, UnitKind, UnitWords, Units}; use crate::runtime::commands::CommandChain; -use crate::runtime::egui::memory::FastMap; +use crate::runtime::egui::memory::{self, FastMap}; use crate::runtime::egui::{pass, repaint, scale, stack, style}; use crate::runtime::frame::PerViewport; use crate::runtime::windows; use crate::style::{EnvKey, GlyphRole, Ink, SurfaceKind, UiTokens}; use craft_behavior::{CanvasTransform, MotionMode}; -use craft_host::Host; use craft_host::target::{Os, ShellInfo}; +use craft_host::{Host, Jobs}; pub use craft_i18n::Direction; pub use craft_i18n::{AgeStyle, Count, Counted, WordRows, WordSet, WordTemplate, Words}; use craft_i18n::{CalendarDate, DateFormat, Format}; @@ -750,6 +750,15 @@ impl Env { PerViewport::::with(ctx, pass::current_viewport(ctx), |envs| envs.root.as_ref().and_then(|env| env.host.clone())) } + /// Where `ctx`'s background work runs: the host's jobs, else the jobs `install` was given, else + /// `craft_host::default_jobs()`. + pub(crate) fn jobs_of(ctx: &Context) -> Arc { + if let Some(host) = Self::host_of(ctx) { + return Arc::clone(host.jobs_shared()); + } + memory::with::(ctx, |installed| installed.0.clone()).unwrap_or_else(craft_host::default_jobs) + } + /// A clone of the innermost app value, else `T::root()`. Large values hold an `Arc`. pub fn get(&self) -> T { self.values.get::() @@ -895,3 +904,13 @@ impl Drop for Restore<'_> { fn motion_mode(ctx: &Context, motion: MotionMode) -> MotionMode { if repaint::animation_time(ctx) > 0.0 { motion } else { motion.lowered_by(MotionMode::Off) } } + +/// The jobs `install` was given, for a context with no host. +#[derive(Default)] +struct InstalledJobs(Option>); + +/// Keeps `jobs` as where `ctx`'s background work runs while no host is installed; `None` leaves +/// `craft_host::default_jobs()`. +pub(crate) fn install_jobs(ctx: &Context, jobs: Option>) { + memory::with::(ctx, |installed| installed.0 = jobs); +} diff --git a/crates/ui-contract/src/runtime/install.rs b/crates/ui-contract/src/runtime/install.rs index 42268e916..c8bcbc798 100644 --- a/crates/ui-contract/src/runtime/install.rs +++ b/crates/ui-contract/src/runtime/install.rs @@ -1,10 +1,11 @@ //! `runtime::install`: adds the runtime plugin once and sets the egui options the runtime owns. use crate::runtime::egui::{clipboard, input, plugin}; -use crate::runtime::env::{SystemReader, system}; +use crate::runtime::env::{self, SystemReader, system}; use crate::runtime::pen::PenSource; use crate::runtime::{commands, frame, pen, windows}; use crate::style::{DuplicateStyle, StyleReplacements}; +use craft_host::Jobs; use craft_host::target::ShellInfo; use craft_window::policy::Decision; use craft_window::restore::Store; @@ -45,6 +46,9 @@ pub struct InstallSpec { /// The clipboard the host installs (system, browser event, memory); without one the runtime uses /// `Clipboard::new(EguiClipboard)`. pub clipboard: Option, + /// Where the context's background work (document faces, texture loads) runs while no host is installed; none + /// runs it on `craft_host::default_jobs()`. A host's jobs come first. + pub jobs: Option>, } /// The modifiers the mouse wheel zooms and scrolls sideways with. @@ -86,9 +90,16 @@ impl InstallSpec { pen: None, stories: false, clipboard: None, + jobs: None, } } + /// Runs the context's background work on `jobs` while no host is installed. + pub fn jobs(mut self, jobs: Arc) -> Self { + self.jobs = Some(jobs); + self + } + /// Installs the host's clipboard (system, browser event, memory) in place of the runtime's own. pub fn clipboard(mut self, clipboard: craft_platform::clipboard::Clipboard) -> Self { self.clipboard = Some(clipboard); @@ -211,6 +222,7 @@ pub fn install(ctx: &Context, spec: InstallSpec) -> Result<(), InstallError> { input::set_wheel_modifiers(ctx, spec.wheel.zoom, spec.wheel.sideways); system::install(ctx, spec.system); pen::install(ctx, spec.pen); + env::install_jobs(ctx, spec.jobs); clipboard::install(ctx, spec.clipboard); windows::install(ctx, with_browser_caps(spec.shell_info), spec.window_system, spec.placement, spec.frame, spec.app_id); frame::set_frame_layers(ctx, spec.frame_layers); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 32f622d66..969b5950c 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1326,6 +1326,7 @@ pub(crate) mod guard { ("fonts::document::Registry", "document faces: cache; a face loads the same whichever run asks, and its repaint request is harmless"), ("runtime::egui::fonts::Providers", "font providers and the served faces: cache; a face is served the same whichever run asks"), ("runtime::egui::fonts::Steps", "fonts plugin begin-pass steps: cache; a step added twice runs once"), + ("runtime::env::InstalledJobs", "the jobs install was given: set once at install, only read after"), // Testing logs. ("runtime::measure::", "measuring-run counts and the skipped-effect log (testing)"), ("runtime::pass_state::Parked", "pass state between passes: moved into the thread and back, not read"), diff --git a/crates/ui-contract/src/testing/suite/variants.rs b/crates/ui-contract/src/testing/suite/variants.rs index a2b9a2caa..e13aed724 100644 --- a/crates/ui-contract/src/testing/suite/variants.rs +++ b/crates/ui-contract/src/testing/suite/variants.rs @@ -221,14 +221,14 @@ fn motion_modes_settle(subject: &Subject) -> Result<(), String> { /// A host whose catalogs offer `ja`, in English. fn hosts() -> Option<(Arc, Arc)> { - use craft_host::{AppInfo, Host}; + use craft_host::{AppInfo, Host, InlineJobs}; let (i18n, problems) = craft_i18n::I18n::from_owned([("ja".to_owned(), String::new(), String::new())], &["ja"]); if !problems.is_empty() { return None; } let i18n = Arc::new(i18n); let japanese = i18n.from_code("ja")?; - let english = Arc::new(Host::builder(AppInfo { id: "suite", name: "Suite", version: "0" }).i18n(i18n).build()); + let english = Arc::new(Host::builder(AppInfo { id: "suite", name: "Suite", version: "0" }).i18n(i18n).jobs(Arc::new(InlineJobs)).build()); Some((english.clone(), Arc::new(english.with_lang(japanese)))) } diff --git a/crates/ui-contract/src/testing/windows.rs b/crates/ui-contract/src/testing/windows.rs index 785d50031..7a4e3f9cc 100644 --- a/crates/ui-contract/src/testing/windows.rs +++ b/crates/ui-contract/src/testing/windows.rs @@ -1,6 +1,7 @@ //! The window host's fixtures: install inputs that open no OS windows, and the scripted system. use crate::runtime::InstallSpec; +use craft_host::InlineJobs; use craft_host::target::ShellInfo; use std::sync::Arc; @@ -9,8 +10,10 @@ pub use crate::runtime::egui::fixture::{FullOutput, RawInput, dragged_id, record pub use craft_window::system::{FakeSystem, NoWindows}; /// An install spec for the running build's shell and a system with no OS services, with the stories' command sets. +/// Background work runs inline, so what a pass asks for lands in the next pass on every machine and a settled frame +/// is the same on every run. pub fn install_spec() -> InstallSpec { - InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).stories() + InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).stories().jobs(Arc::new(InlineJobs)) } /// Makes the shell of `ctx` run on `os`, for a test of the OS matrix: the key table, the chords shown, the chrome, diff --git a/crates/ui-contract/tests/it/fonts/document.rs b/crates/ui-contract/tests/it/fonts/document.rs index 310c78c48..aa48454f9 100644 --- a/crates/ui-contract/tests/it/fonts/document.rs +++ b/crates/ui-contract/tests/it/fonts/document.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, LazyLock, Mutex}; -use std::time::Duration; +use std::thread::ThreadId; use craft_behavior::Metrics; use craft_host::{AppInfo, Host, ManualJobs}; @@ -25,10 +25,11 @@ pub struct PlainStyle { metrics: Metrics, } -/// What the probes asked for: how often a face was loaded and the state each key was last given. +/// What the probes asked for: how often a face was loaded, on which threads, and the state each key was last given. #[derive(Clone, Default)] struct Tally { loads: Arc, + threads: Arc>>, states: Arc>>, } @@ -49,9 +50,10 @@ impl Tally { /// Asks for the face `key`, whose load counts itself in `tally`; a key starting with `panic` names a load that panics. fn ask(cx: &impl FacesCx, key: &str, tally: &Tally) -> FaceState { cx.document_face(key, || { - let (loads, panics) = (Arc::clone(&tally.loads), key.starts_with("panic")); + let (loads, threads, panics) = (Arc::clone(&tally.loads), Arc::clone(&tally.threads), key.starts_with("panic")); move || { loads.fetch_add(1, Ordering::Relaxed); + threads.lock().expect("the threads").push(std::thread::current().id()); assert!(!panics, "a load that panics"); Some(FaceBytes::new(Arc::from(FONT), 0)) } @@ -187,21 +189,19 @@ fn faces_stay_ready_after_the_definitions_are_replaced() { assert_eq!(tally.loads(), 3, "without loading them again"); } -/// Without a host the loads run on `default_jobs`' threads: every face asked for in one pass lands, each loaded once. +/// Without a host the loads run on the jobs the runtime was installed with, inline in a trial: every face asked for in +/// one pass is ready in the next on every machine, each loaded once. #[trial] -fn without_a_host_every_face_asked_for_in_one_pass_lands() { +fn without_a_host_every_face_asked_for_in_one_pass_is_ready_in_the_next() { let mut frames = Frames::new(); let tally = Tally::default(); let wanted = keys(0..8); - for _ in 0..1000 { - frame(&mut frames, &tally, &wanted); - if tally.all_ready(&wanted) { - break; - } - std::thread::sleep(Duration::from_millis(1)); - } - assert!(tally.all_ready(&wanted), "every face lands"); + frame(&mut frames, &tally, &wanted); + frame(&mut frames, &tally, &wanted); + assert!(tally.all_ready(&wanted), "every face lands in the next pass"); assert_eq!(tally.loads(), 8, "and none was cancelled and loaded again"); + let me = std::thread::current().id(); + assert!(tally.threads.lock().expect("the threads").iter().all(|thread| *thread == me), "the loads ran on the trial's thread"); } #[trial] diff --git a/crates/ui-widgets/src/display/picture/stories.rs b/crates/ui-widgets/src/display/picture/stories.rs index 75eb07866..b285a24a9 100644 --- a/crates/ui-widgets/src/display/picture/stories.rs +++ b/crates/ui-widgets/src/display/picture/stories.rs @@ -1,9 +1,5 @@ //! Stories of `Picture`. -use std::sync::Arc; - -use craft_host::InlineJobs; - use super::{Picture, PictureSize}; use crate::contract::Show as _; use crate::list::{ThumbAspect, ThumbSize}; @@ -36,11 +32,10 @@ fn picture_thumbnail(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } /// A picture made off the frame: its source renders as a `Later` job, so the picture shows the placeholder until the -/// job lands on the loader's lanes, then the picture. The job runs inline, so the picture lands in the next frame and -/// not whenever a thread ends: the suite's settled frames are the same on every run. +/// job lands on the loader's lanes, then the picture. #[story(Picture<'static>, covers = [], drive = Drive::Never)] fn picture_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - let options = ThumbnailOptions::new().jobs(Arc::new(InlineJobs)); + let options = ThumbnailOptions::new(); let thumbnails = Thumbnails::::in_context(ui.ctx(), "craft_ui::stories::picture_rendered", options); let source = FakeThumbSource::::new().later(true).opaque(true); Picture::rendered("Rendered", 1, &thumbnails, &source).extent(PictureSize::Thumb(ThumbSize::Large)).show(ui).into() diff --git a/docs/contract-api.md b/docs/contract-api.md index 8165c19bf..34609bca3 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -4015,8 +4015,9 @@ Decision records and findings. Inspected regions ([`record`]) collect pipeline s `runtime::install`: adds the runtime plugin once and sets the egui options the runtime owns. - `craft_ui::runtime::install::InstallError`: `pub enum InstallError { AlreadyInstalled, DuplicateStyle(DuplicateStyle), Commands(commands::CommandDefError), DuringPass }`. Why `install` refused a spec. -- `craft_ui::runtime::install::InstallSpec`: `pub struct InstallSpec { pub shell_info: ShellInfo, pub window_system: Arc, pub placement: Option>>, pub frame_layers: Option, pub looks: StyleReplacements, pub frame: Option, pub system: SystemReader, pub wheel: WheelModifiers, pub app_id: String, pub pen: Option, pub stories: bool, pub clipboard: Option }`. What `install` takes. +- `craft_ui::runtime::install::InstallSpec`: `pub struct InstallSpec { pub shell_info: ShellInfo, pub window_system: Arc, pub placement: Option>>, pub frame_layers: Option, pub looks: StyleReplacements, pub frame: Option, pub system: SystemReader, pub wheel: WheelModifiers, pub app_id: String, pub pen: Option, pub stories: bool, pub clipboard: Option, pub jobs: Option> }`. What `install` takes. - `pub fn new(shell_info: ShellInfo, window_system: Arc) -> Self`. A spec for `shell_info` and `window_system`, with no ghost-layer painter. + - `pub fn jobs(mut self, jobs: Arc) -> Self`. Runs the context's background work on `jobs` while no host is installed. - `pub fn clipboard(mut self, clipboard: craft_platform::clipboard::Clipboard) -> Self`. Installs the host's clipboard (system, browser event, memory) in place of the runtime's own. - `pub fn stories(mut self) -> Self`. Loads the stories' command sets too, for an install that shows stories. - `pub fn placement(mut self, store: Arc>) -> Self`. Sets the store viewport mounts save their window placement in.