Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

smlib dumps: a call's inputs are serialised only when it fails

jyvikoce5fbf40ab23
diff --git a/crates/smlib/src/core.rs b/crates/smlib/src/core.rs
index bdba1de15e..c672ac6fd1 100644
--- a/crates/smlib/src/core.rs
+++ b/crates/smlib/src/core.rs
@@ -419,11 +419,20 @@ pub(crate) static KERNEL: Mutex<Option<Kernel>> = Mutex::new(None);
/// Runs `f` on the process's kernel. 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)
+}
+
+/// [`run`] for a call that reads the bodies `inputs`: should it fail while a dump folder is set,
+/// they are left there ([`dump::failed`]).
+pub(crate) fn run_on<T: dump::Answer>(
+ call: &'static str,
+ 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);
// A profiler span per call: where the kernel's time goes.
let _span = solidcraft_profile::span("solidcore", call);
- dump::begin();
dump::set_current(Some(call));
let r = match catch_unwind(AssertUnwindSafe(|| f(k))) {
Ok(Ok(v)) => Ok(v),
@@ -436,13 +445,13 @@ pub(crate) fn run<T: dump::Answer>(call: &'static str, f: impl FnOnce(&mut Kerne
}
};
dump::set_current(None);
- match &r {
- Ok(v) => {
- if let Some(why) = v.refusal() {
- dump::failed(call, &why);
- }
- }
- Err(e) => dump::failed(call, &e.to_string()),
+ 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);
}
r
}
@@ -470,11 +479,7 @@ pub(crate) fn with_body<T: dump::Answer>(
if body.0.is_poisoned() {
return Err(Error::Internal(format!("{call}: the body was left unfinished by an earlier panic")));
}
- run(call, |k| {
- let mut b = body.0.lock().unwrap_or_else(PoisonError::into_inner);
- dump::input(k, "brep", &b);
- f(k, &mut b)
- })
+ run_on(call, &[("brep", body)], |k| f(k, &mut body.0.lock().unwrap_or_else(PoisonError::into_inner)))
}
/// An axis-aligned box from its lower corner (`SmApiCreateBox`, as `smlib_make_box` checks it:
diff --git a/crates/smlib/src/core/blend.rs b/crates/smlib/src/core/blend.rs
index 8bd296b834..3d1bcb2939 100644
--- a/crates/smlib/src/core/blend.rs
+++ b/crates/smlib/src/core/blend.rs
@@ -52,7 +52,7 @@ use solidcore::topology::face::p4 as face_p4;
use solidcore::topology::topology_traverser::Marks;
use solidcore::topology::{Brep, EdgeId, EdgeuseId, FaceId, FaceuseId, VertexId, edge, vertex};
-use super::{Body, answer, run};
+use super::{Body, answer};
use crate::{Blend, ChamferSecond, Error, Hole, HoleEdge, MAX_POINTS, Result};
/// Why solidcore refuses the 3x2 mixed-convexity corner whose rails cross
@@ -609,11 +609,8 @@ pub(super) fn on_copy(call: &'static str, body: &Body, f: impl FnOnce(&mut Kerne
if body.0.is_poisoned() {
return Err(Error::Internal(format!("{call}: the body was left unfinished by an earlier panic")));
}
- run(call, |k| {
- let g = body.0.lock().unwrap_or_else(PoisonError::into_inner);
- super::dump::input(k, "brep", &g);
- let c = brep_copy(k, &g)?;
- drop(g);
+ super::run_on(call, &[("brep", body)], |k| {
+ let c = brep_copy(k, &body.0.lock().unwrap_or_else(PoisonError::into_inner))?;
f(k, c)
})?
.map(Body::new)
diff --git a/crates/smlib/src/core/boolean.rs b/crates/smlib/src/core/boolean.rs
index 2fac368df1..7581a5f9a5 100644
--- a/crates/smlib/src/core/boolean.rs
+++ b/crates/smlib/src/core/boolean.rs
@@ -19,7 +19,7 @@ use solidcore::topology::brep::p3::brep_copy;
use solidcore::topology::brep::{p1, p2};
use solidcore::topology::{Brep, edge};
-use super::{Body, run};
+use super::{Body, run_on};
use crate::{BooleanOp, Error, Result};
/// What an operation's `SM_API` call gave, before it is a SolidCraft result: the capi's
@@ -86,16 +86,18 @@ fn finish(r: Brep, solid_in: bool, nonmanifold: bool) -> SolidResult<Done> {
/// What a failing call's dump calls its first operands.
const OPERANDS: [&str; 4] = ["a", "b", "c", "d"];
+/// `bodies` as a call's inputs, named as its dump names its operands.
+fn operands<'a>(bodies: &[&'a Body]) -> Vec<(&'static str, &'a Body)> {
+ bodies.iter().enumerate().map(|(n, &b)| (OPERANDS.get(n).copied().unwrap_or("operand"), b)).collect()
+}
+
/// 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.
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.
let mut out = Vec::with_capacity(bodies.len());
- for (n, b) in bodies.iter().enumerate() {
- let g = b.0.lock().unwrap_or_else(PoisonError::into_inner);
- super::dump::input(k, OPERANDS.get(n).copied().unwrap_or("operand"), &g);
- let c = brep_copy(k, &g)?;
- drop(g);
+ for b in bodies {
+ let c = brep_copy(k, &b.0.lock().unwrap_or_else(PoisonError::into_inner))?;
out.push(c);
}
Ok(out)
@@ -141,7 +143,7 @@ fn usable(call: &'static str, bodies: &[&Body]) -> Result<()> {
/// [`Error::NotSolid`] when solid operands give a body that is not closed.
pub(crate) fn boolean(a: &Body, b: &Body, op: BooleanOp) -> Result<Option<Body>> {
usable("SmApiBoolean", &[a, b])?;
- let d = run("SmApiBoolean", |k| {
+ let d = run_on("SmApiBoolean", &operands(&[a, b]), |k| {
let mut c = copies(k, &[a, b])?.into_iter();
let (Some(ca), Some(cb)) = (c.next(), c.next()) else {
return Err(SolidError::invalid_input("smlib_boolean", "no operand"));
@@ -161,7 +163,7 @@ pub(crate) fn union_all(bodies: &[&Body]) -> Result<Body> {
return Err(Error::Argument);
}
usable("smlib_boolean_union_all", bodies)?;
- let d = run("smlib_boolean_union_all", |k| {
+ let d = run_on("smlib_boolean_union_all", &operands(bodies), |k| {
let mut level = copies(k, bodies)?;
let solid_in = all_solid(&level)?;
while level.len() > 1 {
@@ -188,7 +190,7 @@ pub(crate) fn union_all(bodies: &[&Body]) -> Result<Body> {
/// `SmApiBoolean2d` succeeds without a result) or the result is empty.
pub(crate) fn boolean2d(a: &Body, b: &Body, op: BooleanOp) -> Result<Option<Body>> {
usable("SmApiBoolean2d", &[a, b])?;
- let d = run("SmApiBoolean2d", |k| {
+ let d = run_on("SmApiBoolean2d", &operands(&[a, b]), |k| {
let mut c = copies(k, &[a, b])?.into_iter();
let (Some(ca), Some(cb)) = (c.next(), c.next()) else {
return Err(SolidError::invalid_input("smlib_boolean2d", "no operand"));
@@ -219,7 +221,7 @@ pub(crate) fn imprint(body: &Body, tool: &Body) -> Result<Option<Body>> {
return Err(Error::Argument);
}
usable("SmApiBooleanWithOptions", &[body, tool])?;
- let d = run("SmApiBooleanWithOptions", |k| {
+ let d = run_on("SmApiBooleanWithOptions", &operands(&[body, tool]), |k| {
let mut c = copies(k, &[body, tool])?.into_iter();
let (Some(a), Some(t)) = (c.next(), c.next()) else {
return Err(SolidError::invalid_input("smlib_imprint", "no operand"));
diff --git a/crates/smlib/src/core/dump.rs b/crates/smlib/src/core/dump.rs
index 84fc9d8840..686fae63ea 100644
--- a/crates/smlib/src/core/dump.rs
+++ b/crates/smlib/src/core/dump.rs
@@ -1,8 +1,9 @@
//! What a failing solidcore call leaves behind, and which one is running: `smlib_set_dump_dir` and
-//! `smlib_current_call` for this kernel. While a folder is set, each call's B-rep inputs are
-//! written to memory before it runs (it may edit them) and to files only if it fails:
-//! `<n>-<call>.txt`, what failed, and `<n>-<call>-<input>.smb`, each input as a binary `.smb`, which
-//! `Brep::read` reads back.
+//! `smlib_current_call` for this kernel. While a folder is set, a call that fails leaves its B-rep
+//! inputs in it: `<n>-<call>.txt`, what failed, and `<n>-<call>-<input>.smb`, each input as a
+//! binary `.smb`, which `Brep::read` reads back. The inputs are the caller's bodies, which it keeps
+//! until the call's result is known ([`super::run_on`]); they are serialised only when the call
+//! 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};
@@ -11,48 +12,46 @@ use std::sync::{Mutex, PoisonError};
use solidcore::kernel::Kernel;
use solidcore::topology::Brep;
+use super::Body;
use crate::{Error, Result};
static DIR: Mutex<Option<PathBuf>> = Mutex::new(None);
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
-/// The inputs of the call running now, in the order it took them.
-static INPUTS: Mutex<Vec<(&'static str, std::result::Result<Vec<u8>, String>)>> = Mutex::new(Vec::new());
-/// Where failing calls leave their inputs; `None` stops it.
-pub(crate) fn set_dir(dir: Option<PathBuf>) {
- *DIR.lock().unwrap_or_else(PoisonError::into_inner) = dir;
-}
+/// A call's B-rep inputs, by the names its dump gives them, in the order it takes them.
+pub(crate) type Inputs<'a> = &'a [(&'static str, &'a Body)];
-fn dumping() -> bool {
- DIR.lock().unwrap_or_else(PoisonError::into_inner).is_some()
+#[cfg(test)]
+thread_local! {
+ /// How many inputs this thread's calls serialised, for the tests.
+ pub(crate) static SERIALISED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
-/// A new call, with no inputs yet.
-pub(super) fn begin() {
- if dumping() {
- INPUTS.lock().unwrap_or_else(PoisonError::into_inner).clear();
- }
+/// Where failing calls leave their inputs; `None` stops it.
+pub(crate) fn set_dir(dir: Option<PathBuf>) {
+ *DIR.lock().unwrap_or_else(PoisonError::into_inner) = dir;
}
-/// `b` is an input of the running call, by the name `what`.
-pub(crate) fn input(k: &Kernel, what: &'static str, b: &Brep) {
- if dumping() {
- let bytes = super::file::bytes(k, b, false).map_err(|e| e.to_string());
- INPUTS.lock().unwrap_or_else(PoisonError::into_inner).push((what, bytes));
- }
+/// `b` as a binary `.smb`.
+fn serialise(k: &Kernel, b: &Brep) -> std::result::Result<Vec<u8>, String> {
+ #[cfg(test)]
+ SERIALISED.with(|n| n.set(n.get() + 1));
+ super::file::bytes(k, b, false).map_err(|e| e.to_string())
}
fn safe(call: &str) -> String {
call.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect()
}
-/// The running call failed: its inputs go to the folder. Failing to write them fails nothing else.
-pub(super) fn failed(call: &str, why: &str) {
+/// The running call failed: its `inputs` go to the folder, as they are now (a call that edits a
+/// body in place, a query's caches, leaves it edited). Failing to write them fails nothing else.
+pub(super) fn failed(k: &Kernel, call: &str, why: &str, inputs: Inputs<'_>) {
let Some(dir) = DIR.lock().unwrap_or_else(PoisonError::into_inner).clone() else { return };
let n = SEQUENCE.fetch_add(1, Ordering::Relaxed);
let stem = format!("{n:06}-{}", safe(call));
let mut text = format!("{call} -> {why}\nnumeric arguments are not recorded\n");
- for (what, bytes) in INPUTS.lock().unwrap_or_else(PoisonError::into_inner).drain(..) {
+ for &(what, body) in inputs {
+ let bytes = serialise(k, &body.0.lock().unwrap_or_else(PoisonError::into_inner));
match bytes {
Ok(b) => {
let name = format!("{stem}-{what}.smb");
diff --git a/crates/smlib/src/core/split.rs b/crates/smlib/src/core/split.rs
index a7ed15dabc..8d593c88ce 100644
--- a/crates/smlib/src/core/split.rs
+++ b/crates/smlib/src/core/split.rs
@@ -53,7 +53,7 @@ use solidcore::topology::{Brep, EdgeId, FaceId};
use super::blend::status;
use super::sweep::build_faces;
-use super::{Body, run};
+use super::Body;
use crate::ssi::Spec;
use crate::{Error, Result};
use solidcore::topology::brep::p3::brep_copy;
@@ -318,10 +318,9 @@ pub(crate) fn split_faces(body: &Body, faces: &[usize], tools: &[&Spec]) -> Resu
if body.0.is_poisoned() {
return Err(Error::Internal("smlib_split_faces: the body was left unfinished by an earlier panic".to_owned()));
}
- let r = run("smlib_split_faces", |k| {
+ let r = super::run_on("smlib_split_faces", &[("brep", body)], |k| {
let mut a = {
let g = body.0.lock().unwrap_or_else(PoisonError::into_inner);
- super::dump::input(k, "brep", &g);
let count = brep_p1::faces(&g, None)?.len();
let mut seen = std::collections::HashSet::new();
if faces.iter().any(|&f| f >= count || !seen.insert(f)) {
@@ -465,10 +464,7 @@ pub(crate) fn split_body(body: &Body, spec: &Spec) -> Result<Option<(Body, Body)
if body.0.is_poisoned() {
return Err(Error::Internal("smlib_split_body: the body was left unfinished by an earlier panic".to_owned()));
}
- let r = run("smlib_split_body", |k| {
- super::dump::input(k, "brep", &body.0.lock().unwrap_or_else(PoisonError::into_inner));
- both_sides(k, body, false, |k, flip| side(k, body, spec, flip))
- })??;
+ let r = super::run_on("smlib_split_body", &[("brep", body)], |k| both_sides(k, body, false, |k, flip| side(k, body, spec, flip)))??;
Ok(r.map(|(b, f)| (Body::new(b), Body::new(f))))
}
@@ -484,11 +480,9 @@ pub(crate) fn split_body_by_sheet(body: &Body, sheet: &Body, face: usize) -> Res
if body.0.is_poisoned() || sheet.0.is_poisoned() {
return Err(Error::Internal("smlib_split_body_by_sheet: a body was left unfinished by an earlier panic".to_owned()));
}
- let r = run("smlib_split_body_by_sheet", |k| {
- super::dump::input(k, "brep", &body.0.lock().unwrap_or_else(PoisonError::into_inner));
+ let r = super::run_on("smlib_split_body_by_sheet", &[("brep", body), ("sheet", sheet)], |k| {
{
let g = sheet.0.lock().unwrap_or_else(PoisonError::into_inner);
- super::dump::input(k, "sheet", &g);
if !is_sheet(k, &g)? || face >= g.face_list().len() {
return Ok(Err(Error::Argument));
}
diff --git a/crates/smlib/src/core/trim.rs b/crates/smlib/src/core/trim.rs
index 53ba9ab69a..cf7099a1d7 100644
--- a/crates/smlib/src/core/trim.rs
+++ b/crates/smlib/src/core/trim.rs
@@ -57,7 +57,7 @@ use solidcore::topology::{Brep, BrepId, EdgeId, FaceId, LoopId, edge};
use super::blend::{p3, status};
use super::sweep::build_faces;
-use super::{Body, answer, run};
+use super::{Body, answer};
use crate::trim::Continuation;
use crate::{Error, Result};
use solidcore::topology::brep::p3::brep_copy;
@@ -295,12 +295,8 @@ pub(crate) fn untrim_face(body: &Body, point: [f64; 3], tol: f64, holes: Option<
return Err(Error::Internal("smlib_untrim_face: the body was left unfinished by an earlier panic".to_owned()));
}
let at = p3(point);
- run("smlib_untrim_face", |k| {
- let mut whole = {
- let g = body.0.lock().unwrap_or_else(PoisonError::into_inner);
- super::dump::input(k, "brep", &g);
- brep_copy(k, &g)?
- };
+ super::run_on("smlib_untrim_face", &[("brep", body)], |k| {
+ let mut whole = brep_copy(k, &body.0.lock().unwrap_or_else(PoisonError::into_inner))?;
// The face to untrim, in a body of its own (its hole edges lamina there) or in the copy
// of the whole body.
let (mut w, f) = if in_place {
@@ -749,12 +745,8 @@ pub(crate) fn extend_sheet(sheet: &Body, point: [f64; 3], tol: f64, distance: f6
if sheet.0.is_poisoned() {
return Err(Error::Internal("smlib_extend_sheet: the body was left unfinished by an earlier panic".to_owned()));
}
- run("smlib_extend_sheet", |k| {
- let b = {
- let g = sheet.0.lock().unwrap_or_else(PoisonError::into_inner);
- super::dump::input(k, "sheet", &g);
- brep_copy(k, &g)?
- };
+ super::run_on("smlib_extend_sheet", &[("sheet", sheet)], |k| {
+ let b = brep_copy(k, &sheet.0.lock().unwrap_or_else(PoisonError::into_inner))?;
let faces = brep_p1::faces(&b, None)?;
let [f] = faces.as_slice() else { return Ok(Err(Error::Unsupported)) };
let f = *f;
diff --git a/crates/smlib/src/tests.rs b/crates/smlib/src/tests.rs
index 72d8a8d263..28f2c55132 100644
--- a/crates/smlib/src/tests.rs
+++ b/crates/smlib/src/tests.rs
@@ -279,6 +279,29 @@ fn every_entry_point_answers() {
let _ = std::fs::remove_dir_all(&dir);
}
+/// While a dump folder is set, a call that answers serialises none of its inputs, and one that
+/// fails serialises each once: the rig's timings, taken with a folder set, are the kernel's.
+#[test]
+fn only_a_failing_call_serialises_its_inputs() {
+ let _dumps = DUMP_DIR_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let dir = std::env::temp_dir().join(format!("solidcraft-smlib-core-dump-lazy-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ core::dump::set_dir(Some(dir.clone()));
+ let serialised = || core::dump::SERIALISED.with(std::cell::Cell::get);
+ let a = core::make_box([0.0; 3], [10.0; 3]).unwrap();
+ let b = core::make_box([5.0; 3], [10.0; 3]).unwrap();
+ let before = serialised();
+ let v = core::volume(&a, 1e-8);
+ let u = core::boolean::boolean(&a, &b, BooleanOp::Union);
+ let answered = serialised() - before;
+ let r: Result<()> = core::with_body("smlib_test_failure", &a, |_, _| Err(solidcore::SolidError::invalid_input("test", "refused")));
+ let failed = serialised() - before - answered;
+ core::dump::set_dir(None);
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(v.is_ok() && matches!(u, Ok(Some(_))) && r.is_err());
+ assert_eq!((answered, failed), (0, 1));
+}
+
/// A failing solidcore call leaves its inputs and what failed, and an answered one leaves nothing;
/// the call in flight is named, and gone after. A folder is process-wide, so this test is the one
/// that sets it.