diff --git a/crates/engine/src/cmd/sketch_drag.rs b/crates/engine/src/cmd/sketch_drag.rs index d2fab7571..c1c8c851d 100644 --- a/crates/engine/src/cmd/sketch_drag.rs +++ b/crates/engine/src/cmd/sketch_drag.rs @@ -190,6 +190,7 @@ pub(super) fn drag_entity( solves.count += 1; solves.work += budget.spent() - spent; solves.cut |= budget.exhausted(); + solves.numeric |= budget.numeric_exhausted(); let outcome = if !ok { Step::Failed } else if last.sweep_wrapped(sk) { @@ -210,7 +211,15 @@ pub(super) fn drag_entity( let (mut base, mut dt, mut k, mut t) = (0.0, 1.0 / n as f64, 0, 0.0); let mut shortened = false; let mut wrapped = false; + let mut out_of_frame = false; 'walk: while t < 1.0 { + // A live frame whose numerical solves have done their share takes no more steps: the + // rest of the way waits for the next frame (`retry`), instead of seconds of held solves + // in this one, all failing where the geometry can't follow. + if solves.numeric { + out_of_frame = true; + break 'walk; + } if solves.cut && !shortened { shortened = true; let rest = 1.0 - t; @@ -251,7 +260,7 @@ pub(super) fn drag_entity( let fine = dt / HALVINGS as f64; let mut miss = t; let mut first = true; - while spare > 0 && miss - good > fine { + while spare > 0 && miss - good > fine && !solves.numeric { spare -= 1; let mid = if std::mem::take(&mut first) { good + fine } else { 0.5 * (good + miss) }; match step(sk, &last, mid, &mut solves) { @@ -305,7 +314,8 @@ pub(super) fn drag_entity( let d = to - start; if at.dist(to) < 1e-6 || d.dot(d) == 0.0 { 1.0 } else { ((at - start).dot(d) / d.dot(d)).clamp(0.0, 1.0) } }); - let retry = frame.as_ref().is_some_and(Budget::exhausted) && start.zip(at).is_some_and(|(a, b)| a.dist(b) > 1e-9); + let spent = out_of_frame || frame.as_ref().is_some_and(Budget::exhausted); + let retry = spent && start.zip(at).is_some_and(|(a, b)| a.dist(b) > 1e-9); return (Dragged { reached, moving, line_grab, retry }, Left::Solved); } } @@ -320,7 +330,8 @@ pub(super) fn drag_entity( None if good > 0.0 => Left::Solved, None => Left::Unsolved, }; - (Dragged { reached: good, moving, line_grab, retry: false }, left) + // The next frame goes on only from progress: a grab that can't move asks for no more. + (Dragged { reached: good, moving, line_grab, retry: out_of_frame && good > 0.0 }, left) } /// The held solves of one drag: how many, their shared work (including cursor correction), @@ -330,6 +341,8 @@ pub(super) struct Solves { pub count: usize, pub work: usize, pub cut: bool, + /// The frame's numerical solves have done their share ([`Budget::numeric_exhausted`]). + pub numeric: bool, } /// One live frame's decomposition budget (smaller in tests that set one). @@ -338,6 +351,10 @@ fn frame_budget() -> Budget { if let Some(work) = last_drag::frame_work() { return Budget::new(work); } + #[cfg(test)] + if let Some(work) = last_drag::frame_numeric() { + return Budget::frame().with_numeric(work); + } Budget::frame() } @@ -349,8 +366,9 @@ pub(super) mod last_drag { use super::Solves; thread_local! { - static LAST: Cell = const { Cell::new(Solves { count: 0, work: 0, cut: false }) }; + static LAST: Cell = const { Cell::new(Solves { count: 0, work: 0, cut: false, numeric: false }) }; static FRAME: Cell> = const { Cell::new(None) }; + static NUMERIC: Cell> = const { Cell::new(None) }; } pub fn set(s: Solves) { @@ -380,6 +398,25 @@ pub(super) mod last_drag { let _restore = Restore(FRAME.with(|c| c.replace(Some(work)))); f() } + + pub fn frame_numeric() -> Option { + NUMERIC.with(Cell::get) + } + + /// Restores the numerical allowance when dropped, also when the test panics. + struct RestoreNumeric(Option); + + impl Drop for RestoreNumeric { + fn drop(&mut self) { + NUMERIC.with(|c| c.set(self.0)); + } + } + + /// Run `f` with live frames given `work` units for their numerical solves. + pub fn with_frame_numeric(work: usize, f: impl FnOnce() -> R) -> R { + let _restore = RestoreNumeric(NUMERIC.with(|c| c.replace(Some(work)))); + f() + } } /// How one held solve of a drag went. diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rs index 8b2ca858e..24f3b41f4 100644 --- a/crates/engine/src/cmd/sketch_ux_tests.rs +++ b/crates/engine/src/cmd/sketch_ux_tests.rs @@ -1447,6 +1447,27 @@ fn a_drag_out_of_decomposition_budget_takes_short_steps() { assert_eq!(flips, 0); } +/// A live frame whose numerical solves have done their share takes no more held solves. Before, +/// a large sketch's frame could run 64 failing held solves of 150 ms each (10 s), where the +/// geometry couldn't follow. Progress so far stays and asks for another frame (`retry`). +#[test] +fn a_live_frame_stops_once_its_numerical_solves_are_spent() { + let start = hung_arm(); + let h = pt(&start, "eh.end"); + let far = hung_hand_target(&start, 2.0, 1.5); + let drag = |s: &mut Session| run(s, "sketch.drag", json!({"entity": "eh.end", "from": [h.x, h.y], "to": [far.x, far.y], "live": true})); + let mut s = hung_arm(); + drag(&mut s); + let whole = super::drag::last_drag::get(); + let mut s = hung_arm(); + let r = super::drag::last_drag::with_frame_numeric(1, || drag(&mut s)); + let short = super::drag::last_drag::get(); + assert!(short.numeric && short.count < whole.count, "{short:?} against {whole:?}"); + // What it reached stays, and asks for the next frame. + let reached = r["reached"].as_f64().unwrap_or(0.0); + assert!(reached > 0.0 && reached < 1.0 && r["retry"] == json!(true), "{r}"); +} + /// All the held solves of one live frame, halvings included, share one decomposition budget: /// together they do at most a frame's work, and one solve's more. #[test] diff --git a/crates/sketch/src/decompose.rs b/crates/sketch/src/decompose.rs index 58afd2272..0e85462a0 100644 --- a/crates/sketch/src/decompose.rs +++ b/crates/sketch/src/decompose.rs @@ -83,20 +83,44 @@ pub struct Budget { left: usize, spent: usize, cut: bool, + /// A live drag frame's allowance for the numerical solves (LM), which are counted but never + /// stopped by it: once it is spent, the drag takes no more steps this frame (`None`: not + /// counted). + numeric_left: Option, } impl Budget { /// A budget of `work` units: membership scans or estimated dense arithmetic operations. pub fn new(work: usize) -> Budget { - Budget { left: work, spent: 0, cut: false } + Budget { left: work, spent: 0, cut: false, numeric_left: None } } /// The budget of one solve: about 0.3 s, so a hostile sketch can't stall it. pub fn full() -> Budget { Budget::new(MAX_WORK) } - /// The budget of one live drag frame: about 16 ms. + /// The budget of one live drag frame: about 16 ms, and as much again for its numerical + /// solves ([`Budget::numeric_exhausted`]). pub fn frame() -> Budget { - Budget::new(FRAME_WORK) + Budget { numeric_left: Some(FRAME_WORK), ..Budget::new(FRAME_WORK) } + } + /// The frame's numerical solves have done their share of work: a drag takes no more steps + /// this frame and goes on in the next. + pub fn numeric_exhausted(&self) -> bool { + self.numeric_left == Some(0) + } + /// This budget with `work` units for its numerical solves (a frame that runs out sooner). + pub fn with_numeric(self, work: usize) -> Budget { + Budget { numeric_left: Some(work), ..self } + } + /// Whether the numerical solves' work is counted ([`Budget::frame`]). + pub(crate) fn counts_numeric(&self) -> bool { + self.numeric_left.is_some() + } + /// Count a numerical solve's work against the frame's allowance. + pub(crate) fn charge_numeric(&mut self, work: usize) { + if let Some(left) = &mut self.numeric_left { + *left = left.saturating_sub(work); + } } /// Some decomposition or cursor work stopped because the budget ran out. pub fn exhausted(&self) -> bool { diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index 18e374e21..3df93dfbb 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -978,6 +978,26 @@ fn lm(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec)], vars: &[usize], lm_capped(sk, lay, blocks, vars, x, col, MAX_ITERS) } +/// [`lm`], counting its work against a live drag frame's numerical allowance when `budget` has +/// one ([`Budget::frame`]). The solve itself runs as it would without it. +fn lm_in( + sk: &Sketch, + lay: &Layout, + blocks: &[(Block, Vec)], + vars: &[usize], + x: &mut Vec, + col: &[usize], + budget: &mut Budget, +) -> (usize, f64) { + if !budget.counts_numeric() { + return lm(sk, lay, blocks, vars, x, col); + } + let mut meter = Budget::new(usize::MAX); + let out = lm_capped_with_budget(sk, lay, blocks, vars, x, col, MAX_ITERS, Some(&mut meter)).unwrap_or((0, f64::INFINITY)); + budget.charge_numeric(meter.spent()); + out +} + /// [`lm`] with at most `max_iters` iterations. fn lm_capped( sk: &Sketch, @@ -2275,7 +2295,7 @@ fn solve_inner( let rest = unpinned(vars, &pin, None); let rest_blocks = blocks_reading(&sub, &rest); columns(&mut col, &rest, vars); - let (its, r) = if rest.is_empty() { (0, 0.0) } else { lm(sk, &lay, &rest_blocks, &rest, &mut x, &col) }; + let (its, r) = if rest.is_empty() { (0, 0.0) } else { lm_in(sk, &lay, &rest_blocks, &rest, &mut x, &col, budget) }; iterations += its; residual = r; solved = residual < ACCEPT; @@ -2299,7 +2319,7 @@ fn solve_inner( // the seed did not move it. let reseeded = unseeded.as_ref().filter(|plain| vars.iter().any(|v| plain.get(*v).is_some_and(Option::is_some))); if !(solved || pinned_failed && reseeded.is_some()) { - let (its, r) = lm(sk, &lay, &sub, vars, &mut x, &col); + let (its, r) = lm_in(sk, &lay, &sub, vars, &mut x, &col, budget); iterations += its; residual = r; } @@ -2313,7 +2333,7 @@ fn solve_inner( *s = plain.get(v).copied().flatten().unwrap_or(*s0); } } - let (its, r) = lm(sk, &lay, &sub, vars, &mut x, &col); + let (its, r) = lm_in(sk, &lay, &sub, vars, &mut x, &col, budget); iterations += its; residual = r; } @@ -2344,7 +2364,7 @@ fn solve_inner( iterations += its; if !done { // The last sub-step's solution, solved for the new values in one jump. - let (its, r) = lm(sk, &lay, &sub, vars, &mut from, &col); + let (its, r) = lm_in(sk, &lay, &sub, vars, &mut from, &col, budget); iterations += its; done = edit.holds(r, &State { sk, lay: &lay, x: &from }); }