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.
Geometry Service Rust Rewrite — implementation plan
Spec: .ai/plans/2026-07-10-geometry-service-rust-rewrite.md (feasibility plan; §9 decisions resolved — see Locked Decisions)
Research: embedded in the spec (§1 ground truth, ecosystem survey)
Branch: feat/geometry-rs (create from main)
Executor: Claude Opus — this plan is self-contained; no session memory assumed.
Locked decisions (do not re-litigate)
/planconsumes the GLB + graph.json that/convertproduced (signed GET URLs), not the STEP file. New payload shape, new service.- The OCCT cxx bridge is vendored in-repo at
services/geometry-rs/crates/occt-bridge. No fork of opencascade-rs; depend onocct-sysfor the OCCT build only. - No PyO3 phase 0. Straight to Phase A.
- New code lives at
services/geometry-rs/during transition. Pythonservices/geometry/stays untouched and running until the final cutover tasks. - Python planner semantics are frozen for the duration of the port. If
services/geometry/app/plan.pychanges onmainmid-port, STOP and report — goldens must be re-based deliberately.
Rust conventions (apply to every task)
From .ai/skills/rust-best-practices (read references/chapter_01.md, chapter_04.md, chapter_05.md before writing code):
- Errors:
thiserrorenums in library crates (planner,converter,glb,geometry-types,occt-bridge);anyhowonly in theserverbinary. - Never
unwrap()/expect()outside#[cfg(test)]. OCCT and mesh data are hostile inputs. &str/&[T]parameters over owned types; no clones in loops; iterators over manual index loops where clarity allows.- Test names describe behavior:
seated_pair_depths_reports_max_penetration_for_overlapping_boxes(). - Lint gate for every task:
cargo clippy --all-targets --locked -- -D warningsmust pass. - Use the
nalgebraversion re-exported by parry3d (use parry3d::na) — never a separately-pinned nalgebra (version skew breaks the math types). //comments only for non-obvious why (mirrors repo-wide comment rule).
Hard rules from .ai/lessons.md (encoded as task constraints, but read them: lines 114–220)
- Never fabricate a motion. No tier-4 "forced removal". Unsolvable part ⇒
motion: "none"+blockedBy+ warning. - Tolerance ≪ sample spacing.
PENETRATION_TOLERANCE_MM = 0.15vsMAX_SAMPLE_SPACING_MM = 2.0— allowances are pair-scoped and axis-gated, never global. - Fail-closed heuristics. Classification with out-of-range evidence rejects; it never grants an allowance.
- BVH per mesh, built once. Never rebuild per query. "Excluding" a part during its own sweep = unregister the same collision object from the broadphase (rebuilds nothing), re-register after. Blocker discovered mid-sweep ⇒ unregister for the rest of that sweep.
- Fastener names: no ambiguous single tokens (
pinis out); name match + physical sanity cap (max(100mm, 0.35 × assembly diagonal)). - GLB↔graph join must be validated by bbox against graph.json (authoritative), asserting full coverage with max error < 1 mm.
Progress
- Task 1: Scaffold the cargo workspace
- Task 2: Wire types crate (
geometry-types) - Task 3: Fixture generation script (Python-side, emits GLB/graph/STEP test data)
- Task 4: GLB reader with meshopt decode (
glbcrate, read half) - Task 5: SPIKE — meshopt quantization error vs penetration tolerance (GO/NO-GO gate)
- Task 6: Planner scaffolding — constants,
Component, world-part collection - Task 7: Parity tracker (
PARITY.md) enumerating all Python plan tests - Task 8: Collision layer — broadphase manager + calibration suite
- Task 9: Seated pair depths + ordering adjacency
- Task 10: Fastener classification
- Task 11: Rigid merge + embedded pairs
- Task 12: Fastener ring joints
- Task 13: Sandwich detection
- Task 14: Removal planning — tier 1 linear + tier 2 "L"
- Task 15: Tier 3 escape BFS + group removal
- Task 16: Greedy disassembly loop + base re-selection
- Task 17: Precedence DAG, preference topo sort, forward verification
- Task 18: Fixed-sequence mode + units
- Task 19:
plan_steporchestration + plan.json v3 output parity - Task 20: Determinism test, then rayon parallelization
- Task 21: Server binary — axum
/health,/plan,/plan/{jobId} - Task 22: Shadow-comparison harness + large-noisy-model gate
- Task 23: Jobs-side switch —
assembly-plan.tscalls the Rust planner - Task 24: Dev-stack wiring for the Rust planner
- Task 25:
occt-bridgecrate — build skeleton + exception guards - Task 26: Bridge surface — STEP/XCAF document read
- Task 27: Bridge surface — tessellation, volume, bbox, colors
- Task 28: Converter crate — XCAF walk, nodeIds, graph.json parity
- Task 29: GLB writer (
glbcrate, write half) - Task 30: meshopt encode pipeline (replaces gltf-transform)
- Task 31: Server
/convertroute + endpoint tests - Task 32: Rust fixture generator (drop Python from geometry-rs CI)
- Task 33: Converter parity gate (Python vs Rust on fixtures + real STEP)
- Task 34: Dockerfile + CI workflow
- Task 35: Full cutover + Python removal (requires user approval)
Dependencies
- Tasks 1→2→{3,4}→5 are strictly sequential. Task 5 is a GO/NO-GO gate.
- Tasks 6–8 after 5. Tasks 9–13 depend on 8; 9 must precede 10–13 (they consume pair depths). Tasks 10, 11, 12, 13 are mutually independent (parallelizable).
- 14→15→16→17→18→19→20 sequential. 21 needs 19. 22 needs 21. 23 needs 22 pass. 24 needs 23.
- Phase B: 25→26→27→28→29→30→31; 32 after 26; 33 needs 31+32. Phase B can start any time after Task 1 (independent of Phase A beyond scaffolding) if parallel capacity exists.
- 34 needs 31. 35 needs 22 AND 33 green + user sign-off.
Task 1: Scaffold the cargo workspace
Depends on: none Files:
- Create:
services/geometry-rs/Cargo.toml(workspace) - Create:
services/geometry-rs/rust-toolchain.toml - Create:
services/geometry-rs/.gitignore(/target) - Create:
services/geometry-rs/crates/geometry-types/{Cargo.toml,src/lib.rs} - Create:
services/geometry-rs/crates/glb/{Cargo.toml,src/lib.rs} - Create:
services/geometry-rs/crates/planner/{Cargo.toml,src/lib.rs} - Create:
services/geometry-rs/crates/server/{Cargo.toml,src/main.rs}
Steps:
- Verify toolchain:
rustc --version. If rustc is missing or < 1.80, STOP and report — do not install toolchains silently. - Workspace
Cargo.toml:[workspace]withmembers = ["crates/*"],resolver = "2". Central[workspace.dependencies]:serde = { version = "1", features = ["derive"] },serde_json = "1",thiserror = "2",parry3d-f64 = "0.29"(f64 — the Python planner is float64 throughout; f32 would shift every tolerance),rstar = "0.13",meshopt = "0.6",sha1 = "0.10",hex = "0.4",rayon = "1",tokio = { version = "1", features = ["full"] },axum = "0.8",reqwest = { version = "0.12", features = ["stream"] },anyhow = "1",dashmap = "6",tracing = "0.1",tracing-subscriber = "0.3". If a pinned version doesn't resolve, use the nearest compatible latest and note it in the commit message. - Workspace lints in root
Cargo.toml:
Each crate adds[workspace.lints.clippy] unwrap_used = "deny" expect_used = "deny" [workspace.lints.rust] missing_docs = "allow"[lints] workspace = true. In test modules, use#[allow(clippy::unwrap_used, clippy::expect_used)]at the module top. rust-toolchain.toml:[toolchain] channel = "stable" components = ["rustfmt", "clippy"].- Each crate compiles empty (
lib.rswith//! doc line;server/src/main.rsprinting nothing, returningOk(())fromfn main() -> anyhow::Result<()>).
Verify:
cd services/geometry-rs && cargo build --locked 2>&1 | tail -2 && cargo clippy --all-targets --locked -- -D warnings 2>&1 | tail -2
# Expected: "Finished `dev` profile" twice, zero warnings/errors
Out of scope: occt-bridge and converter crates (Phase B, Task 25). No CI workflow yet (Task 34).
Task 2: Wire types crate (geometry-types)
Depends on: Task 1 Files:
- Create:
services/geometry-rs/crates/geometry-types/src/{graph.rs,plan.rs,wire.rs,lib.rs} - Copy from (precedent):
packages/viewer/src/types.ts(graph + motion types),packages/viewer/src/plan.ts(plan v3),services/geometry/app/schemas.py(wire request/response)
Steps:
graph.rs:AssemblyGraph { version: u32 /* =1 */, unit: String /* "mm" */, source_unit: String, component_count: u32, root: AssemblyGraphNode };AssemblyGraphNode { node_id, name, is_assembly, geometry_hash: Option<String>, transform: [f64; 16] /* col-major */, bbox: Bbox { min: [f64;3], max: [f64;3] }, volume: Option<f64>, color: Option<[f32;4]>, children: Vec<AssemblyGraphNode> }. All types#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")].plan.rs: mirrorpackages/viewer/src/plan.tsexactly —AssemblyPlan(version 3, unit "mm",sequence: Vec<String>,components: BTreeMap<String, PlannedComponent>— BTreeMap, not HashMap, for deterministic JSON key order),Motionas a#[serde(tag = "type")]enum with variantslinear,l(serde rename"L"),helix,path,none, plusgroups,warnings, per-componentconfidence/tier/verified/groupId/mergedInto. Read the TS file field-by-field; every field present there must exist here.wire.rs:PlanRequest(NEW shape — this is the contract change):{ jobId: String, source: PlanSource { glbUrl: String, graphUrl: String }, options: PlanOptions }.PlanOptionsportsservices/geometry/app/schemas.pyPlanOptionsverbatim:linearDeflection=0.1, angularDeflection=0.5, clearance=0.5, pathSamples=60, units: Option<Vec<PlanUnit>>, sequence: Option<Vec<Vec<String>>>with defaults via#[serde(default = "...")];PlanUnit { id, name: Option<String>, nodeIds }. AlsoPlanStartResponse,PlanStatusResponse,PlanStats { planMs, tiers: BTreeMap<String, u32>, warnings, verifiedCount },HealthResponse— mirror schemas.py field-for-field, camelCase on the wire.- Reject empty
sequencegroups on deserialize (customDeserializeor avalidate()method returningResult<(), TypesError>), matching the Pydanticfield_validator. - Tests: round-trip a hand-written graph.json sample and a plan.json v3 sample (embed as
include_str!string literals — take real output shapes frompackages/viewer/src/plan.tsdoc comments andservices/geometry/tests/test_convert.pyexpectations); assert unknown fields are ignored (serde default behavior) and camelCase renames hold (assert!(json.contains("\"nodeId\""))).
Verify:
cd services/geometry-rs && cargo test -p geometry-types 2>&1 | tail -3
# Expected: "test result: ok." with 0 failed
Out of scope: ConvertRequest/Response wire types (Phase B, Task 28 adds them to this crate).
Task 3: Fixture generation script (Python-side)
Depends on: Task 1 Files:
- Create:
services/geometry-rs/scripts/make_fixtures.py - Copy from (precedent):
services/geometry/tests/fixtures/make_fixtures.py(STEP generation),services/geometry/app/convert.py(convert_step),services/geometry/app/optimize.py(compress_glb)
Steps:
- Script runs with the Python service's venv: it imports
app.convert.convert_stepandapp.optimize.compress_glbviasys.path.insert(0, "../geometry")(adjust to actual relative path from the script's location). - It generates the three STEP fixtures the Python tests use (
box.step,plates.step,nested.step— reuse the functions inservices/geometry/tests/fixtures/make_fixtures.py) intoservices/geometry-rs/fixtures/, then runsconvert_stepon each producing<name>.glb+<name>.graph.json, thencompress_glbproducing<name>.meshopt.glb. Keep BOTH compressed and uncompressed GLBs — Task 5 needs the pair. - Add
services/geometry-rs/fixtures/toservices/geometry-rs/.gitignore(generated, never committed — repo rule: no binary files). - Rust tests that need fixtures must
skipcleanly whenfixtures/is absent (check path, print"fixtures missing — run scripts/make_fixtures.py", return early). Document this at the top of the script.
Verify:
cd services/geometry && source .venv/bin/activate && cd ../geometry-rs && python scripts/make_fixtures.py && ls fixtures/
# Expected: box.step plates.step nested.step + .glb, .graph.json, .meshopt.glb for each (12 files total minimum)
# If services/geometry/.venv does not exist, STOP and report — do not pip install into the system.
Out of scope: Rust-native fixture generation (Task 32). Committing any fixture binary.
Task 4: GLB reader with meshopt decode (glb crate, read half)
Depends on: Tasks 2, 3 Files:
- Create:
services/geometry-rs/crates/glb/src/{read.rs,meshopt_decode.rs,error.rs} - Modify:
services/geometry-rs/crates/glb/src/lib.rs— exportread_assembly_glb
Steps:
- Parse GLB container manually (12-byte header, JSON chunk, BIN chunk — the format is trivial; do NOT pull the full
gltfcrate import machinery, parse the JSON chunk withserde_json::Valueplus small typed structs for the parts we need: nodes/meshes/accessors/bufferViews/extensions). Rationale: we needextras.nodeId(typed gltf crates drop or complicate extras) andEXT_meshopt_compressionbufferViews (unsupported by gltf-rs). meshopt_decode.rs: decodeEXT_meshopt_compressionbufferViews using themeshoptcrate decoders (decode_vertex_buffer,decode_index_buffer, plus filter decoders for OCTAHEDRAL/QUATERNION/EXPONENTIAL). If themeshoptcrate does not expose a needed decode function, call the correspondingmeshopt-sysFFI function directly behind a safe wrapper — checkmeshopt-sysdocs first; if neither exposes it, STOP and report.- Public API:
read_assembly_glb(bytes: &[u8]) -> Result<GlbAssembly, GlbError>whereGlbAssembly { parts: Vec<GlbPart> },GlbPart { node_id: String, vertices: Vec<[f64; 3]> /* world-space */, indices: Vec<[u32; 3]> }. Compute world transforms by walking the scene node tree (node.matrix or TRS), multiply into vertices. Note: the converter bakes vertices in world space with identity node transforms — but do NOT rely on that; apply transforms anyway (correct in both cases). - Join validation (mandatory, from lessons):
validate_against_graph(assembly: &GlbAssembly, graph: &AssemblyGraph) -> Result<(), GlbError>— every graph leaf (non-assembly node) has a GLB part with matchingnode_id; each part's computed AABB matches the graph node's world bbox within 1.0 mm max component error; error lists every mismatched nodeId. Callers must run this before planning. - Tests (fixture-gated per Task 3): read
plates.meshopt.glb+plates.graph.json→ validation passes, part count matchescomponentCount, 4 plate screws share... (don't assert mesh sharing here — after decode each part has its own vertex copy; assert counts and bbox validation only). Same for uncompressedplates.glb(reader must handle both).
Verify:
cd services/geometry-rs && cargo test -p glb 2>&1 | tail -3
# Expected: "test result: ok." 0 failed (tests skip with a message if fixtures/ absent — run Task 3 first)
Out of scope: GLB writing (Task 29), meshopt encoding (Task 30).
Task 5: SPIKE — quantization error vs penetration tolerance (GO/NO-GO)
Depends on: Task 4 Files:
- Create:
services/geometry-rs/crates/glb/tests/quantization_spike.rs - Create:
services/geometry-rs/SPIKE-QUANTIZATION.md(findings)
Steps:
- For each fixture pair (
<name>.glbvs<name>.meshopt.glb): decode both, match parts by nodeId, compute per-vertex position error (max + p99 across all parts). - Threshold: the planner's collision truth uses
PENETRATION_TOLERANCE_MM = 0.15(scaled up to2.5 × linearDeflection). Quantization error must be ≤ 0.05 mm max (one order below the scaled floor is not achievable; a third of the base tolerance is the bar). - Write measured numbers into
SPIKE-QUANTIZATION.mdwith the verdict. - If error > 0.05 mm: STOP and report with the numbers. The fallback (Python
/convertalso uploads an uncompressedmodel.raw.glbfor the planner) is a contract change that needs user sign-off — do not implement it unilaterally. - If available, also run one real customer GLB (ask the user; the "seat rail" and "SA Mando harness" models are the known references) — record in the same doc.
Verify:
cd services/geometry-rs && cargo test -p glb --test quantization_spike -- --nocapture 2>&1 | tail -5
# Expected: printed max/p99 error per fixture, all max ≤ 0.05, "test result: ok."
Out of scope: Any change to the Python service.
Task 6: Planner scaffolding — constants, Component, world-part collection
Depends on: Task 5 (GO) Files:
- Create:
services/geometry-rs/crates/planner/src/{constants.rs,component.rs,collect.rs,error.rs} - Copy from (precedent):
services/geometry/app/plan.pylines 61–173 (constants),_collect_world_parts(line 2195),_part_volume(line 1110)
Steps:
constants.rs: transcribe EVERY module-level constant fromservices/geometry/app/plan.pylines 61–173 with identical names (Rust SCREAMING_SNAKE, same values):PLAN_VERSION=3,PENETRATION_TOLERANCE_MM=0.15,EXIT_MARGIN_MM=5.0,MAX_SAMPLE_SPACING_MM=2.0,MAX_PATH_SAMPLES=400,MATE_MIN_DEPTH_MM=0.2,MATE_DEPTH_MARGIN_MM=0.3,ORDERING_CONTACT_MM=0.5,MAX_ADJACENCY_DISTANCE_PAIRS=20000,SANDWICH_*(4),MAX_FASTENER_DIAGONAL_FRACTION=0.35,MAX_FASTENER_EXTENT_MM=100.0,MAX_ESCAPE_SEGMENTS=3,MAX_ESCAPE_EXPANSIONS=24,MIN_HOP_FRACTION=0.25,MAX_GROUP_SIZE=4,MAX_GROUP_TESTS=40,GROUP_PROXIMITY_MM=2.0,WORLD_AXES, theFASTENER_NAME_REregex (port to theregexcrate — addregex = "1"to workspace deps; copy the pattern character-for-character from plan.py line 138, including the deliberate absence of a barepintoken), and_mesh_tolerance(linear_deflection)(line 73). Read the actual file — do not trust this list to be exhaustive.component.rs:Componentport of_Component(find the dataclass/class definition in plan.py; fields include node_id, name, mesh (parryTriMesh), world bbox, volume, plus the caches the Python code hangs on the mesh —bvh/volume become owned struct fields instead of monkey-patched attributes).collect.rs:collect_world_parts(glb: &GlbAssembly, graph: &AssemblyGraph) -> Result<Vec<Component>, PlannerError>— port_collect_world_partssemantics: leaves only, world-spaceTriMeshfrom GLB parts (join by nodeId — GLB is the mesh source in Rust; Python re-tessellated from STEP), volume via_part_volumeport: watertight → mesh volume; non-watertight → split into watertight components and sum, else bbox-volume fallback. parry3dTriMeshhas orientation/topology flags; if watertightness cannot be determined from parry, implement a closed-mesh check (every edge shared by exactly 2 triangles) in this crate — small and deterministic.- Unit tests with hand-built meshes (a unit cube TriMesh helper in
#[cfg(test)]— this helper gets reused by every later task; give itsubdivided(size)support now, mirroring thesubdivide_to_size(5.0)lesson for sliding-contact tests).
Verify:
cd services/geometry-rs && cargo test -p planner 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: Any collision logic (Task 8).
Task 7: Parity tracker
Depends on: Task 6 Files:
- Create:
services/geometry-rs/PARITY.md
Steps:
- Run
grep -n "^def test_" services/geometry/tests/test_plan.py(and the class-based variants if any:grep -n "def test_" services/geometry/tests/test_plan.py). List EVERY test name inPARITY.mdas a checkbox table:| Python test | Rust test | Task | Status |, status one ofpending / ported / n-a (reason). - Assign each test to one of Tasks 9–19 by subject (read each test's body to classify: seated/adjacency → 9, fastener classification → 10, merge/embedded → 11, joints → 12, sandwich → 13, removal tiers → 14/15, greedy/base → 16, precedence/topo/verify → 17, fixed-sequence/units → 18, end-to-end/determinism → 19/20).
- Rule for all subsequent tasks: a task is NOT done until its assigned PARITY.md rows are
portedand green.n-arequires a written reason (e.g. tests Python-internal monkey-patching).
Verify:
grep -c "^def test_" services/geometry/tests/test_plan.py && grep -c "| test_" services/geometry-rs/PARITY.md
# Expected: two equal numbers (every Python test has a row)
Out of scope: porting any test yet.
Task 8: Collision layer — broadphase manager + calibration suite
Depends on: Task 6 Files:
- Create:
services/geometry-rs/crates/planner/src/collision.rs - Create:
services/geometry-rs/crates/planner/tests/calibration.rs - Copy from (precedent):
services/geometry/app/plan.py—_mesh_bvh(3121),_unregistered(3138),_contacts_at(3168),_seated_pair_depths(2226),_blocking_depth(3835)
Steps:
- Design a
CollisionWorldowning: per-part parry3dTriMesh(its internal QBVH is the BVH-built-once), anrstar::RTreeof part AABBs as the broadphase (replaces fcl's DynamicAABBTreeCollisionManager), and a registered/unregistered flag set (HashSet<usize>) so unregister/re-register is O(1) bookkeeping, never a rebuild — this implements the two lessons (self-exempt sweep, blocker-unregister-mid-sweep) structurally. Contact { part_a: usize, part_b: usize, point: [f64;3], normal: [f64;3], depth: f64 }. Narrowphase via parry3d mesh-mesh contact manifolds at a transformed pose (parry3d::query::contact/contact_manifoldson TriMesh pairs). Semantic risk lives here: FCL reports per-triangle-pair local penetration; parry manifolds aggregate differently. The calibration suite defines the required semantics; adapt the extraction (e.g. per-manifold-point depth) until calibration passes.- Calibration tests (all with the Task 6 cube helper, subdivided where sliding contact is sustained — lesson from
.ai/lessons.md"Synthetic box meshes fake huge penetration"):- two 10 mm cubes overlapping 0.05 mm face-on → max depth ∈ [0.04, 0.06] (below tolerance ⇒ "seated, not colliding")
- overlapping 1.0 mm → depth ∈ [0.9, 1.1]
- disjoint by 0.1 mm → no contacts
- 5 mm cylinder (tessellated ~32 segments, helper) inside 5.05 mm bore → radial depths all < PENETRATION_TOLERANCE_MM
- subdivided slider seated 0.05 mm into a channel floor, sampled while translating tangentially → depth stays < 0.15 at every sample (the FCL artifact this guards against reported 29.8 mm)
- exact distance between two cubes 0.3 mm apart → ∈ [0.29, 0.31] (parry
distance) - point-containment: centroid of a cube → inside; point 0.1 mm outside a face → outside (parry point projection; this replaces
mesh.containsray-casts)
- If any calibration bound cannot be met by any parry contact-extraction strategy, STOP and report with the failing case and measured values — this invalidates the parry choice and the user must decide (options: different query strategy, or wrapping the C++ FCL — do not choose unilaterally).
seated_pair_depths(world) -> PairDataport (plan.py 2226): one broadphase pass over all registered pairs; per pair: max depth, contact points capped at 64, uncapped normal structure tensorΣ n·nᵀ, contact AABB.
Verify:
cd services/geometry-rs && cargo test -p planner --test calibration 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: path sampling / sweeps (Task 14 builds on contacts_at).
Task 9: Seated pair depths + ordering adjacency
Depends on: Task 8 Files:
- Create:
services/geometry-rs/crates/planner/src/adjacency.rs - Modify:
services/geometry-rs/crates/planner/src/lib.rs— exports - Copy from (precedent):
services/geometry/app/plan.py_ordering_adjacency(1632),_rollup_adjacency(1702),_separation_distance(grep for it)
Steps:
- Port
_ordering_adjacency: inflated-AABB prefilter → exact parry distance for pairs withinORDERING_CONTACT_MM = 0.5; budget capMAX_ADJACENCY_DISTANCE_PAIRS = 20000, past budget degrade to bbox-only adjacency exactly as Python does (read the degradation branch carefully). - Port
_rollup_adjacency(post-merge unit adjacency) and the analytic per-axis_separation_distance. - Port PARITY.md rows assigned to Task 9. Python tests that build synthetic
_Components translate to the Task 6 helper; keep the Python test names as Rust test names (snake-case as-is).
Verify:
cd services/geometry-rs && cargo test -p planner adjacency 2>&1 | tail -3
# Expected: "test result: ok." 0 failed; PARITY.md Task-9 rows flipped to ported
Out of scope: precedence edges (Task 17).
Task 10: Fastener classification
Depends on: Task 9 Files:
- Create:
services/geometry-rs/crates/planner/src/fasteners.rs - Copy from (precedent):
services/geometry/app/plan.py_classify_fasteners(2287),_is_fastener(170),_shank_radius(2364),_symmetry_axis_kind(2721),_symmetry_axis(2758),_axis_from_contacts(2543),_bbox_axis_kind(2584),_normal_clusters(2763),_head_direction(3217)
Steps:
- Port the full cascade: name regex (+ the structural-size sanity cap
max(MAX_FASTENER_EXTENT_MM, MAX_FASTENER_DIAGONAL_FRACTION × assembly diagonal)— lesson: "Electronics Box - 36 Pin") → SVD symmetry axis (rod vs disc from singular-value ratios; useparry3d::na::SVDon the centered vertex matrix) → bbox-extent kind → contact-ring PCA → dominant contact-normal cluster. Read each Python function fully before porting; the singular-value ratio thresholds are load-bearing. _shank_radius: mate-contact radial mean, falling back to vertex-radial 25th percentile (implement percentile by sorting — no numpy; nearest-rank method, verify against numpy's defaultlinearinterpolation on a test vector and match Python's result for the test inputs).- Port PARITY.md Task-10 rows.
Verify:
cd services/geometry-rs && cargo test -p planner fasteners 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: joint detection (Task 12), removal ordering (Task 16).
Task 11: Rigid merge + embedded pairs
Depends on: Task 9 Files:
- Create:
services/geometry-rs/crates/planner/src/merge.rs - Copy from (precedent):
services/geometry/app/plan.py_embedded_pairs(2605),_merge_rigid_groups(2637),_merge_units(479),_eject_fastened_unit_members(412)
Steps:
_embedded_pairs: bbox containment prefilter → point-containment on ≤ 24 sampled inner vertices, > 80 % inside ⇒ embedded (uses Task 8 containment)._merge_rigid_groups: union-find (implement inline — 20 lines; no crate) over deep-interpenetration pairs + embedded pairs; merged cluster becomes one concatenatedTriMesh(rebuild QBVH once for the merged mesh)._merge_units/_eject_fastened_unit_members: caller-specifiedPlanUnitpre-grouping + the fastener-ejection rule (fasteners named in a unit get ejected back out — read the Python for the exact condition).- Port PARITY.md Task-11 rows (embedded-logo test et al.).
Verify:
cd services/geometry-rs && cargo test -p planner merge 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: group removal (Task 15).
Task 12: Fastener ring joints
Depends on: Tasks 10, 11 Files:
- Create:
services/geometry-rs/crates/planner/src/joints.rs - Copy from (precedent):
services/geometry/app/plan.py_fastener_joints(2391),_axis_span(2523),_mate_exempt(3259),_seated_exempt(3278),_self_exempt(3201)
Steps:
- Ring-containment probe: 8 points on circle of
shankRadius × 1.2(+ clearance radius) at 3 heights along the axis; candidate surrounding ≥ 6/8 ⇒ through-part. Point-containment from Task 8. - Exemption model: port
_mate_exempt/_seated_exempt/_self_exemptas a singleExemptionsstruct consulted bycontacts_atfiltering. Lesson constraint: every exemption is pair-scoped and axis-gated with a depth cap (seated interference +MATE_DEPTH_MARGIN_MM); no global allowances. If the Python code has a branch that looks like a blanket allowance, port it exactly anyway (parity first) but flag it in PARITY.md notes. - Port PARITY.md Task-12 rows (unscrew-through-mate, washer-before-bolt, snug counterbore, stud-clamping, never-tunnel-thin-cover…).
Verify:
cd services/geometry-rs && cargo test -p planner joints 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: sweep mechanics (Task 14).
Task 13: Sandwich detection
Depends on: Task 9 Files:
- Create:
services/geometry-rs/crates/planner/src/sandwich.rs - Copy from (precedent):
services/geometry/app/plan.py_sandwiched_parts(1382)
Steps:
- Port
_sandwiched_parts: symmetric eigendecomposition (parry3d::na::SymmetricEigen) of the pair structure tensor; thickness caps BOTH ratio (SANDWICH_MAX_THICKNESS_RATIO=0.3) AND absolute (SANDWICH_MAX_THICKNESS_MM=6.0); axis alignment ≥ 0.9; squish capSANDWICH_MAX_SQUISH_MM=0.6. These dual caps exist because ratio-only classification produced a 33 mm "gasket" (lesson: "Ordering heuristics must be gated on a large noisy model") — do not weaken them. - Port PARITY.md Task-13 rows (gasket ordering, axis-gating, thickness/depth negatives).
Verify:
cd services/geometry-rs && cargo test -p planner sandwich 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: the soft ordering edges it feeds (Task 17).
Task 14: Removal planning — tier 1 linear + tier 2 "L"
Depends on: Tasks 8, 12 Files:
- Create:
services/geometry-rs/crates/planner/src/sweep.rs - Create:
services/geometry-rs/crates/planner/src/removal.rs - Copy from (precedent):
services/geometry/app/plan.py_contacts_at(3168),_path_is_clear/_path_blockers(1178),_plan_removal(3301),_candidate_directions(2789),_free_travel(3856),_recorded_travel(3890),_removal_segments(1162)
Steps:
sweep.rs:contacts_at(world, part, pose, exemptions)(narrowphase at a sampled pose, exemption-filtered),path_is_clear(dense sampling: spacing ≤MAX_SAMPLE_SPACING_MM=2.0, ≤MAX_PATH_SAMPLES=400, bounded by AABBseparation_distance+EXIT_MARGIN_MM),path_blockerswith the blocker-unregister optimization: once a partner exceeds tolerance it is recorded and unregistered for the remainder of that sweep, re-registered before return (lesson: this was the 8× win; the mechanism is the Task 8 flag set).removal.rs:plan_removaltier 1 (candidate directions: symmetry axis ± , contact-normal clusters, world axes — port_candidate_directionsordering exactly; theentanglementsort closure at 3370 decides candidate order and hence output determinism) and tier 2 "L" (lift-then-slide two-segment motions). Motion output = ordered(direction, travel)segments; the recorded plan motion is the reversed removal (port_removal_segments_to_planned, 3803).- Port PARITY.md Task-14 rows (top-down stack, pin-in-bore, rod-axis-preference…). Sliding-contact synthetic tests use the subdivided helper.
Verify:
cd services/geometry-rs && cargo test -p planner removal 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: escape BFS + groups (Task 15), the greedy loop (Task 16).
Task 15: Tier 3 escape BFS + group removal
Depends on: Task 14 Files:
- Create:
services/geometry-rs/crates/planner/src/escape.rs - Modify:
services/geometry-rs/crates/planner/src/removal.rs— tier 3 + group hooks - Copy from (precedent):
services/geometry/app/plan.py_plan_escape(3477),_plan_group_removal(3621),_group_exempt(3584)
Steps:
_plan_escape: axis-aligned hop BFS, ≤MAX_ESCAPE_SEGMENTS=3segments, ≤MAX_ESCAPE_EXPANSIONS=24expansions, hop length ≥MIN_HOP_FRACTIONof part extent. Deterministic expansion order (BTreeMap/sorted frontier — no HashMap iteration order anywhere in planner logic; enforce with a grep in the Verify step)._plan_group_removal: proximity-graph subassembly groups ≤MAX_GROUP_SIZE=4, ≤MAX_GROUP_TESTS=40, proximityGROUP_PROXIMITY_MM=2.0; group treated as one rigid body for the sweep.- No tier 4. If the Python file still contains any forced-removal remnant, do not port it; unsolvable ⇒ flagged (
motion: none,blockedBy, warning) per lesson "Never fabricate a best-effort motion". - Port PARITY.md Task-15 rows (blind-pocket multi-segment escape, group extraction, captive-part flag-or-merge).
Verify:
cd services/geometry-rs && cargo test -p planner escape 2>&1 | tail -3 && ! grep -rn "HashMap" services/geometry-rs/crates/planner/src/{escape,removal,sweep}.rs
# Expected: tests ok; grep exits non-zero (no HashMap in planning-order code paths)
Out of scope: ordering of removal attempts (Task 16).
Task 16: Greedy disassembly loop + base re-selection
Depends on: Tasks 10, 11, 13, 15 Files:
- Create:
services/geometry-rs/crates/planner/src/greedy.rs - Copy from (precedent):
services/geometry/app/plan.py_greedy_disassembly(2815),removal_priority(2868),_reselect_base(1735),_structural_key(1138),_assembly_centroid(1156)
Steps:
- Port
_greedy_disassembly(~300 LOC): the removal_priority ordering (read the closure carefully — priority ranking schedules expensive attempts AND picks flag/merge victims; a mis-ported comparator silently wrecks quality per the "preferences don't belong in removal_priority" lesson), per-partplan_removalattempts, merge-on-failure and flag-on-failure paths. - Port
_reselect_basescoring (mate-degree × volume, exact tuple ordering from thescoreclosure at 1763). - All orderings sort with explicit stable keys ending in
node_idas the final tiebreak (determinism). - Port PARITY.md Task-16 rows.
Verify:
cd services/geometry-rs && cargo test -p planner greedy 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: final sequence ordering (Task 17).
Task 17: Precedence DAG, preference topo sort, forward verification
Depends on: Task 16 Files:
- Create:
services/geometry-rs/crates/planner/src/ordering.rs - Copy from (precedent):
services/geometry/app/plan.py_derive_precedence(1248),_add_joint_edges(1290),_add_sandwich_edges(1483),_add_support_edges(1561),_preference_topo_sort(1861),_connectivity_repair(1816),_verify_sequence(2129),_motion_travel(1371)
Steps:
- Port hard precedence edges (
_derive_precedence,_add_joint_edgeswith itsreachescycle guard) and soft preference edges (_add_sandwich_edges,_add_support_edges— soft edges are preferences consulted only inside the topo sort's tie-break, never hard constraints). - Port
_preference_topo_sort(~270 LOC: connected-growth constraint,is_securing/is_weakly_securedpredicates, thesort_keyclosure at 2075 verbatim) +_connectivity_repair. - Port
_verify_sequence: replay each insertion against parts present at that step; failure demotes to flagged, setsverified: false. - Port PARITY.md Task-17 rows (topo connectivity, washer/bolt/nut ordering end-cases that live at this layer).
Verify:
cd services/geometry-rs && cargo test -p planner ordering 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: wire output (Task 19).
Task 18: Fixed-sequence mode + units
Depends on: Task 17 Files:
- Create:
services/geometry-rs/crates/planner/src/fixed.rs - Copy from (precedent):
services/geometry/app/plan.py_plan_fixed_sequence(844)
Steps:
- Port
_plan_fixed_sequence: caller-supplied ordered groups, each installed as one rigid body against previously-installed groups only; no reordering; forward-collision insertion motion per group. Validation of group membership against graph leaves (unknown nodeId ⇒ error listing the ids, matching the Python behavior — read what it does with unknowns and mirror exactly). - Port PARITY.md Task-18 rows (the entire fixed-sequence and unit merge/eject test set).
Verify:
cd services/geometry-rs && cargo test -p planner fixed 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: re-motion callers in packages/jobs (no TS change in this task).
Task 19: plan_step orchestration + plan.json v3 output parity
Depends on: Tasks 17, 18 Files:
- Create:
services/geometry-rs/crates/planner/src/plan.rs(publicplan_assembly(glb, graph, options) -> Result<PlanOutcome, PlannerError>) - Copy from (precedent):
services/geometry/app/plan.pyplan_step(270),_plan_parts(537),_tally_tiers(1080),_part_to_dict(2179)
Steps:
- Wire the pipeline in
_plan_partsorder: collect → seated depths → adjacency → fasteners → merge → joints → sandwich → greedy → base re-selection → precedence/topo → verify → output.PlanOutcome { plan: AssemblyPlan, component_count, planned_count, stats: PlanStats }. - Output must serialize to the exact plan.json v3 shape (
geometry-types::plan); tiers tally keys match Python's_tally_tiersstrings. - End-to-end fixture test: run
plan_assemblyonplates.meshopt.glb+ graph; assert the 4 screws are planned before/after per current Python behavior — generate the Python reference by running the Python planner on the same fixture fromservices/geometry-rs/scripts/make_fixtures.py(extend the script to also emit<name>.plan.jsonviaapp.plan.plan_step); comparesequence, per-componenttierandmotion.type(NOT float travel values — epsilon-free fields only). - Port remaining PARITY.md end-to-end rows. All PARITY.md rows must now be
portedorn-awith reasons.
Verify:
cd services/geometry-rs && cargo test -p planner 2>&1 | tail -3 && ! grep -n "pending" services/geometry-rs/PARITY.md
# Expected: tests ok; grep exits non-zero (no pending rows left)
Out of scope: HTTP layer (Task 21), parallelism (Task 20).
Task 20: Determinism test, then rayon parallelization
Depends on: Task 19 Files:
- Modify:
services/geometry-rs/crates/planner/src/{sweep.rs,greedy.rs,plan.rs}— rayon - Create:
services/geometry-rs/crates/planner/tests/determinism.rs
Steps:
- FIRST commit the determinism test single-threaded: run
plan_assemblytwice onplatesfixture, assert byte-identicalserde_json::to_vecof the plan (porttest_plan_is_deterministic). - THEN parallelize with rayon, preserving determinism: parallel over candidate directions within
plan_removal(collect all results, pick by the sameentanglementcomparator — an ordered reduction, not first-wins), parallel over pairs inseated_pair_depthsand_embedded_pairs(collect then sort by pair key). Do NOT parallelize across greedy iterations (order-dependent). CollisionWorldmust beSyncfor read-only narrowphase; the unregister flag-set becomes a per-sweep local exclusion list passed by value into parallel closures instead of shared mutation.- Determinism test re-run 5× under
--release; add a timing print (--nocapture) for the fixture plan to document the speedup in the task commit message.
Verify:
cd services/geometry-rs && cargo test -p planner --release --test determinism -- --nocapture 2>&1 | tail -4
# Expected: "test result: ok.", identical-bytes assertion passing, printed timing
Out of scope: micro-optimizations beyond rayon (profile first — lesson: "Profile the planner before optimizing").
Task 21: Server binary — axum /health, /plan, /plan/{jobId}
Depends on: Task 19 Files:
- Create:
services/geometry-rs/crates/server/src/{main.rs,auth.rs,config.rs,jobs.rs,routes.rs,fetch.rs} - Copy from (precedent):
services/geometry/app/main.py(routes, semaphore, job dict),app/auth.py(auth semantics),app/config.py(env vars)
Steps:
config.rs: same env vars, same defaults —GEOMETRY_SERVICE_API_KEY,GEOMETRY_DEV_MODE(only consulted when the key is unset:"true"⇒ allow unauthenticated, anything else ⇒ 401; also disables https-required and TLS-verify),GEOMETRY_MAX_CONCURRENCY(default 2),GEOMETRY_MAX_SOURCE_MB(250),GEOMETRY_ALLOWED_URL_HOSTS(comma list),PORT(default 8000).auth.rs:Authorization: Bearer <key>check as an axum middleware/extractor; constant-time comparison (subtlecrate or length-then-ct_eq).fetch.rs: reqwest streaming GET with size cap enforced on both Content-Length and streamed bytes; URL validation (https unless dev mode; host allowlist);danger_accept_invalid_certs(true)only when dev mode (mirrorsverify_tls).jobs.rs:DashMap<String, PlanJob>keyed by jobId, statespending|running|done|error, 1 h TTL sweep (spawned tokio interval task). Semaphore:tokio::sync::Semaphorewithtry_acquire⇒ 429{"error":"BUSY"}when full. Planner runs intokio::task::spawn_blocking(CPU-bound; rayon inside).routes.rs:GET /health→{"ok":true,"version":<CARGO_PKG_VERSION>}unauthenticated;POST /plan→ validatePlanRequest(new glbUrl/graphUrl shape), 202 +PlanStartResponse;GET /plan/{jobId}→PlanStatusResponsewith inlineplanon done (NEVER an upload URL — lesson: 60 s signed-upload expiry). Unknown jobId ⇒ 404 (callers treat as service-restarted and re-submit).- Endpoint tests with a local hyper/axum stub server serving fixture GLB/graph bytes (port the
StorageStubidea fromservices/geometry/tests/conftest.py): submit → poll → done with a valid plan; auth matrix (5 cases fromservices/geometry/tests/test_api.py); 429 when slots exhausted; https/allowlist/size-cap rejections (fromtest_limits.py).
Verify:
cd services/geometry-rs && cargo test -p server 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: /convert (Task 31). Redis job store (explicitly deferred; DashMap matches Python semantics).
Task 22: Shadow-comparison harness + large-noisy-model gate
Depends on: Task 21 Files:
- Create:
services/geometry-rs/scripts/shadow_compare.py - Create:
services/geometry-rs/SHADOW-RESULTS.md
Steps:
- Script inputs: a directory of
{model.glb, graph.json}pairs (downloaded from real company storage by the user, or the fixture set). For each: run Pythonplan_step(viaservices/geometry/.venv, importingapp.plan) and the Rust planner (cargo run --release -p serveris not needed — add a tinycargo run --release -p planner --example plan_file <glb> <graph>example binary that prints the plan JSON) and diff: sequence order, per-component tier, motion type, flagged set, warning count. Report per-model PASS/DIVERGENCE with the diff. - Timing both sides per model into
SHADOW-RESULTS.md(this is the perf-claim evidence). - Gate (lesson: seat rail is best-case): the comparison set MUST include one large noisy model (the 118-part "SA Mando & Battery Harness" class or the "SA BCU"). Ask the user to provide the GLB/graph pair from a real environment; if unavailable, STOP and report — do not sign off shadow parity on fixtures alone.
- Acceptance: identical sequences OR divergences individually reviewed and explained in SHADOW-RESULTS.md (e.g. equal-priority tie broken differently is acceptable ONLY if the Rust side is internally deterministic and the tie is provably equal-cost; anything else is a bug).
Verify:
cd services/geometry-rs && python scripts/shadow_compare.py fixtures/ && head -20 SHADOW-RESULTS.md
# Expected: PASS for every fixture model; SHADOW-RESULTS.md has a per-model table with timings
Out of scope: production traffic mirroring.
Task 23: Jobs-side switch — assembly-plan.ts calls the Rust planner
Depends on: Task 22 (fixtures PASS at minimum) Files:
- Modify:
packages/jobs/src/inngest/functions/tasks/assembly-plan.ts— payload + URL - Modify:
packages/env/src/index.ts— addGEOMETRY_PLAN_SERVICE_URL(optional) - Copy from (precedent):
packages/jobs/src/inngest/functions/tasks/assembly-convert.ts(signed URL minting withcreateSignedUrl)
Steps:
packages/env/src/index.ts: add optionalGEOMETRY_PLAN_SERVICE_URLnext toGEOMETRY_SERVICE_URL(same pattern; not secret). Empty ⇒ fall back toGEOMETRY_SERVICE_URL(transition switch; removed in Task 35).assembly-plan.ts: before submit, readmodelUpload.glbPathandgraphPathfor the row. If either is missing (convert never succeeded), fail the job with the existing failure path and message"model not converted yet"— do not fall back to the STEP payload. Mint signed GET URLs for both viaclient.storage.from("private").createSignedUrl(path, SIGNED_URL_EXPIRY)(same call pattern the file already uses for the STEP source — replace it). New payload:{ jobId, source: { glbUrl, graphUrl }, options }(options unchanged: units/sequence/deflections pass through). Re-submit path (404 recovery) re-mints both URLs — keep that behavior, it exists for expiry.- Poll loop, timeouts (
AbortSignal.timeout(60_000)), re-submit cap, inline-plan persistence: unchanged. - Escape hatch: if
assembly-plan.tshas drifted from the structure described here (grep forcreateSignedUrland the poll loop first), STOP and re-read the whole file before editing.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs 2>&1 | tail -3
# Expected: "Tasks: 1 successful" (or the package's typecheck task exiting 0)
Out of scope: assembly-convert.ts (unchanged until Phase B cutover). Any ERP route.
Task 24: Dev-stack wiring for the Rust planner
Depends on: Task 23 Files:
- Modify:
packages/dev/src/services/apps.ts— spawn the Rust planner alongside uvicorn - Modify:
packages/dev/src/env.ts— writeGEOMETRY_PLAN_SERVICE_URLinto.env.local
Steps:
- Read
packages/dev/src/services/apps.tslines ~240–282 (the existing geometry uvicorn spawn) — copy its pattern: spawnservices/geometry-rs/target/release/server(orcargo run --release -p serverif the binary is absent — prefer checking for the built binary and printing a skip message"geometry-rs not built — cargo build --release"when missing, mirroring the.venvskip message). Env:PORT= a newPORT_GEOMETRY_RS(default 54008 — checkpackages/dev/src/env.test.ts/ whereverPORT_GEOMETRY54007 is defined and register the new port the same way),GEOMETRY_SERVICE_API_KEY: "dev-local-key",GEOMETRY_DEV_MODE: "true". packages/dev/src/env.ts: writeGEOMETRY_PLAN_SERVICE_URL=http://localhost:54008(or the portless-domain form if that's what the siblingGEOMETRY_SERVICE_URLline does — mirror it exactly, lines ~101–103).- Escape hatch: if the dev package's service-spawning structure differs from this description, STOP, read the file, and follow its actual conventions.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/dev 2>&1 | tail -3
# Expected: typecheck exits 0. Manual smoke (user-run): pnpm dev, then trigger a re-plan in the ERP assembly editor and watch the Rust service logs.
Out of scope: production deployment (Task 34/35).
Task 25: occt-bridge crate — build skeleton + exception guards
Depends on: Task 1 (parallel-safe with Phase A) Files:
- Create:
services/geometry-rs/crates/occt-bridge/{Cargo.toml,build.rs,src/lib.rs,src/bridge/mod.rs,cpp/guard.hpp,cpp/guard.cpp}
Steps:
Cargo.toml:occt-sys = "0.6"(build-dep + dep as its docs prescribe),cxx = "1", build-depcxx-build = "1". If occt-sys 0.6 fails to build on this machine, try the git rev used by opencascade-rsmainand record the pin; if that also fails, STOP with the build log tail.build.rs:cxx_build::bridgeover the bridge modules; add OCCT include path + static libs fromocct-sys(followhttps://github.com/bschwind/opencascade-rs/blob/main/crates/opencascade-sys/build.rsas the reference for whichTK*libs to link — must includeTKXCAF TKLCAF TKCAF TKDESTEP TKXDESTEPequivalents for the pinned OCCT version; the exact TK names for STEP+XCAF in OCCT 7.8 areTKSTEP TKSTEPAttr TKSTEPBase TKSTEP209 TKXDESTEP TKXCAF TKLCAF TKCDF TKVCAFplus coreTKernel TKMath TKBRep TKGeomBase TKGeomAlgo TKG2d TKG3d TKTopAlgo TKShHealing TKMesh TKPrim— verify against the occt-sys lib dir listing at build time and adjust).cpp/guard.hpp: every bridged OCCT call goes through aGUARDED(expr)macro wrappingOCC_CATCH_SIGNALS+try { ... } catch (Standard_Failure const& e) { return err(e.GetMessageString()); } catch (...) { return err("unknown OCCT failure"); }returning aResult-shaped struct cxx can pass (struct OcctResult { bool ok; rust::String error; }pattern). NO OCCT exception may cross the FFI boundary (opencascade-rs issue #172: aborts).- Smoke bridge: one function
occt_version() -> StringreturningOCC_VERSION_COMPLETE, tested from Rust.
Verify:
cd services/geometry-rs && cargo test -p occt-bridge 2>&1 | tail -3
# Expected: "test result: ok." (first build takes ~20-25 min — occt-sys compiles OCCT; do not kill it)
Out of scope: any real OCCT class (Tasks 26–27).
Task 26: Bridge surface — STEP/XCAF document read
Depends on: Task 25 Files:
- Create:
services/geometry-rs/crates/occt-bridge/src/bridge/{step.rs,xcaf.rs}+ matchingcpp/*.cppshims - Copy from (precedent):
services/geometry/app/convert.py_read_stepand the XCAF walk (the class list below is the verified inventory), andhttps://github.com/bschwind/opencascade-rs/blob/main/docs/writing_bindings.mdfor cxx mechanics
Steps:
- Bridge exactly this surface (verified against
convert.py— nothing speculative):STEPCAFControl_Reader(SetColorMode/SetNameMode/SetLayerMode/SetMatMode/ReadFile/Transfer),Interface_Static::SetCVal("xstep.cascade.unit","MM"),IFSelect_ReturnStatus,TDocStd_Documentcreation,XCAFDoc_DocumentTool::ShapeTool,XCAFDoc_ShapeTool::{IsAssembly, GetComponents, GetReferredShape, GetLocation, GetShape, GetFreeShapes},XCAFDoc_ColorTool::GetColor(ColorSurf + ColorGen),TDF_Label/TDF_LabelSequence/TDF_Tool::Entry,TDataStd_Name(GetID/FindAttribute/Get),TopLoc_Location::Transformation+gp_Trsf::Value(i,j),Quantity_ColorRGBAaccessors. - Expose a Rust-idiomatic layer on top of the raw bridge:
read_step_document(path) -> Result<XcafDocument, OcctError>;XcafDocument::free_shapes() -> Vec<Label>;Label::{entry(), name(), is_assembly(), components(), referred_shape(), location_matrix() -> [f64;16], shape()};color_for(label/shape) -> Option<[f32;4]>. Handle template instantiations need per-type C++ typedefs (writing_bindings.md covers this). - Test (fixture-gated): read
fixtures/plates.step→ free shapes count, assembly flags, component names includeM5-SHCS, a color is present. Compare counts againstfixtures/plates.graph.json(produced by Python from the same file).
Verify:
cd services/geometry-rs && cargo test -p occt-bridge step 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: tessellation (Task 27), STEP writing (Task 32).
Task 27: Bridge surface — tessellation, volume, bbox
Depends on: Task 26 Files:
- Create:
services/geometry-rs/crates/occt-bridge/src/bridge/mesh.rs+ shim - Copy from (precedent):
services/geometry/app/convert.py_tessellate(per-face loop), andhttps://github.com/bschwind/opencascade-rs/blob/main/crates/opencascade/src/mesh.rs(the reference tessellation walk)
Steps:
- Bridge:
BRepMesh_IncrementalMeshwith both linear AND angular deflection (the opencascade-rs high-level API only exposes linear — bind the full constructor),TopExp_ExploreroverTopAbs_FACE,BRep_Tool::Triangulation+ node/triangle iteration withTopLoc_Locationtransform applied to nodes,TopAbs_REVERSEDwinding flip,BRepGProp::VolumeProperties+GProp_GProps::Mass,Bnd_Box+BRepBndLib::Add. - Rust API:
tessellate(shape, linear_deflection, angular_deflection) -> Result<MeshData, OcctError>(MeshData { vertices: Vec<[f64;3]>, triangles: Vec<[u32;3]> }),volume(shape) -> Result<f64, OcctError>,bbox(shape) -> Result<([f64;3],[f64;3]), OcctError>. - Test: tessellate the box from
fixtures/box.stepat deflection 0.1/0.5 → triangle count within ±20 % of the count recorded infixtures/box.graph.json-adjacent stats (extendscripts/make_fixtures.pyto dump a<name>.stats.jsonwith Python's per-part triangle counts if not already available); volume of a 10 mm box ∈ [999, 1001] mm³.
Verify:
cd services/geometry-rs && cargo test -p occt-bridge mesh 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: proxy-bbox fallback policy (converter concern, Task 28).
Task 28: Converter crate — XCAF walk, nodeIds, graph.json parity
Depends on: Task 27 Files:
- Create:
services/geometry-rs/crates/converter/{Cargo.toml,src/lib.rs,src/{tree.rs,node_ids.rs,units.rs}} - Modify:
services/geometry-rs/crates/geometry-types/src/wire.rs— addConvertRequest/ConvertResponse/ConvertOptions/ConvertStats(mirrorservices/geometry/app/schemas.pyexactly, including defaultslinearDeflection=0.1, angularDeflection=0.5, compress=true) - Copy from (precedent):
services/geometry/app/convert.py— the whole file (594 LOC), function-by-function
Steps:
- Port
_read_step→_count_leaf_instances(max_parts limit → typedLimitExceedederror) →_build_tree(recursive XCAF walk; per-unique-part tessellation cached by label entry string; per-part tessellation failure ⇒ bbox-proxy mesh + warning, never abort) →_assign_node_ids(SHA1 of"{geometryHash}:{parentPath}:{siblingOrdinal}", first 16 hex chars — the STRING construction must match Python byte-for-byte; read_assign_node_idsand_geometry_hash(grep for it) and replicate the exact hash-input formatting including separators and ordinal formatting) →_compute_world_bboxes. - Port
_detect_source_unit(regex over raw STEP text — pure Rustregex, copy the pattern). - Parity test (fixture-gated): convert
fixtures/plates.step→ produced graph must equalfixtures/plates.graph.jsonwith: nodeIds byte-identical, tree shape identical, floats within 1e-6 relative (transforms/bboxes/volumes), colors identical. Any nodeId mismatch is a hard failure — print both hash inputs on mismatch.
Verify:
cd services/geometry-rs && cargo test -p converter 2>&1 | tail -3
# Expected: "test result: ok." 0 failed, including graph parity for box, plates, nested
Out of scope: GLB output (Task 29).
Task 29: GLB writer (glb crate, write half)
Depends on: Task 28 Files:
- Create:
services/geometry-rs/crates/glb/src/write.rs - Copy from (precedent):
services/geometry/app/glb.py(180 LOC — the entire file)
Steps:
- Port
write_glb: node tree mirrors the graph 1:1; every nodeextras: {"nodeId": ...}; identicalgeometryHashshares one glTF mesh; materials deduped by RGBA; area-weighted smooth vertex normals (port thenp.add.ataccumulation as an index loop); buffers laid out as pygltflib does (positions f32, indices u32, ARRAY_BUFFER/ELEMENT_ARRAY_BUFFER targets). Write the GLB container (header + JSON + BIN, 4-byte padding). - Vertices are baked world-space with identity node transforms — replicate exactly (the viewer and the Task 4 reader both tolerate either, but parity means matching Python's choice).
- Round-trip test:
converteroutput forplates.step→write_glb→ Task 4read_assembly_glb→validate_against_graphpasses; triangle totals equal the converter's tessellation totals; two of the fourM5-SHCSnodes reference the same mesh index (parse the JSON chunk to assert mesh sharing).
Verify:
cd services/geometry-rs && cargo test -p glb write 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: compression (Task 30).
Task 30: meshopt encode pipeline
Depends on: Task 29 Files:
- Create:
services/geometry-rs/crates/glb/src/meshopt_encode.rs - Copy from (precedent): behavior of
gltf-transform meshopt(the only mode used — seeservices/geometry/app/optimize.py); spechttps://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_meshopt_compression/README.md
Steps:
- Implement quantize (positions per gltf-transform defaults) → vertex-cache reorder (
meshopt::optimize_vertex_cache+optimize_vertex_fetch) →encode_vertex_buffer/encode_index_buffer(encode version 0 for decoder compatibility — set viaencode_gltf/encode_index_versionequivalents in the meshopt crate) → rewrite bufferViews withEXT_meshopt_compressionextension JSON +extensionsRequired. - HARD CONSTRAINT: node graph untouched — no join/flatten/dedup/prune (that's why Python never used
gltf-transform optimize). Only bufferView-level rewriting. - Tests: (a) encode
platesGLB → Task 4 reader decodes it →validate_against_graphpasses and max vertex error vs pre-encode ≤ the Task 5 measured bound; (b) compressed size < 60 % of uncompressed for the plates fixture (gltf-transform achieves well under this); (c)extras.nodeIdpreserved on every node (porttest_optimize.py::compression preserves extras). - Escape hatch: if quantization here exceeds the Task 5 bound, raise quantization bits until it passes and record final settings in
SPIKE-QUANTIZATION.md.
Verify:
cd services/geometry-rs && cargo test -p glb meshopt_encode 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: other gltf-transform features (simplification, texture handling — the pipeline has no textures).
Task 31: Server /convert route + endpoint tests
Depends on: Tasks 21, 30 Files:
- Modify:
services/geometry-rs/crates/server/src/routes.rs— add/convert - Copy from (precedent):
services/geometry/app/main.py/converthandler (line 68 onward) andservices/geometry/tests/{test_endpoint.py,test_limits.py}
Steps:
POST /convert: auth → URL validation (all three URLs) → semaphore try-acquire (429 BUSY) → tempdir (tempfilecrate) → streamed download with size cap →converter::convert(...)inspawn_blocking(413LIMIT_EXCEEDEDfor part cap; per-part warnings pass through) → meshopt encode (failure ⇒ keep uncompressed + warning, mirroringcompress_glbfallback) → PUT GLB then graph.json withContent-Type+x-upsert: trueheaders (upload failure ⇒ 502UPLOAD_FAILED) →ConvertResponse { ok, componentCount, unit, stats: { convertMs, meshTriangles, warnings } }.- Endpoint tests against the Task 21 storage stub: full round-trip on
plates.step(assert the stub captured both PUTs and the graph parses), read-failure 4xx, size-cap rejection, part-cap 413, busy 429.
Verify:
cd services/geometry-rs && cargo test -p server convert 2>&1 | tail -3
# Expected: "test result: ok." 0 failed
Out of scope: switching assembly-convert.ts (Task 35).
Task 32: Rust fixture generator
Depends on: Task 26 Files:
- Create:
services/geometry-rs/crates/occt-bridge/src/bridge/primitives.rs+ shim (BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinder, gp_Trsf/gp_Vec transforms, STEPCAFControl_Writer, XCAF SetColor/AddShape/NewShape/AddComponent/UpdateAssemblies) - Create:
services/geometry-rs/crates/converter/src/bin/make_fixtures.rs - Copy from (precedent):
services/geometry/tests/fixtures/make_fixtures.py(133 LOC)
Steps:
- Bridge the fixture-writing surface (listed above — it's the test-only half of the §3 inventory in the spec).
- Port
make_fixtures.pyto a Rust bin producing the samebox.step/plates.step/nested.stepintoservices/geometry-rs/fixtures/. - Cross-check: Rust-generated
plates.stepfed through the Rust converter yields the same component count/names as the Python-generated one (nodeIds may differ if STEP entity ordering differs — assert on names/counts/structure here, NOT hashes).
Verify:
cd services/geometry-rs && cargo run -p converter --bin make_fixtures && ls fixtures/*.step
# Expected: box.step plates.step nested.step regenerated
Out of scope: deleting the Python fixture script (Task 35).
Task 33: Converter parity gate
Depends on: Tasks 31, 32 Files:
- Create:
services/geometry-rs/scripts/convert_compare.py - Modify:
services/geometry-rs/SHADOW-RESULTS.md— converter section
Steps:
- Script: for each STEP in a given directory (fixtures + any real customer STEP files the user provides), run Python
convert_stepand the Rust converter binary; diff graph.json (nodeIds byte-equal, floats 1e-6) and GLB structure (node count, mesh sharing, triangle totals, extras.nodeId set equality). Record timings both sides. - Same gate rule as Task 22: at least one real customer STEP (ask the user) or STOP.
- Viewer smoke: load one Rust-produced meshopt GLB + graph in the running dev app (user-assisted via the
/testskill if a browser check is wanted) — the join inpackages/viewer/src/useAssembly.tsmust produce a fullnodesByIdmap.
Verify:
cd services/geometry-rs && python scripts/convert_compare.py fixtures/ && grep -A5 "## Converter" SHADOW-RESULTS.md
# Expected: PASS per model, nodeId sets byte-identical, timings recorded
Out of scope: production cutover.
Task 34: Dockerfile + CI workflow
Depends on: Task 31 Files:
- Create:
services/geometry-rs/Dockerfile - Create:
.github/workflows/geometry-rs.yml - Copy from (precedent):
.github/workflows/geometry.yml(triggers/structure),services/geometry/Dockerfile(healthcheck pattern)
Steps:
- Dockerfile: stage 1
rust:1-bookworm—cargo build --release -p server(OCCT builds inside; use BuildKit cache mounts for/usr/local/cargo/registryandtarget/); stage 2 — trygcr.io/debian12:latest-class minimal (debian:bookworm-slim): copy the binary,EXPOSE 8000,HEALTHCHECK CMD curl -f http://localhost:8000/health(install curl or use a tiny healthcheck binary — simplest:wget -qO-from busybox layer or compile a--healthflag into the server that curls itself; pick the simplest that works and note it). Check at build time whether the binary needslibfontconfig/libgl(OCCT sometimes links them even headless):lddthe binary in stage 1; add only the apt packageslddproves are needed. - CI workflow: on PR/push touching
services/geometry-rs/**: jobstest(cargo test --release withSwatinem/rust-cache@v2— first uncached run ~25 min, note the timeout at 45 min; fixture-dependent tests skip in CI since fixtures are ungenerated — that's the designed behavior; unit + calibration + parity-on-synthetic still run) anddocker(build only,push: false, GHA cache — mirrorgeometry.yml). - Do NOT add to
deploy.ymlmatrix orsst.config.ts— deployment topology belongs to.ai/specs/2026-07-06-geometry-service-deployment.mdand Task 35's approval.
Verify:
docker build -t geometry-rs-test services/geometry-rs 2>&1 | tail -3 && docker run --rm -d -p 54019:8000 -e GEOMETRY_DEV_MODE=true --name geomrs geometry-rs-test && sleep 2 && curl -s http://localhost:54019/health && docker rm -f geomrs
# Expected: build succeeds; health returns {"ok":true,"version":"..."}
Out of scope: pushing images, SST resources, prod env vars.
Task 35: Full cutover + Python removal — requires explicit user approval before starting
Depends on: Tasks 22 + 33 green on real models, user sign-off Files:
- Modify:
packages/jobs/src/inngest/functions/tasks/assembly-plan.ts— removeGEOMETRY_PLAN_SERVICE_URLfallback (singleGEOMETRY_SERVICE_URL) - Modify:
packages/env/src/index.ts— removeGEOMETRY_PLAN_SERVICE_URL - Modify:
packages/dev/src/services/apps.ts+packages/dev/src/env.ts— spawn only the Rust service on the primary geometry port - Delete:
services/geometry/(entire Python service),.github/workflows/geometry.yml - Rename:
services/geometry-rs/→services/geometry/(update workflow paths, dev spawn paths, script relative paths) - Modify:
.ai/rules/*and any AGENTS.md referencing the Python service (grepservices/geometryacross.ai/and*/AGENTS.md; update per.ai/rules/keep-sources-in-sync.md)
Steps:
- Confirm with the user: shadow results accepted, real-model gates passed, deployment story (per the deployment spec) agreed.
- Execute the file moves/deletes above; re-run the full Rust suite +
pnpm exec turbo run typecheck --filter=@carbon/jobs --filter=@carbon/dev. - Update
.ai/lessons.mdwith any port lessons learned (format: Context → Problem → Rule → Applies to).
Verify:
cd services/geometry && cargo test 2>&1 | tail -3 && pnpm exec turbo run typecheck --filter=@carbon/jobs --filter=@carbon/dev 2>&1 | tail -3 && ! grep -rn "geometry-rs" .github/workflows/ packages/dev/src/
# Expected: all green; no stale geometry-rs references
Out of scope: SST/production deployment execution (separate spec), Redis job store.