feat: Start a new selection's preview without waiting for the obsolete one (#7167) (#7261)

- Leave the running preview behind when the selection moves to another setup, asked to stop
- Keep at most two obsolete previews running; streaming, tools and other inputs wait as before
- Keep no result of a cancelled watched evaluation in the shared evaluation cache
- Test the detaching, the cancel reaching the spawned job, and the cache guard

Co-authored-by: P'tite Tête <asso@ptitetete.com>
This commit is contained in:
P'tite Tête
2026-10-28 01:32:17 +00:00
committed by GitHub
parent 79214b6b49
commit 9fb41f8378
6 changed files with 215 additions and 9 deletions
+1 -1
View File
@@ -2332,7 +2332,7 @@ impl Model {
}
Err(e) => Some(e.to_string().trim_start_matches("the operation failed: ").to_string()),
};
if !self.no_cache {
if !self.no_cache && !watched.cancelled() {
let e = CachedEval {
error: error.clone(),
warning: warning.clone(),
+7
View File
@@ -173,6 +173,13 @@ pub(crate) fn begin(total: usize) -> Evaluation {
}
impl Evaluation {
/// Whether the watcher asked to stop. A feature cut short then (a STEP import that stopped
/// part way) failed only because of it: its result must not be kept for the same inputs, as
/// the evaluation cache is shared with the model a preview was copied from (#7167).
pub(crate) fn cancelled(&self) -> bool {
CURRENT.with(|c| c.borrow().as_ref().is_some_and(|cur| cur.progress.is_cancelled()))
}
/// Feature `index` is next. True when the watcher asked to stop: skip it.
pub(crate) fn step(&self, index: usize) -> bool {
CURRENT.with(|c| {
@@ -78,3 +78,37 @@ fn cancelled_import_stops_and_leaves_the_design_alone() {
assert!(done < total, "stopped part way ({done} of {total})");
let _ = std::fs::remove_file(path);
}
/// A preview cancelled while it imports again (#7167) keeps no "cancelled" result: the scratch
/// session shares the evaluation cache with the design, which then evaluates the same inputs and
/// imports in full.
#[test]
fn a_cancelled_preview_import_leaves_no_failure_in_the_shared_cache() {
let path = step_file("preview", 300);
let mut s = Session::default();
s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "body_name": "first"})).unwrap();
s.execute("file.insert_step", &json!({"path": path})).unwrap();
let import = s.doc.features.iter().position(|f| matches!(f.kind, FeatureKind::Import { .. })).unwrap();
// A new length for the box: the import after it is evaluated again on new inputs.
let redefine =
json!({"feature": s.doc.features[0].id, "command": "solid.box", "params": {"length": 20, "width": 10, "height": 10, "body_name": "first"}});
let mut scratch = s.scratch();
let progress = Arc::new(Progress::default());
let canceller = {
let progress = progress.clone();
std::thread::spawn(move || {
while progress.work().is_none() {
std::thread::yield_now();
}
progress.cancel();
})
};
let _ = solidcraft_doc::progress::watch(progress.clone(), || scratch.execute("timeline.redefine", &redefine));
canceller.join().unwrap();
let (_, done, total) = progress.work().unwrap();
assert!(done < total, "the preview's import stopped part way ({done} of {total})");
s.execute("timeline.redefine", &redefine).unwrap();
let result = &s.model.results[import];
assert!(result.error.is_none() && !result.skipped, "the design imports in full: {:?}", result.error);
let _ = std::fs::remove_file(path);
}
+53 -7
View File
@@ -11,11 +11,13 @@
//! runs once, on OK, and an error it finds shows then, the dialog staying open.
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::sync::mpsc::{Receiver, TryRecvError};
use serde_json::Value;
use solidcraft_engine::Session;
use solidcraft_engine::doc::ModelState;
use solidcraft_engine::doc::progress::Progress;
use solidcraft_engine::geom::{Aabb3, Mesh, Ring, Vec3};
use crate::SolveApp;
@@ -80,11 +82,22 @@ pub struct Built {
type Job = Result<Built, String>;
/// How many obsolete preview jobs may still run, left behind for newer inputs (#7167). Beyond
/// them, a new job waits for the running one as before, so a quick series of picks keeps at
/// most this many kernel computations going beside the current one.
const DETACHED: usize = 2;
#[derive(Default)]
pub struct PreviewState {
/// Key of the commands whose result (or error) is shown.
shown_key: Option<u64>,
running: Option<(u64, Receiver<Job>)>,
/// Asks the running job to stop between features once it is obsolete.
running_progress: Option<Arc<Progress>>,
/// Jobs left behind for inputs that changed to another setup (#7167): asked to stop, their
/// results are dropped when they come. With [`DETACHED`] of them running, the next obsolete
/// job is waited for.
detached: Vec<Receiver<Job>>,
/// The running job builds a tool alone (for a join, cut or intersect).
running_tool: bool,
/// Inputs of a joint or distance preview, excluding only its driven values.
@@ -137,7 +150,7 @@ impl PreviewState {
fn clear(&mut self) {
self.straight.clear();
self.moving.clear();
self.running = None;
self.detach();
self.running_tool = false;
self.running_stream_key = None;
self.shown_key = None;
@@ -155,8 +168,9 @@ impl PreviewState {
/// keeps drawing the last scene it took until the slot it reads hands it another, so a fresh
/// state (another slot, empty) would leave the old preview drawn over the next design.
pub fn reset(&mut self) {
let (slot, key) = (std::mem::take(&mut self.slot), self.key);
*self = PreviewState { slot, key, ..PreviewState::default() };
self.detach();
let (slot, key, detached) = (std::mem::take(&mut self.slot), self.key, std::mem::take(&mut self.detached));
*self = PreviewState { slot, key, detached, ..PreviewState::default() };
self.set_scene(GpuScene::default());
}
@@ -224,6 +238,32 @@ impl PreviewState {
}
}
}
// A detached job's result is never shown: drop it once it is done.
self.detached.retain(|rx| matches!(rx.try_recv(), Err(TryRecvError::Empty)));
// The inputs moved to another setup (another selection, for the features whose distance,
// radius or pose streams) while a job runs: its result could only be dropped, so stop
// waiting for it and let the current inputs start now (#7167). A tool, or a value
// streaming within one setup, still shows each finished result; inputs that don't stream
// wait as before. At most `DETACHED` jobs are left behind; while they run, the next
// obsolete one is waited for as before.
let other_setup = !self.running_tool && stream_key.is_some() && self.running_stream_key.is_some() && self.running_stream_key != stream_key;
if self.running.as_ref().is_some_and(|(k, _)| *k != key) && other_setup && self.detached.len() < DETACHED {
self.detach();
}
}
/// Stop waiting for the running job: ask it to stop between features, and count it among the
/// detached jobs until its thread ends (also when a closed dialog or another design leaves it
/// behind, so `DETACHED` bounds what runs).
fn detach(&mut self) {
if let Some(progress) = self.running_progress.take() {
progress.cancel();
}
if let Some((_, rx)) = self.running.take() {
self.detached.push(rx);
}
self.running_tool = false;
self.running_stream_key = None;
}
}
@@ -348,7 +388,7 @@ pub fn update(app: &mut SolveApp, ctx: &egui::Context) {
return;
}
let scratch = app.session.scratch();
spawn(&mut app.preview, key, scratch, cmds, colors, tool);
spawn(&mut app.preview, key, scratch, cmds, colors, tool, Arc::new(Progress::default()));
}
app.preview.busy = app.preview.running.is_some();
if app.preview.busy {
@@ -368,14 +408,20 @@ fn job_key(cmds: &[(String, Value)], revision: u64, colors: Colors) -> u64 {
/// Start computing the preview of `cmds`: for a tool feature (`tool`), only its tool.
#[cfg(not(target_arch = "wasm32"))]
fn spawn(pv: &mut PreviewState, key: u64, scratch: Session, cmds: Vec<(String, Value)>, colors: Colors, tool: bool) {
fn spawn(pv: &mut PreviewState, key: u64, scratch: Session, cmds: Vec<(String, Value)>, colors: Colors, tool: bool, progress: Arc<Progress>) {
let (tx, rx) = std::sync::mpsc::channel();
// Watched by `progress`, so a job left behind for other inputs skips its remaining features.
let watched = progress.clone();
let spawned = std::thread::Builder::new().name("preview".into()).spawn(move || {
let _ = tx.send(if tool { compute_tool(&scratch, &cmds, colors) } else { compute(&scratch, &cmds, colors) });
let job = solidcraft_engine::doc::progress::watch(watched, || {
if tool { compute_tool(&scratch, &cmds, colors) } else { compute(&scratch, &cmds, colors) }
});
let _ = tx.send(job);
});
match spawned {
Ok(_) => {
pv.running = Some((key, rx));
pv.running_progress = Some(progress);
pv.running_tool = tool;
}
Err(e) => pv.apply(key, Err(e.to_string())),
@@ -384,7 +430,7 @@ fn spawn(pv: &mut PreviewState, key: u64, scratch: Session, cmds: Vec<(String, V
/// No threads on the web: compute right away.
#[cfg(target_arch = "wasm32")]
fn spawn(pv: &mut PreviewState, key: u64, scratch: Session, cmds: Vec<(String, Value)>, colors: Colors, tool: bool) {
fn spawn(pv: &mut PreviewState, key: u64, scratch: Session, cmds: Vec<(String, Value)>, colors: Colors, tool: bool, _progress: Arc<Progress>) {
pv.apply(key, if tool { compute_tool(&scratch, &cmds, colors) } else { compute(&scratch, &cmds, colors) });
}
+116
View File
@@ -175,3 +175,119 @@ fn fillet_preview_keeps_moving_while_its_radius_changes() {
assert!(pv.running.is_none());
}
}
/// Edges picked one after another (#7167): the preview of the previous selection, still
/// running, is left behind and asked to stop, so the current selection's starts at once instead
/// of after it. `DETACHED` jobs are left behind at most: while they run, the next obsolete one is
/// waited for. A radius changing on the same edges still streams (above).
#[test]
fn a_new_selection_does_not_wait_for_the_previous_selections_preview() {
let s = Session::default();
let picks: Vec<Vec<(String, Value)>> = (1..=DETACHED + 2)
.map(|n| {
let edges: Vec<Value> = (0..n).map(|i| json!([5, i, 10])).collect();
vec![("solid.fillet".into(), json!({"edges":edges,"radius":1.0}))]
})
.collect();
let keys = |c: &[(String, Value)]| (job_key(c, s.revision, colors()), stream_key(c, s.revision, colors()));
let running = |pv: &mut PreviewState, c: &[(String, Value)]| {
let (tx, rx) = std::sync::mpsc::channel::<Job>();
let progress = Arc::new(Progress::default());
pv.running = Some((keys(c).0, rx));
pv.running_progress = Some(progress.clone());
pv.running_stream_key = keys(c).1;
(tx, progress)
};
let mut pv = PreviewState::default();
let mut left = Vec::new();
for (n, next) in picks[1..=DETACHED].iter().enumerate() {
let job = running(&mut pv, &picks[n]);
let (key, stream) = keys(next);
pv.poll(key, stream);
assert!(pv.running.is_none(), "selection {} can start at once", n + 2);
assert!(job.1.is_cancelled() && pv.detached.len() == n + 1, "the obsolete job is asked to stop and counted");
left.push(job);
}
let (_tx, waited) = running(&mut pv, &picks[DETACHED]);
let (key, stream) = keys(&picks[DETACHED + 1]);
pv.poll(key, stream);
assert!(pv.running.is_some() && !waited.is_cancelled(), "with {DETACHED} jobs left behind, the next obsolete one is waited for");
// One that was left behind ends: its result is dropped and its place is free again.
left[0].0.send(Err("stopped".into())).unwrap();
pv.poll(key, stream);
assert!(pv.detached.len() == DETACHED && waited.is_cancelled(), "the waited one is left behind in turn");
assert!(pv.running.is_none() && pv.shown_key.is_none() && pv.error.is_none(), "no obsolete result is shown");
// A radius changing on the same edges is the same setup: the running job is kept.
let mut pv = PreviewState::default();
let (_tx, progress) = running(&mut pv, &picks[0]);
let mut bigger = picks[0].clone();
bigger[0].1["radius"] = json!(2.0);
let (key, stream) = keys(&bigger);
pv.poll(key, stream);
assert!(pv.running.is_some() && !progress.is_cancelled() && pv.detached.is_empty());
// A tool, and inputs that don't stream (no stream key), are waited for as before.
let (key, _) = keys(&picks[1]);
for (tool, stream) in [(true, keys(&picks[1]).1), (false, None)] {
let mut pv = PreviewState::default();
let (_tx, progress) = running(&mut pv, &picks[0]);
pv.running_tool = tool;
pv.poll(key, stream);
assert!(pv.running.is_some() && !progress.is_cancelled() && pv.detached.is_empty(), "tool {tool}, stream {stream:?}");
}
// A dialog closed with jobs left behind still counts the one it leaves (it keeps running),
// so no further one is left behind until they end; one that ends without a result too.
let mut pv = PreviewState::default();
let mut senders = Vec::new();
for n in 0..DETACHED {
let (tx, _) = running(&mut pv, &picks[n]);
let (key, stream) = keys(&picks[n + 1]);
pv.poll(key, stream);
senders.push(tx);
}
let (tx, progress) = running(&mut pv, &picks[DETACHED]);
pv.clear();
assert!(progress.is_cancelled() && pv.detached.len() == DETACHED + 1, "the closed dialog's job is counted");
let (_tx, waited) = running(&mut pv, &picks[0]);
let (key, stream) = keys(&picks[1]);
pv.poll(key, stream);
assert!(pv.running.is_some() && !waited.is_cancelled(), "over the limit, the next obsolete job is waited for");
drop(senders);
drop(tx);
pv.poll(key, stream);
assert!(waited.is_cancelled() && pv.detached.len() == 1, "jobs that ended without a result free their places");
}
/// The job `spawn` starts is the one a newer selection asks to stop (#7167): held before its
/// feature, it is left behind, skips it once cancelled and ends; its result is never shown.
#[test]
fn a_preview_left_behind_stops_before_its_next_feature() {
let mut s = Session::new(solidcraft_engine::doc::Document::new("Left behind"));
s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap();
let fillet = s.execute("solid.fillet", &json!({"edges":[[5,0,10]],"radius":1.0})).unwrap()["feature"].as_u64().unwrap();
let redefine = |edges: Value| {
vec![("timeline.redefine".to_string(), json!({"feature":fillet,"command":"solid.fillet","params":{"edges":edges,"radius":2.0}}))]
};
let (first, second) = (redefine(json!([[5, 0, 10]])), redefine(json!([[5, 0, 10], [0, 5, 10]])));
let keys = |c: &[(String, Value)]| (job_key(c, s.revision, colors()), stream_key(c, s.revision, colors()));
assert!(keys(&first).1.is_some() && keys(&first).1 != keys(&second).1, "another selection is another setup");
let mut pv = PreviewState::default();
let progress = Arc::new(Progress::default());
// The job waits before the fillet (feature 1) until it is cancelled.
progress.hold_at(1);
pv.running_stream_key = keys(&first).1;
spawn(&mut pv, keys(&first).0, s.scratch(), first, colors(), false, progress.clone());
let (key, stream) = keys(&second);
pv.poll(key, stream);
assert!(progress.is_cancelled() && pv.running.is_none() && pv.detached.len() == 1, "left behind and asked to stop");
let t0 = std::time::Instant::now();
while !pv.detached.is_empty() {
assert!(t0.elapsed() < std::time::Duration::from_secs(30), "the held job did not stop");
std::thread::sleep(std::time::Duration::from_millis(5));
pv.poll(key, stream);
}
assert!(pv.shown_key.is_none() && !pv.active && pv.error.is_none(), "its result is never shown");
}
+4 -1
View File
@@ -114,7 +114,10 @@ completed drawings publish atomically. The browser still exports synchronously.
- New Body extrusion and face-offset previews show completed intermediate geometry while a
drag continues, then catch up to the exact final value. Changes to the selected geometry,
operation or feature still discard obsolete results. Distance arrows and their value boxes
follow the current frame's input.
follow the current frame's input. When the selection changes while a preview computes (the
next edge picked for a fillet or chamfer), the new selection's preview starts at once: the
obsolete one is asked to stop and its result is dropped, with at most two left running
(#7167).
- Large fine modelled threads use pitch-based helix resolution and tighter faceted
reconstruction fallbacks, preserving thin crests and closed shells on large shafts.