Desktop: one design's long kernel call no longer stops other designs (#11684)
solidcraft-smlib held one process-wide kernel lock for the whole of every solidcore call, so a long call in one design (a modeled thread, a fillet) held up every kernel call in every other design, even after its tab was closed, and a call that never returned held them until restart. Each call now takes a kernel from a pool and the lock is only held to take or put one back. Calls one after another get the same kernel as before; one that starts while another runs gets its own. Each kernel has its own range of procedural blend serials, since a body keeps the serials of the kernel that made it. History commands and delete checks now belong to their design: they wait with its tab, go when it closes, and can't land in another design. An agent's command for a design that left the window is refused at once instead of holding up the requests behind it. Closes #11681 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+39
-10
@@ -6,6 +6,7 @@
|
||||
//! fork fixed in its own sources; each one turned on here says which fork commit it matches.
|
||||
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
use solidcore::geom::attribute::{AttributeStore, ObjectKey};
|
||||
@@ -409,15 +410,43 @@ pub(crate) fn fixes() -> UpstreamFixes {
|
||||
#[cfg(test)]
|
||||
const HELD_BACK: &[&str] = &["fillet_refuse_rounds_breaking_through"];
|
||||
|
||||
/// How far apart two kernels' procedural blend serials start. A body keeps the serials of the
|
||||
/// kernel that made it and may be used on any other, whose memo of solved stations is keyed by
|
||||
/// serial alone: the ranges keep one definition's stations from answering for another's.
|
||||
pub(crate) const BLEND_SERIALS_PER_KERNEL: u64 = 1 << 40;
|
||||
|
||||
/// A new kernel. Each takes the next range of blend serials, the first starting at 0.
|
||||
fn fresh() -> Kernel {
|
||||
static MADE: AtomicU64 = AtomicU64::new(0);
|
||||
let mut k = Kernel::new(&KernelOptions::default());
|
||||
k.fixes = fixes();
|
||||
k.blend_last_serial.set(MADE.fetch_add(1, Ordering::Relaxed).wrapping_mul(BLEND_SERIALS_PER_KERNEL));
|
||||
k
|
||||
}
|
||||
|
||||
pub(crate) static KERNEL: Mutex<Option<Kernel>> = Mutex::new(None);
|
||||
/// Most kernels kept for later calls; those over it are dropped when their call ends.
|
||||
const MOST_IDLE: usize = 8;
|
||||
|
||||
/// Runs `f` on the process's kernel. A panic in solidcore is caught: the kernel, which it may have
|
||||
/// The kernels no call is using, the last used on top. The lock is only held to take or put back
|
||||
/// a kernel, never during a call: a call that runs long (or never returns) holds up nothing but
|
||||
/// its own body, so one design's long operation never delays another's. Calls one after another
|
||||
/// all get the same kernel, as a single kernel would serve them; one that starts while another
|
||||
/// runs gets one of its own (solidcore keeps no global state, and a body's identities are valid
|
||||
/// only in the kernel that issued them, so any kernel takes any body).
|
||||
static IDLE: Mutex<Vec<Kernel>> = Mutex::new(Vec::new());
|
||||
|
||||
fn take_kernel() -> Kernel {
|
||||
IDLE.lock().unwrap_or_else(PoisonError::into_inner).pop().unwrap_or_else(fresh)
|
||||
}
|
||||
|
||||
fn put_kernel(k: Kernel) {
|
||||
let mut idle = IDLE.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if idle.len() < MOST_IDLE {
|
||||
idle.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` on a kernel of its own. A panic in solidcore is caught: the kernel, which it may have
|
||||
/// left half-updated, is replaced by a fresh one and the call fails with [`Error::Internal`].
|
||||
pub(crate) fn run<T: dump::Answer>(call: &'static str, f: impl FnOnce(&mut Kernel) -> std::result::Result<T, solidcore::SolidError>) -> Result<T> {
|
||||
run_on(call, &[], f)
|
||||
@@ -441,11 +470,10 @@ pub(crate) fn run_on<T: dump::Answer>(
|
||||
inputs: dump::Inputs<'_>,
|
||||
f: impl FnOnce(&mut Kernel) -> std::result::Result<T, solidcore::SolidError>,
|
||||
) -> Result<T> {
|
||||
let mut guard = KERNEL.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let k = guard.get_or_insert_with(fresh);
|
||||
let mut k = take_kernel();
|
||||
// A profiler span per call: where the kernel's time goes.
|
||||
let _span = solidcraft_profile::span("solidcore", call);
|
||||
dump::set_current(Some(call));
|
||||
let in_flight = dump::in_flight(call);
|
||||
struct Depth;
|
||||
impl Drop for Depth {
|
||||
fn drop(&mut self) {
|
||||
@@ -454,27 +482,28 @@ pub(crate) fn run_on<T: dump::Answer>(
|
||||
}
|
||||
IN_CALL.with(|d| d.set(d.get() + 1));
|
||||
let depth = Depth;
|
||||
let caught = catch_unwind(AssertUnwindSafe(|| f(k)));
|
||||
let caught = catch_unwind(AssertUnwindSafe(|| f(&mut k)));
|
||||
drop(depth);
|
||||
let r = match caught {
|
||||
Ok(Ok(v)) => Ok(v),
|
||||
Ok(Err(e)) => Err(Error::Solidcore(format!("{call}: {e}"))),
|
||||
Err(p) => {
|
||||
*guard = Some(fresh());
|
||||
k = fresh();
|
||||
let why = p.downcast_ref::<&str>().map(|s| (*s).to_owned()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_default();
|
||||
log::warn!(target: "smlib", "solidcore panicked in {call}: {why}");
|
||||
Err(Error::Internal(format!("{call}: {why}")))
|
||||
}
|
||||
};
|
||||
dump::set_current(None);
|
||||
drop(in_flight);
|
||||
let why = match &r {
|
||||
Ok(v) => v.refusal(),
|
||||
Err(e) => Some(e.to_string()),
|
||||
};
|
||||
if let Some(why) = why {
|
||||
// The kernel the call ran on, or the fresh one that replaced it after a panic.
|
||||
dump::failed(guard.get_or_insert_with(fresh), call, &why, inputs);
|
||||
dump::failed(&k, call, &why, inputs);
|
||||
}
|
||||
put_kernel(k);
|
||||
r
|
||||
}
|
||||
|
||||
@@ -491,7 +520,7 @@ pub(crate) fn answer<T>(r: std::result::Result<T, solidcore::SolidError>) -> std
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` on the kernel and `body`, locking the kernel first.
|
||||
/// Runs `f` on a kernel and `body`, its lock held for the call.
|
||||
pub(crate) fn with_body<T: dump::Answer>(
|
||||
call: &'static str,
|
||||
body: &Body,
|
||||
|
||||
@@ -604,7 +604,7 @@ pub(super) fn finish(b: Brep, solid_in: bool) -> solidcore::Result<Out<Brep>> {
|
||||
Ok(Ok(b))
|
||||
}
|
||||
|
||||
/// Runs `f` on a copy of `body` (`brep_copy`) under the kernel's lock.
|
||||
/// Runs `f` on a copy of `body` (`brep_copy`).
|
||||
pub(super) fn on_copy(call: &'static str, body: &Body, f: impl FnOnce(&mut Kernel, Brep) -> solidcore::Result<Out<Brep>>) -> Result<Body> {
|
||||
if body.0.is_poisoned() {
|
||||
return Err(Error::Internal(format!("{call}: the body was left unfinished by an earlier panic")));
|
||||
|
||||
@@ -92,9 +92,9 @@ fn operands<'a>(bodies: &[&'a Body]) -> Vec<(&'static str, &'a Body)> {
|
||||
}
|
||||
|
||||
/// Copies of `bodies`, in order (a body given twice is copied twice, as the capi copies each
|
||||
/// operand), all made under the kernel's lock.
|
||||
/// operand).
|
||||
fn copies(k: &mut Kernel, bodies: &[&Body]) -> SolidResult<Vec<Brep>> {
|
||||
// Under the kernel's lock (`run` holds it), as every body lock is: two never deadlock.
|
||||
// One body's lock at a time, here as everywhere: two calls never deadlock on them.
|
||||
let mut out = Vec::with_capacity(bodies.len());
|
||||
for b in bodies {
|
||||
let c = brep_copy(k, &b.0.lock().unwrap_or_else(PoisonError::into_inner))?;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! fails, so a call that answers costs nothing more than it would with no folder.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
use solidcore::kernel::Kernel;
|
||||
@@ -90,6 +90,7 @@ plain!(
|
||||
bool,
|
||||
f64,
|
||||
usize,
|
||||
[usize; 2],
|
||||
[usize; 3],
|
||||
([f64; 3], [f64; 3]),
|
||||
Vec<u8>,
|
||||
@@ -103,30 +104,30 @@ plain!(
|
||||
|
||||
impl<T> Answer for Option<T> {}
|
||||
|
||||
/// The longest call name [`current`] gives.
|
||||
const NAME_MAX: usize = 96;
|
||||
static NAME: [AtomicU8; NAME_MAX] = [const { AtomicU8::new(0) }; NAME_MAX];
|
||||
static NAME_LEN: AtomicUsize = AtomicUsize::new(0);
|
||||
/// The calls running now, in the order they started.
|
||||
static IN_FLIGHT: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
|
||||
|
||||
/// `call` is running now (`None`: none is). One at a time, under the kernel's lock.
|
||||
pub(super) fn set_current(call: Option<&str>) {
|
||||
NAME_LEN.store(0, Ordering::SeqCst);
|
||||
let Some(call) = call else { return };
|
||||
let bytes = call.as_bytes();
|
||||
let n = bytes.len().min(NAME_MAX);
|
||||
for (slot, b) in NAME.iter().zip(bytes) {
|
||||
slot.store(*b, Ordering::Relaxed);
|
||||
/// A call in [`current`]'s list until dropped.
|
||||
pub(super) struct InFlight(&'static str);
|
||||
|
||||
impl Drop for InFlight {
|
||||
fn drop(&mut self) {
|
||||
let mut calls = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(at) = calls.iter().position(|c| *c == self.0) {
|
||||
calls.remove(at);
|
||||
}
|
||||
}
|
||||
NAME_LEN.store(n, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// The call running now. Takes no lock, for crash reports, so it may be cut short or mixed with the
|
||||
/// next call's name if read just as one starts.
|
||||
/// `call` is running from now until the answer is dropped.
|
||||
pub(super) fn in_flight(call: &'static str) -> InFlight {
|
||||
IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).push(call);
|
||||
InFlight(call)
|
||||
}
|
||||
|
||||
/// The calls running now, joined by commas. Never waits, for crash reports: `None` as well if a
|
||||
/// call is starting or ending at this very moment.
|
||||
pub(crate) fn current() -> Option<String> {
|
||||
let n = NAME_LEN.load(Ordering::SeqCst);
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
let bytes: Vec<u8> = NAME.iter().take(n).map(|b| b.load(Ordering::Relaxed)).collect();
|
||||
Some(String::from_utf8_lossy(&bytes).into_owned())
|
||||
let calls = IN_FLIGHT.try_lock().ok()?;
|
||||
(!calls.is_empty()).then(|| calls.join(", "))
|
||||
}
|
||||
|
||||
+113
-7
@@ -8,7 +8,6 @@ fn box_end_to_end() {
|
||||
let c = b.try_clone().unwrap();
|
||||
drop(b);
|
||||
assert!((c.volume(1e-7).unwrap() - 6000.0).abs() < 1e-6);
|
||||
assert_eq!(current_call(), None, "no call in flight between calls");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -321,12 +320,8 @@ fn a_failing_solidcore_call_leaves_a_dump_and_names_itself() {
|
||||
});
|
||||
core::dump::set_dir(None);
|
||||
assert!(r.is_err());
|
||||
assert_eq!(seen.lock().unwrap().as_deref(), Some("smlib_test_failure"));
|
||||
{
|
||||
// Under the kernel's lock no solidcore call is in flight.
|
||||
let _kernel = core::KERNEL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
assert_eq!(core::dump::current(), None);
|
||||
}
|
||||
assert!(seen.lock().unwrap().as_deref().is_some_and(|c| c.contains("smlib_test_failure")), "{seen:?}");
|
||||
assert!(!core::dump::current().is_some_and(|c| c.contains("smlib_test_failure")), "no longer in flight");
|
||||
let got: Vec<String> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
let text = got.iter().find(|n| n.ends_with("-smlib_test_failure.txt")).unwrap_or_else(|| panic!("{got:?}"));
|
||||
assert!(std::fs::read_to_string(dir.join(text)).unwrap().contains("refused"));
|
||||
@@ -404,3 +399,114 @@ fn an_edge_a_few_um_past_its_patch_keeps_its_interval() {
|
||||
let [u, v] = solidcraft_geom::brep::pcurve::eval(pc, 1.0).unwrap();
|
||||
assert!((u - 1.0).abs() < 1e-9 && v.abs() < 1e-9, "{u} {v}");
|
||||
}
|
||||
|
||||
/// A solidcore call blocked on a channel until `release`, on its own thread: a call that runs long
|
||||
/// or never returns, as one design's slow operation does.
|
||||
fn call_held_open(body: &str) -> (std::sync::mpsc::Sender<()>, std::thread::JoinHandle<Result<()>>) {
|
||||
let call: &'static str = Box::leak(body.to_owned().into_boxed_str());
|
||||
let (started, is_started) = std::sync::mpsc::channel();
|
||||
let (release, released) = std::sync::mpsc::channel::<()>();
|
||||
let held = std::thread::spawn(move || {
|
||||
core::run(call, |_| {
|
||||
let _ = started.send(());
|
||||
let _ = released.recv();
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
is_started.recv().unwrap();
|
||||
(release, held)
|
||||
}
|
||||
|
||||
/// Runs `f` on another thread and gives its answer; a failure here rather than a test that hangs
|
||||
/// when `f` waits for a call that does not end. The limit is no measure of speed: `f` is free to
|
||||
/// take all of it, and only a wait with no end fails.
|
||||
fn answered<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(f());
|
||||
});
|
||||
rx.recv_timeout(std::time::Duration::from_secs(120)).expect("this call waited for a call on another thread that has not ended")
|
||||
}
|
||||
|
||||
/// One design's long kernel call must never hold up another's: the kernel call of a design closed
|
||||
/// or still open, blocked here on a channel, while another makes and measures a body of its own.
|
||||
#[test]
|
||||
fn a_kernel_call_that_does_not_end_holds_up_no_other_call() {
|
||||
let (release, held) = call_held_open("held_open");
|
||||
let volume = answered(|| {
|
||||
let a = Brep::make_box([0.0; 3], [10.0; 3]).unwrap();
|
||||
let b = Brep::make_box([5.0, 0.0, 0.0], [10.0; 3]).unwrap();
|
||||
a.boolean(&b, BooleanOp::Union).unwrap().unwrap().volume(1e-7).unwrap()
|
||||
});
|
||||
assert!((volume - 1500.0).abs() < 1e-6, "{volume}");
|
||||
assert!(current_call().is_some_and(|c| c.contains("held_open")), "the call still runs");
|
||||
// And one holds up no other held open beside it.
|
||||
let (release_too, held_too) = call_held_open("held_open_too");
|
||||
assert!(current_call().is_some_and(|c| c.contains("held_open") && c.contains("held_open_too")));
|
||||
for (release, held) in [(release, held), (release_too, held_too)] {
|
||||
release.send(()).unwrap();
|
||||
held.join().unwrap().unwrap();
|
||||
}
|
||||
assert!(!current_call().is_some_and(|c| c.contains("held_open")), "neither is in flight any more");
|
||||
}
|
||||
|
||||
/// Bodies are made and used on whichever kernel is free, at the same time on several threads, and
|
||||
/// each answer is the one a single kernel gives: a body made while another call held the first
|
||||
/// kernel is used once it is free, and two bodies from different kernels go into one boolean.
|
||||
#[test]
|
||||
fn bodies_move_between_kernels_and_calls_run_side_by_side() {
|
||||
let (release, held) = call_held_open("held_open");
|
||||
let on_second = answered(|| Brep::make_box([5.0, 0.0, 0.0], [10.0; 3]).unwrap());
|
||||
release.send(()).unwrap();
|
||||
held.join().unwrap().unwrap();
|
||||
let first = Brep::make_box([0.0; 3], [10.0; 3]).unwrap();
|
||||
let v = first.boolean(&on_second, BooleanOp::Subtract).unwrap().unwrap().volume(1e-7).unwrap();
|
||||
assert!((v - 500.0).abs() < 1e-6, "{v}");
|
||||
|
||||
let shared = std::sync::Arc::new(Brep::make_box([0.0; 3], [10.0; 3]).unwrap());
|
||||
let workers: Vec<_> = (0..8)
|
||||
.map(|n| {
|
||||
let shared = shared.clone();
|
||||
std::thread::spawn(move || {
|
||||
for i in 0..20 {
|
||||
let side = 2.0 + f64::from((n + i) % 5);
|
||||
let tool = Brep::make_box([10.0 - side; 3], [side + 1.0; 3]).unwrap();
|
||||
let cut = shared.boolean(&tool, BooleanOp::Subtract).unwrap().unwrap();
|
||||
let rounded = Brep::make_box([0.0; 3], [10.0; 3]).unwrap().fillet(&[[5.0, 0.0, 0.0]], 1e-6, 1.0).unwrap();
|
||||
let lost = (1.0 - std::f64::consts::FRAC_PI_4) * 10.0;
|
||||
assert!((cut.volume(1e-7).unwrap() - (1000.0 - side.powi(3))).abs() < 1e-5);
|
||||
assert!((rounded.volume(1e-7).unwrap() - (1000.0 - lost)).abs() < 1e-4);
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for worker in workers {
|
||||
answered(move || worker.join().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
/// Each kernel has its own range of blend serials: a body keeps the serials of the kernel that
|
||||
/// made it, and another kernel's memo of solved stations must not take them for its own.
|
||||
#[test]
|
||||
fn kernels_never_issue_the_same_blend_serial() {
|
||||
let range = core::BLEND_SERIALS_PER_KERNEL as usize;
|
||||
let ranges = core::run("outer", |outer| {
|
||||
let inner = core::run("inner", |inner| Ok(inner.blend_last_serial.get() as usize)).unwrap_or_default();
|
||||
Ok([outer.blend_last_serial.get() as usize / range, inner / range])
|
||||
});
|
||||
let [outer, inner] = ranges.unwrap();
|
||||
assert_ne!(outer, inner);
|
||||
}
|
||||
|
||||
/// A panic in a call running beside another costs neither: the panicking call's kernel is thrown
|
||||
/// away and the other call and later ones go on.
|
||||
#[test]
|
||||
fn a_panic_beside_a_running_call_costs_only_its_own_kernel() {
|
||||
let (release, held) = call_held_open("held_open");
|
||||
let r: Result<()> = core::run("panicking", |_| panic!("on purpose"));
|
||||
assert!(matches!(r, Err(Error::Internal(_))), "{r:?}");
|
||||
let v = answered(|| Brep::make_box([0.0; 3], [2.0; 3]).unwrap().volume(1e-7).unwrap());
|
||||
assert!((v - 8.0).abs() < 1e-6, "{v}");
|
||||
release.send(()).unwrap();
|
||||
held.join().unwrap().unwrap();
|
||||
}
|
||||
|
||||
@@ -135,6 +135,19 @@ pub(crate) fn changes_the_design(method: &str) -> bool {
|
||||
matches!(method, "engine.execute" | "command" | "engine.script" | "engine.batch")
|
||||
}
|
||||
|
||||
/// Whether `doc` is the design `session` shows, as it is or edited since (an undo step away).
|
||||
fn shows_design(session: &solidcraft_engine::Session, doc: &Arc<solidcraft_engine::doc::Document>) -> bool {
|
||||
Arc::ptr_eq(&session.doc, doc) || session.undo.iter().chain(&session.redo).any(|snap| Arc::ptr_eq(&snap.doc, doc))
|
||||
}
|
||||
|
||||
/// The reply to a request whose design left the window while it computed.
|
||||
fn design_replaced(label: &str) -> Value {
|
||||
json!({
|
||||
"ok": false,
|
||||
"error": format!("the design was replaced (another tab, or a file opened) while `{label}` computed; nothing was applied"),
|
||||
})
|
||||
}
|
||||
|
||||
/// What a request computes off the window thread.
|
||||
enum Work {
|
||||
/// Evaluated ahead: once in, the request runs here. `doc` and `revision` are the design it
|
||||
@@ -490,6 +503,16 @@ impl SolveApp {
|
||||
self.control_job = None;
|
||||
return;
|
||||
}
|
||||
// The design it computes for has left the window (closed, another tab, a file opened):
|
||||
// refused now, however long its computation has left, so the requests behind it, which
|
||||
// are for the design shown, don't wait for it.
|
||||
let left = matches!(&job.work, Work::Ahead { doc, .. } if !shows_design(&self.session, doc));
|
||||
if left {
|
||||
if let Some(job) = self.control_job.take() {
|
||||
let _ = job.req.reply.send(design_replaced(&job.label));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if job.poll().is_none() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
return;
|
||||
@@ -503,13 +526,8 @@ impl SolveApp {
|
||||
let Work::Ahead { commands, doc, revision, tries, kept } = job.work else { return };
|
||||
let s = &self.session;
|
||||
let same = Arc::ptr_eq(&s.doc, &doc);
|
||||
// The design it was computed for is still this one, edited since (an undo step away).
|
||||
let edited = !same && s.undo.iter().chain(&s.redo).any(|snap| Arc::ptr_eq(&snap.doc, &doc));
|
||||
if !same && !edited {
|
||||
let _ = job.req.reply.send(json!({
|
||||
"ok": false,
|
||||
"error": format!("the design was replaced (another tab, or a file opened) while `{}` computed; nothing was applied", job.label),
|
||||
}));
|
||||
if !shows_design(s, &doc) {
|
||||
let _ = job.req.reply.send(design_replaced(&job.label));
|
||||
return;
|
||||
}
|
||||
if (!same || s.revision != revision) && tries < MAX_TRIES {
|
||||
|
||||
@@ -63,6 +63,17 @@ impl Deferred {
|
||||
}
|
||||
}
|
||||
|
||||
/// What one design has computing off the window thread or waiting its turn. It belongs to that
|
||||
/// design: it waits with its tab while another is shown, holds up nothing there, and goes when
|
||||
/// the design closes (the worker runs on to its end and its result is dropped).
|
||||
#[derive(Default)]
|
||||
pub struct DocJobs {
|
||||
deferred: Option<Deferred>,
|
||||
queue: Vec<(String, Value)>,
|
||||
start_after_roll: Option<(String, u64)>,
|
||||
delete_check: Option<DeleteCheck>,
|
||||
}
|
||||
|
||||
/// How a command asked to run off the window thread goes.
|
||||
enum Start {
|
||||
/// It computes off the window thread.
|
||||
@@ -133,6 +144,32 @@ fn replaced_by_a_later_one(id: &str) -> bool {
|
||||
}
|
||||
|
||||
impl SolveApp {
|
||||
/// Swap the active design's [`DocJobs`] for `incoming`, the jobs of the design taking its
|
||||
/// place, and hand back the outgoing ones.
|
||||
pub(crate) fn swap_jobs(&mut self, incoming: DocJobs) -> DocJobs {
|
||||
DocJobs {
|
||||
deferred: std::mem::replace(&mut self.deferred, incoming.deferred),
|
||||
queue: std::mem::replace(&mut self.deferred_queue, incoming.queue),
|
||||
start_after_roll: std::mem::replace(&mut self.start_after_roll, incoming.start_after_roll),
|
||||
delete_check: std::mem::replace(&mut self.delete_check, incoming.delete_check),
|
||||
}
|
||||
}
|
||||
|
||||
/// The active design's revision moved from `before` to `after` only to refresh the views
|
||||
/// (a tab shown again): its jobs were not computed for an older design.
|
||||
pub(crate) fn jobs_view_changed(&mut self, before: u64, after: u64) {
|
||||
if let Some(job) = &mut self.deferred
|
||||
&& job.revision == before
|
||||
{
|
||||
job.revision = after;
|
||||
}
|
||||
if let Some(check) = &mut self.delete_check
|
||||
&& check.revision == before
|
||||
{
|
||||
check.revision = after;
|
||||
}
|
||||
}
|
||||
|
||||
/// A direct exit or editor switch supersedes any queued sketch exit. A late worker must
|
||||
/// never finish a different sketch that was opened while it computed.
|
||||
pub(crate) fn take_sketch_exit(&mut self) -> Option<String> {
|
||||
|
||||
@@ -52,6 +52,8 @@ pub struct DocSlot {
|
||||
edit_in_place: Option<crate::edit_in_place::PartContext>,
|
||||
/// The dialog or tool it had open and its toolbar tab, kept while another design is shown.
|
||||
work: DocWork,
|
||||
/// What it has computing off the window thread or waiting its turn.
|
||||
jobs: crate::deferred::DocJobs,
|
||||
}
|
||||
|
||||
/// What a design was doing when its tab was left, with the "Keep dialogs and tools open when
|
||||
@@ -143,6 +145,7 @@ impl DocSlot {
|
||||
link_stamps: Vec::new(),
|
||||
edit_in_place: None,
|
||||
work: DocWork::default(),
|
||||
jobs: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,6 +251,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot {
|
||||
link_stamps: std::mem::replace(&mut app.docs.link_stamps, slot.link_stamps),
|
||||
edit_in_place: std::mem::replace(&mut app.edit_in_place.active, slot.edit_in_place),
|
||||
work,
|
||||
jobs: app.swap_jobs(slot.jobs),
|
||||
};
|
||||
// Only the displayed design owns the process-wide crash replay journal.
|
||||
app.session.crash_journal = out.session.crash_journal;
|
||||
@@ -267,6 +271,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot {
|
||||
if let Some(pending) = &mut app.pending_feature_edit {
|
||||
pending.view_changed(before, app.session.revision);
|
||||
}
|
||||
app.jobs_view_changed(before, app.session.revision);
|
||||
put_work(app, slot.work, before);
|
||||
out
|
||||
}
|
||||
@@ -544,6 +549,8 @@ pub fn close(app: &mut SolveApp, i: usize, force: bool) {
|
||||
if let Some(a) = app.autosave.as_mut().and_then(|a| a.active.take()) {
|
||||
a.discard();
|
||||
}
|
||||
// What it had computing goes with it: the blank design waits for none of it.
|
||||
app.cancel_computing();
|
||||
app.big_operation = false;
|
||||
crate::sketch_text_move::cancel_drag(app);
|
||||
let rev = app.session.revision;
|
||||
|
||||
@@ -680,6 +680,79 @@ fn an_agent_command_is_refused_when_its_design_was_replaced() {
|
||||
assert!(h.app.session.doc.features.is_empty(), "nothing went into the new design");
|
||||
}
|
||||
|
||||
/// The tab of a design whose command is still computing closes: the requests behind it are for
|
||||
/// the design shown now, and don't wait for a computation that may take minutes. The worker is
|
||||
/// held open here by an agent command that never finishes on this frame's clock: it is refused
|
||||
/// on the next frame, whether or not its result has come in.
|
||||
#[test]
|
||||
fn an_agent_command_for_a_closed_design_is_refused_at_once_and_holds_up_nothing() {
|
||||
let (mut h, tx) = agent_harness();
|
||||
let hole = ask(&tx, "engine.execute", second_hole());
|
||||
h.frames(1);
|
||||
assert!(h.app.agent_computing().is_some());
|
||||
crate::documents::close(&mut h.app, 0, true);
|
||||
h.frames(1);
|
||||
let r = hole.try_recv().expect("refused on the next frame");
|
||||
assert_eq!(r["ok"], false, "{r}");
|
||||
assert!(r["error"].as_str().is_some_and(|e| e.contains("replaced")), "{r}");
|
||||
assert!(h.app.agent_computing().is_none());
|
||||
let next = ask(&tx, "engine.execute", json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}}));
|
||||
assert_eq!(reply_to(&mut h, &next)["ok"], true);
|
||||
assert_eq!(h.app.session.doc.features.len(), 1, "only the new design's box");
|
||||
}
|
||||
|
||||
/// A history command of a design closed while it computes (the last tab: a blank design takes its
|
||||
/// place), and those waiting behind it, go with it: the new design starts with nothing computing,
|
||||
/// its Extrude from a finished sketch doesn't wait for them, and their late result is dropped.
|
||||
#[test]
|
||||
fn a_design_closed_while_its_history_computes_holds_up_nothing() {
|
||||
let mut h = block_boss_hole();
|
||||
let (job, late) = crate::deferred::Deferred::never_done("timeline.roll_to", json!({"position": 1}), h.app.session.revision);
|
||||
h.app.deferred = Some(job);
|
||||
h.app.deferred_queue.push(("timeline.roll_to".into(), json!({"position": 2})));
|
||||
h.app.start_after_roll = Some(("solid.extrude".into(), 1));
|
||||
crate::documents::close(&mut h.app, 0, true);
|
||||
assert!(h.app.computing_since().is_none(), "the blank design has nothing computing");
|
||||
assert!(h.app.deferred.is_none() && h.app.deferred_queue.is_empty() && h.app.start_after_roll.is_none());
|
||||
h.app.home.open = false;
|
||||
h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})).unwrap();
|
||||
h.app.start("solid.extrude");
|
||||
assert!(h.app.start_after_roll.is_none(), "the extrude waits for nothing");
|
||||
assert_eq!(h.app.dialog.as_ref().and_then(|d| d.command()), Some("solid.extrude"));
|
||||
assert!(late.send(None).is_err(), "nobody is left to take the closed design's result");
|
||||
h.frames(2);
|
||||
assert_eq!(h.app.dialog.as_ref().and_then(|d| d.command()), Some("solid.extrude"));
|
||||
}
|
||||
|
||||
/// A design's history command stays with its tab: another tab doesn't wait for it and doesn't get
|
||||
/// its result, even once it is in. Shown again, the design picks it up.
|
||||
#[test]
|
||||
fn a_history_command_stays_with_its_tab() {
|
||||
let mut h = block_boss_hole();
|
||||
let (job, done) = crate::deferred::Deferred::never_done("timeline.roll_to", json!({"position": 1}), h.app.session.revision);
|
||||
h.app.deferred = Some(job);
|
||||
h.app.deferred_queue.push(("timeline.roll_to".into(), json!({"position": 2})));
|
||||
|
||||
crate::documents::new_tab(&mut h.app);
|
||||
assert_eq!(h.app.docs.active, 1);
|
||||
assert!(h.app.computing_since().is_none(), "the new tab has nothing computing");
|
||||
assert!(h.app.deferred.is_none() && h.app.deferred_queue.is_empty());
|
||||
// The other design's command finishes while this one is shown: nothing lands here.
|
||||
done.send(None).unwrap();
|
||||
h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
|
||||
h.app.run_heavy("timeline.roll_to", json!({"position": 0})).unwrap();
|
||||
until_settled(&mut h);
|
||||
assert_eq!(h.app.session.doc.features.len(), 1, "this tab's box and nothing else");
|
||||
assert_eq!(marker(&h), Some(0), "this tab's own marker move ran at once");
|
||||
|
||||
crate::documents::switch(&mut h.app, 0);
|
||||
assert_eq!(h.app.deferred_queue.len(), 1, "the first tab's command and the one behind it came back with it");
|
||||
assert!(h.app.computing_since().is_some());
|
||||
until_settled(&mut h);
|
||||
assert_eq!(marker(&h), Some(2), "they ran on the design they were asked for");
|
||||
}
|
||||
|
||||
/// Stop answers the agent at once, applies nothing, and lets the requests behind it go on.
|
||||
#[test]
|
||||
fn stopping_an_agent_command_applies_nothing_and_goes_on() {
|
||||
|
||||
@@ -1463,6 +1463,8 @@ impl SolveApp {
|
||||
self.applying = None;
|
||||
self.editing_state = None;
|
||||
self.pending_feature_edit = None;
|
||||
// So does what it had computing: none of it may land in the new design.
|
||||
self.cancel_computing();
|
||||
self.tool = None;
|
||||
self.preview.reset();
|
||||
self.cam = Camera::default();
|
||||
|
||||
@@ -519,8 +519,8 @@ drawing and answering while it runs:
|
||||
design changes, from any connection, wait their turn and run in the order they arrived.
|
||||
- A person's edit made meanwhile goes first. The agent's command is then computed again for the
|
||||
design as it is and lands after that edit, never in the middle of it. If the design was replaced
|
||||
(another tab made active, a new file opened), the request fails with `… the design was
|
||||
replaced … nothing was applied`.
|
||||
(another tab made active, a new file opened, its tab closed), the request fails at once with
|
||||
`… the design was replaced … nothing was applied`, and the requests behind it go on.
|
||||
- A chip in the view names the command, with **Stop**. Stop answers
|
||||
`{"ok": false, "stopped": true, "error": "stopped: …; nothing was applied"}` and the requests
|
||||
waiting behind it go on. The computation finishes unseen in the background.
|
||||
|
||||
Reference in New Issue
Block a user