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.
This commit is contained in:
skylartaylor committed 2026-11-25 23:28:29 +01:00
1 parent e55dad05c5
commit 7d2db2e62f
4 files changed
+102 -7

No files matched your search

@@ -200,6 +200,17 @@ fn put_service<S: Send + 'static>(data: &mut Map, handle: Removed) -> Option<Rem
}
}
/// Replaces `to`'s egui memory with a copy of `from`'s, and leaves `to` with its own runtime services (see
/// [`keep_own_services`]). Both contexts' egui memory closures stay in this module, the one layer the workspace's
/// `contract/egui-import` rule lets at egui's memory.
pub(crate) fn copy_memory(from: &Context, to: &Context) {
let copied = from.memory(Clone::clone);
let mut replaced = None;
let gone = keep_own_services(to, || replaced = Some(to.memory_mut(|memory| std::mem::replace(memory, copied))));
drop(replaced);
drop(gone);
}
/// Runs `copy` (which replaces `to`'s egui memory) and leaves `to` with the runtime services it had before: the
/// handles `copy` brought in share another context's state (a `Service` clone shares it), so they are dropped, and a
/// type `to` had none of starts fresh on first use. Returns what was moved out, to drop outside every lock.
+10 -5
View File
@@ -462,6 +462,14 @@ pub(crate) fn adopt<T: Any + Clone + Send + Sync>(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<T: Slot>(ctx: &Context, id: Id, f: impl FnOnce(&mut T)) {
let Some(mut moved) = store::take::<Wrapped<SHOWN, T>>(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<T: Slot>(ctx: &Context, id: Id) {
let moved = pass_state::with::<Registry, _>(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(())
}
+32
View File
@@ -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<Vec<Detacher>> = 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<T: Clone + Send + Sync + 'static, E: Clone + Send + Sync + 'static>(ctx: &Context, id: Id) {
memory::edit_shown::<PendingSlot<T, E>>(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<Id> = Service::<PendingState>::run(from, |state| state.tracked.keys().copied().collect());
if ids.is_empty() {
return;
}
let detachers: Vec<Detacher> = 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<T: Clone + Send + Sync + 'static, E: Clone + Send + Sync + 'static>(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::<T, E>));
let viewport = pass::current_viewport(ctx);
let pass = pass::pass_nr(ctx, viewport);
frame::register_end_sweep(ctx, TypeId::of::<PendingState>(), sweep);
+49 -2
View File
@@ -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<dyn Jobs>) -> Arc<Host> {
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<AtomicUsize>) -> Pending<u32, String> {
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::<u32, String>(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");
}