From 7d2db2e62fbd900ef5650885656b027c4d8af0c8 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 23:28:29 +0100 Subject: [PATCH] Runtime fork: a copied pending slot starts its own job, and the memory copy stays in runtime/egui A fork copies the components' slots by value, but a pending result's slot holds a `Started` handle to the job the window submitted: a copy shared the landing, so the fork that polled first took the window's landed result (`Done` became `Running`) and the window stayed Loading until its owner was evicted. `CancelOnDrop` was shared the same way, so evicting the window's owner no longer cancelled the job. `fork_into` now detaches the copied pending slots: each drops its `Started`, so the fork submits a job of its own on its next real pass and the window keeps the handle whose drop cancels its job. A trial forks a context whose job has landed, polls the fork first, and holds that the window still takes its result. The egui memory swap moves into `runtime/egui/memory.rs` (`copy_memory`), the layer the workspace's `contract/egui-import` rule lets at egui's memory. --- crates/ui-contract/src/runtime/egui/memory.rs | 11 ++++ crates/ui-contract/src/runtime/memory.rs | 15 ++++-- crates/ui-contract/src/runtime/pending.rs | 32 ++++++++++++ crates/ui-contract/tests/it/runtime/fork.rs | 51 ++++++++++++++++++- 4 files changed, 102 insertions(+), 7 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/memory.rs b/crates/ui-contract/src/runtime/egui/memory.rs index 7f84f1301b..761d1a1878 100644 --- a/crates/ui-contract/src/runtime/egui/memory.rs +++ b/crates/ui-contract/src/runtime/egui/memory.rs @@ -200,6 +200,17 @@ fn put_service(data: &mut Map, handle: Removed) -> Option(ctx: &Context, owner: Id, id: }); } +/// Edits the shown slot of type `T` under `id` in place, outside a memory stage: the slot moves out of context data, +/// `f` edits it, and it moves back. `f` runs no call that reaches the context. +pub(crate) fn edit_shown(ctx: &Context, id: Id, f: impl FnOnce(&mut T)) { + let Some(mut moved) = store::take::>(ctx, id) else { return }; + f(&mut moved.0); + store::put(ctx, id, moved); +} + /// Moves the shown slot of type `T` under `id` out of context data into the graveyard, as eviction does. pub(crate) fn dispose_shown(ctx: &Context, id: Id) { let moved = pass_state::with::(ctx, |reg| { @@ -1029,10 +1037,7 @@ pub fn fork_into(from: &Context, to: &Context) -> Result<(), ForkError> { if frame::in_pass(to) { return Err(ForkError::DuringPass); } - let copied = from.memory(Clone::clone); - let mut replaced = None; - let gone = store::keep_own_services(to, || replaced = Some(to.memory_mut(|memory| std::mem::replace(memory, copied)))); - drop(replaced); - drop(gone); + store::copy_memory(from, to); + pending::detach_fork(from, to); Ok(()) } diff --git a/crates/ui-contract/src/runtime/pending.rs b/crates/ui-contract/src/runtime/pending.rs index bb2165f550..1ce0d5bd1e 100644 --- a/crates/ui-contract/src/runtime/pending.rs +++ b/crates/ui-contract/src/runtime/pending.rs @@ -9,6 +9,7 @@ use craft_host::queue::{Cancel, JobQueue, Priority, QueueOptions}; use craft_host::{Jobs, Wake}; use egui::{Context, Id, IdMap, ViewportId}; use std::any::TypeId; +use std::sync::OnceLock; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; @@ -224,8 +225,39 @@ pub fn finish_jobs(ctx: &Context, timeout: Duration) -> bool { queue.is_none_or(|queue| queue.finish(timeout)) } +/// The slot types a fork detaches, one entry per type, added when its first slot is tracked. +/// Detaches the copied slot `Id` in the context the fork made: the `PendingSlot` type states what it drops. +type Detacher = fn(&Context, Id); + +static DETACHERS: Mutex> = Mutex::new(Vec::new()); + +/// Detaches the pending results of the copied slot `id`: the fork keeps what the slot showed and drops the `Started` +/// it shared with the context it was copied from, so it neither takes that context's landed result nor holds its +/// cancellation. +fn detach_slot(ctx: &Context, id: Id) { + memory::edit_shown::>(ctx, id, |slot| slot.started = None); +} + +/// Detaches the pending results `from` started from `to`, which copied `from`'s memory (`memory::fork_into`): each +/// copied slot drops the `Started` handle it shares with `from`, so neither context takes the other's landed result, and +/// the window alone keeps the handle whose drop cancels the job. `to` submits its own job on its next real pass. +pub(crate) fn detach_fork(from: &Context, to: &Context) { + let ids: Vec = Service::::run(from, |state| state.tracked.keys().copied().collect()); + if ids.is_empty() { + return; + } + let detachers: Vec = DETACHERS.lock().unwrap_or_else(PoisonError::into_inner).clone(); + for id in ids { + for detach in &detachers { + detach(to, id); + } + } +} + /// Notes that `id` was asked for in this pass of the running viewport. fn track(ctx: &Context, id: Id, owner: Id) { + static REGISTERED: OnceLock<()> = OnceLock::new(); + REGISTERED.get_or_init(|| DETACHERS.lock().unwrap_or_else(PoisonError::into_inner).push(detach_slot::)); let viewport = pass::current_viewport(ctx); let pass = pass::pass_nr(ctx, viewport); frame::register_end_sweep(ctx, TypeId::of::(), sweep); diff --git a/crates/ui-contract/tests/it/runtime/fork.rs b/crates/ui-contract/tests/it/runtime/fork.rs index 3b37d4af4e..793f2c287a 100644 --- a/crates/ui-contract/tests/it/runtime/fork.rs +++ b/crates/ui-contract/tests/it/runtime/fork.rs @@ -2,13 +2,17 @@ //! components' scroll offsets included, and keeps a runtime of its own: it runs passes inside the window's, and what it //! does stays its own. -use craft_ui::contract::{ContainerProps, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft_host::{AppInfo, Host, Jobs, ManualJobs}; +use craft_ui::contract::{ContainerProps, Job, Pending, Props as _, Remember as _, Scroll, Show as _, ShowContainer as _}; use craft_ui::runtime::memory::{ForkError, fork_into}; use craft_ui::testing::layout::{Block, in_region}; +use craft_ui::testing::memory::{Stage, global}; use craft_ui::testing::{Frames, pointer, trial}; use craft_ui_test_kit::body::Slab; use egui::{Pos2, Rect, Ui, Vec2}; -use std::cell::Cell; +use std::cell::{Cell, RefCell}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; const VIEW: Vec2 = Vec2::new(300.0, 200.0); const ORIGIN: Pos2 = Pos2::new(10.0, 10.0); @@ -71,3 +75,46 @@ fn fork_into_a_context_running_a_pass_is_refused() { }); assert_eq!(refused.into_inner(), Some(Err(ForkError::DuringPass))); } + +fn host_over(jobs: Arc) -> Arc { + Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).jobs(jobs).build()) +} + +/// The pending result of `"k"` under `id`'s stage, polled in a real pass. The job's answer is how many jobs this run of +/// the trial submitted before it, so a fork's own submission is told from the window's. +fn poll(ui: &Ui, id: egui::Id, attempts: &Arc) -> Pending { + let attempts = Arc::clone(attempts); + let mut stage = Stage::open(ui.ctx(), id); + let result = stage + .pending("k", move || { + let attempt = attempts.fetch_add(1, Ordering::Relaxed); + Job::new(move |_, _| Ok::(attempt as u32)) + }) + .clone(); + stage.finish(); + result +} + +#[trial] +fn a_copied_pending_slot_takes_no_landed_result_from_the_context_it_was_forked_from() { + let jobs = Arc::new(ManualJobs::new()); + let attempts = Arc::new(AtomicUsize::new(0)); + let id = global("fork.pending", "owner"); + let mut window = Frames::new(); + let mut shadow = Frames::new(); + window.host(host_over(jobs.clone())); + shadow.host(host_over(jobs.clone())); + let (seen, shadow_seen) = (RefCell::new(Pending::default()), RefCell::new(Pending::default())); + window.frame(vec![], |ui| *seen.borrow_mut() = poll(ui, id, &attempts)); + assert!(matches!(*seen.borrow(), Pending::Loading { .. }), "the window waits for its job: {:?}", seen.borrow()); + jobs.run_all(); + assert_eq!(attempts.load(Ordering::Relaxed), 1, "the window submitted the job once"); + + fork_into(&window.ctx, &shadow.ctx).expect("the shadow runs no pass"); + // The shadow polls first, before the window takes what landed. + shadow.frame(vec![], |ui| *shadow_seen.borrow_mut() = poll(ui, id, &attempts)); + window.frame(vec![], |ui| *seen.borrow_mut() = poll(ui, id, &attempts)); + assert_eq!(*seen.borrow(), Pending::Ready(0), "the window still takes its own landed result"); + assert_eq!(*shadow_seen.borrow(), Pending::Loading { progress: None }, "the fork submits a job of its own"); + assert_eq!(attempts.load(Ordering::Relaxed), 2, "the fork's job is its own submission"); +}