Skip to content

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

Reuse placement-independent model results (#6525) (#6527)

takuto-NAd24554107552
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 38e7c50efb..1593907692 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -2,6 +2,8 @@
#[path = "placed_mesh.rs"]
mod placed_mesh;
+#[path = "placement_reuse.rs"]
+mod placement_reuse;
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
@@ -1294,6 +1296,10 @@ pub struct Model {
primed: Option<(u64, Arc<std::collections::HashMap<u64, FeatureResult>>)>,
/// Shared with copies of this evaluator; states hold only a weak reference.
frame_bodies: Arc<std::sync::Mutex<FrameBodies>>,
+ /// Inputs proven to describe placement-independent geometry, and the state they produced.
+ placement_inputs: Option<placement_reuse::Inputs>,
+ /// All evaluated features use supported local inputs; computed with the existing owner index.
+ placement_local: bool,
}
/// Parameters a feature uses directly (inputs, sketch dimensions and the expressions of a
@@ -2014,6 +2020,7 @@ impl Model {
pub fn adopt_solved_sketches(&mut self, doc: &mut Document) -> usize {
let solved: Vec<SolvedSketch> = self.edited_sketches(doc).cloned().collect();
let Some(first) = solved.iter().filter_map(|s| doc.features.iter().position(|f| f.id == s.feature)).min() else { return 0 };
+ self.placement_inputs = None;
for s in &solved {
if let Ok(stored) = doc.sketch_mut(s.feature) {
adopt_solution(stored, &s.sketch);
@@ -2101,6 +2108,8 @@ impl Model {
/// Re-evaluate the document, reusing results up to the first changed feature.
pub fn evaluate(&mut self, doc: &Document) {
+ self.placement_inputs = None;
+ self.placement_local = true;
let (vals, perr) = evaluation_values(doc);
self.param_errors = perr;
self.frame_bodies.lock().unwrap_or_else(|e| e.into_inner()).next_generation();
@@ -2128,6 +2137,7 @@ impl Model {
}
let watched = crate::progress::begin(doc.features.len());
for (i, f) in doc.features.iter().enumerate() {
+ self.placement_local = self.placement_local && placement_reuse::local_geometry(f, &feature_component);
let rolled_back = i >= marker;
// Retain at most one active result per rolled-back feature, even across several
// marker moves. Build the map anew so deleted features release their states too.
@@ -2344,6 +2354,7 @@ impl Model {
state: state.clone(),
});
}
+ self.placement_local = self.placement_local && out.iter().all(|r| !r.skipped && !r.stale && !r.unkept && r.error.is_none());
self.results = out;
self.last_recomputed = recomputed;
self.recomputed += recomputed;
@@ -2465,6 +2476,7 @@ impl Model {
/// Set every result's fingerprint to `doc`'s, so the next evaluation reuses every result
/// (after a change that builds nothing differently).
pub fn refingerprint(&mut self, doc: &Document) {
+ self.placement_inputs = None;
let (vals, _) = evaluation_values(doc);
let marker = doc.marker.unwrap_or(usize::MAX);
self.step_digests = StepDigests::of(doc, &self.step_digests);
diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rs
index 41f5150baf..d4a82fe4b1 100644
--- a/crates/doc/src/eval_cost_tests.rs
+++ b/crates/doc/src/eval_cost_tests.rs
@@ -474,3 +474,145 @@ fn placed_bodies_taken_as_before_keep_their_measure() {
let again = world_state_reusing(&doc, &state, &mut cache);
assert_eq!(counted(|| assert_eq!(again.bodies[0].measure().unwrap().centroid, centroid)).measures, 0);
}
+
+#[test]
+fn shared_evaluation_requires_its_actual_model_and_unmodified_geometry_inputs() {
+ let mut doc = Document::new("shared evaluation");
+ let feature = doc
+ .add_feature(
+ FeatureKind::Box {
+ corner: point_expr(Vec3::ZERO),
+ length: "2".into(),
+ width: "3".into(),
+ height: "4".into(),
+ operation: Operation::NewBody,
+ },
+ None,
+ )
+ .unwrap();
+ let mut doc = Arc::new(doc);
+ let mut model = Model::new();
+ assert!(model.evaluate_shared(&doc));
+ let original = model.state();
+ assert!(!model.evaluate_shared(&doc));
+ assert_eq!(model.last_recomputed, 0);
+ assert!(Arc::ptr_eq(&original, &model.state()));
+
+ // A geometry edit must be seen even when a caller did not evaluate it before moving.
+ let FeatureKind::Box { length, .. } = &mut Arc::make_mut(&mut doc).feature_mut(feature).unwrap().kind else { panic!("box") };
+ *length = "5".into();
+ assert!(model.evaluate_shared(&doc));
+ assert!((model.state().bodies[0].measure().unwrap().volume - 60.).abs() < 1e-8);
+ assert!((original.bodies[0].measure().unwrap().volume - 24.).abs() < 1e-8);
+ assert!(!model.evaluate_shared(&doc));
+
+ let mut other_doc = (*doc).clone();
+ let FeatureKind::Box { length, .. } = &mut other_doc.feature_mut(feature).unwrap().kind else { panic!("box") };
+ *length = "7".into();
+ let mut other = Model::new();
+ other.evaluate(&other_doc);
+ model.results = other.results;
+ assert!(model.evaluate_shared(&doc), "replaced results cannot use the retained proof");
+ assert_eq!(model.state().bodies.len(), 1);
+ model.no_cache = true;
+ assert!(model.evaluate_shared(&doc));
+ model.no_cache = false;
+ assert!(model.evaluate_shared(&doc));
+ let ahead = model.clone();
+ model.prime(&ahead);
+ assert!(model.evaluate_shared(&doc), "primed results use normal evaluation");
+ model.unprime();
+ assert!(model.evaluate_shared(&doc));
+ model.evaluate(&doc);
+ assert!(model.evaluate_shared(&doc), "the borrowed-document API invalidates the shared-input proof");
+ Arc::make_mut(&mut doc).set_param("Width", "6 mm", None, None).unwrap();
+ let FeatureKind::Box { width, .. } = &mut Arc::make_mut(&mut doc).feature_mut(feature).unwrap().kind else { panic!("box") };
+ *width = "Width".into();
+ assert!(model.evaluate_shared(&doc));
+ assert!((model.state().bodies[0].measure().unwrap().volume - 120.).abs() < 1e-8);
+ Arc::make_mut(&mut doc).set_param("Width", "9 mm", None, None).unwrap();
+ assert!(model.evaluate_shared(&doc));
+ assert!((model.state().bodies[0].measure().unwrap().volume - 180.).abs() < 1e-8);
+ // A primitive's label can change its result without replacing the geometry state.
+ // Restoring the earlier document must restore that label and fingerprint too.
+ let name = doc.feature(feature).unwrap().name.clone();
+ let mut renamed = (*doc).clone();
+ renamed.feature_mut(feature).unwrap().name = "Renamed box".into();
+ assert!(model.rename_feature(&renamed, feature));
+ assert!(model.evaluate_shared(&doc), "refingerprinted results must not keep the old shared-input proof");
+ assert_eq!(model.result(feature).unwrap().name, name);
+ assert!(model.is_current(&doc));
+}
+
+#[test]
+fn shared_imported_mesh_inputs_keep_payload_identity_and_invalidate_replacements() {
+ let mut doc = Document::new("shared mesh input");
+ let component = doc.add_component(Some("Part"), 0).unwrap();
+ let feature = doc
+ .add_feature(
+ FeatureKind::MeshImport {
+ file: "triangle.stl".into(),
+ meshes: vec![MeshData {
+ name: "Triangle".into(),
+ positions: Arc::from([0., 0., 0., 1., 0., 0., 0., 1., 0.]),
+ triangles: Arc::from([0, 1, 2]),
+ color: None,
+ }],
+ },
+ None,
+ )
+ .unwrap();
+ doc.feature_mut(feature).unwrap().component = component;
+ let mut doc = Arc::new(doc);
+ let mut model = Model::new();
+ assert!(model.evaluate_shared(&doc));
+ let original = model.state();
+ Arc::make_mut(&mut doc).occurrences[0].transform = rigid(Vec3::new(10., 0., 0.), Vec3::ZERO, Vec3::Z, 0.3);
+ assert!(!model.evaluate_shared(&doc));
+ assert!(Arc::ptr_eq(&original, &model.state()));
+ for edit in 0..5 {
+ let FeatureKind::MeshImport { meshes, .. } = &mut Arc::make_mut(&mut doc).feature_mut(feature).unwrap().kind else { panic!("mesh") };
+ let mesh = &mut meshes[0];
+ match edit {
+ 0 => Arc::make_mut(&mut mesh.positions)[3] = 2.,
+ 1 => Arc::make_mut(&mut mesh.triangles).swap(1, 2),
+ 2 => mesh.color = Some([0.2, 0.4, 0.6]),
+ 3 => mesh.name = "Renamed".into(),
+ _ => mesh.positions = Arc::from(mesh.positions.to_vec()),
+ }
+ assert!(model.evaluate_shared(&doc), "mesh edit {edit} must invalidate");
+ assert!(model.results.iter().all(|r| r.error.is_none()));
+ let mut fresh = Model::new();
+ fresh.no_cache = true;
+ fresh.evaluate(&doc);
+ let (actual, expected) = (model.state(), fresh.state());
+ assert_eq!(actual.bodies[0].name, expected.bodies[0].name);
+ let (actual, expected) = (actual.bodies[0].mesh(), expected.bodies[0].mesh());
+ assert_eq!(actual.positions, expected.positions);
+ assert_eq!(actual.triangles, expected.triangles);
+ assert_eq!(actual.normals, expected.normals);
+ assert!(!model.evaluate_shared(&doc));
+ }
+}
+
+#[test]
+fn shared_evaluation_refreshes_live_sketches_and_keeps_unknown_features_conservative() {
+ let mut doc = Document::new("live and unknown inputs");
+ let feature = doc.add_feature(line_sketch(PlaneRef::Origin { name: "XY".into() }, Vec2::new(2., 1.)), None).unwrap();
+ let mut doc = Arc::new(doc);
+ let mut model = Model::new();
+ assert!(model.evaluate_shared(&doc));
+ assert!(!model.evaluate_shared(&doc));
+ let solved = model.state().sketch(feature).unwrap().clone();
+ let mut live = solved.sketch.clone();
+ live.points[1].pos.y += 2.;
+ assert!(model.show_live_sketch(feature, live, solved.report.clone()));
+ assert!(model.is_stale());
+ assert!(model.evaluate_shared(&doc));
+ assert!(!model.is_stale());
+ assert_eq!(model.state().sketch(feature).unwrap().sketch.points, solved.sketch.points);
+ Arc::make_mut(&mut doc).add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Origin { name: "XY".into() } }, None).unwrap();
+ assert!(model.evaluate_shared(&doc));
+ assert!(model.results.iter().all(|r| r.error.is_none()));
+ assert!(model.evaluate_shared(&doc), "an unclassified feature must keep the ordinary evaluation path");
+}
diff --git a/crates/doc/src/placement_reuse.rs b/crates/doc/src/placement_reuse.rs
new file mode 100644
index 0000000000..865451ca32
--- /dev/null
+++ b/crates/doc/src/placement_reuse.rs
@@ -0,0 +1,222 @@
+//! Retain a proven evaluation across changes to assembly placement. Unknown feature kinds
+//! use the ordinary evaluator; adding an eligible kind requires checking all of its inputs.
+
+use super::{Document, Feature, FeatureKind, Model, ModelState, Operation, PlaneRef};
+use std::sync::{Arc, Weak};
+
+#[derive(Clone, Debug)]
+pub(super) struct Inputs {
+ document: Arc<Document>,
+ state: Weak<ModelState>,
+}
+
+impl Model {
+ /// Evaluate a shared document, retaining a proof for subsequent placement-only changes.
+ /// Returns whether the timeline was evaluated. The normal `evaluate` remains available
+ /// for callers without a shared document and invalidates this proof.
+ ///
+ /// Only explicitly supported local geometry qualifies. Geometry edits, unknown feature
+ /// kinds, stale/primed results and `no_cache` continue through the ordinary evaluator.
+ pub fn evaluate_shared(&mut self, doc: &Arc<Document>) -> bool {
+ let reusable = !self.no_cache
+ && self.primed.is_none()
+ && self.placement_inputs.as_ref().is_some_and(|inputs| {
+ inputs.state.upgrade().is_some_and(|state| Arc::ptr_eq(&state, &self.state()))
+ && !self.is_stale()
+ && (Arc::ptr_eq(doc, &inputs.document) || same_geometry_inputs(doc, &inputs.document))
+ });
+ if reusable {
+ self.last_recomputed = 0;
+ self.last_restored = 0;
+ return false;
+ }
+ self.evaluate(doc);
+ if !self.no_cache && self.primed.is_none() && self.placement_local {
+ self.placement_inputs = Some(Inputs { document: doc.clone(), state: Arc::downgrade(&self.state()) });
+ }
+ true
+ }
+
+ /// [`Model::refingerprint`] for a shared document: a proof that held for the results before
+ /// is kept for `doc`, since nothing was built differently (pinned body names, say).
+ pub fn refingerprint_shared(&mut self, doc: &Arc<Document>) {
+ let proven = !self.no_cache
+ && self.primed.is_none()
+ && self.placement_inputs.as_ref().is_some_and(|inputs| inputs.state.upgrade().is_some_and(|state| Arc::ptr_eq(&state, &self.state())))
+ && !self.is_stale();
+ self.refingerprint(doc);
+ if proven && self.placement_local {
+ self.placement_inputs = Some(Inputs { document: doc.clone(), state: Arc::downgrade(&self.state()) });
+ }
+ }
+}
+
+fn local_plane(plane: &PlaneRef, depth: usize) -> bool {
+ if depth > crate::MAX_PLACEMENT_DEPTH {
+ return false;
+ }
+ match plane {
+ PlaneRef::Origin { name: _ } | PlaneRef::Custom { plane: _ } | PlaneRef::Placed { origin: _, x_dir: _, y_dir: _ } => true,
+ PlaneRef::Offset { base, distance: _ }
+ | PlaneRef::Flipped { base, about_y: _ }
+ | PlaneRef::AtAngle { base, axis_origin: _, axis_dir: _, angle: _, line: None } => local_plane(base, depth + 1),
+ _ => false,
+ }
+}
+
+pub(super) fn local_geometry(f: &Feature, components: &std::collections::HashMap<u64, u64>) -> bool {
+ // Persistent picked-face/edge attachments can move an otherwise literal input.
+ if !f.face_names.is_empty() || !f.edge_names.is_empty() || !f.edge_refs.is_empty() {
+ return false;
+ }
+ match &f.kind {
+ FeatureKind::Box { corner: _, length: _, width: _, height: _, operation: Operation::NewBody }
+ | FeatureKind::Cylinder { base: _, axis: _, radius: _, height: _, operation: Operation::NewBody }
+ | FeatureKind::Sphere { center: _, radius: _, operation: Operation::NewBody }
+ | FeatureKind::Torus { center: _, major: _, minor: _, operation: Operation::NewBody }
+ | FeatureKind::Import { file: _, step: _, components: _, skip: _ }
+ | FeatureKind::MeshImport { file: _, meshes: _ } => true,
+ FeatureKind::Sketch { plane, sketch } => sketch.links.is_empty() && sketch.wires.is_empty() && local_plane(plane, 0),
+ FeatureKind::Extrude { sketch, profiles: _, extent, operation: Operation::NewBody, targets: _, thin: _ } => {
+ let crate::Extent {
+ distance: _,
+ convention: _,
+ direction: _,
+ distance2: _,
+ start_offset: _,
+ through_all,
+ taper: _,
+ to,
+ to_offset: _,
+ from,
+ } = extent;
+ to.is_none() && from.is_none() && !through_all && components.get(&sketch.0) == Some(&f.component)
+ }
+ _ => false,
+ }
+}
+
+/// Every non-placement field is named, so a new input requires an explicit decision here.
+/// Assembly records do not feed any of the feature kinds accepted by `local_geometry`.
+fn same_geometry_inputs(a: &Document, b: &Document) -> bool {
+ let Document {
+ render,
+ format,
+ format_pending,
+ name,
+ units,
+ metadata,
+ params,
+ features,
+ marker,
+ next_id,
+ reserved_body_names,
+ components,
+ occurrences: _,
+ assembly: _,
+ sheet,
+ plastic,
+ parts,
+ links,
+ configs,
+ favorites,
+ canvases,
+ param_comments,
+ text_params,
+ next_component_color_index,
+ materials,
+ user_materials,
+ appearances,
+ body_components,
+ body_offsets,
+ browser_groups,
+ timeline_groups,
+ browser_order,
+ named_views,
+ visibility,
+ } = a;
+ (Arc::ptr_eq(render, &b.render) || *render == b.render)
+ && *format == b.format
+ && *format_pending == b.format_pending
+ && *name == b.name
+ && *units == b.units
+ && *metadata == b.metadata
+ && *params == b.params
+ && features.len() == b.features.len()
+ && features.iter().zip(&b.features).all(|(a, b)| same_feature(a, b))
+ && *marker == b.marker
+ && *next_id == b.next_id
+ && *reserved_body_names == b.reserved_body_names
+ && *components == b.components
+ && *sheet == b.sheet
+ && *plastic == b.plastic
+ && *parts == b.parts
+ && *links == b.links
+ && *configs == b.configs
+ && *favorites == b.favorites
+ && *canvases == b.canvases
+ && *param_comments == b.param_comments
+ && *text_params == b.text_params
+ && *next_component_color_index == b.next_component_color_index
+ && *materials == b.materials
+ && *user_materials == b.user_materials
+ && *appearances == b.appearances
+ && *body_components == b.body_components
+ && *body_offsets == b.body_offsets
+ && *browser_groups == b.browser_groups
+ && *timeline_groups == b.timeline_groups
+ && *browser_order == b.browser_order
+ && *named_views == b.named_views
+ && *visibility == b.visibility
+}
+
+/// Compare feature definitions without traversing immutable imported payloads. A replacement
+/// allocation conservatively evaluates again, even when it happens to contain equal bytes.
+fn same_feature(a: &Feature, b: &Feature) -> bool {
+ let Feature {
+ id,
+ name,
+ suppressed,
+ body_names,
+ param_names,
+ component,
+ edge_refs,
+ edge_names,
+ face_names,
+ participants,
+ shell_piece_order,
+ kernel_piece_order,
+ inserted,
+ link_faces,
+ kind,
+ } = a;
+ *id == b.id
+ && *name == b.name
+ && *suppressed == b.suppressed
+ && *body_names == b.body_names
+ && *param_names == b.param_names
+ && *component == b.component
+ && *edge_refs == b.edge_refs
+ && *edge_names == b.edge_names
+ && *face_names == b.face_names
+ && *participants == b.participants
+ && *shell_piece_order == b.shell_piece_order
+ && *kernel_piece_order == b.kernel_piece_order
+ && *inserted == b.inserted
+ && *link_faces == b.link_faces
+ && match (kind, &b.kind) {
+ (FeatureKind::MeshImport { file: a, meshes }, FeatureKind::MeshImport { file: b, meshes: other }) => {
+ a == b
+ && meshes.len() == other.len()
+ && meshes.iter().zip(other).all(|(a, b)| {
+ let crate::MeshData { name, positions, triangles, color } = a;
+ *name == b.name && *color == b.color && Arc::ptr_eq(positions, &b.positions) && Arc::ptr_eq(triangles, &b.triangles)
+ })
+ }
+ (
+ FeatureKind::Import { file: a, step, components, skip },
+ FeatureKind::Import { file: b, step: other, components: other_components, skip: other_skip },
+ ) => a == b && Arc::ptr_eq(step, other) && components == other_components && skip == other_skip,
+ (a, b) => a == b,
+ }
+}
diff --git a/crates/engine/src/crash_tests.rs b/crates/engine/src/crash_tests.rs
index 799e3a2b56..13a1ab5998 100644
--- a/crates/engine/src/crash_tests.rs
+++ b/crates/engine/src/crash_tests.rs
@@ -53,6 +53,22 @@ fn child() {
set_environment("Renderer: test");
let mut s = Session { crash_journal: true, ..Default::default() };
s.execute("solid.box", &json!({"length": 10, "width": 20, "height": 30})).unwrap();
+ if mode == "read_only" {
+ let state = STATE.get().unwrap();
+ let before = read_live_journal(state);
+ assert_eq!(before.base, json!("new"));
+ assert_eq!(before.replay, vec![json!({"command":"solid.box","params":{"length":10,"width":20,"height":30}})]);
+ let evaluations = s.evaluations;
+ s.execute("document.inspect", &json!({})).unwrap();
+ assert_eq!(s.evaluations, evaluations, "reading the design does not evaluate it");
+ let after = read_live_journal(state);
+ assert_eq!(after.base, before.base, "a read must not rebase the recovery journal");
+ assert_eq!(after.replay, before.replay, "the command that made the box must remain replayable");
+ assert!(after.in_flight.is_none());
+ end_session();
+ println!("READ_ONLY_JOURNAL_OK");
+ return;
+ }
// Commands that only read are not kept.
for _ in 0..50 {
s.execute("document.inspect", &json!({})).unwrap();
@@ -179,6 +195,14 @@ fn accepted_prepared_commands_replay_and_discarded_work_is_not_journaled() {
let _ = fs::remove_dir_all(directory);
}
+#[test]
+fn a_read_only_command_keeps_the_replay_after_body_names_are_pinned() {
+ let directory = fresh_dir("read-only");
+ let (output, ok) = run_child(&directory, "read_only");
+ assert!(ok && output.contains("READ_ONLY_JOURNAL_OK"), "{output}");
+ let _ = fs::remove_dir_all(directory);
+}
+
fn only_report(dir: &Path) -> (Summary, Value) {
let all = list(dir);
assert_eq!(all.len(), 1, "{all:?}");
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index e9e28f0e81..85600713be 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -541,7 +541,7 @@ impl Session {
.and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok());
let model = adopted.unwrap_or_else(|| {
let mut model = Model::new();
- model.evaluate(&doc);
+ model.evaluate_shared(&doc);
model
});
Session {
@@ -822,10 +822,11 @@ impl Session {
}
pub fn refresh(&mut self) {
- self.model.evaluate(&self.doc);
- #[cfg(test)]
- {
- self.evaluations += 1;
+ if self.model.evaluate_shared(&self.doc) {
+ #[cfg(test)]
+ {
+ self.evaluations += 1;
+ }
}
self.revision += 1;
self.prune_occurrence_state();
@@ -940,7 +941,7 @@ impl Session {
}
doc.reserved_body_names.extend(reserve);
// The pinned names are the ones the bodies have: no result changes, so none is evaluated.
- self.model.refingerprint(&self.doc);
+ self.model.refingerprint_shared(&self.doc);
}
/// A hidden construction plane stays hidden when the design renames it, or undo or redo
@@ -1175,10 +1176,8 @@ impl Session {
for (host, _) in additional_jobs {
self.register_render_job_host(host)?;
}
- if outermost && crash::enabled() {
- // A failed command leaves the design as it was (restored below).
+ let crash_outcome = if outermost && crash::enabled() {
let failed = r.as_ref().err().map(ToString::to_string);
- let after = if failed.is_some() { &before.doc } else { &self.doc };
// Commands that only read leave no trace (the journal keeps what a replay needs).
let changed = !Arc::ptr_eq(&self.doc, &before.doc)
|| self.active_sketch != before.active_sketch
@@ -1186,13 +1185,15 @@ impl Session {
|| self.active_component != active_before.0
|| self.active_occurrence_path != active_before.1
|| spec.id.starts_with("select.");
- crash::command_done(self.crash_journal, changed, &before.doc, after, spec.id, given, failed.map_or(Ok(()), Err));
- }
+ Some((before.doc.clone(), changed, failed))
+ } else {
+ None
+ };
let changed = !Arc::ptr_eq(&self.doc, &before.doc);
// Hiding or showing (`browser.visibility`) leaves the document alone, so it needs its own
// test: it is saved with the design and has an undo step of its own.
let hidden = self.visibility != before.visibility;
- match r {
+ let result = match r {
Ok((v, live_edit)) => {
let v = if changed { self.with_created(spec.id, params, &before, v) } else { v };
if changed || hidden {
@@ -1236,7 +1237,14 @@ impl Session {
}
Err(e)
}
+ };
+ if let Some((before, changed, failed)) = crash_outcome {
+ // Refresh and body-name pinning can copy the shared document. Remember the final
+ // document, so the next command does not mistake that work for an outside edit
+ // and discard the replay. Failed commands have restored their document by now.
+ crash::command_done(self.crash_journal, changed, &before, &self.doc, spec.id, given, failed.map_or(Ok(()), Err));
}
+ result
}
/// A sketch command's result gets `created`: the ids of the points, curves, constraints and
diff --git a/crates/engine/src/world_placement_cache_tests.rs b/crates/engine/src/world_placement_cache_tests.rs
index 9c736b7fb1..9fa2685292 100644
--- a/crates/engine/src/world_placement_cache_tests.rs
+++ b/crates/engine/src/world_placement_cache_tests.rs
@@ -7,6 +7,177 @@ fn run(session: &mut Session, command: &str, params: Value) -> Value {
session.execute(command, &params).unwrap_or_else(|error| panic!("{command}: {error}"))
}
+#[test]
+fn geometry_independent_moves_do_not_evaluate_the_timeline() {
+ let mut session = Session::default();
+ let created = run(&mut session, "component.create", json!({"name":"Part","grounded":false}));
+ let occurrence = created["occurrence"].as_u64().unwrap();
+ run(&mut session, "solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Block"}));
+ let definitions = session.model.state();
+ let before = session.evaluations;
+ run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[10,0,0],"capture":true}));
+ assert_eq!(session.evaluations - before, 0, "a placement-independent model must not enter timeline evaluation");
+ let world = session.world_state();
+ let block = world.bodies.iter().find(|b| b.source_name.as_deref() == Some("Block")).unwrap();
+ assert!(block.mesh().bounds().min.dist(Vec3::new(10., 0., 0.)) < 1e-9);
+ assert!(Arc::ptr_eq(&definitions, &session.model.state()));
+ assert_fresh_world(&session);
+ for command in ["edit.undo", "edit.redo"] {
+ let before = session.evaluations;
+ run(&mut session, command, json!({}));
+ assert_eq!(session.evaluations, before, "{command} must share the placement reuse decision");
+ assert!(Arc::ptr_eq(&definitions, &session.model.state()));
+ assert_fresh_world(&session);
+ }
+ let mut scratch = session.scratch();
+ run(&mut scratch, "occurrence.move", json!({"occurrence":occurrence,"translate":[5,0,0],"capture":true}));
+ assert_eq!(scratch.evaluations, 0);
+ assert!(Arc::ptr_eq(&definitions, &scratch.model.state()));
+ assert_fresh_world(&scratch);
+ assert!(session.world_state().bodies[0].mesh().bounds().min.dist(Vec3::new(10., 0., 0.)) < 1e-9);
+}
+
+fn assert_fresh_world(session: &Session) {
+ let mut fresh = crate::doc::Model::new();
+ fresh.no_cache = true;
+ fresh.evaluate(&session.doc);
+ assert!(fresh.results.iter().all(|r| r.error.is_none()));
+ let expected = crate::doc::world_state(&session.doc, &fresh.state());
+ let actual = session.world_state();
+ assert_eq!(actual.bodies.len(), expected.bodies.len());
+ for (a, b) in actual.bodies.iter().zip(&expected.bodies) {
+ assert_eq!(a.name, b.name);
+ assert_eq!(a.component, b.component);
+ let (a, b) = (a.mesh(), b.mesh());
+ assert_eq!(a.triangles, b.triangles);
+ assert_eq!(a.tri_face, b.tri_face);
+ assert_eq!(a.edge_faces, b.edge_faces);
+ assert_eq!(a.positions.len(), b.positions.len());
+ assert_eq!(a.normals.len(), b.normals.len());
+ for (a, b) in a.positions.iter().zip(&b.positions) {
+ assert!(a.dist(*b) < 1e-8);
+ }
+ for (a, b) in a.normals.iter().zip(&b.normals) {
+ assert!(a.dist(*b) < 1e-8);
+ }
+ }
+}
+
+#[test]
+fn geometry_independent_joint_drive_and_reach_keep_the_evaluated_model() {
+ let mut session = Session::default();
+ let created = run(&mut session, "component.create", json!({"name":"Rotor","grounded":false}));
+ let occurrence = created["occurrence"].as_u64().unwrap();
+ run(&mut session, "solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Block"}));
+ run(&mut session, "joint.as_built", json!({"type":"revolute","name":"Turn","a":0,"b":"Rotor","at":{"occurrence":0,"point":[0,0,0],"z":[0,0,1]}}));
+ let definitions = session.model.state();
+ for angle in [30_f64, -45., 90.] {
+ let before = session.evaluations;
+ let answer = run(&mut session, "joint.drive", json!({"joint":"Turn","value":angle,"quiet":true}));
+ assert_eq!(answer["errors"], json!([]));
+ assert_eq!(answer["conflicts"], json!([]));
+ assert_eq!(session.evaluations, before);
+ assert!(Arc::ptr_eq(&definitions, &session.model.state()));
+ let m = crate::doc::joints::occurrence_world(&session.doc, occurrence);
+ let expected = Vec3::new(2. * angle.to_radians().cos(), 2. * angle.to_radians().sin(), 0.);
+ assert!(crate::doc::apply_point(&m, Vec3::new(2., 0., 0.)).dist(expected) < 1e-8);
+ assert_fresh_world(&session);
+ }
+ let at = crate::doc::apply_point(&crate::doc::joints::occurrence_world(&session.doc, occurrence), Vec3::new(2., 0., 0.));
+ let before = session.evaluations;
+ let answer =
+ run(&mut session, "joint.reach", json!({"occurrence":occurrence,"at":[at.x,at.y,at.z],"point":[2.,0.,0.],"quiet":true,"continuous":true}));
+ assert_eq!(answer["reached"], true, "{answer}");
+ assert_eq!(session.evaluations, before);
+ assert!(Arc::ptr_eq(&definitions, &session.model.state()));
+ assert_fresh_world(&session);
+ for command in ["edit.undo", "edit.redo"] {
+ let before = session.evaluations;
+ run(&mut session, command, json!({}));
+ assert_eq!(session.evaluations, before);
+ assert_fresh_world(&session);
+ }
+}
+
+#[test]
+fn geometry_independent_fixed_sketch_extrusions_reuse_only_their_geometry() {
+ let mut session = Session::default();
+ let created = run(&mut session, "component.create", json!({"name":"Part","grounded":false}));
+ let occurrence = created["occurrence"].as_u64().unwrap();
+ run(&mut session, "sketch.create", json!({"plane":"XY"}));
+ run(&mut session, "sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[2,3]}));
+ run(&mut session, "sketch.finish", json!({}));
+ run(&mut session, "solid.extrude", json!({"distance":4,"operation":"new"}));
+ let definitions = session.model.state();
+ let before = session.evaluations;
+ run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[10,0,0],"capture":true}));
+ assert_eq!(session.evaluations, before);
+ assert!(Arc::ptr_eq(&definitions, &session.model.state()));
+ assert_fresh_world(&session);
+ // An edit made directly before the move is not the model's evaluated input, even though
+ // the command itself changes only placement. The proof must name the evaluated document.
+ let sketch = session.doc.features.iter().find(|f| matches!(f.kind, crate::doc::FeatureKind::Sketch { .. })).unwrap().id;
+ session.doc_mut().sketch_mut(sketch).unwrap().points[1].pos.x += 1.;
+ let before = session.evaluations;
+ run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[1,0,0],"capture":true}));
+ assert!(session.evaluations > before);
+ assert_fresh_world(&session);
+}
+
+#[test]
+fn placement_dependent_cross_component_cuts_still_evaluate_and_undo() {
+ use crate::doc::{Document, FeatureKind, Model, Operation, point_expr};
+ let mut document = Document::new("cross-component placement dependency");
+ let plate = document.add_component(Some("Plate"), 0).unwrap();
+ let tools = document.add_component(Some("Tools"), 0).unwrap();
+ for occurrence in &mut document.occurrences {
+ occurrence.grounded = occurrence.component == tools;
+ }
+ let feature = document
+ .add_feature(
+ FeatureKind::Box {
+ corner: point_expr(Vec3::ZERO),
+ length: "10".into(),
+ width: "10".into(),
+ height: "4".into(),
+ operation: Operation::NewBody,
+ },
+ None,
+ )
+ .unwrap();
+ document.feature_mut(feature).unwrap().component = plate;
+ let mut model = Model::new();
+ model.evaluate(&document);
+ let plate_body = model.state().bodies[0].name.clone();
+ let feature = document
+ .add_feature(
+ FeatureKind::Box {
+ corner: point_expr(Vec3::new(4., 4., -1.)),
+ length: "2".into(),
+ width: "2".into(),
+ height: "6".into(),
+ operation: Operation::Cut,
+ },
+ None,
+ )
+ .unwrap();
+ let feature = document.feature_mut(feature).unwrap();
+ feature.component = tools;
+ feature.participants = vec![plate_body.clone()];
+ let mut session = Session::new(document);
+ run(&mut session, "joint.as_built", json!({"type":"slider","name":"Slide","a":0,"b":"Plate","at":{"occurrence":0,"point":[0,0,0],"z":[1,0,0]}}));
+ assert!((session.model.state().body(&plate_body).unwrap().measure().unwrap().volume - 384.).abs() < 1e-7);
+ for (command, params, volume) in
+ [("joint.drive", json!({"joint":"Slide","value":5,"quiet":true}), 392.), ("edit.undo", json!({}), 384.), ("edit.redo", json!({}), 392.)]
+ {
+ let before = session.evaluations;
+ run(&mut session, command, params);
+ assert!(session.evaluations > before, "{command} must update the cut");
+ assert!((session.model.state().body(&plate_body).unwrap().measure().unwrap().volume - volume).abs() < 1e-7);
+ assert_fresh_world(&session);
+ }
+}
+
#[test]
fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joint_frames() {
let mut session = Session::default();
diff --git a/docs/perf.md b/docs/perf.md
index 6f36e29cb8..597abdd999 100644
--- a/docs/perf.md
+++ b/docs/perf.md
@@ -902,3 +902,79 @@ edited New Body and Offset Face drag regressions fail while Join passes. With th
all six distance-preview regressions pass, covering intermediate geometry, exact final
convergence, unchanged document/undo, obsolete errors and setup changes. A separate regression
checks the arrow's position on each held input frame.
+
+## Placement-only model reuse
+
+`Model::evaluate_shared(&Arc<Document>)` retains the document that produced a model and a weak
+reference to that exact model state. A subsequent shared document can keep the model without
+entering `Model::evaluate` when its geometry inputs are unchanged and all its features have
+explicitly supported local inputs. Session opening and refresh use this entry point; drive,
+reach, occurrence movement, scratch sessions and Undo/Redo share its decision. Joint solving,
+motion traces, view revision and world placement still follow the normal refresh path.
+
+Eligibility is computed during ordinary evaluation with its existing feature-owner index.
+The initial supported set is new-body boxes/cylinders/spheres/tori, embedded STEP/mesh imports,
+sketches on explicit local planes without links or 3D wires, and new-body extrudes of their own
+component's sketches without To Object, From Object or Through All. Other features, attachments,
+failed/skipped/stale results, primed evaluation and `no_cache` retain ordinary evaluation.
+The borrowed-document `evaluate` invalidates the retained proof. A saved model establishes a
+shared-input proof on its first ordinary refresh; this does not change saved model formats.
+Renaming results and adopting solved sketches also invalidate it: result labels and
+fingerprints can change while the geometry state stays identical.
+
+Every non-placement document field and every feature field is compared explicitly. Immutable
+import arrays/text are accepted by retained Arc identity; replacing an allocation conservatively
+evaluates again, including an equal-content replacement. New fields of the document, feature,
+mesh or supported feature variants require a decision in this comparison/eligibility policy.
+There is still a linear comparison of lightweight feature definitions and result freshness on a
+new document Arc. This is not a constant-time geometry revision system; the avoided work is the
+evaluator, parameter/context preparation, fingerprints and imported-payload traversal.
+
+Regression tests in the existing placement-cache and evaluation-cost suites check zero timeline
+evaluations, real world-space vertices/normals/topology against fresh evaluation, actual joint
+poses, retained snapshots, scratch and Undo/Redo. Direct geometry/parameter changes, mesh payload
+and metadata replacements, foreign model results, live sketches and unknown features invalidate
+or retain the fallback. The cross-component cut control is a 10 x 10 x 4 mm plate and a 2 x 2 x
+6 mm tool: after a 5 mm slider move it still evaluates to 392 mm3, undo to 384 mm3, redo to 392 mm3.
+
+### Release measurements (2026-10-25)
+
+Windows x64, Intel Core i9-14900K, Rust 1.99.0, release profile (opt-level 3, thin LTO, 16 codegen
+units). Baseline is main `ac53fc1e6fab85a50bdc410178cc75133183393f`; the changed build adds only
+this placement-reuse implementation. Each new process warms canonical meshes and eight operations,
+then runs 64 alternating +10/-10 degree drives/reaches. Three pairs alternate which build runs
+first. Numbers below are medians of the three per-run command/total medians, in milliseconds.
+Total includes the command, world placement and canonical display/reference mesh preparation;
+it excludes UI scene packing, GPU/presentation and input-to-photon latency.
+
+To separate additional benefit from #5480, a second comparison includes that same PR's
+`4720ac3c3f296bfc1d957c0363c656bce8d845cd` implementation in both builds, preserving main's
+feature-JSON and body-measurement caches when integrating it locally:
+
+| Case, with #5480 in both builds | Command before | Command after | Total before | Total after |
+| --- | ---: | ---: | ---: | ---: |
+| One moving component, 256 box bodies | 0.8599 | 0.5457 | 2.7114 | 2.3632 |
+| SO-101 drive | 0.3829 | 0.1363 | 1.4217 | 1.1349 |
+| SO-101 reach (the drag command) | 0.4024 | 0.1401 | 1.4474 | 1.1314 |
+| Cross-component cut, fallback control | 0.0335 | 0.0339 | 0.0842 | 0.0866 |
+
+That is 36.5% less command time / 12.8% less total for 256 bodies, and 65.2% / 21.8% for SO-101
+reach in this integration. The fallback control has no intended speedup; its small absolute
+variation is retained in the table. Against main alone, 256 bodies measure 0.8666 -> 0.5524 ms
+command and 2.7039 -> 2.3913 ms total. SO-101 reach measures 2.8656 -> 0.1443 ms command and
+4.0597 -> 1.1411 ms total; that larger difference overlaps #5480 and is not additive to it.
+
+Every pair agrees on all 64 command responses and occurrence matrices, the final world-space
+position/normal/topology hash, body/triangle counts and Undo/Redo. SO-101 retains its public
+13 bodies / 398,884 triangles; its input SHA-256 is
+`a335456ea4fba3729d41f901374575c785a14d2c4e6bf3bb7081d64062f3f7cb`.
+
+A separate counting build uses #6465's recorder from `969c15c2`, with only the model-evaluation
+and feature-fingerprint hooks wired. It records 1 evaluation / 256 fingerprints -> 0 / 0 for
+256 boxes, and 1 / 1 -> 0 / 0 for SO-101 drive and reach. The cut control stays at 1 / 3.
+The captures are complete for those two instrumented units; no claim is made about the other
+recorder units. The control explicitly disables reuse while retaining the ordinary feature
+cache. These counting-only hooks/switch are absent from the published source and timing builds.
+
+[Reproduction code, exact source/executable hashes and per-operation release samples](https://gist.github.com/takuto-NA/cf4c0c9a40f50d44e1b6cda96bba18bd)
+cover both baseline contexts and the independent counting probe.