Skip to main content

brep_kernel/csg/boolean/
mod.rs

1pub(crate) mod profile;
2use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5use crate::imprint::{
6    EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7    ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10use crate::topology::{
11    adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12    ShellRecord, VertexRecord,
13};
14use 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};
24use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26use 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(crate) 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;
195mod sector;
196mod assemble;
197mod operand_state;
198mod rim;
199mod coincident;
200mod touch;
201mod reseat;
202
203use rim::*;
204use select::*;
205use coincident::*;
206use touch::TouchCensus;
207pub(crate) 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(crate) 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.
526fn 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::tolerance::solid_scale(first)
823        .max(crate::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.
1112const 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)]
1138struct MirrorTrend {
1139    /// The last rung refused by its mirror: its offset and signed error.
1140    last: Option<(f64, f64)>,
1141    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    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    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(crate) 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(crate) fn unresolved_merge_refusal_enabled() -> bool {
1197    crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1198}
1199
1200fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1201    let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1202    let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1203    Some(KernelRefusal::unsupported(
1204        KernelStage::Intersect,
1205        "below_modelling_tolerance",
1206        format!(
1207            "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1208             another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1209             ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1210             welded away"
1211        ),
1212    ))
1213}
1214
1215fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1216    let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1217    let message = format!(
1218        "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1219         another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1220         modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1221        error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1222    );
1223    Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1224}
1225
1226/// The first pair of planar faces (one per operand) whose planes are nearly
1227/// parallel and whose boundaries stand within [`BELOW_TOLERANCE_BAND`] of the
1228/// other's plane, with overlapping extents, but which are not one plane.
1229fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1230    let scale = crate::tolerance::solid_scale(first).max(crate::tolerance::solid_scale(second)).max(1.0);
1231    planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1232}
1233
1234/// The first pair of nearly parallel planar faces (one per operand) with
1235/// overlapping extents whose largest separation is above `lower` and at most
1236/// `upper`.
1237fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1238    struct Planar {
1239        id: u64,
1240        origin: Vec3,
1241        normal: Vec3,
1242        corners: Vec<Vec3>,
1243        bounds: crate::spatial::Aabb,
1244    }
1245    let read = |solid: &BrepSolid| -> Vec<Planar> {
1246        let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1247        solid
1248            .shells
1249            .iter()
1250            .flat_map(|shell| &shell.faces)
1251            .filter_map(|face| {
1252                if !face.surface.is_affine().ok()? {
1253                    return None;
1254                }
1255                let origin = face.surface.control_points[0][0].point().ok()?;
1256                let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1257                let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1258                let normal = a.cross(b).normalized().ok()?;
1259                let corners: Vec<Vec3> = face
1260                    .loops
1261                    .iter()
1262                    .flat_map(|lp| &lp.coedges)
1263                    .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1264                    .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1265                    .flatten()
1266                    .collect();
1267                if corners.is_empty() {
1268                    return None;
1269                }
1270                let bounds = crate::spatial::Aabb::from_points(corners.clone());
1271                Some(Planar { id: face.id, origin, normal, corners, bounds })
1272            })
1273            .collect()
1274    };
1275    let (faces_a, faces_b) = (read(first), read(second));
1276    for a in &faces_a {
1277        for b in &faces_b {
1278            if a.normal.cross(b.normal).length() > 1e-3 {
1279                continue;
1280            }
1281            if !a.bounds.intersects(b.bounds, upper) {
1282                continue;
1283            }
1284            let separation = a
1285                .corners
1286                .iter()
1287                .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1288                .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1289                .fold(0.0f64, f64::max);
1290            if separation > lower && separation <= upper {
1291                return Some((a.id, b.id, separation));
1292            }
1293        }
1294    }
1295    None
1296}
1297
1298fn one_use_edges(solid: &BrepSolid) -> usize {
1299    let mut uses: HashMap<u64, usize> = HashMap::default();
1300    for coedge in solid
1301        .shells
1302        .iter()
1303        .flat_map(|shell| &shell.faces)
1304        .flat_map(|face| &face.loops)
1305        .flat_map(|loop_record| &loop_record.coedges)
1306    {
1307        *uses.entry(coedge.edge_id).or_default() += 1;
1308    }
1309    solid
1310        .edges
1311        .iter()
1312        .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1313        .count()
1314}
1315
1316/// A body's enclosed volume, zero for an empty one.
1317fn body_volume(solid: &BrepSolid) -> Option<f64> {
1318    if solid.shells.is_empty() {
1319        return Some(0.0);
1320    }
1321    solid_signed_volume(solid).ok().map(f64::abs)
1322}
1323
1324/// What the exact lane's other operations say `operation` on these operands
1325/// must enclose.
1326struct InclusionExclusion {
1327    /// The rescued operation's volume in terms of V(first), V(second) and
1328    /// V(first ∩ second).
1329    formula: &'static str,
1330    /// The exact-lane boolean that supplied V(first ∩ second).
1331    reading: &'static str,
1332    /// That boolean's enclosed volume.
1333    read: f64,
1334    /// The volume `formula` gives.
1335    expected: f64,
1336}
1337
1338/// The volume `operation` on these operands must have, by inclusion–exclusion.
1339/// Any one exact-lane boolean of the same two operands fixes V(first ∩ second),
1340/// and with the operands' own volumes that fixes all four operations. The
1341/// readings are tried intersection, union, then difference, each in both
1342/// operand orders: the exact lane is not order-symmetric (the helmet's cutter
1343/// ∩ helmet refuses where helmet ∩ cutter clears). The rescued operation itself,
1344/// in its own order, is skipped, since it is the one that refused, unless
1345/// `own_first` asks for it to be read first (a rung's mirror, where it is a
1346/// different pair of operands). `None` when no reading clears or an operand has
1347/// no volume.
1348fn inclusion_exclusion_volume(
1349    first: &BrepSolid,
1350    second: &BrepSolid,
1351    operation: BooleanOperation,
1352    options: &BooleanOptions,
1353    va: Option<f64>,
1354    vb: Option<f64>,
1355    own_first: bool,
1356) -> Option<InclusionExclusion> {
1357    use BooleanOperation::{Intersect, Subtract, Union};
1358    let (va, vb) = (va?, vb?);
1359    let own = match operation {
1360        Intersect => (Intersect, false, "first ∩ second"),
1361        Union => (Union, false, "first ∪ second"),
1362        Subtract => (Subtract, false, "first − second"),
1363    };
1364    let readings = [
1365        (Intersect, false, "first ∩ second"),
1366        (Intersect, true, "second ∩ first"),
1367        (Union, false, "first ∪ second"),
1368        (Union, true, "second ∪ first"),
1369        (Subtract, false, "first − second"),
1370        (Subtract, true, "second − first"),
1371    ];
1372    let own_reading = own_first.then_some(own);
1373    let leading = usize::from(own_first);
1374    for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
1375        if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
1376            continue;
1377        }
1378        let (x, y) = if swapped { (second, first) } else { (first, second) };
1379        let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
1380            .ok()
1381            .and_then(|outcome| body_volume(&outcome.value))
1382        else {
1383            continue;
1384        };
1385        let intersection = match (other, swapped) {
1386            (Intersect, _) => read,
1387            (Union, _) => va + vb - read,
1388            (Subtract, false) => va - read,
1389            (Subtract, true) => vb - read,
1390        };
1391        let (formula, expected) = match operation {
1392            Intersect => ("V(first ∩ second)", intersection),
1393            Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
1394            Subtract => ("V(first) − V(first ∩ second)", va - intersection),
1395        };
1396        return Some(InclusionExclusion { formula, reading, read, expected });
1397    }
1398    None
1399}
1400
1401/// The worst planar face of either operand whose STRAIGHT boundary sits
1402/// farther off its plane than the assembly weld radius:
1403/// `(operand index, face id, gap, weld)`. Mirrors the STEP importer's planar
1404/// split predicate (`step_import::builder::planar_split`) on a finished
1405/// solid: a plane, a single loop of straight non-degenerate edges, and a
1406/// boundary vertex beyond the weld. `None` means no such face, so a failure
1407/// may still be a genuine degeneracy worth a perturbation rung. Only
1408/// consulted on the failure path.
1409fn planar_operand_off_its_plane(
1410    first: &BrepSolid,
1411    second: &BrepSolid,
1412    options: &BooleanOptions,
1413) -> Option<(u8, u64, f64, f64)> {
1414    let policy = options
1415        .tolerances
1416        .clone()
1417        .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
1418    let weld = crate::tolerance::assembler_weld(policy.model);
1419    let mut worst: Option<(u8, u64, f64)> = None;
1420    for (operand, solid) in [(0u8, first), (1u8, second)] {
1421        let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
1422        for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1423            let Some(crate::AnalyticSurface::Plane {
1424                origin,
1425                u_dir,
1426                v_dir,
1427                ..
1428            }) = face.surface.analytic()
1429            else {
1430                continue;
1431            };
1432            let [loop_record] = face.loops.as_slice() else {
1433                continue;
1434            };
1435            let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
1436                continue;
1437            };
1438            let mut off_plane = 0.0f64;
1439            let mut straight = true;
1440            for coedge in &loop_record.coedges {
1441                let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
1442                    straight = false;
1443                    break;
1444                };
1445                let (Some(start), Some(end)) =
1446                    (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
1447                else {
1448                    straight = false;
1449                    break;
1450                };
1451                let chord = end.sub(start);
1452                let length = chord.length();
1453                if edge.degenerate || length <= weld {
1454                    straight = false;
1455                    break;
1456                }
1457                let direction = chord.scale(1.0 / length);
1458                for fraction in [0.25, 0.5, 0.75] {
1459                    let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
1460                        straight = false;
1461                        break;
1462                    };
1463                    let delta = point.sub(start);
1464                    let along = delta.dot(direction);
1465                    if delta.sub(direction.scale(along)).length() > weld
1466                        || along < -weld
1467                        || along > length + weld
1468                    {
1469                        straight = false;
1470                        break;
1471                    }
1472                }
1473                if !straight {
1474                    break;
1475                }
1476                off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
1477            }
1478            if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
1479                worst = Some((operand, face.id, off_plane));
1480            }
1481        }
1482    }
1483    worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
1484}
1485
1486/// CSG volume inequality bounds (no extra boolean needed) with 1% relative slack.
1487/// `va`, `vb`, `vr` are absolute volumes of operand A, operand B, and the result.
1488fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
1489    let slack = 1e-2 * (va + vb).max(1.0);
1490    match operation {
1491        // max(A,B) ≤ A∪B ≤ A+B
1492        BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
1493        // A−B ≤ A (and ≥ 0)
1494        BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
1495        // A∩B ≤ min(A,B)
1496        BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
1497    }
1498}
1499
1500// ---------------------------------------------------------------------------
1501// N-ary booleans (Golovanov T4.4)
1502//
1503// Union / intersect / subtract of N solids in ONE imprint+fragment pass.  This
1504// is a NEW ADDITIVE entry point: the binary `boolean_operation` above is left
1505// byte-identical.  The pipeline mirrors the binary one but generalizes the two
1506// operand-specific stages to N operands:
1507//
1508//   1. Imprint EVERY unordered pair (i, j) so every mutual intersection edge is
1509//      present on both operands' faces, and accumulate all pairs into ONE global
1510//      imprint (operand indices remapped to 0..N, piece/vertex ids made globally
1511//      unique, per-face piece lists and per-edge split parameters merged).
1512//   2. Split + fragment each operand by that single global imprint, so each
1513//      operand's faces are cut by ALL of its intersections at once.
1514//   3. Select fragments in one pass: the per-fragment keep decision generalizes
1515//      from "vs one other solid" to "vs the SET of other solids" (see
1516//      `nary_keep`).  Because every pair is imprinted, a fragment's interior lies
1517//      wholly inside or wholly outside each other operand, so a single interior
1518//      test point per (fragment, other-solid) is an exact membership verdict.
1519//   4. Assemble with the same machinery (`assemble_fragments`), then merge and
1520//      validate exactly as the binary path does.
1521// ---------------------------------------------------------------------------
1522
1523/// Reverse a fragment's orientation (surface sense + every coedge), the same
1524/// transform the binary Subtract path applies to the second operand's kept
1525/// fragments.  Extracted so the n-ary selector can reuse it verbatim.
1526fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
1527    fragment.same_sense = !fragment.same_sense;
1528    for loop_record in &mut fragment.loops {
1529        loop_record.coedges.reverse();
1530        for coedge in &mut loop_record.coedges {
1531            coedge.forward = !coedge.forward;
1532            coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
1533        }
1534    }
1535    Ok(())
1536}
1537
1538/// Imprint every unordered pair of operands and fold the pairwise
1539/// `ImprintResultRecord`s into ONE global imprint whose operand indices are the
1540/// operands' global positions (0..N).  Piece and vertex ids are re-based to be
1541/// globally unique; `by_face` piece lists and `edge_splits` parameter lists are
1542/// MERGED per key so `fragment_face` (which takes the first `by_face` match) and
1543/// `apply_edge_splits` (which collects one entry per edge) see every cut.
1544fn build_nary_imprint(
1545    operands: &[BrepSolid],
1546    options: &ImprintOptions,
1547) -> Result<ImprintResultRecord, KernelRefusal> {
1548    let mut section_evidence = false;
1549    let mut vertices: Vec<ImprintVertex> = Vec::new();
1550    let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
1551    let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
1552    let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
1553    let mut next_vertex_id: u64 = 1;
1554    let mut next_piece_id: u64 = 1;
1555
1556    for i in 0..operands.len() {
1557        for j in (i + 1)..operands.len() {
1558            let pair = build_imprints(&operands[i], &operands[j], options)?;
1559            let remap = |operand: u8| -> u8 {
1560                if operand == 0 {
1561                    i as u8
1562                } else {
1563                    j as u8
1564                }
1565            };
1566
1567            section_evidence = section_evidence || pair.section_evidence;
1568            let mut vertex_map: HashMap<u64, u64> = HashMap::default();
1569            for vertex in &pair.vertices {
1570                let global = next_vertex_id;
1571                next_vertex_id += 1;
1572                vertex_map.insert(vertex.id, global);
1573                vertices.push(ImprintVertex {
1574                    id: global,
1575                    point: vertex.point,
1576                });
1577            }
1578
1579            let mut piece_map: HashMap<u64, u64> = HashMap::default();
1580            for piece in &pair.pieces {
1581                let global = next_piece_id;
1582                next_piece_id += 1;
1583                piece_map.insert(piece.id, global);
1584                let mut mapped = piece.clone();
1585                mapped.id = global;
1586                mapped.start_vertex_id = *vertex_map
1587                    .get(&piece.start_vertex_id)
1588                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1589                mapped.end_vertex_id = *vertex_map
1590                    .get(&piece.end_vertex_id)
1591                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1592                for pcurve in &mut mapped.pcurves {
1593                    pcurve.operand = remap(pcurve.operand);
1594                }
1595                mapped.support_faces = [
1596                    FaceKey {
1597                        operand: remap(piece.support_faces[0].operand),
1598                        face_id: piece.support_faces[0].face_id,
1599                    },
1600                    FaceKey {
1601                        operand: remap(piece.support_faces[1].operand),
1602                        face_id: piece.support_faces[1].face_id,
1603                    },
1604                ];
1605                pieces.push(mapped);
1606            }
1607
1608            for entry in &pair.by_face {
1609                let list = by_face
1610                    .entry((remap(entry.operand), entry.face_id))
1611                    .or_default();
1612                for piece_id in &entry.piece_ids {
1613                    let global = *piece_map.get(piece_id).ok_or_else(|| {
1614                        KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
1615                    })?;
1616                    list.push(global);
1617                }
1618            }
1619
1620            for split in &pair.edge_splits {
1621                edge_splits
1622                    .entry((remap(split.operand), split.edge_id))
1623                    .or_default()
1624                    .extend(split.parameters.iter().copied());
1625            }
1626        }
1627    }
1628
1629    Ok(ImprintResultRecord {
1630        vertices,
1631        pieces,
1632        tangent_nodes: Vec::new(),
1633        barrier_edges: Vec::new(),
1634        section_evidence,
1635        cosurface_pairs: Vec::new(),
1636        tangent_sections: Vec::new(),
1637        by_face: by_face
1638            .into_iter()
1639            .map(|((operand, face_id), piece_ids)| FaceImprints {
1640                operand,
1641                face_id,
1642                piece_ids,
1643            })
1644            .collect(),
1645        edge_splits: edge_splits
1646            .into_iter()
1647            .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
1648                operand,
1649                edge_id,
1650                parameters,
1651            })
1652            .collect(),
1653    })
1654}
1655
1656/// N-ary union / intersect / subtract of `operands` in ONE imprint+fragment
1657/// pass (Golovanov T4.4).  Additive: does not touch the binary path.
1658///
1659/// - `Union`   : the boundary of `∪ operands`.
1660/// - `Intersect`: the boundary of `∩ operands`.
1661/// - `Subtract`: `operands[0]` minus the union of `operands[1..]`.
1662///
1663/// `N = 1` returns the sole operand; `N = 2` runs the same general pipeline and
1664/// reproduces the binary result (same volume, valid).  Returns a clear `Err`
1665/// when the operands cannot assemble into a closed, valid solid.
1666pub fn boolean_operation_nary(
1667    operands: &[BrepSolid],
1668    operation: BooleanOperation,
1669) -> Result<BrepSolid, KernelRefusal> {
1670    boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
1671}
1672
1673/// [`boolean_operation_nary`] under the caller's [`BooleanOptions`]: the
1674/// tolerance, the coplanar-face merge and its `keep_unmerged_name_substrs`
1675/// list are honoured exactly as the binary path honours them, so a caller that
1676/// falls back from a sequence of binary unions to one arrangement (the sheet
1677/// metal walk with adjacent bends) keeps the same face partition contract.
1678pub fn boolean_operation_nary_with_options(
1679    operands: &[BrepSolid],
1680    operation: BooleanOperation,
1681    options: &BooleanOptions,
1682) -> Result<BrepSolid, KernelRefusal> {
1683    if operands.len() > 1 {
1684        if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
1685            return boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
1686                .map_err(|error| scaled.refusal(error))
1687                .and_then(|solid| scaled.back(&solid));
1688        }
1689    }
1690    if operands.is_empty() {
1691        return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
1692    }
1693    if operands.len() == 1 {
1694        return Ok(operands[0].clone());
1695    }
1696    if operands.len() > 255 {
1697        return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
1698    }
1699    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
1700
1701    // One tolerance policy for the whole set: the largest-scale operand's policy
1702    // dominates (every derived band is monotonic in scale), matching how the
1703    // binary path takes `for_pair` = max of the two scales.
1704    let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
1705    for operand in &operands[1..] {
1706        let candidate = KernelTolerances::for_solid(operand, options.tolerance);
1707        if candidate.sew_search > policy.sew_search {
1708            policy = candidate;
1709        }
1710    }
1711    policy.check().or_input(KernelStage::Collect, "tolerances")?;
1712    let tolerance = policy.model;
1713
1714    // Per-operand fuse-first healing, exactly as the binary path (a no-op on
1715    // clean input, so clean operands are untouched).
1716    let mut healed = operands.to_vec();
1717    for operand in &mut healed {
1718        crate::heal::heal_operands(operand, &policy)?;
1719        // Then refit any inherited trim off the pcurve construction contract
1720        // whose edge lies on every carrier (a no-op without one).
1721        crate::heal::refit_inherited_trims(operand, &policy)?;
1722        // Same operand normalization as the binary path: seam edges for
1723        // seamless full-period band faces.
1724        normalize_operand_band_seams(operand)?;
1725    }
1726
1727    // 1. Imprint every pair into one global imprint.
1728    let mut imprint_options = options.imprint.clone();
1729    imprint_options.tolerance = tolerance;
1730    let imprint = build_nary_imprint(&healed, &imprint_options)?;
1731
1732    // 2. Split every operand's edges, then fragment its faces, by that imprint.
1733    let mut split = Vec::with_capacity(healed.len());
1734    for (index, operand) in healed.iter().enumerate() {
1735        split.push(apply_edge_splits(operand, index as u8, &imprint)?);
1736    }
1737    let mut fragments = Vec::with_capacity(split.len());
1738    for (index, solid) in split.iter().enumerate() {
1739        fragments.push(fragment_solid(solid, index as u8, &imprint)?);
1740    }
1741
1742    // 3. Select fragments in one pass against the set of other operands.
1743    let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
1744
1745    // 4. Assemble + normalize + validate, mirroring the binary tail.
1746    let solids: HashMap<u8, &BrepSolid> = split
1747        .iter()
1748        .enumerate()
1749        .map(|(index, solid)| (index as u8, solid))
1750        .collect();
1751    let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
1752    let solid = if options.merge_coplanar_faces
1753        && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
1754    {
1755        let merged = merge_same_surface_faces_excluding(
1756            &solid,
1757            tolerance,
1758            &options.keep_unmerged_name_substrs,
1759        )?;
1760        merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?
1761    } else {
1762        solid
1763    };
1764    let validation = solid.validate_detailed(&policy);
1765    if !validation.issues.is_empty() {
1766        return Err(KernelRefusal::new(
1767            RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
1768            KernelStage::Validate,
1769            format!(
1770            "boolean_operation_nary: invalid result: {:?}",
1771            validation.issues
1772        )));
1773    }
1774    if debug {
1775        if let Ok(report) =
1776            crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
1777        {
1778            if report.is_flagged() {
1779                eprintln!(
1780                    "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
1781                    report.disagreement_rate,
1782                    report.disagreements.len(),
1783                    report.considered,
1784                    report.sample_disagreement()
1785                );
1786            }
1787        }
1788    }
1789    Ok(solid)
1790}
1791
1792/// TANGENT-NODE ATTRIBUTION.
1793///
1794/// The imprint's second-order filter decides which tangential contacts are
1795/// isolated NODES the arrangement can carve, and marches those instead of
1796/// refusing. It cannot decide a THIRD-order singularity — where the transverse
1797/// branch is tangent to a contact curve, every second-order quantity vanishes
1798/// together and the contact reads as a clean saddle at every stopping rule
1799/// (`imprint/tangent_contact.rs`). The assembly is the authority on whether an
1800/// admitted node was really imprintable, so a tear downstream of one is
1801/// reported AGAINST THE NODE rather than as an anonymous degeneracy: same
1802/// refusal class the whole tangent-node family carries, naming the point.
1803///
1804/// Only classes that are ALREADY perturbation-eligible are re-attributed, so a
1805/// refusal that could never take the ladder still cannot. The stage's own
1806/// message — the one-use edges, the genus — is NOT carried into the refusal:
1807/// `tangent_node_assembly` and `torus_torus_singular_refusal` hold the
1808/// tangent-node refusal to naming its cause without the arrangement's
1809/// symptom text ("open between", "genus", "pcurve"), the policy the class
1810/// exists for. It is printed under `BREP_DEBUG_BOOL` instead, so what the
1811/// assembly actually read is still there for a reader of the trace.
1812///
1813/// It does decide WHICH refusals are retried, though, and since 2026-09-13 that
1814/// matters: `boolean_operation`'s failure arm gates `TangentNodeSingularity` out
1815/// of the perturbation ladder (the TANGENT-NODE GATE there) and reads the class
1816/// AFTER this rewrite. So a tear downstream of an ADMITTED node — whatever class
1817/// the pipeline actually raised — declines the ladder along with the tangent-node
1818/// family proper. That is the conservative direction and the same claim the class
1819/// makes (a tear after a node is the node proving unimprintable). Anything added
1820/// to this rewrite widens that gate: read the gate when you touch the
1821/// attribution.
1822fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
1823    let Some(node) = nodes.first() else {
1824        return error;
1825    };
1826    if !error.class.perturbation_eligible()
1827        || matches!(error.class, RefusalClass::TangentNodeSingularity)
1828    {
1829        return error;
1830    }
1831    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
1832        eprintln!(
1833            "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
1834            node.x, node.y, node.z, error.message
1835        );
1836    }
1837    KernelRefusal::new(
1838        RefusalClass::TangentNodeSingularity,
1839        error.stage,
1840        format!(
1841            "boolean: unsupported singular/tangent-node surface intersection \
1842             at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
1843             assemble into a closed shell",
1844            node.x, node.y, node.z
1845        ),
1846    )
1847}
1848
1849/// The tangent-curve lane's attribution: an ASSEMBLY refusal whose faces the
1850/// imprint found touching along a CURVE is reported against that contact, by
1851/// its faces and its ends, in the tangent-node class — the arrangement's own
1852/// message (an open loop, a one-use edge) is the symptom, the contact is the
1853/// cause, and the class keeps the refusal out of the perturbation ladder
1854/// exactly as an admitted node's tear is kept out
1855/// (`attribute_to_tangent_node`). The original message is carried along so
1856/// nothing the stage said is hidden.
1857///
1858/// REACH: the faces the refusal names, and only those. `origins` maps the
1859/// assembled result's face ids (minted one per selected fragment, from 1, in
1860/// order) back to operand faces; the ids are read off the message's
1861/// `face <id>` (validate's open-loop issues) and `on faces [<id> '…`
1862/// (one-use edges) entries, and the rewrite happens only when one of them is
1863/// a face the section INVOLVES (`TangentSectionRecord::faces`: the carriers'
1864/// faces and the faces across the edges its ends lie on). A refusal naming no
1865/// face, or only faces the contact does not touch — a model with a benign
1866/// recorded contact (a blind pocket touching a wall) that fails elsewhere —
1867/// keeps its class and enters the ladder as it always did. With
1868/// `ImprintOptions::tangent_curve_lane` off the sections are empty and
1869/// nothing is rewritten.
1870fn attribute_to_tangent_section(
1871    error: KernelRefusal,
1872    sections: &[crate::imprint::TangentSectionRecord],
1873    origins: &[FaceKey],
1874) -> KernelRefusal {
1875    if sections.is_empty()
1876        || !error.class.perturbation_eligible()
1877        || matches!(error.class, RefusalClass::TangentNodeSingularity)
1878    {
1879        return error;
1880    }
1881    let named = refusal_result_faces(&error.message)
1882        .into_iter()
1883        .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
1884        .collect::<Vec<FaceKey>>();
1885    // A record the lane's own sites minted before one the grazing-pierce
1886    // path minted (`TangentSectionRecord::grazing`): the sprocket slit star's
1887    // cutter names its traced contact, not the pierce of a neighbouring pair.
1888    let involving = |fallback: bool| {
1889        sections.iter().find(|section| {
1890            section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
1891        })
1892    };
1893    let Some(section) = involving(false).or_else(|| involving(true)) else {
1894        return error;
1895    };
1896    // A clipped end sits on a trim at round-off, and `-0.000000` names no
1897    // place: print what six decimals can show.
1898    let at = |point: Vec3| {
1899        let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
1900        format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
1901    };
1902    // The grazing pierces (`imprint/driver.rs`, 2026-10-17): trim edges that
1903    // pierce the other carrier inside both trims below the seed gate while
1904    // the pair marched nothing. A record the lane built stands on its contact
1905    // and carries them as a note; a record standing on the pierces ALONE
1906    // (its `start` IS the first pierce) is named by them.
1907    let pierces = (!section.grazing.is_empty()).then(|| {
1908        let shown = section.grazing.len().min(4);
1909        let mut listed = section.grazing[..shown]
1910            .iter()
1911            .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
1912            .collect::<Vec<_>>()
1913            .join(", ");
1914        if section.grazing.len() > shown {
1915            listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
1916        }
1917        listed
1918    });
1919    let pierce_only = section.pierce_only();
1920    let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
1921        format!(
1922            "cross at a grazing angle: a trim edge pierces the other carrier inside both \
1923             trims at {pierces}, below the marcher's start gate, and no transverse section was \
1924             marched between the pierces — a near-tangent crossing born on a tangent contact \
1925             (a third-order singularity) the imprint does not build yet"
1926        )
1927    } else if section.planar {
1928        format!(
1929            "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
1930             imprint does not build yet",
1931            at(section.start),
1932            at(section.end),
1933            section.length,
1934            section.stations,
1935            if section.closed { ", closed" } else { "" }
1936        )
1937    } else {
1938        format!(
1939            "touch along a curve through {} with neither carrier planar, a curved/curved \
1940             tangent contact the lane does not trace yet",
1941            at(section.start)
1942        )
1943    };
1944    let shape = match (pierce_only, pierces) {
1945        (false, Some(pierces)) => format!(
1946            "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
1947             below the marcher's start gate, with no transverse section marched"
1948        ),
1949        _ => shape,
1950    };
1951    let involved = named
1952        .iter()
1953        .filter(|face| section.faces.contains(face))
1954        .map(|face| format!("{}/{}", face.operand, face.face_id))
1955        .collect::<Vec<_>>()
1956        .join(", ");
1957    KernelRefusal::new(
1958        RefusalClass::TangentNodeSingularity,
1959        error.stage,
1960        format!(
1961            "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
1962             the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
1963            section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
1964            error.message
1965        ),
1966    )
1967}
1968
1969/// The RESULT face ids an assembly refusal names: every `face <id>` (the
1970/// validator's "loop … of face <id> is open …") and every `<id> '` entry of an
1971/// `on faces [...]` list (the one-use edge census). Nothing else in the
1972/// message is read.
1973fn refusal_result_faces(message: &str) -> Vec<u64> {
1974    let mut ids = Vec::new();
1975    let digits_after = |text: &str| -> Option<u64> {
1976        let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
1977        text[..end].parse().ok()
1978    };
1979    for (index, _) in message.match_indices("face ") {
1980        if let Some(id) = digits_after(&message[index + "face ".len()..]) {
1981            ids.push(id);
1982        }
1983    }
1984    if let Some(start) = message.find("on faces [") {
1985        let rest = &message[start + "on faces [".len()..];
1986        let list = &rest[..rest.find(']').unwrap_or(rest.len())];
1987        for entry in list.split(", ") {
1988            let entry = entry.trim_start();
1989            if let Some(id) = digits_after(entry) {
1990                if entry[id.to_string().len()..].starts_with(" '") {
1991                    ids.push(id);
1992                }
1993            }
1994        }
1995    }
1996    ids.sort_unstable();
1997    ids.dedup();
1998    ids
1999}
2000
2001pub fn boolean_operation_with_diagnostics(
2002    first: &BrepSolid,
2003    second: &BrepSolid,
2004    operation: BooleanOperation,
2005    options: &BooleanOptions,
2006) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2007    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2008        let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2009            .map_err(|error| scaled.refusal(error))?;
2010        outcome.value = scaled.back(&outcome.value)?;
2011        outcome.diagnostics.count_n("working_scale.fired", 1);
2012        outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2013        return Ok(outcome);
2014    }
2015    let _account = profile::Scope::new("boolean.other");
2016    let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2017    if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2018        let started = Instant::now();
2019        let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2020        profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2021        return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs);
2022    }
2023    boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs)
2024}
2025
2026fn boolean_operation_with_diagnostics_impl(
2027    first: &BrepSolid,
2028    second: &BrepSolid,
2029    operation: BooleanOperation,
2030    options: &BooleanOptions,
2031    closed_inputs: bool,
2032) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2033    // One coedge-check memo per operation (`BREP_VALIDATE_COEDGE_MEMO`): the
2034    // assembly, face-merge and closing validations re-read coedges unchanged.
2035    let _coedge_memo = crate::topology::CoedgeMemoScope::open(crate::topology::coedge_memo_enabled());
2036    // Plan 1.6: only a declared Sheet enters the trim path. The unchanged
2037    // Solid path continues below; no kind is inferred from failed closure.
2038    if matches!(operation, BooleanOperation::Intersect)
2039        && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2040        && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2041            Ok("1") => true,
2042            Ok("0") => false,
2043            _ => options.sheet_trim,
2044        }
2045    {
2046        return sheet::trim(first, second, options);
2047    }
2048    // OPERAND-KIND GATE. A body that DECLARES itself a Sheet has no
2049    // inside, so a union or subtract with it has no solid answer; the
2050    // survey (record 2026-10-12, table 2) measured the arrangement
2051    // returning a validating solid of volume 3.5 when the sheet's opening
2052    // lay outside the other operand. Read from the declaration only,
2053    // before any arrangement work (nothing infers a kind from the edge
2054    // census; an undeclared open body is the closure gate's below).
2055    // Intersect is not gated here.
2056    if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2057        if let Some(operand) = [first, second]
2058            .iter()
2059            .position(|solid| solid.kind == crate::BodyKind::Sheet)
2060        {
2061            return Err(KernelRefusal::input(
2062                KernelStage::Collect,
2063                "sheet_operand",
2064                format!(
2065                    "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2066                     subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2067                ),
2068            ));
2069        }
2070    }
2071    // Inside/outside is undefined for an open operand, even if its opening
2072    // misses the other operand and the constructed result happens to validate.
2073    // Count existing edge uses, without modifying/healing either operand.
2074    // Keep failures on their original path and preserve their class/evidence;
2075    // the existing perturbation gate already diagnoses open failed operands.
2076    let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2077    let closure_started = closed_inputs.then(Instant::now);
2078    if closed_inputs {
2079        for (operand, solid) in [first, second].into_iter().enumerate() {
2080            let open = one_use_edges(solid);
2081            if open > 0 {
2082                return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2083                    "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2084                )));
2085            }
2086        }
2087    }
2088    if let Some(started) = closure_started {
2089        let ms = started.elapsed().as_secs_f64() * 1000.0;
2090        profile_stage("operand_closure_ms", ms);
2091        outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2092    }
2093    Ok(outcome)
2094}
2095
2096fn boolean_operation_with_diagnostics_core(
2097    first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2098) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2099
2100    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`):
2101    // the outermost entry runs the operation on translated operands.
2102    if let Some(offset) = crate::recentre::control_offset_at_entry() {
2103        return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2104    }
2105    // The recentre guard: operands far from the origin in their own
2106    // units run at the origin.
2107    let mut bounds = operand_bounds(first);
2108    bounds.include(operand_bounds(second));
2109    if let Some(offset) = crate::recentre::guard_offset(bounds) {
2110        crate::recentre::profile_fired("boolean", offset, bounds);
2111        let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2112        outcome.diagnostics.count_n("recentre.fired", 1);
2113        outcome.diagnostics.measure_max("recentre.distance", offset.length());
2114        return Ok(outcome);
2115    }
2116    let mut tangent_nodes = Vec::new();
2117    let (mut outcome, soundness_candidates) =
2118        boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2119            .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2120    // The assembly's single exit. A boolean can hand back a body whose walls
2121    // pass through each other while `validate()` is silent and the volume
2122    // measures right, which is exactly the failure a regularized boolean must
2123    // not report as success. A crossing the OPERANDS already had is theirs and
2124    // passes through — the defect came in with the input and refusing it here
2125    // would blame the wrong operation — so the operands are only scanned when
2126    // the result is flagged, and the common case pays for one scan. The
2127    // acceptance's refusal is typed at its origin (an `UnsoundResult` naming
2128    // the defect and the faces); it was classed `Internal` here while
2129    // `accept_sound_against` still returned text. Timed as its own stage: the
2130    // record's phase split read only the pipeline's `timing.*` measures, and
2131    // on a 108-face disjoint union this scan was 185 of 226 ms end to end.
2132    let stage_started = Instant::now();
2133    let accepted = match &soundness_candidates {
2134        // Pass-through: the faces the operation touched, their
2135        // neighbours and every face whose box reaches the other operand.
2136        Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2137        None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2138    };
2139    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2140    profile_stage("soundness_ms", stage_ms);
2141    outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2142    outcome.value = accepted?;
2143    Ok(outcome)
2144}
2145
2146/// [`boolean_operation_with_diagnostics`] with both operands translated by
2147/// `offset` for the operation and the result translated back. Refusal
2148/// messages name the translated coordinates.
2149pub fn boolean_operation_with_diagnostics_at_offset(
2150    first: &BrepSolid,
2151    second: &BrepSolid,
2152    operation: BooleanOperation,
2153    options: &BooleanOptions,
2154    offset: Vec3,
2155) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2156    boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2157}
2158
2159/// The translated run behind the control and the guard.
2160fn boolean_translated(
2161    first: &BrepSolid,
2162    second: &BrepSolid,
2163    operation: BooleanOperation,
2164    options: &BooleanOptions,
2165    offset: Vec3,
2166    kind: crate::recentre::EntryKind,
2167) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2168    let _entry = crate::recentre::TranslatedEntry::open(kind);
2169    let translate = |solid: &BrepSolid, offset: Vec3| {
2170        crate::recentre::translate_solid(solid, offset).map_err(|message| {
2171            KernelRefusal::internal(
2172                KernelStage::Collect,
2173                "translation_control",
2174                format!("boolean: the translation control could not move an operand: {message}"),
2175            )
2176        })
2177    };
2178    let moved_first = translate(first, offset)?;
2179    let moved_second = translate(second, offset)?;
2180    let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
2181    let value = translate(&outcome.value, offset.scale(-1.0))?;
2182    Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
2183}
2184
2185/// Stage wall-clock line on stderr when `BREP_PROFILE` is set — the same switch
2186/// `imprint.profile` and `assemble.*_ms` use — so a REFUSED boolean, whose
2187/// `KernelDiagnostics` never reach a caller, still shows where its time went.
2188fn profile_stage(code: &str, ms: f64) {
2189    let row = match code {
2190        "heal_ms" => Some("boolean.operand_prepare"),
2191        "imprint_ms" => Some("boolean.imprint"),
2192        "edge_split_ms" => Some("boolean.edge_split"),
2193        "fragment_ms" => Some("boolean.fragment"),
2194        "select_ms" => Some("boolean.select"),
2195        "assemble_ms" => Some("boolean.assemble"),
2196        "face_merge_ms" => Some("boolean.face_merge"),
2197        "soundness_ms" => Some("boolean.soundness"),
2198        "operand_closure_ms" => Some("boolean.operand_closure"),
2199        "seam_prepare_ms" => Some("boolean.seam_prepare"),
2200        "final_validate_ms" => Some("boolean.final_validate"),
2201        _ => None,
2202    };
2203    if let Some(row) = row { profile::record(row, ms); }
2204    if crate::profile::profile_enabled() {
2205        profile_line!("boolean.{code}={ms:.2}");
2206    }
2207}
2208
2209/// `BREP_BOOLEAN_DUMP` names a directory. Every binary boolean then writes its
2210/// stages there as JSON — the two split operands, the selected fragments, the
2211/// assembled solid and the merged one — numbered per process, so a probe can
2212/// read a face's loops at each stage without replaying the document.
2213struct BooleanStageDump {
2214    directory: std::path::PathBuf,
2215    serial: usize,
2216}
2217
2218impl BooleanStageDump {
2219    fn open() -> Option<Self> {
2220        static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2221        let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
2222        let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2223        Some(Self { directory: directory.into(), serial })
2224    }
2225
2226    fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
2227        let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
2228        match serde_json::to_string(value) {
2229            Ok(text) => {
2230                if let Err(error) = std::fs::write(&path, text) {
2231                    eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
2232                }
2233            }
2234            Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
2235        }
2236    }
2237}
2238
2239/// The tolerance policy a binary boolean of `first` and `second` runs under.
2240fn boolean_policy(
2241    first: &BrepSolid,
2242    second: &BrepSolid,
2243    options: &BooleanOptions,
2244) -> Result<KernelTolerances, KernelRefusal> {
2245    let policy = options
2246        .tolerances
2247        .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2248    policy.check().or_input(KernelStage::Collect, "tolerances")?;
2249    Ok(policy)
2250}
2251
2252/// The operands as the imprint reads them: healed, with their band seams
2253/// normalized.
2254fn prepared_operands(
2255    first: &BrepSolid,
2256    second: &BrepSolid,
2257    policy: &KernelTolerances,
2258) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2259    // Fuse-first operand healing (Lever A): before any intersection touches the
2260    // operands, snap each one's near-coincident / off-plane vertices to exact
2261    // and re-anchor the incident edge curves onto them, so noisy
2262    // near-degenerate input (points that should coincide but drifted, vertices
2263    // a few microns off a planar face) cannot tip a fixed downstream band over
2264    // the edge.  Healing is per-operand, validate-gated, and — because a clean
2265    // operand has no vertices within `heal_tol` and none off its planes — a
2266    // no-op that leaves the boolean output byte-identical on clean inputs.
2267    let stage_started = Instant::now();
2268    let mut first_owned = first.clone();
2269    let mut second_owned = second.clone();
2270    crate::heal::heal_operands(&mut first_owned, policy)?;
2271    crate::heal::heal_operands(&mut second_owned, policy)?;
2272    profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2273    // Then refit, on each operand's own carriers, any inherited trim off the
2274    // pcurve construction contract whose edge lies on every incident carrier
2275    // (`heal::refit_inherited_trims`; a byte-identical no-op without one).
2276    let refit_started = Instant::now();
2277    crate::heal::refit_inherited_trims(&mut first_owned, policy)?;
2278    crate::heal::refit_inherited_trims(&mut second_owned, policy)?;
2279    profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
2280    if crate::profile::profile_enabled() {
2281        let (hits, misses) = crate::reading_memo::counts();
2282        profile_line!("boolean.reading_memo hits={hits} misses={misses}");
2283    }
2284    profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2285    // Seamless full-period band faces (STEP import) break the seam-aware
2286    // imprint/arrangement machinery; normalize them to the seam-carrying
2287    // topology native periodic faces use. No-op on operands without such
2288    // faces. See `insert_periodic_band_seam_edges`.
2289    normalize_operand_band_seams(&mut first_owned)?;
2290    normalize_operand_band_seams(&mut second_owned)?;
2291    Ok((first_owned, second_owned))
2292}
2293
2294fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
2295    let mut imprint_options = options.imprint.clone();
2296    imprint_options.tolerance = tolerance;
2297    imprint_options
2298}
2299
2300/// The two operands a binary boolean's arrangement reads: prepared as the
2301/// boolean prepares them, with every boundary edge split where the imprint's
2302/// sections meet it. These are the `NNN-first` and `NNN-second` stages
2303/// `BREP_BOOLEAN_DUMP` writes, not the operands at the boolean's entry.
2304///
2305/// A boolean must read the same on these as on the operands it split them
2306/// from: the splits are vertices its own imprint puts on those edges anyway.
2307/// Where it does not, an imprint lane is deciding on what the input happens to
2308/// have split, and that is a defect.
2309pub fn boolean_split_operands(
2310    first: &BrepSolid,
2311    second: &BrepSolid,
2312    options: &BooleanOptions,
2313) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2314    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2315        let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
2316            .map_err(|error| scaled.refusal(error))?;
2317        return Ok((scaled.back(&split_first)?, scaled.back(&split_second)?));
2318    }
2319    let policy = boolean_policy(first, second, options)?;
2320    let (first, second) = prepared_operands(first, second, &policy)?;
2321    let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
2322    let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
2323    let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
2324    Ok((split_first, split_second))
2325}
2326
2327/// Conservative bounds of an operand: its vertices and every face's control
2328/// net (a NURBS lies in the hull of its controls). A control net that cannot
2329/// be read bounds everything, so nothing is left out for want of a reading.
2330fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
2331    let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
2332    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2333        match crate::Aabb::from_surface_controls(&face.surface) {
2334            Ok(face_bounds) => bounds.include(face_bounds),
2335            Err(_) => {
2336                return crate::Aabb {
2337                    minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2338                    maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2339                }
2340            }
2341        }
2342    }
2343    bounds
2344}
2345
2346/// Row 12's gate: the boxes are separated or touch exactly in at least two
2347/// axes. A trimmed face lies in its carrier's control-net box when every
2348/// weight is positive, so a point interior to both operands would lie
2349/// strictly inside both boxes in every axis; two such axes leave a line or a
2350/// point of contact, which has no area to merge.
2351fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2352    apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
2353}
2354
2355/// One apart axis: no point can be interior to both operands (see
2356/// [`line_or_point_contact`]), though the boxes may share a face's area.
2357fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2358    apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
2359}
2360
2361/// The axes in which the boxes are separated or touch exactly (no band).
2362fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
2363    let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
2364    [
2365        apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
2366        apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
2367        apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
2368    ]
2369    .into_iter()
2370    .filter(|&apart| apart)
2371    .count()
2372}
2373
2374/// A plain solid whose faces lie in their control-net boxes: every weight positive.
2375fn plain_hull_solid(solid: &BrepSolid) -> bool {
2376    solid.kind == crate::BodyKind::Solid
2377        && solid.cells.is_empty()
2378        && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
2379            face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
2380        })
2381}
2382
2383/// The result faces the soundness scan reads under pass-through: the
2384/// examined faces (touched and their neighbours) and every other face whose
2385/// control-net box reaches the OTHER operand's bounds within `band`. A face
2386/// outside both is an operand's own, clear of everything the operation added.
2387fn soundness_candidates(
2388    solid: &BrepSolid,
2389    scope: &AssemblyScope,
2390    bounds: [crate::Aabb; 2],
2391    band: f64,
2392) -> HashSet<u64> {
2393    let mut candidates = HashSet::default();
2394    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2395        if scope.examined.contains(&face.id) {
2396            candidates.insert(face.id);
2397            continue;
2398        }
2399        let Some(&operand) = scope.operand_of.get(&face.id) else {
2400            candidates.insert(face.id);
2401            continue;
2402        };
2403        let other = bounds[usize::from(operand == 0)];
2404        match crate::Aabb::from_surface_controls(&face.surface) {
2405            Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
2406            _ => {
2407                candidates.insert(face.id);
2408            }
2409        }
2410    }
2411    candidates
2412}
2413
2414/// The empty solid a legitimately empty boolean returns.
2415fn empty_solid() -> BrepSolid {
2416    BrepSolid {
2417        mass_properties_cache: Default::default(),
2418        cells: Default::default(),
2419        id: 0,
2420        vertices: Vec::new(),
2421        edges: Vec::new(),
2422        shells: Vec::new(),
2423        genus: 0,
2424        kind: crate::BodyKind::Solid,
2425    }
2426}
2427
2428/// The two operands as one solid, shell by shell: ids minted afresh in the
2429/// assembler's order (the first operand's faces, then the second's), the
2430/// second operand's face names suffixed where they clash with the first's
2431/// as the assembler suffixes a split face, geometry copied byte for byte,
2432/// genus the sum. Nothing is welded: the operands are disjoint.
2433fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
2434    let mut vertices = Vec::new();
2435    let mut edges = Vec::new();
2436    let mut shells = Vec::new();
2437    let mut used_face_names = HashSet::<String>::default();
2438    let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
2439    for operand in [first, second] {
2440        let vertex_base = vertices.len() as u64;
2441        let edge_base = edges.len() as u64;
2442        let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
2443        for (index, vertex) in operand.vertices.iter().enumerate() {
2444            let id = vertex_base + index as u64 + 1;
2445            vertex_ids.insert(vertex.id, id);
2446            vertices.push(VertexRecord { id, point: vertex.point });
2447        }
2448        let mut edge_ids: HashMap<u64, u64> = HashMap::default();
2449        for (index, edge) in operand.edges.iter().enumerate() {
2450            let id = edge_base + index as u64 + 1;
2451            edge_ids.insert(edge.id, id);
2452            edges.push(EdgeRecord {
2453                id,
2454                curve: edge.curve.clone(),
2455                t0: edge.t0,
2456                t1: edge.t1,
2457                start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
2458                end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
2459                degenerate: edge.degenerate,
2460                name: edge.name.clone(),
2461            });
2462        }
2463        for shell in &operand.shells {
2464            let mut faces = Vec::with_capacity(shell.faces.len());
2465            for face in &shell.faces {
2466                let loops = face
2467                    .loops
2468                    .iter()
2469                    .map(|loop_record| {
2470                        let coedges = loop_record
2471                            .coedges
2472                            .iter()
2473                            .map(|coedge| {
2474                                let id = next_coedge_id;
2475                                next_coedge_id += 1;
2476                                CoedgeRecord {
2477                                    id,
2478                                    edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
2479                                    forward: coedge.forward,
2480                                    pcurve: coedge.pcurve.clone(),
2481                                }
2482                            })
2483                            .collect();
2484                        let id = next_loop_id;
2485                        next_loop_id += 1;
2486                        LoopRecord { id, coedges }
2487                    })
2488                    .collect();
2489                let name = face.name.clone().map(|base| {
2490                    if used_face_names.insert(base.clone()) {
2491                        base
2492                    } else {
2493                        let mut suffix = 1usize;
2494                        loop {
2495                            let candidate = format!("{base}_{suffix}");
2496                            if used_face_names.insert(candidate.clone()) {
2497                                break candidate;
2498                            }
2499                            suffix += 1;
2500                        }
2501                    }
2502                });
2503                faces.push(FaceRecord {
2504                    id: next_face_id,
2505                    surface: face.surface.clone(),
2506                    same_sense: face.same_sense,
2507                    loops,
2508                    name,
2509                });
2510                next_face_id += 1;
2511            }
2512            shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
2513        }
2514    }
2515    BrepSolid {
2516        mass_properties_cache: Default::default(),
2517        cells: Default::default(),
2518        id: 1,
2519        vertices,
2520        edges,
2521        shells,
2522        genus: first.genus + second.genus,
2523        kind: crate::BodyKind::Solid,
2524    }
2525}
2526
2527/// The binary boolean. The second value is the soundness scan's candidate
2528/// faces under pass-through (`None` reads the whole result).
2529fn boolean_pipeline(
2530    first: &BrepSolid,
2531    second: &BrepSolid,
2532    operation: BooleanOperation,
2533    options: &BooleanOptions,
2534    tangent_nodes: &mut Vec<Vec3>,
2535) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
2536    let _work = crate::imprint::work_profile::Scope::open("boolean");
2537    let replaced_operands = operand_state::replace_operands(first, second, operation, options);
2538    let (first, second) = match &replaced_operands {
2539        Some((first, second)) => (first, second),
2540        None => (first, second),
2541    };
2542    let policy = boolean_policy(first, second, options)?;
2543    let tolerance = policy.model;
2544    // DISJOINT FAST PATH. A box test on the control-net hulls, not "no
2545    // section evidence": a tool inside the other operand also leaves no
2546    // evidence and must stay on the pipeline, where a union is the outer
2547    // operand, a subtract the outer with a void shell and an intersect the
2548    // tool. Operands clear of each other by more than the search band can
2549    // touch nothing, so nothing is prepared, imprinted, assembled or
2550    // scanned: a union is the two operands side by side, a subtract the
2551    // first operand, an intersect the legitimate-empty result below. The
2552    // soundness scan is skipped as well (an empty candidate set): the
2553    // operands cannot cross each other, and a crossing an operand carried in
2554    // passes through the full acceptance unrepaired exactly the same.
2555    //
2556    // CONTACT FAST PATH (row 12): boxes that only meet along a line or at a
2557    // point, read exactly; see `line_or_point_contact`.
2558    let bounds = [operand_bounds(first), operand_bounds(second)];
2559    let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
2560    let contact = !disjoint
2561        && contact_fast_path(options)
2562        && options.seam_reseat_later_references.is_some()
2563        && line_or_point_contact(first, second, bounds);
2564    // One apart axis already leaves no common interior, so an intersect is
2565    // empty even where the boxes share a face's area (which is why a union or
2566    // a subtract stays on the pipeline). Nothing survives to carry an id, so
2567    // no caller has to say what follows.
2568    let contact = contact
2569        || (!disjoint
2570            && matches!(operation, BooleanOperation::Intersect)
2571            && contact_fast_path(options)
2572            && boxes_share_no_interior(first, second, bounds));
2573    if disjoint || contact {
2574        let operation_started = Instant::now();
2575        let mut diagnostics = KernelDiagnostics::default();
2576        diagnostics.count_n(
2577            "collect.faces",
2578            first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
2579        );
2580        diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
2581        diagnostics.measure_max("tolerance.model", policy.model);
2582        diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2583        let value = match operation {
2584            BooleanOperation::Union => concatenate_disjoint(first, second),
2585            BooleanOperation::Subtract => first.clone(),
2586            BooleanOperation::Intersect => {
2587                diagnostics.event(
2588                    DiagnosticSeverity::Info,
2589                    KernelStage::Select,
2590                    "boolean.empty_result",
2591                    format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2592                );
2593                empty_solid()
2594            }
2595        };
2596        let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
2597        profile_stage("disjoint_fast_path_ms", stage_ms);
2598        diagnostics.measure_max("timing.total_ms", stage_ms);
2599        return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
2600    }
2601    let heal_started = Instant::now();
2602    let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
2603    let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
2604    let first = &first_owned;
2605    let second = &second_owned;
2606
2607    let mut diagnostics = KernelDiagnostics::default();
2608    // Operand preparation ran before `timing.total_ms` opens and was absent
2609    // from every phase split; it is 1.6 of a disjoint box union's 7.2 ms.
2610    diagnostics.measure_max("timing.heal_ms", heal_ms);
2611    // Every pcurve fit made while this scope is open — the imprint's sections,
2612    // the assembler's rebuilt trims, the merge's re-fits — is tallied, so the
2613    // outcome can say whether every curved trim reached its floor instead of
2614    // letting a sample-ceiling exit pass for a met one (`pcurve.unmet_floor`).
2615    let fit_scope = crate::PcurveFitScope::open();
2616    // And every POLYLINE fit: a marched section's interpolant is measured
2617    // against the tolerance it was given, so `fit.polyline.unmet_tolerance`
2618    // reports a section that could not reach it (`geometry/fit.rs`).
2619    let polyline_scope = crate::PolylineFitScope::open();
2620    let operation_started = Instant::now();
2621    diagnostics.count_n(
2622        "collect.faces",
2623        first
2624            .shells
2625            .iter()
2626            .chain(&second.shells)
2627            .map(|shell| shell.faces.len() as u64)
2628            .sum(),
2629    );
2630    diagnostics.measure_max("tolerance.model", policy.model);
2631    diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2632
2633    let imprint_options = boolean_imprint_options(options, tolerance);
2634    let stage_started = Instant::now();
2635    let imprint = build_imprints(first, second, &imprint_options)?;
2636    tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
2637    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2638        for piece in &imprint.pieces {
2639            let start = piece.curve.evaluate(piece.t0);
2640            let end = piece.curve.evaluate(piece.t1);
2641            eprintln!(
2642                "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
2643                piece.id, piece.support_faces, piece.t0, piece.t1, start, end
2644            );
2645        }
2646        for entry in &imprint.by_face {
2647            eprintln!(
2648                "by_face operand={} face={} pieces={:?}",
2649                entry.operand, entry.face_id, entry.piece_ids
2650            );
2651        }
2652        for split in &imprint.edge_splits {
2653            eprintln!(
2654                "edge_split operand={} edge={} params={:?}",
2655                split.operand, split.edge_id, split.parameters
2656            );
2657        }
2658    }
2659    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2660    profile_stage("imprint_ms", stage_ms);
2661    diagnostics.measure_max("timing.imprint_ms", stage_ms);
2662    diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
2663    diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
2664    diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
2665    let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
2666    diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
2667    diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
2668    let touch = TouchCensus::build([first, second], &imprint);
2669    touch.report(&mut diagnostics);
2670    let stage_started = Instant::now();
2671    let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
2672    let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
2673    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2674    profile_stage("edge_split_ms", stage_ms);
2675    diagnostics.measure_max("timing.edge_split_ms", stage_ms);
2676    let stage_started = Instant::now();
2677    crate::classification::classify_profile_begin();
2678    let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
2679    let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
2680    crate::classification::classify_profile_report("fragment");
2681    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2682    profile_stage("fragment_ms", stage_ms);
2683    diagnostics.measure_max("timing.fragment_ms", stage_ms);
2684    diagnostics.count_n(
2685        "fragment.candidates",
2686        (fragments_a.len() + fragments_b.len()) as u64,
2687    );
2688    touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
2689    // Operand surface samples for the LEGITIMATE-EMPTY adjudication below:
2690    // every fragment test point is a 3D point ON its operand's boundary and
2691    // inside its face trim, so they witness where the operands' materials sit
2692    // relative to each other without extra geometry work.
2693    let a_surface_samples: Vec<Vec3> = fragments_a
2694        .iter()
2695        .flat_map(|fragment| {
2696            std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2697        })
2698        .collect();
2699    let b_surface_samples: Vec<Vec3> = fragments_b
2700        .iter()
2701        .flat_map(|fragment| {
2702            std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2703        })
2704        .collect();
2705    let stage_started = Instant::now();
2706    let mut barrier_edges: HashSet<(u8, u64)> = imprint
2707        .pieces
2708        .iter()
2709        .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
2710        .collect();
2711    barrier_edges.extend(imprint.barrier_edges.iter().copied());
2712    // The barrier set is keyed on ORIGINAL edge ids, but a barrier edge the
2713    // imprint also SPLIT (rotated equator-tangency: the overlapped cap ring
2714    // gains a junction at the sphere-seam crossing) reaches fragment
2715    // selection as its minted sub-edge ids. Remap the barrier through the
2716    // split ledger — keeping the originals too for unsplit references.
2717    for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
2718        let minted: Vec<(u8, u64)> = barrier_edges
2719            .iter()
2720            .filter(|(barrier_operand, _)| *barrier_operand == operand)
2721            .filter_map(|(_, edge_id)| split_map.get(edge_id))
2722            .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
2723            .collect();
2724        barrier_edges.extend(minted);
2725    }
2726    crate::classification::classify_profile_begin();
2727    let coincident = coincident_pairs(
2728        &fragments_a,
2729        &fragments_b,
2730        first,
2731        second,
2732        &imprint.cosurface_pairs,
2733        tolerance,
2734    )?;
2735    let sector_mode = sector::sector_mode(options);
2736    let mut select_census = sector::SelectCensus::default();
2737    let mut selected = select_fragments(
2738        fragments_a,
2739        fragments_b,
2740        first,
2741        second,
2742        operation,
2743        tolerance,
2744        &barrier_edges,
2745        &imprint,
2746        &coincident,
2747        sector_mode,
2748        &mut select_census,
2749    )?;
2750    let resewn = resew_coincident_rims(
2751        &mut selected,
2752        [&split_first, &split_second],
2753        [first, second],
2754        &imprint.cosurface_pairs,
2755        operation,
2756        tolerance,
2757    )?;
2758    diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
2759    diagnostics.count_n("select.rims_resewn", resewn as u64);
2760    crate::classification::classify_profile_report("select");
2761    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2762    profile_stage("select_ms", stage_ms);
2763    diagnostics.measure_max("timing.select_ms", stage_ms);
2764    diagnostics.count_n("select.fragments", selected.len() as u64);
2765    // One census line per selection as well.
2766    diagnostics.count_n("select.sector_eligible", select_census.eligible);
2767    diagnostics.count_n("select.sector_primary", select_census.sector_primary);
2768    diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
2769    diagnostics.count_n("select.sector_disagree", select_census.disagree);
2770    diagnostics.count_n("select.ray_casts", select_census.ray_casts);
2771    diagnostics.count_n("select.on_votes", select_census.on_votes);
2772    diagnostics.count_n("select.overturns", select_census.overturns);
2773    if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
2774        sector::sector_census_line(|| {
2775            format!(
2776                "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
2777                selected.len(),
2778                select_census.eligible,
2779                select_census.sector_primary,
2780                select_census.sector_fallback,
2781                select_census.disagree,
2782                select_census.ray_casts,
2783                select_census.on_votes,
2784                select_census.overturns
2785            )
2786        });
2787    }
2788    // LEGITIMATE-EMPTY RESULTS: an intersect of DISJOINT operands (or a
2789    // subtract whose left operand is entirely CONSUMED by the right) selects
2790    // zero fragments, and assembly used to refuse with "operation produced no
2791    // boundary faces" — 384 of the 474 post-wrapped-band pool errors were
2792    // this, not bugs. Empty is only blessed on TWO independent proofs:
2793    //   (a) the imprint recorded NO section evidence (no accepted pierce
2794    //       seed, no traced SSI branch, no minted piece) — a silently-lost
2795    //       section (the trial-489 class) always leaves upstream evidence
2796    //       even when every downstream sub-segment is clipped away, while
2797    //       pure material disjointness leaves none (verified: 489's
2798    //       recreated silent-miss state keeps erroring; per-face surface
2799    //       samples ALONE missed its 235 mm³ pocket, which is why (a) is
2800    //       required and sampling alone was rejected);
2801    //   (b) the operands' surface samples agree (every fragment test point
2802    //       classified against the other solid):
2803    //       intersect — no sample of either operand strictly inside the
2804    //       other; subtract — no left-operand sample strictly outside the
2805    //       right.
2806    // Contact/graze pairs (evidence exists, material still disjoint) stay
2807    // errors — conservative by design. Escape hatch: BREP_EMPTY_BOOLEAN=0
2808    // restores the unconditional error.
2809    if selected.is_empty()
2810        && !imprint.section_evidence
2811        && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
2812    {
2813        let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2814            for &sample in samples {
2815                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
2816                    return Ok(true);
2817                }
2818            }
2819            Ok(false)
2820        };
2821        let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2822            for &sample in samples {
2823                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
2824                    return Ok(true);
2825                }
2826            }
2827            Ok(false)
2828        };
2829        let legitimate = match operation {
2830            BooleanOperation::Intersect => {
2831                !strictly_inside(&a_surface_samples, second)?
2832                    && !strictly_inside(&b_surface_samples, first)?
2833            }
2834            BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
2835            BooleanOperation::Union => false,
2836        };
2837        if legitimate {
2838            diagnostics.event(
2839                DiagnosticSeverity::Info,
2840                KernelStage::Select,
2841                "boolean.empty_result",
2842                format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2843            );
2844            fit_scope.close().report_into(&mut diagnostics);
2845            polyline_scope.close().report_into(&mut diagnostics);
2846            diagnostics.measure_max(
2847                "timing.total_ms",
2848                operation_started.elapsed().as_secs_f64() * 1_000.0,
2849            );
2850            return Ok((
2851                KernelOutcome {
2852                    value: empty_solid(),
2853                    diagnostics,
2854                },
2855                None,
2856            ));
2857        }
2858    }
2859    let solids = [(0, &split_first), (1, &split_second)]
2860        .into_iter()
2861        .collect::<HashMap<_, _>>();
2862    let dump = BooleanStageDump::open();
2863    if let Some(dump) = &dump {
2864        dump.write("first", &split_first);
2865        dump.write("second", &split_second);
2866        dump.write("selected", &selected);
2867    }
2868    let stage_started = Instant::now();
2869    // Result face `k` is minted from `selected[k - 1]` (one face per fragment,
2870    // ids from 1 in order): the map the tangent-section attribution reads a
2871    // refusal's face ids through.
2872    let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
2873        Vec::new()
2874    } else {
2875        selected
2876            .iter()
2877            .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
2878            .collect()
2879    };
2880    // A record the grazing-pierce path minted (`TangentSectionRecord::
2881    // grazing` non-empty, whether or not the lane then found a contact to
2882    // name) yields to a tangent NODE the imprint classified: the node is the
2883    // nearer cause and `attribute_to_tangent_node` names it on the way out
2884    // (the G1 elbow over its own-radius arm: the arm's cap circle also
2885    // pierces the elbow under the seed gate, and the lane sees the join).
2886    let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
2887        .tangent_sections
2888        .iter()
2889        .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
2890        .cloned()
2891        .collect();
2892    let attribute = |error: KernelRefusal| {
2893        attribute_to_tangent_section(error, &attributable, &assembled_origins)
2894    };
2895    let cellular_result = matches!(operation, BooleanOperation::Union)
2896        && cellular::enabled(options)
2897        && cellular::complete_contact(first, second, &selected, tolerance);
2898    let (solid, scope) = if cellular_result {
2899        (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
2900            .map_err(attribute)?, None)
2901    } else if untouched_passthrough(options) {
2902        assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
2903            .map_err(attribute)?
2904    } else {
2905        (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
2906    };
2907    if let Some(scope) = &scope {
2908        diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
2909    }
2910    if let Some(dump) = &dump {
2911        dump.write("assembled", &solid);
2912    }
2913    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2914    profile_stage("assemble_ms", stage_ms);
2915    diagnostics.measure_max("timing.assemble_ms", stage_ms);
2916    let stage_started = Instant::now();
2917    let declines_before = crate::face_merge::declines_served();
2918    if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
2919        let issues = solid.validate();
2920        eprintln!(
2921            "pre-merge validation: {} issue(s){}",
2922            issues.len(),
2923            issues
2924                .first()
2925                .map(|issue| format!(" — first: {}", issue.message))
2926                .unwrap_or_default()
2927        );
2928    }
2929    let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
2930        && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2931    {
2932        let merged = match &scope {
2933            // Every pair merges as before (an operand's own coplanar
2934            // neighbours included); the closing validation reads the
2935            // examined faces and the merged ones.
2936            Some(scope) => merge_same_surface_faces_scoped(
2937                &solid,
2938                tolerance,
2939                &options.keep_unmerged_name_substrs,
2940                &scope.examined,
2941            )?,
2942            None => merge_same_surface_faces_excluding(
2943                &solid,
2944                tolerance,
2945                &options.keep_unmerged_name_substrs,
2946            )?,
2947        };
2948        // Face merging can make previously separate collinear boundary
2949        // segments incident to the same pair of faces. Run continuation
2950        // cleanup again, matching the post-merge normalization performed by
2951        // the former assembly pipeline.
2952        merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?
2953    } else {
2954        solid
2955    };
2956    if let Some(dump) = &dump {
2957        dump.write("merged", &solid);
2958    }
2959    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2960    profile_stage("face_merge_ms", stage_ms);
2961    if crate::profile::profile_enabled() {
2962        profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
2963    }
2964    diagnostics.measure_max("timing.face_merge_ms", stage_ms);
2965    let validation_started = Instant::now();
2966    let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
2967    profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
2968    diagnostics.count_n("validate.issues", validation.issues.len() as u64);
2969    diagnostics.count_n(
2970        "validate.wire_warnings",
2971        validation.wire_warnings.len() as u64,
2972    );
2973    diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
2974    for warning in &validation.wire_warnings {
2975        diagnostics.event(
2976            DiagnosticSeverity::Warning,
2977            KernelStage::Validate,
2978            "validate.uv_wire",
2979            warning.message.clone(),
2980        );
2981    }
2982    for issue in &validation.issues {
2983        diagnostics.event(
2984            DiagnosticSeverity::Error,
2985            KernelStage::Validate,
2986            "validate.brep",
2987            issue.message.clone(),
2988        );
2989    }
2990    fit_scope.close().report_into(&mut diagnostics);
2991    polyline_scope.close().report_into(&mut diagnostics);
2992    diagnostics.measure_max(
2993        "timing.total_ms",
2994        operation_started.elapsed().as_secs_f64() * 1_000.0,
2995    );
2996    if !validation.issues.is_empty() {
2997        return Err(KernelRefusal::new(
2998            RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2999            KernelStage::Validate,
3000            format!(
3001            "boolean_operation: invalid result: {:?}",
3002            validation.issues
3003        )));
3004    }
3005    // Optional semantic oracle (off by default, no perf hit): under
3006    // BREP_DEBUG_BOOL, cross-check the well-formed result against the CSG
3007    // point-membership expectation and scan for residual coincident-but-unwelded
3008    // geometry. Purely diagnostic and NON-rejecting — a statistical check must
3009    // never fail a valid op (see oracle.rs) — so it only ever warns.
3010    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3011        if let Ok(report) =
3012            crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
3013        {
3014            if report.is_flagged() {
3015                eprintln!(
3016                    "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
3017                    report.disagreement_rate,
3018                    report.disagreements.len(),
3019                    report.considered,
3020                    report.sample_disagreement()
3021                );
3022            }
3023        }
3024        let fusable_band = crate::tolerance::assembler_weld(policy.model);
3025        let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
3026        if !fusables.is_empty() {
3027            eprintln!(
3028                "[oracle] {} residual fusable(s) after weld; sample {:?}",
3029                fusables.len(),
3030                fusables.first()
3031            );
3032        }
3033    }
3034    let candidates = scope.as_ref().map(|scope| {
3035        let candidates = soundness_candidates(
3036            &solid,
3037            scope,
3038            [operand_bounds(first), operand_bounds(second)],
3039            policy.sew_search,
3040        );
3041        diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
3042        crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
3043        candidates
3044    });
3045    Ok((
3046        KernelOutcome {
3047            value: solid,
3048            diagnostics,
3049        },
3050        candidates,
3051    ))
3052}
3053