Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(assembler): derive geometry hash from positions only, not triangulation

Sidwebworks1f02b3baf900
diff --git a/apps/assembler/src/cache.rs b/apps/assembler/src/cache.rs
index 97f8824540..80743a9e42 100644
--- a/apps/assembler/src/cache.rs
+++ b/apps/assembler/src/cache.rs
@@ -13,7 +13,8 @@ use std::sync::{Arc, Mutex};
/// LRU (below) AND the Redis job/result-pointer store (`store.rs`). Bump on ANY
/// converter OR planner behavior change so every stale entry, in every cache,
/// auto-misses. This is the "content-hash key + CODE_VERSION" auto-invalidation.
-pub const CODE_VERSION: u32 = 2;
+// v3: geometry_hash recipe changed to position-only (nodeIds renamed globally).
+pub const CODE_VERSION: u32 = 3;
pub struct CachedConvert {
pub glb: Bytes,
diff --git a/crates/converter/examples/dump_tree.rs b/crates/converter/examples/dump_tree.rs
new file mode 100644
index 0000000000..1b436047d5
--- /dev/null
+++ b/crates/converter/examples/dump_tree.rs
@@ -0,0 +1,38 @@
+//! Temp harness: build_tree a CAD file, print one line per leaf node:
+//! nodeId, geometryHash, name, verts, tris, volume, bbox. Usage:
+//! cargo run --release -p converter --example dump_tree -- <in.step|in.xbf>
+
+use converter::graph::AssemblyNode;
+
+fn walk(n: &AssemblyNode, out: &mut Vec<String>) {
+ if let Some(m) = &n.mesh {
+ out.push(format!(
+ "{}\t{}\t{}\t{}\t{}\t{:.6}\t{:.3},{:.3},{:.3}\t{:.3},{:.3},{:.3}",
+ n.node_id,
+ m.geometry_hash,
+ n.name,
+ m.positions.len(),
+ m.indices.len(),
+ n.volume.unwrap_or(0.0),
+ n.bbox_min[0],
+ n.bbox_min[1],
+ n.bbox_min[2],
+ n.bbox_max[0],
+ n.bbox_max[1],
+ n.bbox_max[2],
+ ));
+ }
+ for c in &n.children {
+ walk(c, out);
+ }
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let root = converter::convert::build_tree(&args[1], 0.1, 0.5).expect("build_tree");
+ let mut lines = Vec::new();
+ walk(&root, &mut lines);
+ for l in lines {
+ println!("{l}");
+ }
+}
diff --git a/crates/converter/examples/make_xbf.rs b/crates/converter/examples/make_xbf.rs
new file mode 100644
index 0000000000..6977610808
--- /dev/null
+++ b/crates/converter/examples/make_xbf.rs
@@ -0,0 +1,16 @@
+//! Temp harness: STEP → BinXCAF (.xbf) retained raw. Usage:
+//! cargo run --release -p converter --example make_xbf -- <in.step> <out.xbf>
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let t = std::time::Instant::now();
+ converter::convert::step_to_xbf(&args[1], &args[2]).expect("step_to_xbf");
+ let in_len = std::fs::metadata(&args[1]).unwrap().len();
+ let out_len = std::fs::metadata(&args[2]).unwrap().len();
+ eprintln!(
+ "xbf written: {} -> {} bytes in {:.1}s",
+ in_len,
+ out_len,
+ t.elapsed().as_secs_f64()
+ );
+}
diff --git a/crates/converter/examples/mesh_diff.rs b/crates/converter/examples/mesh_diff.rs
new file mode 100644
index 0000000000..fa980561bb
--- /dev/null
+++ b/crates/converter/examples/mesh_diff.rs
@@ -0,0 +1,121 @@
+//! Temp probe: compare the tessellation of same-named leaves between two CAD
+//! files (STEP vs xbf). Prints per-node vertex-delta stats to characterize the
+//! drift. Usage:
+//! cargo run --release -p converter --example mesh_diff -- <a> <b> [name-filter]
+
+use converter::graph::AssemblyNode;
+
+fn collect<'a>(n: &'a AssemblyNode, out: &mut Vec<&'a AssemblyNode>) {
+ if n.mesh.is_some() {
+ out.push(n);
+ }
+ for c in &n.children {
+ collect(c, out);
+ }
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let filter = args.get(3).cloned();
+ let ra = converter::convert::build_tree(&args[1], 0.1, 0.5).expect("a");
+ let rb = converter::convert::build_tree(&args[2], 0.1, 0.5).expect("b");
+ let (mut la, mut lb) = (Vec::new(), Vec::new());
+ collect(&ra, &mut la);
+ collect(&rb, &mut lb);
+ assert_eq!(la.len(), lb.len(), "leaf count");
+
+ for (a, b) in la.iter().zip(lb.iter()) {
+ let (ma, mb) = (a.mesh.as_ref().unwrap(), b.mesh.as_ref().unwrap());
+ if ma.geometry_hash == mb.geometry_hash {
+ continue;
+ }
+ if let Some(f) = &filter {
+ if !a.name.contains(f.as_str()) {
+ continue;
+ }
+ }
+ println!(
+ "=== {} verts={} tris={} idx_equal={}",
+ a.name,
+ ma.positions.len(),
+ ma.indices.len(),
+ ma.indices == mb.indices
+ );
+ if ma.positions.len() != mb.positions.len() {
+ println!(" VERT COUNT differs: {} vs {}", ma.positions.len(), mb.positions.len());
+ continue;
+ }
+ let mut ndiff = 0usize;
+ let mut max_d = 0f64;
+ let mut first: Vec<String> = Vec::new();
+ for (i, (pa, pb)) in ma.positions.iter().zip(mb.positions.iter()).enumerate() {
+ let d = ((pa[0] - pb[0]) as f64).abs().max(((pa[1] - pb[1]) as f64).abs()).max(((pa[2] - pb[2]) as f64).abs());
+ if d > 0.0 {
+ ndiff += 1;
+ if d > max_d {
+ max_d = d;
+ }
+ if first.len() < 5 {
+ first.push(format!(
+ " v{}: a=({:.9},{:.9},{:.9}) b=({:.9},{:.9},{:.9}) d={:.3e}",
+ i, pa[0], pa[1], pa[2], pb[0], pb[1], pb[2], d
+ ));
+ }
+ }
+ }
+ println!(
+ " differing verts: {}/{} max_delta={:.3e} mm",
+ ndiff,
+ ma.positions.len(),
+ max_d
+ );
+ for l in first {
+ println!("{l}");
+ }
+ // Classify the index difference: positional triangle compare —
+ // identical / same cycle rotated / winding-flipped / different triple;
+ // then whole-array set compare (order shuffle vs content change).
+ let (mut same, mut rot, mut flip, mut other) = (0usize, 0usize, 0usize, 0usize);
+ for (ta, tb) in ma.indices.iter().zip(mb.indices.iter()) {
+ let [a0, a1, a2] = *ta;
+ let [b0, b1, b2] = *tb;
+ if (a0, a1, a2) == (b0, b1, b2) {
+ same += 1;
+ } else if (a0, a1, a2) == (b1, b2, b0) || (a0, a1, a2) == (b2, b0, b1) {
+ rot += 1;
+ } else if (a0, a1, a2) == (b0, b2, b1)
+ || (a0, a1, a2) == (b2, b1, b0)
+ || (a0, a1, a2) == (b1, b0, b2)
+ {
+ flip += 1;
+ } else {
+ other += 1;
+ }
+ }
+ println!(" tris positional: same={same} rotated={rot} winding_flipped={flip} different={other}");
+ let norm = |idx: &[[u32; 3]], keep_winding: bool| {
+ let mut v: Vec<[u32; 3]> = idx
+ .iter()
+ .map(|t| {
+ if keep_winding {
+ // canonical rotation, winding preserved
+ let [a, b, c] = *t;
+ let m = a.min(b).min(c);
+ if m == a { [a, b, c] } else if m == b { [b, c, a] } else { [c, a, b] }
+ } else {
+ let mut s = *t;
+ s.sort_unstable();
+ s
+ }
+ })
+ .collect();
+ v.sort_unstable();
+ v
+ };
+ println!(
+ " as sets: same_winding_set_equal={} unordered_set_equal={}",
+ norm(&ma.indices, true) == norm(&mb.indices, true),
+ norm(&ma.indices, false) == norm(&mb.indices, false)
+ );
+ }
+}
diff --git a/crates/converter/src/graph.rs b/crates/converter/src/graph.rs
index 775f0e668a..a28895ed38 100644
--- a/crates/converter/src/graph.rs
+++ b/crates/converter/src/graph.rs
@@ -25,7 +25,7 @@ pub struct PartMesh {
impl PartMesh {
pub fn new(positions: Vec<[f32; 3]>, indices: Vec<[u32; 3]>, is_proxy: bool) -> Self {
- let geometry_hash = geometry_hash(&positions, &indices);
+ let geometry_hash = geometry_hash(&positions);
PartMesh {
positions,
indices,
diff --git a/crates/converter/src/nodeid.rs b/crates/converter/src/nodeid.rs
index 353f75acd0..66e0010514 100644
--- a/crates/converter/src/nodeid.rs
+++ b/crates/converter/src/nodeid.rs
@@ -1,23 +1,39 @@
-//! Stable nodeId derivation — byte-identical to `app/convert.py`
-//! (`_geometry_hash`, `_node_id`). Existing stored graphs/plans reference these
-//! IDs, so they must match Python exactly.
+//! Stable nodeId derivation.
+//!
+//! Identity comes from the part's quantized vertex positions ONLY — never from
+//! the triangulation topology. BRepMesh's Delaunay breaks near-co-circular
+//! quads by an epsilon comparison in UV space, so the chosen diagonal can flip
+//! on last-ulp parametrization noise (e.g. a BinXCAF raw roundtrip) while the
+//! 3D vertices stay bit-identical. Hashing indices made identity depend on
+//! that tie — a compacted raw re-read would silently rename a handful of
+//! parts. Positions are micron-quantized ints sorted into a canonical order,
+//! so the hash is also immune to vertex-emission-order ties.
+//!
+//! (v1 of this hash matched the retired Python pipeline byte-for-byte and
+//! included raw indices; changing the recipe renames every nodeId once —
+//! stored graphs/plans/mappings regenerate on re-conversion.)
use sha1::{Digest, Sha1};
-/// `_geometry_hash`: sha1 over quantized positions (mm×1000, round-half-even to
-/// int64) then uint32 indices, both little-endian row-major — matching numpy
-/// `.astype(float64)*1000`, `np.round` (rint = ties-to-even), `.tobytes()`.
-pub fn geometry_hash(positions: &[[f32; 3]], indices: &[[u32; 3]]) -> String {
+/// sha1 over the part's quantized vertex positions (mm×1000, round-half-even
+/// to int64, little-endian), sorted as (x, y, z) triples. Triangle indices are
+/// deliberately excluded — see module docs.
+pub fn geometry_hash(positions: &[[f32; 3]]) -> String {
+ let mut quantized: Vec<[i64; 3]> = positions
+ .iter()
+ .map(|p| {
+ [
+ (p[0] as f64 * 1000.0).round_ties_even() as i64,
+ (p[1] as f64 * 1000.0).round_ties_even() as i64,
+ (p[2] as f64 * 1000.0).round_ties_even() as i64,
+ ]
+ })
+ .collect();
+ quantized.sort_unstable();
let mut hasher = Sha1::new();
- for p in positions {
- for &c in p {
- let q = (c as f64 * 1000.0).round_ties_even() as i64;
- hasher.update(q.to_le_bytes());
- }
- }
- for tri in indices {
- for &i in tri {
- hasher.update(i.to_le_bytes());
+ for q in &quantized {
+ for &c in q {
+ hasher.update(c.to_le_bytes());
}
}
hex(&hasher.finalize())
@@ -44,18 +60,35 @@ mod tests {
use super::*;
#[test]
- fn geometry_hash_matches_python() {
- // Reference values captured from app.convert._geometry_hash.
+ fn geometry_hash_ignores_vertex_order() {
+ let a = [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
+ let b = [[1.0f32, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]];
+ assert_eq!(geometry_hash(&a), geometry_hash(&b));
+ }
+
+ #[test]
+ fn geometry_hash_distinguishes_geometry() {
+ let a = [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
+ let b = [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.5]];
+ assert_ne!(geometry_hash(&a), geometry_hash(&b));
+ // Sub-half-micron wiggle quantizes away.
+ let c = [[0.0002f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
+ assert_eq!(geometry_hash(&a), geometry_hash(&c));
+ }
+
+ #[test]
+ fn geometry_hash_stable_value() {
+ // Pinned so an accidental recipe change (quantization, sort, endian)
+ // is loud — this exact value is what stored graphs reference from now.
let pos = [
[0.0f32, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[1.0, 1.0, 1.0],
];
- let idx = [[0u32, 1, 2], [1, 3, 2]];
assert_eq!(
- geometry_hash(&pos, &idx),
- "9e21fed301a9b2683e3e381282e35ac1bb0576fb"
+ geometry_hash(&pos),
+ "23ddd092dc128b8467a7e243e0a58e9865dd4357"
);
}