Skip to main content

brep_boolean/csg/boolean/
mod.rs

1pub mod profile;
2pub use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4pub use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5pub use crate::imprint::{
6    EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7    ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10pub use crate::topology::{
11    adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12    ShellRecord, VertexRecord,
13};
14pub use crate::{
15    KernelRefusal, OrRefuse, RefusalClass,
16    apply_edge_splits, apply_edge_splits_with_map, build_imprints, build_pcurve_on_surface,
17    build_pcurve_on_surface_range, classify_surface_pair,
18    fragment_solid, interpolate_curve, merge_curve_continuation_edges,
19    merge_same_surface_faces_excluding, merge_same_surface_faces_scoped,
20    project_point_to_curve, project_point_to_surface, solid_signed_volume, solid_signed_volume_for_sign, AffineTransform,
21    DiagnosticSeverity, KernelDiagnostics, KernelOutcome, KernelStage, KernelTolerances, NurbsCurve,
22    PointClass, SolidClassifier, SurfacePairRelation, Vec3,
23};
24pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26pub use web_time::Instant;
27
28thread_local! {
29    /// Running count (per thread) of one-use edges the EDGE-CONFORMANCE
30    /// repair lanes merged or bridged.  The lanes only fire on an assembly
31    /// that would otherwise refuse, so a zero delta across an operation is
32    /// an honest witness that the boolean assembled cleanly without the
33    /// repair.  Test-observable; not part of any result.
34    pub static CONFORMANCE_REPAIRS: std::cell::Cell<u64> =
35        const { std::cell::Cell::new(0) };
36}
37
38#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum BooleanOperation {
41    Union,
42    Intersect,
43    Subtract,
44}
45
46#[derive(Clone, Debug, Deserialize)]
47pub struct BooleanOptions {
48    #[serde(default = "default_tolerance")]
49    pub tolerance: f64,
50    /// Optional complete accuracy/search policy.  `tolerance` remains the
51    /// backwards-compatible model-identity shorthand when this is absent.
52    #[serde(default)]
53    pub tolerances: Option<KernelTolerances>,
54    #[serde(default)]
55    pub imprint: ImprintOptions,
56    /// Coalesce adjacent result fragments after assembly. This defaults to
57    /// true to preserve the kernel's normal clean-boundary behavior.
58    #[serde(default = "default_true")]
59    pub merge_coplanar_faces: bool,
60    /// Face-name substrings that PIN a result face out of the coplanar/cosurface
61    /// merge (only consulted when [`Self::merge_coplanar_faces`] is on). A face whose
62    /// `name` CONTAINS any of these is emitted unchanged instead of being
63    /// coalesced with a mergeable neighbour; faces matching none merge exactly as
64    /// before. Default empty — no caller sees a behavior change unless it opts
65    /// in. Sheet metal uses this to keep every thickness/side wall face per
66    /// outline segment in the folded solid (so a flange can still attach to a
67    /// specific segment: fusing two collinear thickness faces would erase the
68    /// segment boundary).
69    #[serde(default)]
70    pub keep_unmerged_name_substrs: Vec<String>,
71    /// On by default since the 2026-10-10 census read the 94-case manifest
72    /// unchanged with it; `BREP_UNTOUCHED_PASSTHROUGH` overrides either way
73    /// (`0` off, anything else on).
74    #[serde(default = "default_true")]
75    pub untouched_passthrough: bool,
76    /// On by default since the 2026-10-10 census;
77    /// `BREP_DISJOINT_FAST_PATH` overrides either way (`0` off, anything
78    /// else on).
79    #[serde(default = "default_true")]
80    pub disjoint_fast_path: bool,
81    /// Lane X row 12: when, in at least two axes, one operand's control-net
82    /// box ends at or before the other's begins (exactly, no band), the
83    /// operands can share no interior and touch on a line or at a point: the
84    /// disjoint path's answers hold. Every control weight must be positive
85    /// (the hull property), both operands plain solids, and the caller must
86    /// say what follows (`seam_reseat_later_references` is `Some`), so a
87    /// caller that cannot keeps today's ids. On by default since the row 12
88    /// census; `BREP_CONTACT_FAST_PATH` overrides either way (`0` off,
89    /// anything else on).
90    #[serde(default = "default_true")]
91    pub contact_fast_path: bool,
92    /// OFF by default: the 94-case census read unchanged with it, but the
93    /// kernel battery's `offset_subtract_fixture` pins a result whose
94    /// untouched planar face carries an open trim joint of 8.7e-4 from its
95    /// coarse polyline operand, which the whole-solid joints pass closes and
96    /// the scoped pass leaves as the operand had it; and the row buys no
97    /// measurable time (the record of 2026-10-10). `BREP_TOUCHED_ASSEMBLY`
98    /// overrides either way (`0` off, anything else on).
99    #[serde(default)]
100    pub touched_assembly: bool,
101    /// On by default since the 2026-10-11 census (the whole kernel battery,
102    /// the 94-case manifest and `hlr_tests` green with it on, every manifest
103    /// fragment the sector decides agreeing with the ray cast);
104    /// `BREP_SECTOR_CLASS` overrides either way (`0`/`off` the escape hatch,
105    /// `check` for the differential run that logs disagreements to
106    /// `BREP_SECTOR_CENSUS`, anything else on). Appended at the end of the
107    /// struct (2026-10-11).
108    #[serde(default = "default_true")]
109    pub sector_classification: bool,
110    /// Non-manifold plan 1.6: trim a declared Sheet by a Solid with Intersect.
111    /// On after the 2026-10-14 Sheet census and whole-kernel qualification.
112    /// BREP_SHEET_TRIM overrides this option (1 enables, 0 disables).
113    #[serde(default = "default_true")]
114    pub sheet_trim: bool,
115    /// Preserve the closed operand regions at a lower-dimensional union
116    /// contact as explicit cells. Opt-in pending the Cellular census.
117    /// BREP_KEEP_CELLS overrides this option (1 enables, 0 disables).
118    #[serde(default)]
119    pub keep_cells: bool,
120    /// The references later features hold (their `inputParams` text), when
121    /// the caller knows them: `Some` admits the operand seam re-seat
122    /// (`BREP_SEAM_RESEAT`, lane X row 11b) for every cylinder wall none of
123    /// them names; `None` (the caller cannot tell) never re-seats.
124    #[serde(default)]
125    pub seam_reseat_later_references: Option<Vec<String>>,
126}
127
128/// [`BooleanOptions::touched_assembly`] under its environment override.
129fn touched_assembly(options: &BooleanOptions) -> bool {
130    match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
131        Ok("0") => false,
132        Ok(_) => true,
133        Err(_) => options.touched_assembly,
134    }
135}
136
137/// [`BooleanOptions::disjoint_fast_path`] under its environment override.
138fn disjoint_fast_path(options: &BooleanOptions) -> bool {
139    match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
140        Ok("0") => false,
141        Ok(_) => true,
142        Err(_) => options.disjoint_fast_path,
143    }
144}
145
146/// [`BooleanOptions::contact_fast_path`] under its environment override.
147fn contact_fast_path(options: &BooleanOptions) -> bool {
148    match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
149        Ok("0") => false,
150        Ok(_) => true,
151        Err(_) => options.contact_fast_path,
152    }
153}
154
155/// [`BooleanOptions::untouched_passthrough`] under its environment override.
156fn untouched_passthrough(options: &BooleanOptions) -> bool {
157    match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
158        Ok("0") => false,
159        Ok(_) => true,
160        Err(_) => options.untouched_passthrough,
161    }
162}
163
164fn default_tolerance() -> f64 {
165    1e-7
166}
167
168fn default_true() -> bool {
169    true
170}
171
172impl Default for BooleanOptions {
173    fn default() -> Self {
174        Self {
175            tolerance: default_tolerance(),
176            tolerances: None,
177            imprint: ImprintOptions::default(),
178            merge_coplanar_faces: true,
179            keep_unmerged_name_substrs: Vec::new(),
180            untouched_passthrough: true,
181            disjoint_fast_path: true,
182            contact_fast_path: true,
183            touched_assembly: false,
184            sector_classification: true,
185            sheet_trim: true,
186            keep_cells: false,
187            seam_reseat_later_references: None,
188        }
189    }
190}
191
192mod select;
193mod sheet;
194mod cellular;
195pub mod sector;
196pub mod assemble;
197mod operand_state;
198mod rim;
199mod coincident;
200mod touch;
201mod reseat;
202
203pub use rim::*;
204use select::*;
205use coincident::*;
206use touch::TouchCensus;
207pub use assemble::{
208    assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
209    clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
210};
211use assemble::{assemble_fragments_scoped, AssemblyScope};
212// Currently referenced only inside `assemble`, so the re-export is unused.
213#[allow(unused_imports)]
214pub use assemble::apply_assembly_heal_chain;
215
216
217/// A boolean's operands at the working scale (`brep/rescale.rs`): unless `BREP_WORKING_SCALE=0`, operands whose combined box diagonal
218/// is below 1/16 are scaled up by a power of two, and the result is scaled back.
219struct WorkingScale {
220    factor: f64,
221    solids: Vec<BrepSolid>,
222    options: BooleanOptions,
223}
224
225impl WorkingScale {
226    fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
227        let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
228            return Ok(None);
229        };
230        let Some(factor) = crate::rescale::guard_factor(bounds) else {
231            return Ok(None);
232        };
233        crate::rescale::profile_fired("boolean", factor, bounds);
234        let solids = operands
235            .iter()
236            .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
237            .collect::<Result<Vec<_>, _>>()?;
238        // The one length the options carry in model units.
239        let mut options = options.clone();
240        options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
241        Ok(Some(Self { factor, solids, options }))
242    }
243
244    fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
245        crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
246    }
247
248    fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
249        crate::rescale::name_scale(error, self.factor)
250    }
251}
252
253pub fn boolean_operation(
254    first: &BrepSolid,
255    second: &BrepSolid,
256    operation: BooleanOperation,
257    options: &BooleanOptions,
258) -> Result<BrepSolid, KernelRefusal> {
259    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
260        return boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
261            .map_err(|error| scaled.refusal(error))
262            .and_then(|solid| scaled.back(&solid));
263    }
264    match boolean_operation_with_diagnostics(first, second, operation, options) {
265        Ok(outcome) => {
266            // An empty difference or common part of two solids whose faces only
267            // nearly coincide is the near pair read as one, not the answer.
268            if below_tolerance_refusal_enabled()
269                && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
270                && !matches!(operation, BooleanOperation::Union)
271            {
272                if let Some(refusal) = below_tolerance_refusal(first, second, None) {
273                    return Err(refusal);
274                }
275            }
276            if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
277                if let Some(refusal) = unresolved_merge_refusal(first, second) {
278                    return Err(refusal);
279                }
280            }
281            Ok(outcome.value)
282        }
283        Err(error) => {
284            if below_tolerance_refusal_enabled() {
285                if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
286                    return Err(refusal);
287                }
288            }
289            // Perturbation-fallback lane (Simulation of Simplicity). The exact
290            // arrangement only errs on a DEGENERACY here (coincident /
291            // near-tangent carrier faces make it structurally inconsistent) —
292            // e.g. a partial torus whose equatorial circles lie exactly in a box
293            // face. Retry once on a rigidly perturbed second operand; accept only
294            // an oracle-clean, volume-consistent result. See
295            // `perturbation_retry`.
296            if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
297                || !error.class.perturbation_eligible()
298            {
299                return Err(error);
300            }
301            // OPERAND-CONSISTENCY GATE. A rigid nudge lifts a coincidence
302            // BETWEEN the operands; it cannot reconcile an operand with
303            // itself. A planar face whose straight boundary sits farther off
304            // its plane than the assembly weld — the shape the STEP importer's
305            // planar split repairs, so it reaches here only on a body built
306            // some other way — fails the exact arrangement for every rung
307            // alike: the 2026-09-12 mesh-import report paid twenty ~7 s rungs
308            // for one 3.4e-3 gap before the import split existed. Name the
309            // gap and stop. The predicate is deliberately the splitter's own,
310            // not a pcurve-error band: vendor bodies whose fitted edges stand
311            // a few 1e-4 off curved faces are legitimate input (per-entity
312            // tolerances) and keep every rung.
313            // OPERAND-CLOSURE GATE. A boolean of a body that is not a closed
314            // shell has no solid answer, exact or nudged: its inside is not
315            // defined, and its volume depends on the reference point. The
316            // slimmed fuzz fixtures (13, 14 and 15, operand A cut from a larger
317            // part by a box filter) carry 54, 97 and 66 edges that bound one
318            // face; every one of their 20 rungs refused on the exact lane, and
319            // 15's identity was read from an intersection with the open shell.
320            // Only consulted on the failure path, so nothing that succeeds
321            // today changes. Escape hatch: BREP_OPEN_OPERAND_GATE=0.
322            if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
323                if let Some((operand, open)) = [first, second]
324                    .iter()
325                    .enumerate()
326                    .find_map(|(operand, solid)| {
327                        let open = one_use_edges(solid);
328                        (open > 0).then_some((operand, open))
329                    })
330                {
331                    return Err(error.with_message(|message| format!(
332                        "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
333                         only one face, so no boolean of it encloses a solid and no perturbation \
334                         can close it"
335                    )));
336                }
337            }
338            if let Some((operand, face_id, deviation, weld)) =
339                planar_operand_off_its_plane(first, second, options)
340            {
341                return Err(error.with_message(|message| format!(
342                    "{message}; operand {operand} face {face_id} is a plane whose straight \
343                     boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
344                     no perturbation can reconcile — the body's planes must contain their \
345                     boundary before it can take part in an exact boolean"
346                )));
347            }
348            // INTERNAL-TANGENCY PINCH GATE. Perturbation is only legitimate
349            // where the exact arrangement is UNSTABLE but its ANSWER is not:
350            // the nearby transversal case must carry the same topology the
351            // degenerate one does. An internal tangency in a DIFFERENCE breaks
352            // exactly that premise — the exact `A − B` pinches to zero
353            // thickness along the contact, so an epsilon either tears the wall
354            // open (a through-slot where the exact answer has intact material)
355            // or leaves a sub-micron web. Both are within epsilon in Hausdorff
356            // distance and in volume, so neither the oracle (boundary skip
357            // band) nor the 1% CSG volume bound can see them, and the lane
358            // would ship the tolerant-kernel sliver this kernel refuses. Only
359            // consulted on the failure path, so nothing that succeeds today can
360            // change; the honest exact-path error is returned instead.
361            // Escape hatch for tamper-verification: BREP_PINCH_GATE=0.
362            if matches!(operation, BooleanOperation::Subtract)
363                && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
364                && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
365                    .unwrap_or(false)
366            {
367                // The exact answer exists where the contact only touches: see
368                // `subtract_through_the_common_part`. Not a perturbation.
369                if let Some(solid) = subtract_through_the_common_part(first, second, options) {
370                    return Ok(solid);
371                }
372                return Err(error.with_message(|message| format!(
373                    "{message}; internal tangency: the operands touch tangentially with \
374                     co-directed normals, so the exact difference pinches to zero thickness \
375                     (non-manifold, unrepresentable in a boundary model) — refusing rather \
376                     than returning a perturbed sliver"
377                )));
378            }
379            // TANGENT-NODE GATE, same doctrine as the pinch gate above and for
380            // the same reason. A 4-valent tangent node is refused because the
381            // kernel cannot imprint it, and perturbation is only legitimate
382            // where the exact arrangement is UNSTABLE but its ANSWER is not:
383            // the nudged configuration resolves the kiss one way or the other
384            // and the kernel has no claim on which. Until 2026-09-13 the ladder
385            // could not produce a candidate here at all; with `fit_polyline`
386            // measuring its own result the equal-radius torus pair's LAST rung
387            // (3.0e-3 of scale) assembles, validates, and passes the semantic
388            // oracle at 399 samples with a zero disagreement rate, reading
389            // 299.4998500 against the ideal union's 299.6 — a 0.03% error that
390            // is the nudge's, not the kernel's answer. Shipping that would
391            // answer a question this class exists to decline, so the class does
392            // not take the ladder. Escape hatch for measuring it:
393            // BREP_TANGENT_NODE_GATE=0.
394            if matches!(error.class, RefusalClass::TangentNodeSingularity)
395                && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
396            {
397                return Err(error);
398            }
399            // The union of two bodies tangent inside one another has an exact
400            // answer the arrangement of the difference reaches: see
401            // `union_through_the_difference`. Not a perturbation.
402            if matches!(operation, BooleanOperation::Union) {
403                if let Some(solid) = union_through_the_difference(first, second, options) {
404                    return Ok(solid);
405                }
406            }
407            match perturbation_retry(first, second, operation, options) {
408                Ok(solid) => Ok(solid),
409                Err(refused) if refused.is_empty() => Err(error),
410                Err(refused) => {
411                    Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
412                }
413            }
414        }
415    }
416}
417
418/// Grid resolution (per parameter direction, endpoints included) used to probe a
419/// face pair for a tangential contact. Endpoints and the midpoint are both
420/// sampled, so a contact sitting on a periodic seam (a cylinder's `u = 0`
421/// ruling) and one sitting at a face's parametric centre are both hit exactly.
422const PINCH_PROBE_STEPS: usize = 8;
423
424/// `|n_a × n_b|` bound below which two unit normals count as parallel — the same
425/// bound `csg::imprint`'s pair classifier uses (`PAIR_ANGULAR_TOLERANCE`).
426const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
427
428/// Parameter-space step (fraction of the domain span) taken around a contact
429/// sample to prove the contact is LOWER-DIMENSIONAL — a tangency curve/point
430/// rather than a cosurface patch.
431const PINCH_SEPARATION_STEP: f64 = 1e-2;
432
433/// `first − second` as `first − (first ∩ second)`, on the exact lane only, for a
434/// difference the pinch gate is about to refuse (`BREP_PINCH_COMMON_RETRY`,
435/// default on; `=0` leaves the refusal).
436///
437/// The two are the same set, and the second form is often the arrangement the
438/// exact lane can build where the first is not. A cylinder cut by a smaller one
439/// tangent to it inside along a ruling, the cutter running on past both caps
440/// (a crescent; brep-bench probe 2026-11-12): each cap's section circle is
441/// tangent to the cap's own rim, the cap's loops do not close, and the cut
442/// refused; with the cutter flush with the caps it built, exact. The common part
443/// IS the cutter made flush, it is built without trouble (it has no thin wall),
444/// and cutting it away meets the first operand only in faces they share.
445///
446/// Nothing is nudged, so the pinch gate's reason for refusing a PERTURBED
447/// answer does not apply; what is accepted is an exact-lane body that validates
448/// and whose volume is `V(first) − V(first ∩ second)` to the drift bar. Any
449/// other outcome returns `None` and the gate's refusal stands.
450fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
451    // With the tangent imprint switched off the caller has asked for the
452    // recorded-only lane, whose answer to a pinch is its refusal.
453    if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
454        return None;
455    }
456    let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
457    if common.shells.iter().all(|shell| shell.faces.is_empty()) {
458        return None;
459    }
460    let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
461    if !cut.validate().is_empty() {
462        return None;
463    }
464    let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
465    let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
466    ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
467}
468
469/// `first ∪ second` as `second ∪ (first − second)`, on the exact lane only, for
470/// a union that failed where the operands touch tangentially with co-directed
471/// normals (`BREP_TANGENT_UNION_DIFFERENCE_RETRY`, default on; `=0` leaves the
472/// union to the paths it had).
473///
474/// The two are the same set. A cylinder holding a smaller one tangent to it
475/// inside along a ruling, the smaller running on past a cap: the union's
476/// arrangement leaves the cap's section circle tangent to the cap's own rim and
477/// the shell does not close, while the difference builds (the crescent) and the
478/// smaller body joins it along faces the two share. Accepted only when it
479/// validates and its volume is `V(first − second) + V(second)` to the drift bar;
480/// any other outcome returns `None` and the union goes on as before.
481fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
482    if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
483        return None;
484    }
485    let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
486    if !pinches(first, second) && !pinches(second, first) {
487        return None;
488    }
489    let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
490        Ok(outcome) => outcome.value,
491        Err(_) => subtract_through_the_common_part(first, second, options)?,
492    };
493    if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
494        return None;
495    }
496    let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
497    if !union.validate().is_empty() {
498        return None;
499    }
500    let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
501    let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
502    ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
503}
504
505/// Would the exact `first − second` PINCH to zero thickness at a tangential
506/// contact?
507///
508/// True when some face of `first` and some face of `second` touch tangentially
509/// (surfaces within the contact band, normals parallel) with CO-DIRECTED outward
510/// normals, at a contact that is lower-dimensional (the surfaces separate as you
511/// step away from it).
512///
513/// Co-directed outward normals at a tangency mean one solid lies locally INSIDE
514/// the other: subtracting leaves material on both sides of the contact that
515/// meets there at zero thickness — a non-manifold pinch no boundary model can
516/// represent. Anti-directed normals are the harmless EXTERNAL tangency (a
517/// cylinder resting against a wall): the difference simply keeps `first` intact.
518/// The lower-dimensionality requirement excludes a CO-SURFACE contact (a pocket
519/// wall flush with an outer wall — co-directed normals, but the surfaces stay
520/// coincident in every direction), where the difference is perfectly well
521/// behaved.
522///
523/// Conservative by construction: it only reports a pinch it can actually witness
524/// on the probe grid, and a miss just leaves the perturbation lane to its
525/// existing gates.
526pub fn subtract_pinches_at_internal_tangency(
527    first: &BrepSolid,
528    second: &BrepSolid,
529    tolerance: f64,
530) -> Result<bool, KernelRefusal> {
531    // Same contact band the imprint pair classifier uses for its sampled
532    // "these carriers touch" verdict.
533    let contact = (tolerance * 100.0).max(1e-12);
534    let probes_a = first
535        .shells
536        .iter()
537        .flat_map(|shell| &shell.faces)
538        .map(PinchProbe::of)
539        .collect::<Result<Vec<_>, _>>()?;
540    let probes_b = second
541        .shells
542        .iter()
543        .flat_map(|shell| &shell.faces)
544        .map(PinchProbe::of)
545        .collect::<Result<Vec<_>, _>>()?;
546    for probe_a in &probes_a {
547        for probe_b in &probes_b {
548            // Sampled-hull cull, so the (failure-path-only) cost stays linear in
549            // the faces that actually touch rather than quadratic in every face.
550            // The hull is built from the probe grid, so it can under-cover a
551            // curved carrier between samples: pad it by a percent of the pair's
552            // size before culling. Over-keeping a pair only costs a probe that
553            // finds nothing.
554            let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
555            if probe_a.separation(probe_b) > contact + pad {
556                continue;
557            }
558            // CO-SURFACE contacts are 2-dimensional, not tangencies: two flush
559            // walls (a pocket's side coincident with an outer wall, a cylinder
560            // cap lying in a box face) have co-directed normals wherever the
561            // solids nest, yet the difference there is perfectly well behaved.
562            // Only a LOWER-dimensional contact pinches, so drop the pair the
563            // pair classifier calls cosurface before probing it.
564            if classify_surface_pair(
565                &probe_a.face.surface,
566                &probe_b.face.surface,
567                tolerance,
568                PINCH_ANGULAR_TOLERANCE,
569            ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
570            .relation
571                == SurfacePairRelation::Cosurface
572            {
573                continue;
574            }
575            if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
576                return Ok(true);
577            }
578        }
579    }
580    Ok(false)
581}
582
583/// A face's probe grid plus the grid's bounding box, built once per face so the
584/// pair loop only pays for a hull comparison.
585struct PinchProbe<'a> {
586    face: &'a FaceRecord,
587    /// `(u, v, point)` on the face's carrier surface.
588    samples: Vec<(f64, f64, Vec3)>,
589    minimum: [f64; 3],
590    maximum: [f64; 3],
591}
592
593impl<'a> PinchProbe<'a> {
594    fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
595        let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
596        let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
597        let steps = PINCH_PROBE_STEPS as f64;
598        let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
599        let mut minimum = [f64::INFINITY; 3];
600        let mut maximum = [f64::NEG_INFINITY; 3];
601        for i in 0..=PINCH_PROBE_STEPS {
602            let u = u0 + (u1 - u0) * i as f64 / steps;
603            for j in 0..=PINCH_PROBE_STEPS {
604                let v = v0 + (v1 - v0) * j as f64 / steps;
605                let Ok(point) = face.surface.evaluate(u, v) else {
606                    continue;
607                };
608                for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
609                    minimum[axis] = minimum[axis].min(value);
610                    maximum[axis] = maximum[axis].max(value);
611                }
612                samples.push((u, v, point));
613            }
614        }
615        Ok(Self {
616            face,
617            samples,
618            minimum,
619            maximum,
620        })
621    }
622
623    /// Largest side of the sampled hull (0 when nothing sampled).
624    fn extent(&self) -> f64 {
625        (0..3)
626            .map(|axis| self.maximum[axis] - self.minimum[axis])
627            .fold(0.0f64, f64::max)
628    }
629
630    /// Axis-aligned gap between the two sampled hulls (0 when they overlap).
631    fn separation(&self, other: &Self) -> f64 {
632        let mut gap: f64 = 0.0;
633        for axis in 0..3 {
634            gap = gap.max(self.minimum[axis] - other.maximum[axis]);
635            gap = gap.max(other.minimum[axis] - self.maximum[axis]);
636        }
637        gap
638    }
639}
640
641/// One face pair of [`subtract_pinches_at_internal_tangency`]: probe both
642/// surfaces on a grid, keep samples that land on the other surface inside BOTH
643/// trims with parallel co-directed outward normals, and accept only where the
644/// contact provably separates nearby.
645fn faces_touch_with_codirected_normals(
646    probe_a: &PinchProbe<'_>,
647    probe_b: &PinchProbe<'_>,
648    contact: f64,
649) -> Result<bool, KernelRefusal> {
650    for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
651        let source = probe.face;
652        let target = other.face;
653        for &(u, v, point) in &probe.samples {
654            let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
655            if projection.distance > contact {
656                continue;
657            }
658            // A pole (collapsed du × dv) has no reliable orientation here;
659            // skipping it keeps the predicate conservative.
660            let (Ok(source_normal), Ok(target_normal)) = (
661                source.surface.normal(u, v),
662                target.surface.normal(projection.u, projection.v),
663            ) else {
664                continue;
665            };
666            let source_outward = outward_normal(source_normal, source.same_sense);
667            let target_outward = outward_normal(target_normal, target.same_sense);
668            if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
669                || source_outward.dot(target_outward) <= 0.0
670            {
671                continue;
672            }
673            if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
674                == PolygonClass::Outside
675                || parameter_point_in_face(
676                    target,
677                    Vec2 {
678                        x: projection.u,
679                        y: projection.v,
680                    },
681                    1e-6,
682                ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
683            {
684                continue;
685            }
686            if contact_separates_locally(source, target, u, v, contact)? {
687                return Ok(true);
688            }
689        }
690    }
691    Ok(false)
692}
693
694fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
695    if same_sense {
696        normal
697    } else {
698        normal.scale(-1.0)
699    }
700}
701
702/// Does the contact at `source(u, v)` LEAVE the contact band when you step away
703/// from it in parameter space? A tangency curve or point does (stepping across
704/// the tangency separates the surfaces quadratically); a cosurface patch does
705/// not (it stays coincident in every direction). Steps are clamped into the
706/// domain, so a sample on a seam or a domain edge probes only inward.
707fn contact_separates_locally(
708    source: &FaceRecord,
709    target: &FaceRecord,
710    u: f64,
711    v: f64,
712    contact: f64,
713) -> Result<bool, KernelRefusal> {
714    let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
715    let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
716    let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
717    let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
718    for (probe_u, probe_v) in [
719        ((u + step_u).min(u1), v),
720        ((u - step_u).max(u0), v),
721        (u, (v + step_v).min(v1)),
722        (u, (v - step_v).max(v0)),
723    ] {
724        if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
725            continue;
726        }
727        let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
728            continue;
729        };
730        // A generous multiple of the band: the step must clear it decisively,
731        // never on projection noise.
732        if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
733            return Ok(true);
734        }
735    }
736    Ok(false)
737}
738
739/// Deterministic perturbation-fallback (Simulation of Simplicity), the textbook
740/// CAD answer to an exact/near-tangent arrangement degeneracy, adopted after six
741/// incremental arrangement/imprint/fragment fixes for the near-tangent class were
742/// each falsified, rather than attempting a seventh. Rigidly TRANSLATE the second operand by a tiny
743/// epsilon so the degenerate contact becomes a clean transversal crossing, redo
744/// the boolean, and accept the result ONLY if it is (a) topologically valid —
745/// guaranteed by `assemble`'s own gate returning `Ok` — (b) semantically equal to
746/// the exact CSG of the ORIGINAL operands (the point-classification oracle), and
747/// (c) volume-consistent with the CSG inequality bounds. A wrong perturbed result
748/// is rejected on (b)/(c), so this lane preserves the engine's fail-safe property:
749/// it can only turn a degeneracy-error into a CORRECT solid, never a wrong one.
750///
751/// INVARIANT — no recursion: this calls `boolean_operation_with_diagnostics`
752/// (the EXACT path), never `boolean_operation`, so the fallback can never
753/// re-enter itself. A future refactor must preserve that.
754///
755/// (d) THE IDENTITY. Where the exact lane answers one of the other operations
756/// on the same operands, inclusion–exclusion names the volume this result
757/// must have, and a rung that misses it by more than the case gate's own drift
758/// band (`VOLUME_DRIFT_REL` of that volume, `VOLUME_DRIFT_ABS` floor) is
759/// refused by name. (c)'s 1% of the operands' total cannot see an error in a
760/// small removed volume: on the helmet's cutter − helmet (2026-09-15) the rung
761/// at fraction 3e-4 moved the helmet 5.2e-3, 2.3% of its size, passed the
762/// oracle at 1 in 336, and read 999.999899266 against V(cutter) − V(cutter ∩
763/// helmet) = 999.999905792: 6.9% too much material removed. Where no other
764/// operation clears on the exact lane there is no identity to hold, and the
765/// rung is held to (e) instead. Escape hatch for measuring it:
766/// BREP_PERTURB_IDENTITY=0 (which also lifts (e)).
767///
768/// (e) THE MIRROR. Where no exact-lane boolean of the operands clears in
769/// either order, the rung is held to itself moved the other way: the same
770/// operation, or failing that any sibling reading, on the second operand moved
771/// by −offset, with V(first) and V(second) from the mass integrator and the
772/// operation's sign, names the volume the mirrored rung encloses. A rigid
773/// translation changes the answer to first order in the offset, so half the
774/// difference between the rung's body and its mirror is the body's
775/// first-order translation error, and it must clear the same drift band. A
776/// rung whose mirror clears no boolean at all has nothing to check it and is
777/// refused by name. On 22_sag_boundary_identity_t164 (2026-09-15) the four
778/// shipped rescues at offset 9.7e-4 disagreed with each other through V(∩) by
779/// 4.3e-2 (the difference moves the part; the others move the sphere), against
780/// a bar of 5e-6. Escape hatch: BREP_PERTURB_MIRROR=0.
781///
782/// (d) and (e) run before (b), the oracle, which costs more than either.
783///
784/// (f) THE EARLY EXIT. Along one direction the mirror's error grows with the
785/// offset (`MirrorTrend` states the law and its measurement), so a direction
786/// whose two refused rungs read one sign, growing, is not tried at larger
787/// offsets, and the refusal names it. booleanIssue's refusal walked 20 rungs,
788/// each with its mirror, in 40.5 s against the case's 30 s. Escape hatch:
789/// BREP_MIRROR_EARLY_EXIT=0.
790///
791/// `Err` carries one sentence per rung refused on (d), empty when none was.
792fn perturbation_retry(
793    first: &BrepSolid,
794    second: &BrepSolid,
795    operation: BooleanOperation,
796    options: &BooleanOptions,
797) -> Result<BrepSolid, Vec<String>> {
798    // Generic translation directions: each has a substantial component on ALL
799    // three axes, so whatever axis the coincidence normal lies along (an
800    // equatorial plane flush with a box face, a cap plane flush with a side
801    // face, …) at least one direction has a component that lifts the contact off
802    // exact tangency. Axis-aligned directions are deliberately excluded — a nudge
803    // parallel to the coincident plane leaves the degeneracy in place (verified:
804    // pure ±X / ±Z never rescue the flush-torus case). Fixed, not hash-seeded
805    // as the lane was first sketched: the seeding's only purpose was to rule out
806    // RNG/clock nondeterminism, which fixed vectors already satisfy, and four
807    // diverse directions cover any axis-aligned normal.
808    const DIRECTIONS: [[f64; 3]; 4] = [
809        [0.4034, 0.7973, 0.4491],
810        [0.7973, 0.4491, 0.4034],
811        [0.4491, 0.4034, 0.7973],
812        [0.5774, -0.5774, 0.5774],
813    ];
814    // Fractions of operand scale, ordered SMALLEST-FIRST so the accepted solid
815    // carries the least geometric offset. Sized above the near-tangent sliver
816    // dead zone and below local feature size; the ladder + accept-gate make the
817    // exact magnitude non-critical (a rung that lands in a dead zone simply fails
818    // the gate and the next rung is tried).
819    const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
820
821    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
822    let scale = crate::solid_tolerance::solid_scale(first)
823        .max(crate::solid_tolerance::solid_scale(second))
824        .max(1.0);
825
826    // Original operand volumes for the CSG inequality backstop (the oracle skips
827    // points near boundaries, so a wrong thin shell hugging the flush face is
828    // invisible to it but shows up here).
829    let _caller = crate::mass_caller("boolean.perturbation_rescue");
830    let va = solid_signed_volume(first).ok().map(f64::abs);
831    let vb = solid_signed_volume(second).ok().map(f64::abs);
832    let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
833    // (e) is held only with (d): `BREP_PERTURB_MIRROR=0` alone ships a rung
834    // with no identity on (a)–(c), as before.
835    let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
836    // (f) A direction whose mirror errors say no larger offset can clear is
837    // closed. Escape hatch: `BREP_MIRROR_EARLY_EXIT=0` walks every rung.
838    let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
839    let mut trends = [MirrorTrend::default(); 4];
840    // Measured once, on the first rung that clears (a)–(c).
841    let mut identity: Option<Option<InclusionExclusion>> = None;
842    let mut refused = Vec::new();
843    // `BREP_DEBUG_PERTURB_LADDER=1`: every rung's disposition on stderr, and
844    // for every rung that builds, its miss against the identity, measured
845    // before the ladder starts. Changes no decision.
846    let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
847    let ladder_start = web_time::Instant::now();
848    if ladder {
849        let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
850        match &measured {
851            Some(identity) => eprintln!(
852                "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
853                identity.formula, identity.expected, identity.reading, identity.read, va, vb
854            ),
855            None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
856        }
857        identity = Some(measured);
858    }
859    let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
860        let volume = body_volume(candidate);
861        match (identity, volume) {
862            (Some(Some(identity)), Some(volume)) => format!(
863                "volume {volume:.9} miss {:+.3e} bar {:.3e}",
864                volume - identity.expected,
865                crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
866            ),
867            (_, Some(volume)) => format!("volume {volume:.9}"),
868            _ => "no volume".to_string(),
869        }
870    };
871
872    for &fraction in &FRACTIONS {
873        let magnitude = scale * fraction;
874        for (direction, dir) in DIRECTIONS.iter().enumerate() {
875            if trends[direction].closed {
876                if ladder {
877                    eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
878                }
879                continue;
880            }
881            let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
882            let translate = match AffineTransform::new([
883                1.0, 0.0, 0.0, offset[0], //
884                0.0, 1.0, 0.0, offset[1], //
885                0.0, 0.0, 1.0, offset[2], //
886                0.0, 0.0, 0.0, 1.0,
887            ]) {
888                Ok(transform) => transform,
889                Err(_) => continue,
890            };
891            let moved = match crate::transform_brep(second, translate, false) {
892                Ok(solid) => solid,
893                Err(_) => continue,
894            };
895            let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
896            let rung_start = web_time::Instant::now();
897            let candidate =
898                match boolean_operation_with_diagnostics(first, &moved, operation, options) {
899                    Ok(outcome) => outcome.value,
900                    Err(error) => {
901                        if ladder {
902                            eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
903                        }
904                        continue;
905                    }
906                };
907            let built = rung_start.elapsed();
908            // A perturbation must not "rescue" a case into emptiness.
909            if candidate.shells.is_empty() {
910                if ladder {
911                    eprintln!("[ladder] {rung}: empty");
912                }
913                continue;
914            }
915            // (c) Volume must satisfy the CSG inequality for the ORIGINAL
916            // operands (generous 1% relative slack: catches gross wrongness —
917            // doubled/halved bodies, missing lobes — without rejecting the
918            // legitimate sub-micron offset).
919            if let (Some(va), Some(vb)) = (va, vb) {
920                if let Ok(vr) = solid_signed_volume(&candidate) {
921                    if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
922                        if ladder {
923                            eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
924                        }
925                        continue;
926                    }
927                }
928            }
929            // (d) and (e) run before (b): each costs a volume, and (e) one
930            // exact-lane boolean, where the oracle classifies 400 points. A
931            // rung ships only when every gate clears, so the order decides
932            // which gate names a refusal, never which rung ships.
933            let bounded = rung_start.elapsed();
934            // (d) The exact lane's inclusion–exclusion identity.
935            if hold_identity {
936                let identity = identity.get_or_insert_with(|| {
937                    let identity =
938                        inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
939                    if debug && identity.is_none() {
940                        eprintln!(
941                            "[perturb] no exact-lane boolean of these operands clears in either \
942                             order; no identity to hold"
943                        );
944                    }
945                    identity
946                });
947                if let Some(identity) = identity {
948                    let expected = identity.expected;
949                    let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
950                    let volume = body_volume(&candidate);
951                    let miss = volume.map(|volume| (volume - expected).abs());
952                    if !miss.is_some_and(|miss| miss <= bar) {
953                        let sentence = format!(
954                            "perturbation rung dir={dir:?} fraction={fraction:.1e} \
955                             (offset {magnitude:.3e}) refused: its body reads {} against the \
956                             inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
957                             {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
958                            volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
959                            identity.formula,
960                            identity.reading,
961                            identity.read,
962                            miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
963                        );
964                        if debug {
965                            eprintln!("[perturb] {sentence}");
966                        }
967                        if ladder {
968                            eprintln!(
969                                "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
970                                volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
971                                volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
972                            );
973                        }
974                        refused.push(sentence);
975                        continue;
976                    }
977                } else if hold_mirror {
978                    // (e) No exact reading of these operands: the rung's
979                    // mirror.
980                    let mirror_start = web_time::Instant::now();
981                    let mirrored = AffineTransform::new([
982                        1.0, 0.0, 0.0, -offset[0], //
983                        0.0, 1.0, 0.0, -offset[1], //
984                        0.0, 0.0, 1.0, -offset[2], //
985                        0.0, 0.0, 0.0, 1.0,
986                    ])
987                    .ok()
988                    .and_then(|transform| crate::transform_brep(second, transform, false).ok());
989                    let mirror = mirrored.as_ref().and_then(|mirrored| {
990                        inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
991                    });
992                    let mirror_time = mirror_start.elapsed();
993                    let volume = body_volume(&candidate);
994                    let mut measured = None;
995                    let verdict = match (&mirror, volume) {
996                        (Some(mirror), Some(volume)) => {
997                            let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
998                            let miss = 0.5 * (volume - mirror.expected).abs();
999                            measured = Some((0.5 * (volume - mirror.expected), bar));
1000                            if ladder {
1001                                eprintln!(
1002                                    "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1003                                    mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1004                                );
1005                            }
1006                            (miss > bar).then(|| format!(
1007                                "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1008                                 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1009                                 operands clears, so the rung is held to its mirror: its body reads \
1010                                 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1011                                 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1012                                 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1013                                mirror.formula, mirror.expected, mirror.reading, mirror.read
1014                            ))
1015                        }
1016                        _ => Some(format!(
1017                            "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1018                             (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1019                             clears, and none clears with the second operand moved −offset either, \
1020                             so nothing checks the rung's body{}",
1021                            volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1022                        )),
1023                    };
1024                    match verdict {
1025                        None => trends[direction].cleared(),
1026                        Some(sentence) => {
1027                            if debug {
1028                                eprintln!("[perturb] {sentence}");
1029                            }
1030                            if ladder {
1031                                eprintln!(
1032                                    "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1033                                    rung_start.elapsed().as_secs_f64() * 1e3,
1034                                    built.as_secs_f64() * 1e3,
1035                                    (bounded - built).as_secs_f64() * 1e3,
1036                                    mirror_time.as_secs_f64() * 1e3,
1037                                    ladder_start.elapsed().as_secs_f64()
1038                                );
1039                            }
1040                            refused.push(sentence);
1041                            // (f) Two refused rungs of one sign, growing, close
1042                            // the direction.
1043                            let closure = measured.and_then(|(error, bar)| {
1044                                let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1045                                Some((earlier, error, bar))
1046                            });
1047                            if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1048                                let closed = format!(
1049                                    "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1050                                     rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1051                                     {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1052                                     growing, so no larger offset along it comes back to the volume drift bar \
1053                                     {bar:.3e}"
1054                                );
1055                                if debug {
1056                                    eprintln!("[perturb] {closed}");
1057                                }
1058                                if ladder {
1059                                    eprintln!("[ladder] {closed}");
1060                                }
1061                                refused.push(closed);
1062                            }
1063                            continue;
1064                        }
1065                    }
1066                }
1067            }
1068            // (b) Semantic agreement with the exact CSG of the ORIGINAL
1069            // operands. Reject a vacuous verdict (skip-band swallowed every
1070            // sample so nothing was actually checked).
1071            match crate::oracle::boolean_semantic_disagreement(
1072                first, second, operation, &candidate, 400,
1073            ) {
1074                Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1075                    if ladder {
1076                        eprintln!(
1077                            "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1078                            report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1079                        );
1080                    }
1081                    if debug {
1082                        eprintln!(
1083                            "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1084                             magnitude={magnitude:.3e} offset={offset:?} \
1085                             (oracle considered={} rate={:.4})",
1086                            report.considered, report.disagreement_rate
1087                        );
1088                    }
1089                    return Ok(candidate);
1090                }
1091                report => {
1092                    if ladder {
1093                        let verdict = match &report {
1094                            Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1095                            Err(error) => format!("oracle error {error:?}"),
1096                        };
1097                        eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1098                    }
1099                    continue;
1100                }
1101            }
1102        }
1103    }
1104    if debug {
1105        eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1106    }
1107    Err(refused)
1108}
1109
1110/// The perturbation ladder's offsets, as fractions of the operands' scale,
1111/// smallest first.
1112pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1113
1114/// (f) One ladder direction's rungs refused by their mirrors.
1115///
1116/// Along one direction a rung's signed first-order translation error, half
1117/// its body less its mirror's reading, reads s(δ) = kδ + r: a slope k from the
1118/// translation, and a remainder r from the degeneracy the rung steps over,
1119/// which does not grow with the offset. Two refused rungs at δ₁ < δ₂ with one
1120/// sign and |s(δ₂)| ≥ |s(δ₁)| fix k's sign as theirs, so every larger offset
1121/// reads farther from zero than s(δ₂), which is already beyond the drift bar:
1122/// the direction is closed. Rungs of one sign that shrink toward zero, or that
1123/// change sign, say nothing about k, and the direction stays open; a rung whose
1124/// mirror clears starts the direction's record again.
1125///
1126/// Measured 2026-09-15 (`BREP_DEBUG_PERTURB_LADDER=1` prints s). On
1127/// 22_sag_boundary_identity_t164, all four operations and all four
1128/// directions, s/δ keeps one sign and holds to 3.6% over the ladder's 100× of
1129/// offset (r ≈ 0; −22.23 .. −22.34 on the intersection's first direction). On
1130/// booleanIssue's flush partial torus union, s/δ holds to 0.5% and 8.5% on two
1131/// directions, and to 1.2% on a third past its smallest rung, whose remainder
1132/// reads −43.4 against the slope's −24.5. The first direction's smallest rung
1133/// reads −1.891e-2 where its slope, +2.3 .. +2.6, gives +3.5e-3 (r ≈ −2.2e-2),
1134/// and its next measured rung +3.510e-2: a change of sign, which keeps it open.
1135/// A closed direction's skipped rung would have had to fall to the bar, 8.3e2 ..
1136/// 1.5e6 times below the smallest refused |s| on those rows, to have cleared.
1137#[derive(Clone, Copy, Default)]
1138pub struct MirrorTrend {
1139    /// The last rung refused by its mirror: its offset and signed error.
1140    last: Option<(f64, f64)>,
1141    pub closed: bool,
1142}
1143
1144impl MirrorTrend {
1145    /// Records a rung refused by its mirror at `offset` with signed error
1146    /// `error`. When it and the direction's last refused rung close the
1147    /// direction, and `close` allows it, the direction is closed and the
1148    /// earlier rung's (offset, signed error) returned.
1149    pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1150        let earlier = self
1151            .last
1152            .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1153            .filter(|_| close);
1154        self.last = Some((offset, error));
1155        self.closed |= earlier.is_some();
1156        earlier
1157    }
1158
1159    /// A rung whose mirror clears: the direction's record starts again.
1160    pub fn cleared(&mut self) {
1161        self.last = None;
1162    }
1163}
1164
1165/// Non-degenerate edges a solid's faces use exactly once.
1166/// BELOW-TOLERANCE REFUSAL (`BREP_BELOW_TOLERANCE_REFUSAL`, default on, `=0` off). Two
1167/// planar faces, one of each operand, that are nearly parallel and stand no
1168/// farther apart over their shared extent than [`BELOW_TOLERANCE_BAND`] but not
1169/// exactly on one another are a configuration the kernel cannot resolve: its
1170/// weld floor is 1e-5 and its face arrangements resolve a few 1e-5, so the
1171/// slivers between such faces fall under the modelling tolerance. A cube
1172/// against a copy turned 1e-4 deg moves its corners 1.2e-5 to 2.5e-5: the exact
1173/// arrangement failed, and the perturbation ladder then answered a nudged pair
1174/// 8.5e-5 out in volume; at 1e-6 deg the face pairs read as coincident and the
1175/// difference came back empty. Consulted only where the exact lane failed or
1176/// returned an empty difference or common part, so nothing that answers today
1177/// changes; the refusal names the pair and the modelling tolerance instead of
1178/// shipping a nudged or empty solid.
1179pub fn below_tolerance_refusal_enabled() -> bool {
1180    crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1181}
1182
1183/// Ten weld floors: the separation under which two near-coincident planar faces
1184/// are read as below the modelling tolerance.
1185const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1186
1187/// UNRESOLVED-MERGE REFUSAL (`BREP_UNRESOLVED_MERGE_REFUSAL`, default off). A
1188/// union or common part that SUCCEEDS over two planar faces, one of each
1189/// operand, standing farther apart than the coincidence band (1e-6: closer
1190/// faces are one surface by the kernel's definition) but no farther than the
1191/// weld floor (1e-5) has welded the two faces into one: a unit cube united
1192/// with a copy raised 3e-6 came back as the cube, valid, 2e-6 out in volume,
1193/// where the difference of the same pair already refuses by this name. The
1194/// step between such faces is neither a coincidence nor resolvable, so the
1195/// answer is the refusal.
1196pub fn unresolved_merge_refusal_enabled() -> bool {
1197    crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1198}
1199
1200/// SLIVER SHELLS (`BREP_SLIVER_SHELL_DROP`, default on, `=0` off). A solid
1201/// result of several shells, one of which is closed and encloses no material
1202/// (its volume over its area, the thickness of the slab it would be, under
1203/// [`SLIVER_SHELL_THICKNESS`] of the body's size: round-off), carries a sheet the arrangement could not
1204/// resolve, left closed on itself: a measure-zero set, not a void. A cylinder
1205/// of radius 5 with a coaxial one of radius 4.99999 between the same end
1206/// planes gave their common part the inner cylinder plus 64 closed sheets
1207/// over the 1e-5 rings at its ends, 6e-4 over in area and refused by STEP
1208/// export ("a void shell lies inside no outward shell"). Such shells are
1209/// dropped, with the edges and vertices only they used; the point set is
1210/// unchanged. Sheet and other non-solid bodies, open shells, and a body whose
1211/// every shell would go are left as they are.
1212pub fn sliver_shell_drop_enabled() -> bool {
1213    crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1214}
1215
1216/// The thickness, as a fraction of the body's size, under which a closed shell
1217/// encloses nothing: round-off. The sheets read 0 and 7e-17 thick; a real
1218/// slab 1e-7 thick beside a unit cube is material and stays.
1219const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1220
1221/// Drops the sliver shells of `solid` (see [`sliver_shell_drop_enabled`]) and
1222/// returns how many went.
1223fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1224    if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1225        return 0;
1226    }
1227    let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1228    let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1229    let mut drop = vec![false; solid.shells.len()];
1230    for (index, shell) in solid.shells.iter().enumerate() {
1231        if shell.faces.is_empty() {
1232            continue;
1233        }
1234        // Closed: every proper edge the shell uses, used exactly twice by it.
1235        let mut uses: HashMap<u64, usize> = HashMap::default();
1236        for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1237            if !degenerate.contains(&coedge.edge_id) {
1238                *uses.entry(coedge.edge_id).or_default() += 1;
1239            }
1240        }
1241        if uses.is_empty() || uses.values().any(|&count| count != 2) {
1242            continue;
1243        }
1244        let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1245        let Ok(mass) = crate::solid_mass_properties(&alone) else {
1246            continue;
1247        };
1248        let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1249        if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1250            eprintln!(
1251                "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1252                solid.shells.len(),
1253                mass.volume,
1254                mass.surface_area
1255            );
1256        }
1257        drop[index] = thickness < floor;
1258    }
1259    let dropped = drop.iter().filter(|&&d| d).count();
1260    if dropped == 0 || dropped == solid.shells.len() {
1261        return 0;
1262    }
1263    let mut index = 0;
1264    solid.shells.retain(|_| {
1265        let keep = !drop[index];
1266        index += 1;
1267        keep
1268    });
1269    let used_edges: std::collections::HashSet<u64> = solid
1270        .shells
1271        .iter()
1272        .flat_map(|shell| &shell.faces)
1273        .flat_map(|face| &face.loops)
1274        .flat_map(|lp| &lp.coedges)
1275        .map(|coedge| coedge.edge_id)
1276        .collect();
1277    solid.edges.retain(|edge| used_edges.contains(&edge.id));
1278    let used_vertices: std::collections::HashSet<u64> =
1279        solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1280    solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1281    solid.mass_properties_cache = Default::default();
1282    // A dropped shell may have carried handles: the genus is read again.
1283    refresh_derived_genus(solid);
1284    dropped
1285}
1286
1287fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1288    let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1289    let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1290    Some(KernelRefusal::unsupported(
1291        KernelStage::Intersect,
1292        "below_modelling_tolerance",
1293        format!(
1294            "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1295             another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1296             ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1297             welded away"
1298        ),
1299    ))
1300}
1301
1302fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1303    let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1304    let message = format!(
1305        "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1306         another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1307         modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1308        error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1309    );
1310    Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1311}
1312
1313/// The first pair of planar faces (one per operand) whose planes are nearly
1314/// parallel and whose boundaries stand within [`BELOW_TOLERANCE_BAND`] of the
1315/// other's plane, with overlapping extents, but which are not one plane.
1316fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1317    let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1318    planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1319}
1320
1321/// The first pair of nearly parallel planar faces (one per operand) with
1322/// overlapping extents whose largest separation is above `lower` and at most
1323/// `upper`.
1324fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1325    struct Planar {
1326        id: u64,
1327        origin: Vec3,
1328        normal: Vec3,
1329        corners: Vec<Vec3>,
1330        bounds: crate::spatial::Aabb,
1331    }
1332    let read = |solid: &BrepSolid| -> Vec<Planar> {
1333        let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1334        solid
1335            .shells
1336            .iter()
1337            .flat_map(|shell| &shell.faces)
1338            .filter_map(|face| {
1339                if !face.surface.is_affine().ok()? {
1340                    return None;
1341                }
1342                let origin = face.surface.control_points[0][0].point().ok()?;
1343                let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1344                let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1345                let normal = a.cross(b).normalized().ok()?;
1346                let corners: Vec<Vec3> = face
1347                    .loops
1348                    .iter()
1349                    .flat_map(|lp| &lp.coedges)
1350                    .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1351                    .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1352                    .flatten()
1353                    .collect();
1354                if corners.is_empty() {
1355                    return None;
1356                }
1357                let bounds = crate::spatial::Aabb::from_points(corners.clone());
1358                Some(Planar { id: face.id, origin, normal, corners, bounds })
1359            })
1360            .collect()
1361    };
1362    let (faces_a, faces_b) = (read(first), read(second));
1363    for a in &faces_a {
1364        for b in &faces_b {
1365            if a.normal.cross(b.normal).length() > 1e-3 {
1366                continue;
1367            }
1368            if !a.bounds.intersects(b.bounds, upper) {
1369                continue;
1370            }
1371            let separation = a
1372                .corners
1373                .iter()
1374                .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1375                .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1376                .fold(0.0f64, f64::max);
1377            if separation > lower && separation <= upper {
1378                return Some((a.id, b.id, separation));
1379            }
1380        }
1381    }
1382    None
1383}
1384
1385pub fn one_use_edges(solid: &BrepSolid) -> usize {
1386    let mut uses: HashMap<u64, usize> = HashMap::default();
1387    for coedge in solid
1388        .shells
1389        .iter()
1390        .flat_map(|shell| &shell.faces)
1391        .flat_map(|face| &face.loops)
1392        .flat_map(|loop_record| &loop_record.coedges)
1393    {
1394        *uses.entry(coedge.edge_id).or_default() += 1;
1395    }
1396    solid
1397        .edges
1398        .iter()
1399        .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1400        .count()
1401}
1402
1403/// A body's enclosed volume, zero for an empty one.
1404fn body_volume(solid: &BrepSolid) -> Option<f64> {
1405    if solid.shells.is_empty() {
1406        return Some(0.0);
1407    }
1408    solid_signed_volume(solid).ok().map(f64::abs)
1409}
1410
1411/// What the exact lane's other operations say `operation` on these operands
1412/// must enclose.
1413struct InclusionExclusion {
1414    /// The rescued operation's volume in terms of V(first), V(second) and
1415    /// V(first ∩ second).
1416    formula: &'static str,
1417    /// The exact-lane boolean that supplied V(first ∩ second).
1418    reading: &'static str,
1419    /// That boolean's enclosed volume.
1420    read: f64,
1421    /// The volume `formula` gives.
1422    expected: f64,
1423}
1424
1425/// The volume `operation` on these operands must have, by inclusion–exclusion.
1426/// Any one exact-lane boolean of the same two operands fixes V(first ∩ second),
1427/// and with the operands' own volumes that fixes all four operations. The
1428/// readings are tried intersection, union, then difference, each in both
1429/// operand orders: the exact lane is not order-symmetric (the helmet's cutter
1430/// ∩ helmet refuses where helmet ∩ cutter clears). The rescued operation itself,
1431/// in its own order, is skipped, since it is the one that refused, unless
1432/// `own_first` asks for it to be read first (a rung's mirror, where it is a
1433/// different pair of operands). `None` when no reading clears or an operand has
1434/// no volume.
1435fn inclusion_exclusion_volume(
1436    first: &BrepSolid,
1437    second: &BrepSolid,
1438    operation: BooleanOperation,
1439    options: &BooleanOptions,
1440    va: Option<f64>,
1441    vb: Option<f64>,
1442    own_first: bool,
1443) -> Option<InclusionExclusion> {
1444    use BooleanOperation::{Intersect, Subtract, Union};
1445    let (va, vb) = (va?, vb?);
1446    let own = match operation {
1447        Intersect => (Intersect, false, "first ∩ second"),
1448        Union => (Union, false, "first ∪ second"),
1449        Subtract => (Subtract, false, "first − second"),
1450    };
1451    let readings = [
1452        (Intersect, false, "first ∩ second"),
1453        (Intersect, true, "second ∩ first"),
1454        (Union, false, "first ∪ second"),
1455        (Union, true, "second ∪ first"),
1456        (Subtract, false, "first − second"),
1457        (Subtract, true, "second − first"),
1458    ];
1459    let own_reading = own_first.then_some(own);
1460    let leading = usize::from(own_first);
1461    for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
1462        if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
1463            continue;
1464        }
1465        let (x, y) = if swapped { (second, first) } else { (first, second) };
1466        let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
1467            .ok()
1468            .and_then(|outcome| body_volume(&outcome.value))
1469        else {
1470            continue;
1471        };
1472        let intersection = match (other, swapped) {
1473            (Intersect, _) => read,
1474            (Union, _) => va + vb - read,
1475            (Subtract, false) => va - read,
1476            (Subtract, true) => vb - read,
1477        };
1478        let (formula, expected) = match operation {
1479            Intersect => ("V(first ∩ second)", intersection),
1480            Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
1481            Subtract => ("V(first) − V(first ∩ second)", va - intersection),
1482        };
1483        return Some(InclusionExclusion { formula, reading, read, expected });
1484    }
1485    None
1486}
1487
1488/// The worst planar face of either operand whose STRAIGHT boundary sits
1489/// farther off its plane than the assembly weld radius:
1490/// `(operand index, face id, gap, weld)`. Mirrors the STEP importer's planar
1491/// split predicate (`step_import::builder::planar_split`) on a finished
1492/// solid: a plane, a single loop of straight non-degenerate edges, and a
1493/// boundary vertex beyond the weld. `None` means no such face, so a failure
1494/// may still be a genuine degeneracy worth a perturbation rung. Only
1495/// consulted on the failure path.
1496fn planar_operand_off_its_plane(
1497    first: &BrepSolid,
1498    second: &BrepSolid,
1499    options: &BooleanOptions,
1500) -> Option<(u8, u64, f64, f64)> {
1501    let policy = options
1502        .tolerances
1503        .clone()
1504        .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
1505    let weld = crate::tolerance::assembler_weld(policy.model);
1506    let mut worst: Option<(u8, u64, f64)> = None;
1507    for (operand, solid) in [(0u8, first), (1u8, second)] {
1508        let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
1509        for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1510            let Some(crate::AnalyticSurface::Plane {
1511                origin,
1512                u_dir,
1513                v_dir,
1514                ..
1515            }) = face.surface.analytic()
1516            else {
1517                continue;
1518            };
1519            let [loop_record] = face.loops.as_slice() else {
1520                continue;
1521            };
1522            let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
1523                continue;
1524            };
1525            let mut off_plane = 0.0f64;
1526            let mut straight = true;
1527            for coedge in &loop_record.coedges {
1528                let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
1529                    straight = false;
1530                    break;
1531                };
1532                let (Some(start), Some(end)) =
1533                    (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
1534                else {
1535                    straight = false;
1536                    break;
1537                };
1538                let chord = end.sub(start);
1539                let length = chord.length();
1540                if edge.degenerate || length <= weld {
1541                    straight = false;
1542                    break;
1543                }
1544                let direction = chord.scale(1.0 / length);
1545                for fraction in [0.25, 0.5, 0.75] {
1546                    let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
1547                        straight = false;
1548                        break;
1549                    };
1550                    let delta = point.sub(start);
1551                    let along = delta.dot(direction);
1552                    if delta.sub(direction.scale(along)).length() > weld
1553                        || along < -weld
1554                        || along > length + weld
1555                    {
1556                        straight = false;
1557                        break;
1558                    }
1559                }
1560                if !straight {
1561                    break;
1562                }
1563                off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
1564            }
1565            if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
1566                worst = Some((operand, face.id, off_plane));
1567            }
1568        }
1569    }
1570    worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
1571}
1572
1573/// CSG volume inequality bounds (no extra boolean needed) with 1% relative slack.
1574/// `va`, `vb`, `vr` are absolute volumes of operand A, operand B, and the result.
1575fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
1576    let slack = 1e-2 * (va + vb).max(1.0);
1577    match operation {
1578        // max(A,B) ≤ A∪B ≤ A+B
1579        BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
1580        // A−B ≤ A (and ≥ 0)
1581        BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
1582        // A∩B ≤ min(A,B)
1583        BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
1584    }
1585}
1586
1587// ---------------------------------------------------------------------------
1588// N-ary booleans (Golovanov T4.4)
1589//
1590// Union / intersect / subtract of N solids in ONE imprint+fragment pass.  This
1591// is a NEW ADDITIVE entry point: the binary `boolean_operation` above is left
1592// byte-identical.  The pipeline mirrors the binary one but generalizes the two
1593// operand-specific stages to N operands:
1594//
1595//   1. Imprint EVERY unordered pair (i, j) so every mutual intersection edge is
1596//      present on both operands' faces, and accumulate all pairs into ONE global
1597//      imprint (operand indices remapped to 0..N, piece/vertex ids made globally
1598//      unique, per-face piece lists and per-edge split parameters merged).
1599//   2. Split + fragment each operand by that single global imprint, so each
1600//      operand's faces are cut by ALL of its intersections at once.
1601//   3. Select fragments in one pass: the per-fragment keep decision generalizes
1602//      from "vs one other solid" to "vs the SET of other solids" (see
1603//      `nary_keep`).  Because every pair is imprinted, a fragment's interior lies
1604//      wholly inside or wholly outside each other operand, so a single interior
1605//      test point per (fragment, other-solid) is an exact membership verdict.
1606//   4. Assemble with the same machinery (`assemble_fragments`), then merge and
1607//      validate exactly as the binary path does.
1608// ---------------------------------------------------------------------------
1609
1610/// Reverse a fragment's orientation (surface sense + every coedge), the same
1611/// transform the binary Subtract path applies to the second operand's kept
1612/// fragments.  Extracted so the n-ary selector can reuse it verbatim.
1613fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
1614    fragment.same_sense = !fragment.same_sense;
1615    for loop_record in &mut fragment.loops {
1616        loop_record.coedges.reverse();
1617        for coedge in &mut loop_record.coedges {
1618            coedge.forward = !coedge.forward;
1619            coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
1620        }
1621    }
1622    Ok(())
1623}
1624
1625/// Imprint every unordered pair of operands and fold the pairwise
1626/// `ImprintResultRecord`s into ONE global imprint whose operand indices are the
1627/// operands' global positions (0..N).  Piece and vertex ids are re-based to be
1628/// globally unique; `by_face` piece lists and `edge_splits` parameter lists are
1629/// MERGED per key so `fragment_face` (which takes the first `by_face` match) and
1630/// `apply_edge_splits` (which collects one entry per edge) see every cut.
1631fn build_nary_imprint(
1632    operands: &[BrepSolid],
1633    options: &ImprintOptions,
1634) -> Result<ImprintResultRecord, KernelRefusal> {
1635    let mut section_evidence = false;
1636    let mut vertices: Vec<ImprintVertex> = Vec::new();
1637    let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
1638    let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
1639    let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
1640    let mut next_vertex_id: u64 = 1;
1641    let mut next_piece_id: u64 = 1;
1642
1643    for i in 0..operands.len() {
1644        for j in (i + 1)..operands.len() {
1645            let pair = build_imprints(&operands[i], &operands[j], options)?;
1646            let remap = |operand: u8| -> u8 {
1647                if operand == 0 {
1648                    i as u8
1649                } else {
1650                    j as u8
1651                }
1652            };
1653
1654            section_evidence = section_evidence || pair.section_evidence;
1655            let mut vertex_map: HashMap<u64, u64> = HashMap::default();
1656            for vertex in &pair.vertices {
1657                let global = next_vertex_id;
1658                next_vertex_id += 1;
1659                vertex_map.insert(vertex.id, global);
1660                vertices.push(ImprintVertex {
1661                    id: global,
1662                    point: vertex.point,
1663                });
1664            }
1665
1666            let mut piece_map: HashMap<u64, u64> = HashMap::default();
1667            for piece in &pair.pieces {
1668                let global = next_piece_id;
1669                next_piece_id += 1;
1670                piece_map.insert(piece.id, global);
1671                let mut mapped = piece.clone();
1672                mapped.id = global;
1673                mapped.start_vertex_id = *vertex_map
1674                    .get(&piece.start_vertex_id)
1675                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1676                mapped.end_vertex_id = *vertex_map
1677                    .get(&piece.end_vertex_id)
1678                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1679                for pcurve in &mut mapped.pcurves {
1680                    pcurve.operand = remap(pcurve.operand);
1681                }
1682                mapped.support_faces = [
1683                    FaceKey {
1684                        operand: remap(piece.support_faces[0].operand),
1685                        face_id: piece.support_faces[0].face_id,
1686                    },
1687                    FaceKey {
1688                        operand: remap(piece.support_faces[1].operand),
1689                        face_id: piece.support_faces[1].face_id,
1690                    },
1691                ];
1692                pieces.push(mapped);
1693            }
1694
1695            for entry in &pair.by_face {
1696                let list = by_face
1697                    .entry((remap(entry.operand), entry.face_id))
1698                    .or_default();
1699                for piece_id in &entry.piece_ids {
1700                    let global = *piece_map.get(piece_id).ok_or_else(|| {
1701                        KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
1702                    })?;
1703                    list.push(global);
1704                }
1705            }
1706
1707            for split in &pair.edge_splits {
1708                edge_splits
1709                    .entry((remap(split.operand), split.edge_id))
1710                    .or_default()
1711                    .extend(split.parameters.iter().copied());
1712            }
1713        }
1714    }
1715
1716    Ok(ImprintResultRecord {
1717        vertices,
1718        pieces,
1719        tangent_nodes: Vec::new(),
1720        barrier_edges: Vec::new(),
1721        section_evidence,
1722        cosurface_pairs: Vec::new(),
1723        tangent_sections: Vec::new(),
1724        by_face: by_face
1725            .into_iter()
1726            .map(|((operand, face_id), piece_ids)| FaceImprints {
1727                operand,
1728                face_id,
1729                piece_ids,
1730            })
1731            .collect(),
1732        edge_splits: edge_splits
1733            .into_iter()
1734            .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
1735                operand,
1736                edge_id,
1737                parameters,
1738            })
1739            .collect(),
1740    })
1741}
1742
1743/// N-ary union / intersect / subtract of `operands` in ONE imprint+fragment
1744/// pass (Golovanov T4.4).  Additive: does not touch the binary path.
1745///
1746/// - `Union`   : the boundary of `∪ operands`.
1747/// - `Intersect`: the boundary of `∩ operands`.
1748/// - `Subtract`: `operands[0]` minus the union of `operands[1..]`.
1749///
1750/// `N = 1` returns the sole operand; `N = 2` runs the same general pipeline and
1751/// reproduces the binary result (same volume, valid).  Returns a clear `Err`
1752/// when the operands cannot assemble into a closed, valid solid.
1753pub fn boolean_operation_nary(
1754    operands: &[BrepSolid],
1755    operation: BooleanOperation,
1756) -> Result<BrepSolid, KernelRefusal> {
1757    boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
1758}
1759
1760/// [`boolean_operation_nary`] under the caller's [`BooleanOptions`]: the
1761/// tolerance, the coplanar-face merge and its `keep_unmerged_name_substrs`
1762/// list are honoured exactly as the binary path honours them, so a caller that
1763/// falls back from a sequence of binary unions to one arrangement (the sheet
1764/// metal walk with adjacent bends) keeps the same face partition contract.
1765pub fn boolean_operation_nary_with_options(
1766    operands: &[BrepSolid],
1767    operation: BooleanOperation,
1768    options: &BooleanOptions,
1769) -> Result<BrepSolid, KernelRefusal> {
1770    if operands.len() > 1 {
1771        if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
1772            return boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
1773                .map_err(|error| scaled.refusal(error))
1774                .and_then(|solid| scaled.back(&solid));
1775        }
1776    }
1777    if operands.is_empty() {
1778        return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
1779    }
1780    if operands.len() == 1 {
1781        return Ok(operands[0].clone());
1782    }
1783    if operands.len() > 255 {
1784        return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
1785    }
1786    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
1787
1788    // One tolerance policy for the whole set: the largest-scale operand's policy
1789    // dominates (every derived band is monotonic in scale), matching how the
1790    // binary path takes `for_pair` = max of the two scales.
1791    let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
1792    for operand in &operands[1..] {
1793        let candidate = KernelTolerances::for_solid(operand, options.tolerance);
1794        if candidate.sew_search > policy.sew_search {
1795            policy = candidate;
1796        }
1797    }
1798    policy.check().or_input(KernelStage::Collect, "tolerances")?;
1799    let tolerance = policy.model;
1800
1801    // Per-operand fuse-first healing, exactly as the binary path (a no-op on
1802    // clean input, so clean operands are untouched).
1803    let mut healed = operands.to_vec();
1804    for operand in &mut healed {
1805        crate::heal::heal_operands(operand, &policy)?;
1806        // Then refit any inherited trim off the pcurve construction contract
1807        // whose edge lies on every carrier (a no-op without one).
1808        crate::heal::refit_inherited_trims(operand, &policy)?;
1809        // Same operand normalization as the binary path: seam edges for
1810        // seamless full-period band faces.
1811        normalize_operand_band_seams(operand)?;
1812    }
1813
1814    // 1. Imprint every pair into one global imprint.
1815    let mut imprint_options = options.imprint.clone();
1816    imprint_options.tolerance = tolerance;
1817    let imprint = build_nary_imprint(&healed, &imprint_options)?;
1818
1819    // 2. Split every operand's edges, then fragment its faces, by that imprint.
1820    let mut split = Vec::with_capacity(healed.len());
1821    for (index, operand) in healed.iter().enumerate() {
1822        split.push(apply_edge_splits(operand, index as u8, &imprint)?);
1823    }
1824    let mut fragments = Vec::with_capacity(split.len());
1825    for (index, solid) in split.iter().enumerate() {
1826        fragments.push(fragment_solid(solid, index as u8, &imprint)?);
1827    }
1828
1829    // 3. Select fragments in one pass against the set of other operands.
1830    let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
1831
1832    // 4. Assemble + normalize + validate, mirroring the binary tail.
1833    let solids: HashMap<u8, &BrepSolid> = split
1834        .iter()
1835        .enumerate()
1836        .map(|(index, solid)| (index as u8, solid))
1837        .collect();
1838    let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
1839    let solid = if options.merge_coplanar_faces
1840        && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
1841    {
1842        let merged = merge_same_surface_faces_excluding(
1843            &solid,
1844            tolerance,
1845            &options.keep_unmerged_name_substrs,
1846        )?;
1847        merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?
1848    } else {
1849        solid
1850    };
1851    let validation = solid.validate_detailed(&policy);
1852    if !validation.issues.is_empty() {
1853        return Err(KernelRefusal::new(
1854            RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
1855            KernelStage::Validate,
1856            format!(
1857            "boolean_operation_nary: invalid result: {:?}",
1858            validation.issues
1859        )));
1860    }
1861    if debug {
1862        if let Ok(report) =
1863            crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
1864        {
1865            if report.is_flagged() {
1866                eprintln!(
1867                    "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
1868                    report.disagreement_rate,
1869                    report.disagreements.len(),
1870                    report.considered,
1871                    report.sample_disagreement()
1872                );
1873            }
1874        }
1875    }
1876    Ok(solid)
1877}
1878
1879/// TANGENT-NODE ATTRIBUTION.
1880///
1881/// The imprint's second-order filter decides which tangential contacts are
1882/// isolated NODES the arrangement can carve, and marches those instead of
1883/// refusing. It cannot decide a THIRD-order singularity — where the transverse
1884/// branch is tangent to a contact curve, every second-order quantity vanishes
1885/// together and the contact reads as a clean saddle at every stopping rule
1886/// (`imprint/tangent_contact.rs`). The assembly is the authority on whether an
1887/// admitted node was really imprintable, so a tear downstream of one is
1888/// reported AGAINST THE NODE rather than as an anonymous degeneracy: same
1889/// refusal class the whole tangent-node family carries, naming the point.
1890///
1891/// Only classes that are ALREADY perturbation-eligible are re-attributed, so a
1892/// refusal that could never take the ladder still cannot. The stage's own
1893/// message — the one-use edges, the genus — is NOT carried into the refusal:
1894/// `tangent_node_assembly` and `torus_torus_singular_refusal` hold the
1895/// tangent-node refusal to naming its cause without the arrangement's
1896/// symptom text ("open between", "genus", "pcurve"), the policy the class
1897/// exists for. It is printed under `BREP_DEBUG_BOOL` instead, so what the
1898/// assembly actually read is still there for a reader of the trace.
1899///
1900/// It does decide WHICH refusals are retried, though, and since 2026-09-13 that
1901/// matters: `boolean_operation`'s failure arm gates `TangentNodeSingularity` out
1902/// of the perturbation ladder (the TANGENT-NODE GATE there) and reads the class
1903/// AFTER this rewrite. So a tear downstream of an ADMITTED node — whatever class
1904/// the pipeline actually raised — declines the ladder along with the tangent-node
1905/// family proper. That is the conservative direction and the same claim the class
1906/// makes (a tear after a node is the node proving unimprintable). Anything added
1907/// to this rewrite widens that gate: read the gate when you touch the
1908/// attribution.
1909fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
1910    let Some(node) = nodes.first() else {
1911        return error;
1912    };
1913    if !error.class.perturbation_eligible()
1914        || matches!(error.class, RefusalClass::TangentNodeSingularity)
1915    {
1916        return error;
1917    }
1918    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
1919        eprintln!(
1920            "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
1921            node.x, node.y, node.z, error.message
1922        );
1923    }
1924    KernelRefusal::new(
1925        RefusalClass::TangentNodeSingularity,
1926        error.stage,
1927        format!(
1928            "boolean: unsupported singular/tangent-node surface intersection \
1929             at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
1930             assemble into a closed shell",
1931            node.x, node.y, node.z
1932        ),
1933    )
1934}
1935
1936/// The tangent-curve lane's attribution: an ASSEMBLY refusal whose faces the
1937/// imprint found touching along a CURVE is reported against that contact, by
1938/// its faces and its ends, in the tangent-node class — the arrangement's own
1939/// message (an open loop, a one-use edge) is the symptom, the contact is the
1940/// cause, and the class keeps the refusal out of the perturbation ladder
1941/// exactly as an admitted node's tear is kept out
1942/// (`attribute_to_tangent_node`). The original message is carried along so
1943/// nothing the stage said is hidden.
1944///
1945/// REACH: the faces the refusal names, and only those. `origins` maps the
1946/// assembled result's face ids (minted one per selected fragment, from 1, in
1947/// order) back to operand faces; the ids are read off the message's
1948/// `face <id>` (validate's open-loop issues) and `on faces [<id> '…`
1949/// (one-use edges) entries, and the rewrite happens only when one of them is
1950/// a face the section INVOLVES (`TangentSectionRecord::faces`: the carriers'
1951/// faces and the faces across the edges its ends lie on). A refusal naming no
1952/// face, or only faces the contact does not touch — a model with a benign
1953/// recorded contact (a blind pocket touching a wall) that fails elsewhere —
1954/// keeps its class and enters the ladder as it always did. With
1955/// `ImprintOptions::tangent_curve_lane` off the sections are empty and
1956/// nothing is rewritten.
1957pub fn attribute_to_tangent_section(
1958    error: KernelRefusal,
1959    sections: &[crate::imprint::TangentSectionRecord],
1960    origins: &[FaceKey],
1961) -> KernelRefusal {
1962    if sections.is_empty()
1963        || !error.class.perturbation_eligible()
1964        || matches!(error.class, RefusalClass::TangentNodeSingularity)
1965    {
1966        return error;
1967    }
1968    let named = refusal_result_faces(&error.message)
1969        .into_iter()
1970        .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
1971        .collect::<Vec<FaceKey>>();
1972    // A record the lane's own sites minted before one the grazing-pierce
1973    // path minted (`TangentSectionRecord::grazing`): the sprocket slit star's
1974    // cutter names its traced contact, not the pierce of a neighbouring pair.
1975    let involving = |fallback: bool| {
1976        sections.iter().find(|section| {
1977            section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
1978        })
1979    };
1980    let Some(section) = involving(false).or_else(|| involving(true)) else {
1981        return error;
1982    };
1983    // A clipped end sits on a trim at round-off, and `-0.000000` names no
1984    // place: print what six decimals can show.
1985    let at = |point: Vec3| {
1986        let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
1987        format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
1988    };
1989    // The grazing pierces (`imprint/driver.rs`, 2026-10-17): trim edges that
1990    // pierce the other carrier inside both trims below the seed gate while
1991    // the pair marched nothing. A record the lane built stands on its contact
1992    // and carries them as a note; a record standing on the pierces ALONE
1993    // (its `start` IS the first pierce) is named by them.
1994    let pierces = (!section.grazing.is_empty()).then(|| {
1995        let shown = section.grazing.len().min(4);
1996        let mut listed = section.grazing[..shown]
1997            .iter()
1998            .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
1999            .collect::<Vec<_>>()
2000            .join(", ");
2001        if section.grazing.len() > shown {
2002            listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2003        }
2004        listed
2005    });
2006    let pierce_only = section.pierce_only();
2007    let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2008        format!(
2009            "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2010             trims at {pierces}, below the marcher's start gate, and no transverse section was \
2011             marched between the pierces — a near-tangent crossing born on a tangent contact \
2012             (a third-order singularity) the imprint does not build yet"
2013        )
2014    } else if section.planar {
2015        format!(
2016            "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2017             imprint does not build yet",
2018            at(section.start),
2019            at(section.end),
2020            section.length,
2021            section.stations,
2022            if section.closed { ", closed" } else { "" }
2023        )
2024    } else {
2025        format!(
2026            "touch along a curve through {} with neither carrier planar, a curved/curved \
2027             tangent contact the lane does not trace yet",
2028            at(section.start)
2029        )
2030    };
2031    let shape = match (pierce_only, pierces) {
2032        (false, Some(pierces)) => format!(
2033            "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2034             below the marcher's start gate, with no transverse section marched"
2035        ),
2036        _ => shape,
2037    };
2038    let involved = named
2039        .iter()
2040        .filter(|face| section.faces.contains(face))
2041        .map(|face| format!("{}/{}", face.operand, face.face_id))
2042        .collect::<Vec<_>>()
2043        .join(", ");
2044    KernelRefusal::new(
2045        RefusalClass::TangentNodeSingularity,
2046        error.stage,
2047        format!(
2048            "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2049             the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2050            section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2051            error.message
2052        ),
2053    )
2054}
2055
2056/// The RESULT face ids an assembly refusal names: every `face <id>` (the
2057/// validator's "loop … of face `<id>` is open …") and every `<id> '` entry of an
2058/// `on faces [...]` list (the one-use edge census). Nothing else in the
2059/// message is read.
2060pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2061    let mut ids = Vec::new();
2062    let digits_after = |text: &str| -> Option<u64> {
2063        let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2064        text[..end].parse().ok()
2065    };
2066    for (index, _) in message.match_indices("face ") {
2067        if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2068            ids.push(id);
2069        }
2070    }
2071    if let Some(start) = message.find("on faces [") {
2072        let rest = &message[start + "on faces [".len()..];
2073        let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2074        for entry in list.split(", ") {
2075            let entry = entry.trim_start();
2076            if let Some(id) = digits_after(entry) {
2077                if entry[id.to_string().len()..].starts_with(" '") {
2078                    ids.push(id);
2079                }
2080            }
2081        }
2082    }
2083    ids.sort_unstable();
2084    ids.dedup();
2085    ids
2086}
2087
2088pub fn boolean_operation_with_diagnostics(
2089    first: &BrepSolid,
2090    second: &BrepSolid,
2091    operation: BooleanOperation,
2092    options: &BooleanOptions,
2093) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2094    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2095        let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2096            .map_err(|error| scaled.refusal(error))?;
2097        outcome.value = scaled.back(&outcome.value)?;
2098        outcome.diagnostics.count_n("working_scale.fired", 1);
2099        outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2100        return Ok(outcome);
2101    }
2102    let _account = profile::Scope::new("boolean.other");
2103    let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2104    if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2105        let started = Instant::now();
2106        let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2107        profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2108        return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2109    }
2110    boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
2111}
2112
2113/// [`drop_sliver_shells`] on a boolean's outcome, counted in its diagnostics.
2114fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
2115    let dropped = drop_sliver_shells(&mut outcome.value);
2116    if dropped > 0 {
2117        outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
2118    }
2119    outcome
2120}
2121
2122pub fn boolean_operation_with_diagnostics_impl(
2123    first: &BrepSolid,
2124    second: &BrepSolid,
2125    operation: BooleanOperation,
2126    options: &BooleanOptions,
2127    closed_inputs: bool,
2128) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2129    // One coedge-check memo per operation: the
2130    // assembly, face-merge and closing validations re-read coedges unchanged.
2131    let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
2132    // Plan 1.6: only a declared Sheet enters the trim path. The unchanged
2133    // Solid path continues below; no kind is inferred from failed closure.
2134    if matches!(operation, BooleanOperation::Intersect)
2135        && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2136        && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2137            Ok("1") => true,
2138            Ok("0") => false,
2139            _ => options.sheet_trim,
2140        }
2141    {
2142        return sheet::trim(first, second, options);
2143    }
2144    // OPERAND-KIND GATE. A body that DECLARES itself a Sheet has no
2145    // inside, so a union or subtract with it has no solid answer; the
2146    // survey (record 2026-10-12, table 2) measured the arrangement
2147    // returning a validating solid of volume 3.5 when the sheet's opening
2148    // lay outside the other operand. Read from the declaration only,
2149    // before any arrangement work (nothing infers a kind from the edge
2150    // census; an undeclared open body is the closure gate's below).
2151    // Intersect is not gated here.
2152    if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2153        if let Some(operand) = [first, second]
2154            .iter()
2155            .position(|solid| solid.kind == crate::BodyKind::Sheet)
2156        {
2157            return Err(KernelRefusal::input(
2158                KernelStage::Collect,
2159                "sheet_operand",
2160                format!(
2161                    "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2162                     subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2163                ),
2164            ));
2165        }
2166    }
2167    // Inside/outside is undefined for an open operand, even if its opening
2168    // misses the other operand and the constructed result happens to validate.
2169    // Count existing edge uses, without modifying/healing either operand.
2170    // Keep failures on their original path and preserve their class/evidence;
2171    // the existing perturbation gate already diagnoses open failed operands.
2172    let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2173    let closure_started = closed_inputs.then(Instant::now);
2174    if closed_inputs {
2175        for (operand, solid) in [first, second].into_iter().enumerate() {
2176            let open = one_use_edges(solid);
2177            if open > 0 {
2178                return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2179                    "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2180                )));
2181            }
2182        }
2183    }
2184    if let Some(started) = closure_started {
2185        let ms = started.elapsed().as_secs_f64() * 1000.0;
2186        profile_stage("operand_closure_ms", ms);
2187        outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2188    }
2189    Ok(outcome)
2190}
2191
2192fn boolean_operation_with_diagnostics_core(
2193    first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2194) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2195
2196    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`):
2197    // the outermost entry runs the operation on translated operands.
2198    if let Some(offset) = crate::recentre::control_offset_at_entry() {
2199        return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2200    }
2201    // The recentre guard: operands far from the origin in their own
2202    // units run at the origin.
2203    let mut bounds = operand_bounds(first);
2204    bounds.include(operand_bounds(second));
2205    if let Some(offset) = crate::recentre::guard_offset(bounds) {
2206        crate::recentre::profile_fired("boolean", offset, bounds);
2207        let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2208        outcome.diagnostics.count_n("recentre.fired", 1);
2209        outcome.diagnostics.measure_max("recentre.distance", offset.length());
2210        return Ok(outcome);
2211    }
2212    let mut tangent_nodes = Vec::new();
2213    let (mut outcome, soundness_candidates) =
2214        boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2215            .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2216    // The assembly's single exit. A boolean can hand back a body whose walls
2217    // pass through each other while `validate()` is silent and the volume
2218    // measures right, which is exactly the failure a regularized boolean must
2219    // not report as success. A crossing the OPERANDS already had is theirs and
2220    // passes through — the defect came in with the input and refusing it here
2221    // would blame the wrong operation — so the operands are only scanned when
2222    // the result is flagged, and the common case pays for one scan. The
2223    // acceptance's refusal is typed at its origin (an `UnsoundResult` naming
2224    // the defect and the faces); it was classed `Internal` here while
2225    // `accept_sound_against` still returned text. Timed as its own stage: the
2226    // record's phase split read only the pipeline's `timing.*` measures, and
2227    // on a 108-face disjoint union this scan was 185 of 226 ms end to end.
2228    let stage_started = Instant::now();
2229    let accepted = match &soundness_candidates {
2230        // Pass-through: the faces the operation touched, their
2231        // neighbours and every face whose box reaches the other operand.
2232        Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2233        None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2234    };
2235    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2236    profile_stage("soundness_ms", stage_ms);
2237    outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2238    outcome.value = accepted?;
2239    Ok(outcome)
2240}
2241
2242/// [`boolean_operation_with_diagnostics`] with both operands translated by
2243/// `offset` for the operation and the result translated back. Refusal
2244/// messages name the translated coordinates.
2245pub fn boolean_operation_with_diagnostics_at_offset(
2246    first: &BrepSolid,
2247    second: &BrepSolid,
2248    operation: BooleanOperation,
2249    options: &BooleanOptions,
2250    offset: Vec3,
2251) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2252    boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2253}
2254
2255/// The translated run behind the control and the guard.
2256fn boolean_translated(
2257    first: &BrepSolid,
2258    second: &BrepSolid,
2259    operation: BooleanOperation,
2260    options: &BooleanOptions,
2261    offset: Vec3,
2262    kind: crate::recentre::EntryKind,
2263) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2264    let _entry = crate::recentre::TranslatedEntry::open(kind);
2265    let translate = |solid: &BrepSolid, offset: Vec3| {
2266        crate::recentre::translate_solid(solid, offset).map_err(|message| {
2267            KernelRefusal::internal(
2268                KernelStage::Collect,
2269                "translation_control",
2270                format!("boolean: the translation control could not move an operand: {message}"),
2271            )
2272        })
2273    };
2274    let moved_first = translate(first, offset)?;
2275    let moved_second = translate(second, offset)?;
2276    let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
2277    let value = translate(&outcome.value, offset.scale(-1.0))?;
2278    Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
2279}
2280
2281/// Stage wall-clock line on stderr when `BREP_PROFILE` is set — the same switch
2282/// `imprint.profile` and `assemble.*_ms` use — so a REFUSED boolean, whose
2283/// `KernelDiagnostics` never reach a caller, still shows where its time went.
2284fn profile_stage(code: &str, ms: f64) {
2285    let row = match code {
2286        "heal_ms" => Some("boolean.operand_prepare"),
2287        "imprint_ms" => Some("boolean.imprint"),
2288        "edge_split_ms" => Some("boolean.edge_split"),
2289        "fragment_ms" => Some("boolean.fragment"),
2290        "select_ms" => Some("boolean.select"),
2291        "assemble_ms" => Some("boolean.assemble"),
2292        "face_merge_ms" => Some("boolean.face_merge"),
2293        "soundness_ms" => Some("boolean.soundness"),
2294        "operand_closure_ms" => Some("boolean.operand_closure"),
2295        "seam_prepare_ms" => Some("boolean.seam_prepare"),
2296        "final_validate_ms" => Some("boolean.final_validate"),
2297        _ => None,
2298    };
2299    if let Some(row) = row { profile::record(row, ms); }
2300    if crate::profile::profile_enabled() {
2301        profile_line!("boolean.{code}={ms:.2}");
2302    }
2303}
2304
2305/// `BREP_BOOLEAN_DUMP` names a directory. Every binary boolean then writes its
2306/// stages there as JSON — the two split operands, the selected fragments, the
2307/// assembled solid and the merged one — numbered per process, so a probe can
2308/// read a face's loops at each stage without replaying the document.
2309struct BooleanStageDump {
2310    directory: std::path::PathBuf,
2311    serial: usize,
2312}
2313
2314impl BooleanStageDump {
2315    fn open() -> Option<Self> {
2316        static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2317        let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
2318        let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2319        Some(Self { directory: directory.into(), serial })
2320    }
2321
2322    fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
2323        let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
2324        match serde_json::to_string(value) {
2325            Ok(text) => {
2326                if let Err(error) = std::fs::write(&path, text) {
2327                    eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
2328                }
2329            }
2330            Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
2331        }
2332    }
2333}
2334
2335/// The tolerance policy a binary boolean of `first` and `second` runs under.
2336pub fn boolean_policy(
2337    first: &BrepSolid,
2338    second: &BrepSolid,
2339    options: &BooleanOptions,
2340) -> Result<KernelTolerances, KernelRefusal> {
2341    let policy = options
2342        .tolerances
2343        .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2344    policy.check().or_input(KernelStage::Collect, "tolerances")?;
2345    Ok(policy)
2346}
2347
2348/// The operands as the imprint reads them: healed, with their band seams
2349/// normalized.
2350fn prepared_operands(
2351    first: &BrepSolid,
2352    second: &BrepSolid,
2353    policy: &KernelTolerances,
2354) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2355    // Fuse-first operand healing (Lever A): before any intersection touches the
2356    // operands, snap each one's near-coincident / off-plane vertices to exact
2357    // and re-anchor the incident edge curves onto them, so noisy
2358    // near-degenerate input (points that should coincide but drifted, vertices
2359    // a few microns off a planar face) cannot tip a fixed downstream band over
2360    // the edge.  Healing is per-operand, validate-gated, and — because a clean
2361    // operand has no vertices within `heal_tol` and none off its planes — a
2362    // no-op that leaves the boolean output byte-identical on clean inputs.
2363    let stage_started = Instant::now();
2364    let mut first_owned = first.clone();
2365    let mut second_owned = second.clone();
2366    crate::heal::heal_operands(&mut first_owned, policy)?;
2367    crate::heal::heal_operands(&mut second_owned, policy)?;
2368    profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2369    // Then refit, on each operand's own carriers, any inherited trim off the
2370    // pcurve construction contract whose edge lies on every incident carrier
2371    // (`heal::refit_inherited_trims`; a byte-identical no-op without one).
2372    let refit_started = Instant::now();
2373    crate::heal::refit_inherited_trims(&mut first_owned, policy)?;
2374    crate::heal::refit_inherited_trims(&mut second_owned, policy)?;
2375    profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
2376    if crate::profile::profile_enabled() {
2377        let (hits, misses) = crate::reading_memo::counts();
2378        profile_line!("boolean.reading_memo hits={hits} misses={misses}");
2379    }
2380    profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2381    // Seamless full-period band faces (STEP import) break the seam-aware
2382    // imprint/arrangement machinery; normalize them to the seam-carrying
2383    // topology native periodic faces use. No-op on operands without such
2384    // faces. See `insert_periodic_band_seam_edges`.
2385    normalize_operand_band_seams(&mut first_owned)?;
2386    normalize_operand_band_seams(&mut second_owned)?;
2387    Ok((first_owned, second_owned))
2388}
2389
2390fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
2391    let mut imprint_options = options.imprint.clone();
2392    imprint_options.tolerance = tolerance;
2393    imprint_options
2394}
2395
2396/// The two operands a binary boolean's arrangement reads: prepared as the
2397/// boolean prepares them, with every boundary edge split where the imprint's
2398/// sections meet it. These are the `NNN-first` and `NNN-second` stages
2399/// `BREP_BOOLEAN_DUMP` writes, not the operands at the boolean's entry.
2400///
2401/// A boolean must read the same on these as on the operands it split them
2402/// from: the splits are vertices its own imprint puts on those edges anyway.
2403/// Where it does not, an imprint lane is deciding on what the input happens to
2404/// have split, and that is a defect.
2405pub fn boolean_split_operands(
2406    first: &BrepSolid,
2407    second: &BrepSolid,
2408    options: &BooleanOptions,
2409) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2410    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2411        let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
2412            .map_err(|error| scaled.refusal(error))?;
2413        return Ok((scaled.back(&split_first)?, scaled.back(&split_second)?));
2414    }
2415    let policy = boolean_policy(first, second, options)?;
2416    let (first, second) = prepared_operands(first, second, &policy)?;
2417    let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
2418    let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
2419    let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
2420    Ok((split_first, split_second))
2421}
2422
2423/// Conservative bounds of an operand: its vertices and every face's control
2424/// net (a NURBS lies in the hull of its controls). A control net that cannot
2425/// be read bounds everything, so nothing is left out for want of a reading.
2426fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
2427    let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
2428    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2429        match crate::Aabb::from_surface_controls(&face.surface) {
2430            Ok(face_bounds) => bounds.include(face_bounds),
2431            Err(_) => {
2432                return crate::Aabb {
2433                    minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2434                    maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2435                }
2436            }
2437        }
2438    }
2439    bounds
2440}
2441
2442/// Row 12's gate: the boxes are separated or touch exactly in at least two
2443/// axes. A trimmed face lies in its carrier's control-net box when every
2444/// weight is positive, so a point interior to both operands would lie
2445/// strictly inside both boxes in every axis; two such axes leave a line or a
2446/// point of contact, which has no area to merge.
2447fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2448    apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
2449}
2450
2451/// One apart axis: no point can be interior to both operands (see
2452/// [`line_or_point_contact`]), though the boxes may share a face's area.
2453fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2454    apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
2455}
2456
2457/// The axes in which the boxes are separated or touch exactly (no band).
2458fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
2459    let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
2460    [
2461        apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
2462        apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
2463        apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
2464    ]
2465    .into_iter()
2466    .filter(|&apart| apart)
2467    .count()
2468}
2469
2470/// A plain solid whose faces lie in their control-net boxes: every weight positive.
2471fn plain_hull_solid(solid: &BrepSolid) -> bool {
2472    solid.kind == crate::BodyKind::Solid
2473        && solid.cells.is_empty()
2474        && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
2475            face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
2476        })
2477}
2478
2479/// The result faces the soundness scan reads under pass-through: the
2480/// examined faces (touched and their neighbours) and every other face whose
2481/// control-net box reaches the OTHER operand's bounds within `band`. A face
2482/// outside both is an operand's own, clear of everything the operation added.
2483fn soundness_candidates(
2484    solid: &BrepSolid,
2485    scope: &AssemblyScope,
2486    bounds: [crate::Aabb; 2],
2487    band: f64,
2488) -> HashSet<u64> {
2489    let mut candidates = HashSet::default();
2490    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2491        if scope.examined.contains(&face.id) {
2492            candidates.insert(face.id);
2493            continue;
2494        }
2495        let Some(&operand) = scope.operand_of.get(&face.id) else {
2496            candidates.insert(face.id);
2497            continue;
2498        };
2499        let other = bounds[usize::from(operand == 0)];
2500        match crate::Aabb::from_surface_controls(&face.surface) {
2501            Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
2502            _ => {
2503                candidates.insert(face.id);
2504            }
2505        }
2506    }
2507    candidates
2508}
2509
2510/// The empty solid a legitimately empty boolean returns.
2511fn empty_solid() -> BrepSolid {
2512    BrepSolid {
2513        mass_properties_cache: Default::default(),
2514        cells: Default::default(),
2515        id: 0,
2516        vertices: Vec::new(),
2517        edges: Vec::new(),
2518        shells: Vec::new(),
2519        genus: 0,
2520        kind: crate::BodyKind::Solid,
2521    }
2522}
2523
2524/// The two operands as one solid, shell by shell: ids minted afresh in the
2525/// assembler's order (the first operand's faces, then the second's), the
2526/// second operand's face names suffixed where they clash with the first's
2527/// as the assembler suffixes a split face, geometry copied byte for byte,
2528/// genus the sum. Nothing is welded: the operands are disjoint.
2529fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
2530    let mut vertices = Vec::new();
2531    let mut edges = Vec::new();
2532    let mut shells = Vec::new();
2533    let mut used_face_names = HashSet::<String>::default();
2534    let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
2535    for operand in [first, second] {
2536        let vertex_base = vertices.len() as u64;
2537        let edge_base = edges.len() as u64;
2538        let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
2539        for (index, vertex) in operand.vertices.iter().enumerate() {
2540            let id = vertex_base + index as u64 + 1;
2541            vertex_ids.insert(vertex.id, id);
2542            vertices.push(VertexRecord { id, point: vertex.point });
2543        }
2544        let mut edge_ids: HashMap<u64, u64> = HashMap::default();
2545        for (index, edge) in operand.edges.iter().enumerate() {
2546            let id = edge_base + index as u64 + 1;
2547            edge_ids.insert(edge.id, id);
2548            edges.push(EdgeRecord {
2549                id,
2550                curve: edge.curve.clone(),
2551                t0: edge.t0,
2552                t1: edge.t1,
2553                start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
2554                end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
2555                degenerate: edge.degenerate,
2556                name: edge.name.clone(),
2557            });
2558        }
2559        for shell in &operand.shells {
2560            let mut faces = Vec::with_capacity(shell.faces.len());
2561            for face in &shell.faces {
2562                let loops = face
2563                    .loops
2564                    .iter()
2565                    .map(|loop_record| {
2566                        let coedges = loop_record
2567                            .coedges
2568                            .iter()
2569                            .map(|coedge| {
2570                                let id = next_coedge_id;
2571                                next_coedge_id += 1;
2572                                CoedgeRecord {
2573                                    id,
2574                                    edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
2575                                    forward: coedge.forward,
2576                                    pcurve: coedge.pcurve.clone(),
2577                                }
2578                            })
2579                            .collect();
2580                        let id = next_loop_id;
2581                        next_loop_id += 1;
2582                        LoopRecord { id, coedges }
2583                    })
2584                    .collect();
2585                let name = face.name.clone().map(|base| {
2586                    if used_face_names.insert(base.clone()) {
2587                        base
2588                    } else {
2589                        let mut suffix = 1usize;
2590                        loop {
2591                            let candidate = format!("{base}_{suffix}");
2592                            if used_face_names.insert(candidate.clone()) {
2593                                break candidate;
2594                            }
2595                            suffix += 1;
2596                        }
2597                    }
2598                });
2599                faces.push(FaceRecord {
2600                    id: next_face_id,
2601                    surface: face.surface.clone(),
2602                    same_sense: face.same_sense,
2603                    loops,
2604                    name,
2605                });
2606                next_face_id += 1;
2607            }
2608            shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
2609        }
2610    }
2611    BrepSolid {
2612        mass_properties_cache: Default::default(),
2613        cells: Default::default(),
2614        id: 1,
2615        vertices,
2616        edges,
2617        shells,
2618        genus: first.genus + second.genus,
2619        kind: crate::BodyKind::Solid,
2620    }
2621}
2622
2623/// The binary boolean. The second value is the soundness scan's candidate
2624/// faces under pass-through (`None` reads the whole result).
2625fn boolean_pipeline(
2626    first: &BrepSolid,
2627    second: &BrepSolid,
2628    operation: BooleanOperation,
2629    options: &BooleanOptions,
2630    tangent_nodes: &mut Vec<Vec3>,
2631) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
2632    let _work = crate::imprint::work_profile::Scope::open("boolean");
2633    let replaced_operands = operand_state::replace_operands(first, second, operation, options);
2634    let (first, second) = match &replaced_operands {
2635        Some((first, second)) => (first, second),
2636        None => (first, second),
2637    };
2638    let policy = boolean_policy(first, second, options)?;
2639    let tolerance = policy.model;
2640    // DISJOINT FAST PATH. A box test on the control-net hulls, not "no
2641    // section evidence": a tool inside the other operand also leaves no
2642    // evidence and must stay on the pipeline, where a union is the outer
2643    // operand, a subtract the outer with a void shell and an intersect the
2644    // tool. Operands clear of each other by more than the search band can
2645    // touch nothing, so nothing is prepared, imprinted, assembled or
2646    // scanned: a union is the two operands side by side, a subtract the
2647    // first operand, an intersect the legitimate-empty result below. The
2648    // soundness scan is skipped as well (an empty candidate set): the
2649    // operands cannot cross each other, and a crossing an operand carried in
2650    // passes through the full acceptance unrepaired exactly the same.
2651    //
2652    // CONTACT FAST PATH (row 12): boxes that only meet along a line or at a
2653    // point, read exactly; see `line_or_point_contact`.
2654    let bounds = [operand_bounds(first), operand_bounds(second)];
2655    let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
2656    let contact = !disjoint
2657        && contact_fast_path(options)
2658        && options.seam_reseat_later_references.is_some()
2659        && line_or_point_contact(first, second, bounds);
2660    // One apart axis already leaves no common interior, so an intersect is
2661    // empty even where the boxes share a face's area (which is why a union or
2662    // a subtract stays on the pipeline). Nothing survives to carry an id, so
2663    // no caller has to say what follows.
2664    let contact = contact
2665        || (!disjoint
2666            && matches!(operation, BooleanOperation::Intersect)
2667            && contact_fast_path(options)
2668            && boxes_share_no_interior(first, second, bounds));
2669    if disjoint || contact {
2670        let operation_started = Instant::now();
2671        let mut diagnostics = KernelDiagnostics::default();
2672        diagnostics.count_n(
2673            "collect.faces",
2674            first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
2675        );
2676        diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
2677        diagnostics.measure_max("tolerance.model", policy.model);
2678        diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2679        let value = match operation {
2680            BooleanOperation::Union => concatenate_disjoint(first, second),
2681            BooleanOperation::Subtract => first.clone(),
2682            BooleanOperation::Intersect => {
2683                diagnostics.event(
2684                    DiagnosticSeverity::Info,
2685                    KernelStage::Select,
2686                    "boolean.empty_result",
2687                    format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2688                );
2689                empty_solid()
2690            }
2691        };
2692        let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
2693        profile_stage("disjoint_fast_path_ms", stage_ms);
2694        diagnostics.measure_max("timing.total_ms", stage_ms);
2695        return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
2696    }
2697    let heal_started = Instant::now();
2698    let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
2699    let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
2700    let first = &first_owned;
2701    let second = &second_owned;
2702
2703    let mut diagnostics = KernelDiagnostics::default();
2704    // Operand preparation ran before `timing.total_ms` opens and was absent
2705    // from every phase split; it is 1.6 of a disjoint box union's 7.2 ms.
2706    diagnostics.measure_max("timing.heal_ms", heal_ms);
2707    // Every pcurve fit made while this scope is open — the imprint's sections,
2708    // the assembler's rebuilt trims, the merge's re-fits — is tallied, so the
2709    // outcome can say whether every curved trim reached its floor instead of
2710    // letting a sample-ceiling exit pass for a met one (`pcurve.unmet_floor`).
2711    let fit_scope = crate::PcurveFitScope::open();
2712    // And every POLYLINE fit: a marched section's interpolant is measured
2713    // against the tolerance it was given, so `fit.polyline.unmet_tolerance`
2714    // reports a section that could not reach it (`geometry/fit.rs`).
2715    let polyline_scope = crate::PolylineFitScope::open();
2716    let operation_started = Instant::now();
2717    diagnostics.count_n(
2718        "collect.faces",
2719        first
2720            .shells
2721            .iter()
2722            .chain(&second.shells)
2723            .map(|shell| shell.faces.len() as u64)
2724            .sum(),
2725    );
2726    diagnostics.measure_max("tolerance.model", policy.model);
2727    diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2728
2729    let imprint_options = boolean_imprint_options(options, tolerance);
2730    let stage_started = Instant::now();
2731    let imprint = build_imprints(first, second, &imprint_options)?;
2732    tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
2733    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2734        for piece in &imprint.pieces {
2735            let start = piece.curve.evaluate(piece.t0);
2736            let end = piece.curve.evaluate(piece.t1);
2737            eprintln!(
2738                "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
2739                piece.id, piece.support_faces, piece.t0, piece.t1, start, end
2740            );
2741        }
2742        for entry in &imprint.by_face {
2743            eprintln!(
2744                "by_face operand={} face={} pieces={:?}",
2745                entry.operand, entry.face_id, entry.piece_ids
2746            );
2747        }
2748        for split in &imprint.edge_splits {
2749            eprintln!(
2750                "edge_split operand={} edge={} params={:?}",
2751                split.operand, split.edge_id, split.parameters
2752            );
2753        }
2754    }
2755    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2756    profile_stage("imprint_ms", stage_ms);
2757    diagnostics.measure_max("timing.imprint_ms", stage_ms);
2758    diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
2759    diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
2760    diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
2761    let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
2762    diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
2763    diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
2764    let touch = TouchCensus::build([first, second], &imprint);
2765    touch.report(&mut diagnostics);
2766    let stage_started = Instant::now();
2767    let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
2768    let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
2769    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2770    profile_stage("edge_split_ms", stage_ms);
2771    diagnostics.measure_max("timing.edge_split_ms", stage_ms);
2772    let stage_started = Instant::now();
2773    crate::classification::classify_profile_begin();
2774    let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
2775    let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
2776    crate::classification::classify_profile_report("fragment");
2777    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2778    profile_stage("fragment_ms", stage_ms);
2779    diagnostics.measure_max("timing.fragment_ms", stage_ms);
2780    diagnostics.count_n(
2781        "fragment.candidates",
2782        (fragments_a.len() + fragments_b.len()) as u64,
2783    );
2784    touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
2785    // Operand surface samples for the LEGITIMATE-EMPTY adjudication below:
2786    // every fragment test point is a 3D point ON its operand's boundary and
2787    // inside its face trim, so they witness where the operands' materials sit
2788    // relative to each other without extra geometry work.
2789    let a_surface_samples: Vec<Vec3> = fragments_a
2790        .iter()
2791        .flat_map(|fragment| {
2792            std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2793        })
2794        .collect();
2795    let b_surface_samples: Vec<Vec3> = fragments_b
2796        .iter()
2797        .flat_map(|fragment| {
2798            std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2799        })
2800        .collect();
2801    let stage_started = Instant::now();
2802    let mut barrier_edges: HashSet<(u8, u64)> = imprint
2803        .pieces
2804        .iter()
2805        .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
2806        .collect();
2807    barrier_edges.extend(imprint.barrier_edges.iter().copied());
2808    // The barrier set is keyed on ORIGINAL edge ids, but a barrier edge the
2809    // imprint also SPLIT (rotated equator-tangency: the overlapped cap ring
2810    // gains a junction at the sphere-seam crossing) reaches fragment
2811    // selection as its minted sub-edge ids. Remap the barrier through the
2812    // split ledger — keeping the originals too for unsplit references.
2813    for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
2814        let minted: Vec<(u8, u64)> = barrier_edges
2815            .iter()
2816            .filter(|(barrier_operand, _)| *barrier_operand == operand)
2817            .filter_map(|(_, edge_id)| split_map.get(edge_id))
2818            .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
2819            .collect();
2820        barrier_edges.extend(minted);
2821    }
2822    crate::classification::classify_profile_begin();
2823    let coincident = coincident_pairs(
2824        &fragments_a,
2825        &fragments_b,
2826        first,
2827        second,
2828        &imprint.cosurface_pairs,
2829        tolerance,
2830    )?;
2831    let sector_mode = sector::sector_mode(options);
2832    let mut select_census = sector::SelectCensus::default();
2833    let mut selected = select_fragments(
2834        fragments_a,
2835        fragments_b,
2836        first,
2837        second,
2838        operation,
2839        tolerance,
2840        &barrier_edges,
2841        &imprint,
2842        &coincident,
2843        sector_mode,
2844        &mut select_census,
2845    )?;
2846    let resewn = resew_coincident_rims(
2847        &mut selected,
2848        [&split_first, &split_second],
2849        [first, second],
2850        &imprint.cosurface_pairs,
2851        operation,
2852        tolerance,
2853    )?;
2854    diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
2855    diagnostics.count_n("select.rims_resewn", resewn as u64);
2856    crate::classification::classify_profile_report("select");
2857    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2858    profile_stage("select_ms", stage_ms);
2859    diagnostics.measure_max("timing.select_ms", stage_ms);
2860    diagnostics.count_n("select.fragments", selected.len() as u64);
2861    // One census line per selection as well.
2862    diagnostics.count_n("select.sector_eligible", select_census.eligible);
2863    diagnostics.count_n("select.sector_primary", select_census.sector_primary);
2864    diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
2865    diagnostics.count_n("select.sector_disagree", select_census.disagree);
2866    diagnostics.count_n("select.ray_casts", select_census.ray_casts);
2867    diagnostics.count_n("select.on_votes", select_census.on_votes);
2868    diagnostics.count_n("select.overturns", select_census.overturns);
2869    if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
2870        sector::sector_census_line(|| {
2871            format!(
2872                "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
2873                selected.len(),
2874                select_census.eligible,
2875                select_census.sector_primary,
2876                select_census.sector_fallback,
2877                select_census.disagree,
2878                select_census.ray_casts,
2879                select_census.on_votes,
2880                select_census.overturns
2881            )
2882        });
2883    }
2884    // LEGITIMATE-EMPTY RESULTS: an intersect of DISJOINT operands (or a
2885    // subtract whose left operand is entirely CONSUMED by the right) selects
2886    // zero fragments, and assembly used to refuse with "operation produced no
2887    // boundary faces" — 384 of the 474 post-wrapped-band pool errors were
2888    // this, not bugs. Empty is only blessed on TWO independent proofs:
2889    //   (a) the imprint recorded NO section evidence (no accepted pierce
2890    //       seed, no traced SSI branch, no minted piece) — a silently-lost
2891    //       section (the trial-489 class) always leaves upstream evidence
2892    //       even when every downstream sub-segment is clipped away, while
2893    //       pure material disjointness leaves none (verified: 489's
2894    //       recreated silent-miss state keeps erroring; per-face surface
2895    //       samples ALONE missed its 235 mm³ pocket, which is why (a) is
2896    //       required and sampling alone was rejected);
2897    //   (b) the operands' surface samples agree (every fragment test point
2898    //       classified against the other solid):
2899    //       intersect — no sample of either operand strictly inside the
2900    //       other; subtract — no left-operand sample strictly outside the
2901    //       right.
2902    // Contact/graze pairs (evidence exists, material still disjoint) stay
2903    // errors — conservative by design. Escape hatch: BREP_EMPTY_BOOLEAN=0
2904    // restores the unconditional error.
2905    if selected.is_empty()
2906        && !imprint.section_evidence
2907        && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
2908    {
2909        let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2910            for &sample in samples {
2911                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
2912                    return Ok(true);
2913                }
2914            }
2915            Ok(false)
2916        };
2917        let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2918            for &sample in samples {
2919                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
2920                    return Ok(true);
2921                }
2922            }
2923            Ok(false)
2924        };
2925        let legitimate = match operation {
2926            BooleanOperation::Intersect => {
2927                !strictly_inside(&a_surface_samples, second)?
2928                    && !strictly_inside(&b_surface_samples, first)?
2929            }
2930            BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
2931            BooleanOperation::Union => false,
2932        };
2933        if legitimate {
2934            diagnostics.event(
2935                DiagnosticSeverity::Info,
2936                KernelStage::Select,
2937                "boolean.empty_result",
2938                format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2939            );
2940            fit_scope.close().report_into(&mut diagnostics);
2941            polyline_scope.close().report_into(&mut diagnostics);
2942            diagnostics.measure_max(
2943                "timing.total_ms",
2944                operation_started.elapsed().as_secs_f64() * 1_000.0,
2945            );
2946            return Ok((
2947                KernelOutcome {
2948                    value: empty_solid(),
2949                    diagnostics,
2950                },
2951                None,
2952            ));
2953        }
2954    }
2955    let solids = [(0, &split_first), (1, &split_second)]
2956        .into_iter()
2957        .collect::<HashMap<_, _>>();
2958    let dump = BooleanStageDump::open();
2959    if let Some(dump) = &dump {
2960        dump.write("first", &split_first);
2961        dump.write("second", &split_second);
2962        dump.write("selected", &selected);
2963    }
2964    let stage_started = Instant::now();
2965    // Result face `k` is minted from `selected[k - 1]` (one face per fragment,
2966    // ids from 1 in order): the map the tangent-section attribution reads a
2967    // refusal's face ids through.
2968    let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
2969        Vec::new()
2970    } else {
2971        selected
2972            .iter()
2973            .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
2974            .collect()
2975    };
2976    // A record the grazing-pierce path minted (`TangentSectionRecord::
2977    // grazing` non-empty, whether or not the lane then found a contact to
2978    // name) yields to a tangent NODE the imprint classified: the node is the
2979    // nearer cause and `attribute_to_tangent_node` names it on the way out
2980    // (the G1 elbow over its own-radius arm: the arm's cap circle also
2981    // pierces the elbow under the seed gate, and the lane sees the join).
2982    let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
2983        .tangent_sections
2984        .iter()
2985        .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
2986        .cloned()
2987        .collect();
2988    let attribute = |error: KernelRefusal| {
2989        attribute_to_tangent_section(error, &attributable, &assembled_origins)
2990    };
2991    let cellular_result = matches!(operation, BooleanOperation::Union)
2992        && cellular::enabled(options)
2993        && cellular::complete_contact(first, second, &selected, tolerance);
2994    let (solid, scope) = if cellular_result {
2995        (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
2996            .map_err(attribute)?, None)
2997    } else if untouched_passthrough(options) {
2998        assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
2999            .map_err(attribute)?
3000    } else {
3001        (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
3002    };
3003    if let Some(scope) = &scope {
3004        diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
3005    }
3006    if let Some(dump) = &dump {
3007        dump.write("assembled", &solid);
3008    }
3009    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3010    profile_stage("assemble_ms", stage_ms);
3011    diagnostics.measure_max("timing.assemble_ms", stage_ms);
3012    let stage_started = Instant::now();
3013    let declines_before = crate::face_merge::declines_served();
3014    let area_checks_before = crate::face_merge::boundary_area_checks();
3015    if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
3016        let issues = solid.validate();
3017        eprintln!(
3018            "pre-merge validation: {} issue(s){}",
3019            issues.len(),
3020            issues
3021                .first()
3022                .map(|issue| format!(" — first: {}", issue.message))
3023                .unwrap_or_default()
3024        );
3025    }
3026    let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
3027        && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
3028    {
3029        let merged = match &scope {
3030            // Every pair merges as before (an operand's own coplanar
3031            // neighbours included); the closing validation reads the
3032            // examined faces and the merged ones.
3033            Some(scope) => merge_same_surface_faces_scoped(
3034                &solid,
3035                tolerance,
3036                &options.keep_unmerged_name_substrs,
3037                &scope.examined,
3038            )?,
3039            None => merge_same_surface_faces_excluding(
3040                &solid,
3041                tolerance,
3042                &options.keep_unmerged_name_substrs,
3043            )?,
3044        };
3045        // Face merging can make previously separate collinear boundary
3046        // segments incident to the same pair of faces. Run continuation
3047        // cleanup again, matching the post-merge normalization performed by
3048        // the former assembly pipeline.
3049        merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?
3050    } else {
3051        solid
3052    };
3053    if let Some(dump) = &dump {
3054        dump.write("merged", &solid);
3055    }
3056    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3057    profile_stage("face_merge_ms", stage_ms);
3058    if crate::profile::profile_enabled() {
3059        profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
3060        let area_checks = crate::face_merge::boundary_area_checks();
3061        if area_checks != area_checks_before {
3062            profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
3063        }
3064    }
3065    diagnostics.measure_max("timing.face_merge_ms", stage_ms);
3066    let validation_started = Instant::now();
3067    let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
3068    profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
3069    diagnostics.count_n("validate.issues", validation.issues.len() as u64);
3070    diagnostics.count_n(
3071        "validate.wire_warnings",
3072        validation.wire_warnings.len() as u64,
3073    );
3074    diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
3075    for warning in &validation.wire_warnings {
3076        diagnostics.event(
3077            DiagnosticSeverity::Warning,
3078            KernelStage::Validate,
3079            "validate.uv_wire",
3080            warning.message.clone(),
3081        );
3082    }
3083    for issue in &validation.issues {
3084        diagnostics.event(
3085            DiagnosticSeverity::Error,
3086            KernelStage::Validate,
3087            "validate.brep",
3088            issue.message.clone(),
3089        );
3090    }
3091    fit_scope.close().report_into(&mut diagnostics);
3092    polyline_scope.close().report_into(&mut diagnostics);
3093    diagnostics.measure_max(
3094        "timing.total_ms",
3095        operation_started.elapsed().as_secs_f64() * 1_000.0,
3096    );
3097    if !validation.issues.is_empty() {
3098        return Err(KernelRefusal::new(
3099            RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
3100            KernelStage::Validate,
3101            format!(
3102            "boolean_operation: invalid result: {:?}",
3103            validation.issues
3104        )));
3105    }
3106    // Optional semantic oracle (off by default, no perf hit): under
3107    // BREP_DEBUG_BOOL, cross-check the well-formed result against the CSG
3108    // point-membership expectation and scan for residual coincident-but-unwelded
3109    // geometry. Purely diagnostic and NON-rejecting — a statistical check must
3110    // never fail a valid op (see oracle.rs) — so it only ever warns.
3111    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3112        if let Ok(report) =
3113            crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
3114        {
3115            if report.is_flagged() {
3116                eprintln!(
3117                    "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
3118                    report.disagreement_rate,
3119                    report.disagreements.len(),
3120                    report.considered,
3121                    report.sample_disagreement()
3122                );
3123            }
3124        }
3125        let fusable_band = crate::tolerance::assembler_weld(policy.model);
3126        let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
3127        if !fusables.is_empty() {
3128            eprintln!(
3129                "[oracle] {} residual fusable(s) after weld; sample {:?}",
3130                fusables.len(),
3131                fusables.first()
3132            );
3133        }
3134    }
3135    let candidates = scope.as_ref().map(|scope| {
3136        let candidates = soundness_candidates(
3137            &solid,
3138            scope,
3139            [operand_bounds(first), operand_bounds(second)],
3140            policy.sew_search,
3141        );
3142        diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
3143        crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
3144        candidates
3145    });
3146    Ok((
3147        KernelOutcome {
3148            value: solid,
3149            diagnostics,
3150        },
3151        candidates,
3152    ))
3153}
3154