Skip to main content

brep_boolean/csg/boolean/
mod.rs

1pub mod profile;
2pub use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4pub use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5pub use crate::imprint::{
6    EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7    ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10pub use crate::topology::{
11    adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12    ShellRecord, VertexRecord,
13};
14pub use crate::{
15    KernelRefusal, OrRefuse, RefusalClass,
16    apply_edge_splits, apply_edge_splits_with_map, build_imprints, build_pcurve_on_surface,
17    build_pcurve_on_surface_range, classify_surface_pair,
18    fragment_solid, interpolate_curve, merge_curve_continuation_edges,
19    merge_same_surface_faces_excluding, merge_same_surface_faces_scoped,
20    project_point_to_curve, project_point_to_surface, solid_signed_volume, solid_signed_volume_for_sign, AffineTransform,
21    DiagnosticSeverity, KernelDiagnostics, KernelOutcome, KernelStage, KernelTolerances, NurbsCurve,
22    PointClass, SolidClassifier, SurfacePairRelation, Vec3,
23};
24pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26pub use web_time::Instant;
27
28thread_local! {
29    /// Running count (per thread) of one-use edges the EDGE-CONFORMANCE
30    /// repair lanes merged or bridged.  The lanes only fire on an assembly
31    /// that would otherwise refuse, so a zero delta across an operation is
32    /// an honest witness that the boolean assembled cleanly without the
33    /// repair.  Test-observable; not part of any result.
34    pub static CONFORMANCE_REPAIRS: std::cell::Cell<u64> =
35        const { std::cell::Cell::new(0) };
36}
37
38#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum BooleanOperation {
41    Union,
42    Intersect,
43    Subtract,
44}
45
46#[derive(Clone, Debug, Deserialize)]
47pub struct BooleanOptions {
48    #[serde(default = "default_tolerance")]
49    pub tolerance: f64,
50    /// Optional complete accuracy/search policy.  `tolerance` remains the
51    /// backwards-compatible model-identity shorthand when this is absent.
52    #[serde(default)]
53    pub tolerances: Option<KernelTolerances>,
54    #[serde(default)]
55    pub imprint: ImprintOptions,
56    /// Coalesce adjacent result fragments after assembly. This defaults to
57    /// true to preserve the kernel's normal clean-boundary behavior.
58    #[serde(default = "default_true")]
59    pub merge_coplanar_faces: bool,
60    /// Face-name substrings that PIN a result face out of the coplanar/cosurface
61    /// merge (only consulted when [`Self::merge_coplanar_faces`] is on). A face whose
62    /// `name` CONTAINS any of these is emitted unchanged instead of being
63    /// coalesced with a mergeable neighbour; faces matching none merge exactly as
64    /// before. Default empty — no caller sees a behavior change unless it opts
65    /// in. Sheet metal uses this to keep every thickness/side wall face per
66    /// outline segment in the folded solid (so a flange can still attach to a
67    /// specific segment: fusing two collinear thickness faces would erase the
68    /// segment boundary).
69    #[serde(default)]
70    pub keep_unmerged_name_substrs: Vec<String>,
71    /// On by default since the 2026-10-10 census read the 94-case manifest
72    /// unchanged with it; `BREP_UNTOUCHED_PASSTHROUGH` overrides either way
73    /// (`0` off, anything else on).
74    #[serde(default = "default_true")]
75    pub untouched_passthrough: bool,
76    /// On by default since the 2026-10-10 census;
77    /// `BREP_DISJOINT_FAST_PATH` overrides either way (`0` off, anything
78    /// else on).
79    #[serde(default = "default_true")]
80    pub disjoint_fast_path: bool,
81    /// Lane X row 12: when, in at least two axes, one operand's control-net
82    /// box ends at or before the other's begins (exactly, no band), the
83    /// operands can share no interior and touch on a line or at a point: the
84    /// disjoint path's answers hold. Every control weight must be positive
85    /// (the hull property), both operands plain solids, and the caller must
86    /// say what follows (`seam_reseat_later_references` is `Some`), so a
87    /// caller that cannot keeps today's ids. On by default since the row 12
88    /// census; `BREP_CONTACT_FAST_PATH` overrides either way (`0` off,
89    /// anything else on).
90    #[serde(default = "default_true")]
91    pub contact_fast_path: bool,
92    /// OFF by default: the 94-case census read unchanged with it, but the
93    /// kernel battery's `offset_subtract_fixture` pins a result whose
94    /// untouched planar face carries an open trim joint of 8.7e-4 from its
95    /// coarse polyline operand, which the whole-solid joints pass closes and
96    /// the scoped pass leaves as the operand had it; and the row buys no
97    /// measurable time (the record of 2026-10-10). `BREP_TOUCHED_ASSEMBLY`
98    /// overrides either way (`0` off, anything else on).
99    #[serde(default)]
100    pub touched_assembly: bool,
101    /// On by default since the 2026-10-11 census (the whole kernel battery,
102    /// the 94-case manifest and `hlr_tests` green with it on, every manifest
103    /// fragment the sector decides agreeing with the ray cast);
104    /// `BREP_SECTOR_CLASS` overrides either way (`0`/`off` the escape hatch,
105    /// `check` for the differential run that logs disagreements to
106    /// `BREP_SECTOR_CENSUS`, anything else on). Appended at the end of the
107    /// struct (2026-10-11).
108    #[serde(default = "default_true")]
109    pub sector_classification: bool,
110    /// Non-manifold plan 1.6: trim a declared Sheet by a Solid with Intersect.
111    /// On after the 2026-10-14 Sheet census and whole-kernel qualification.
112    /// BREP_SHEET_TRIM overrides this option (1 enables, 0 disables).
113    #[serde(default = "default_true")]
114    pub sheet_trim: bool,
115    /// Preserve the closed operand regions at a lower-dimensional union
116    /// contact as explicit cells. Opt-in pending the Cellular census.
117    /// BREP_KEEP_CELLS overrides this option (1 enables, 0 disables).
118    #[serde(default)]
119    pub keep_cells: bool,
120    /// The references later features hold (their `inputParams` text), when
121    /// the caller knows them: `Some` admits the operand seam re-seat
122    /// (`BREP_SEAM_RESEAT`, lane X row 11b) for every cylinder wall none of
123    /// them names; `None` (the caller cannot tell) never re-seats.
124    #[serde(default)]
125    pub seam_reseat_later_references: Option<Vec<String>>,
126    /// The references later features hold, as for
127    /// [`Self::seam_reseat_later_references`]: `Some` admits the seam rejoin
128    /// (`BREP_FACE_MERGE_RESEAM`), which joins two pieces of one cylinder or
129    /// frustum split only along the carrier's seam, unless a reference that
130    /// names something on the body as merged would name something else, or
131    /// nothing, on the joined one; `None` never rejoins.
132    #[serde(default)]
133    pub seam_rejoin_later_references: Option<Vec<String>>,
134}
135
136thread_local! {
137    static WITHOUT_PERTURBATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
138}
139
140/// Runs `action` with this thread's booleans refusing a degenerate exact
141/// arrangement where they would retry it on rigidly perturbed operands (the
142/// perturbation ladder, the last resort after the exact recoveries, which
143/// still run): for a caller with a fallback of its own (another layout of the
144/// same cut), which comes back with the ladder only where every fallback
145/// refused.
146pub fn without_perturbation<T>(action: impl FnOnce() -> T) -> T {
147    struct Restore(bool);
148    impl Drop for Restore {
149        fn drop(&mut self) {
150            WITHOUT_PERTURBATION.with(|cell| cell.set(self.0));
151        }
152    }
153    let _restore = Restore(WITHOUT_PERTURBATION.with(|cell| cell.replace(true)));
154    action()
155}
156
157/// [`BooleanOptions::touched_assembly`] under its environment override.
158fn touched_assembly(options: &BooleanOptions) -> bool {
159    match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
160        Ok("0") => false,
161        Ok(_) => true,
162        Err(_) => options.touched_assembly,
163    }
164}
165
166/// [`BooleanOptions::disjoint_fast_path`] under its environment override.
167fn disjoint_fast_path(options: &BooleanOptions) -> bool {
168    match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
169        Ok("0") => false,
170        Ok(_) => true,
171        Err(_) => options.disjoint_fast_path,
172    }
173}
174
175/// [`BooleanOptions::contact_fast_path`] under its environment override.
176fn contact_fast_path(options: &BooleanOptions) -> bool {
177    match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
178        Ok("0") => false,
179        Ok(_) => true,
180        Err(_) => options.contact_fast_path,
181    }
182}
183
184/// [`BooleanOptions::untouched_passthrough`] under its environment override.
185fn untouched_passthrough(options: &BooleanOptions) -> bool {
186    match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
187        Ok("0") => false,
188        Ok(_) => true,
189        Err(_) => options.untouched_passthrough,
190    }
191}
192
193fn default_tolerance() -> f64 {
194    1e-7
195}
196
197fn default_true() -> bool {
198    true
199}
200
201impl Default for BooleanOptions {
202    fn default() -> Self {
203        Self {
204            tolerance: default_tolerance(),
205            tolerances: None,
206            imprint: ImprintOptions::default(),
207            merge_coplanar_faces: true,
208            keep_unmerged_name_substrs: Vec::new(),
209            untouched_passthrough: true,
210            disjoint_fast_path: true,
211            contact_fast_path: true,
212            touched_assembly: false,
213            sector_classification: true,
214            sheet_trim: true,
215            keep_cells: false,
216            seam_reseat_later_references: None,
217            seam_rejoin_later_references: None,
218        }
219    }
220}
221
222mod select;
223mod sheet;
224mod cellular;
225pub mod sector;
226pub mod assemble;
227mod operand_state;
228mod rim;
229mod coincident;
230mod touch;
231pub(crate) mod reseat;
232mod ball_align;
233mod rejoin;
234mod window_retry;
235mod isotropic_chart;
236mod dedicated;
237pub use dedicated::{register_dedicated_boolean, DedicatedBoolean};
238
239pub use rim::*;
240use select::*;
241use coincident::*;
242use touch::TouchCensus;
243pub use assemble::{
244    assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
245    clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
246};
247use assemble::{assemble_fragments_scoped, AssemblyScope};
248// Currently referenced only inside `assemble`, so the re-export is unused.
249#[allow(unused_imports)]
250pub use assemble::apply_assembly_heal_chain;
251
252
253/// A boolean's operands at the working scale (`brep/rescale.rs`): unless `BREP_WORKING_SCALE=0`, operands whose combined box diagonal
254/// is below 1/16 are scaled up by a power of two, and the result is scaled back.
255/// Under `BREP_LARGE_WORKING_SCALE`, a refused large operation also tries a
256/// smaller working scale. Its successful original result always takes precedence.
257struct WorkingScale {
258    factor: f64,
259    solids: Vec<BrepSolid>,
260    options: BooleanOptions,
261}
262
263thread_local! {
264    // The original attempt includes its nested boolean calls. Only after it
265    // refuses do we try the large-model working scale; unwind restores it.
266    static ORIGINAL_WORKING_SCALE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
267}
268
269impl WorkingScale {
270    fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
271        let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
272            return Ok(None);
273        };
274        let Some(factor) = crate::rescale::guard_factor(bounds).or_else(|| {
275            if ORIGINAL_WORKING_SCALE.with(|state| state.get()) { None }
276            else { crate::rescale::large_guard_factor(bounds) }
277        }) else {
278            return Ok(None);
279        };
280        crate::rescale::profile_fired("boolean", factor, bounds);
281        let solids = operands
282            .iter()
283            .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
284            .collect::<Result<Vec<_>, _>>()?;
285        // The one length the options carry in model units.
286        let mut options = options.clone();
287        options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
288        Ok(Some(Self { factor, solids, options }))
289    }
290
291    /// Retain the original successful result bit for bit. A failed fallback
292    /// retains the original refusal too, rather than replacing its evidence.
293    fn run<T>(
294        &self,
295        original: impl FnOnce() -> Result<T, KernelRefusal>,
296        scaled: impl FnOnce() -> Result<T, KernelRefusal>,
297    ) -> Result<T, KernelRefusal> {
298        if self.factor >= 1.0 { return scaled(); }
299        struct Restore(bool);
300        impl Drop for Restore {
301            fn drop(&mut self) { ORIGINAL_WORKING_SCALE.with(|state| state.set(self.0)); }
302        }
303        let answer = {
304            let _restore = Restore(ORIGINAL_WORKING_SCALE.with(|state| state.replace(true)));
305            original()
306        };
307        match answer {
308            Ok(value) => Ok(value),
309            Err(original) => scaled().or(Err(original)),
310        }
311    }
312
313    fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
314        crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
315    }
316
317    fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
318        crate::rescale::name_scale(error, self.factor)
319    }
320}
321
322pub fn boolean_operation(
323    first: &BrepSolid,
324    second: &BrepSolid,
325    operation: BooleanOperation,
326    options: &BooleanOptions,
327) -> Result<BrepSolid, KernelRefusal> {
328    // A dedicated route that recognises both operands answers for them; where
329    // it refuses, the general boolean below still runs.
330    if let Some(Ok(solid)) = dedicated::dedicated(first, second, operation) {
331        return Ok(solid);
332    }
333    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
334        return scaled.run(
335            || boolean_operation(first, second, operation, options),
336            || boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
337                .map_err(|error| scaled.refusal(error))
338                .and_then(|solid| scaled.back(&solid)),
339        );
340    }
341    // Inside the isotropic-chart attempt (`isotropic_chart.rs`) the window
342    // retry is not run: that attempt is itself a retry, cheap or refused.
343    if isotropic_chart::active() {
344        return boolean_operation_unscaled(first, second, operation, options);
345    }
346    boolean_operation_unscaled(first, second, operation, options).or_else(|refused| {
347        // The isotropic-chart attempt was made on the first refusal; the
348        // window retry's own attempts do not repeat it.
349        isotropic_chart::suppressed(|| window_retry::retry(first, second, operation, options, refused, boolean_operation_unscaled))
350    })
351}
352
353/// [`boolean_operation`] on operands already at their working scale.
354fn boolean_operation_unscaled(
355    first: &BrepSolid,
356    second: &BrepSolid,
357    operation: BooleanOperation,
358    options: &BooleanOptions,
359) -> Result<BrepSolid, KernelRefusal> {
360    match boolean_operation_with_diagnostics(first, second, operation, options) {
361        Ok(outcome) => {
362            // An empty difference or common part of two solids whose faces only
363            // nearly coincide is the near pair read as one, not the answer.
364            if below_tolerance_refusal_enabled()
365                && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
366                && !matches!(operation, BooleanOperation::Union)
367            {
368                if let Some(refusal) = below_tolerance_refusal(first, second, None) {
369                    if let Some(answer) = below_tolerance_answer(first, second, operation) {
370                        return Ok(answer);
371                    }
372                    if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
373                        return Ok(answer);
374                    }
375                    return Err(refusal);
376                }
377            }
378            if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
379                if let Some(refusal) = unresolved_merge_refusal(first, second) {
380                    return Err(refusal);
381                }
382            }
383            // A union or common part the exact lane did write over a near pair
384            // welds the slivers between the pair partly; the inclusion is exact.
385            if below_tolerance_slivers_enabled()
386                && !matches!(operation, BooleanOperation::Subtract)
387                && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
388                && near_coincident_planar_faces(first, second).is_some()
389            {
390                if let Some(answer) = below_tolerance_answer(first, second, operation) {
391                    return Ok(answer);
392                }
393            }
394            Ok(outcome.value)
395        }
396        Err(error) => {
397            if below_tolerance_refusal_enabled() {
398                if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
399                    if let Some(answer) = below_tolerance_answer(first, second, operation) {
400                        return Ok(answer);
401                    }
402                    if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
403                        return Ok(answer);
404                    }
405                    return Err(refusal);
406                }
407            }
408            // `BREP_BOOLEAN_ISOTROPIC_CHART` (default on since 2026-11-28; `=0` off): a refusal on operands
409            // whose face charts are far from isotropic is retried FIRST with those
410            // charts rescaled (an exact reparametrisation, `isotropic_chart.rs`),
411            // ahead of the perturbation and window ladders, which on the benchy's
412            // port cut spent 71 s failing before it. A boolean that builds is
413            // never re-run; a rescaled attempt that refuses (it runs without the
414            // perturbation and window retries) leaves this refusal to the
415            // ladders below exactly as before.
416            if isotropic_chart::isotropic_chart_on() && !isotropic_chart::active() && !isotropic_chart::is_suppressed() {
417                let (a, b) = (isotropic_chart::isotropic(first), isotropic_chart::isotropic(second));
418                if a.is_some() || b.is_some() {
419                    let (a, b) = (a.as_ref().unwrap_or(first), b.as_ref().unwrap_or(second));
420                    match isotropic_chart::with_active(|| boolean_operation(a, b, operation, options)) {
421                        Ok(result) => match isotropic_chart_identity(first, second, a, b, operation, options, &result) {
422                            Ok(()) => return Ok(result),
423                            Err(why) => {
424                                if std::env::var("BREP_DEBUG_BOOL").is_ok() {
425                                    eprintln!("isotropic chart: the rescaled boolean is not admitted ({why}); on to the perturbation ladder");
426                                }
427                            }
428                        },
429                        Err(second_refusal) => {
430                            if std::env::var("BREP_DEBUG_BOOL").is_ok() {
431                                eprintln!("isotropic chart: the rescaled boolean refused too ({second_refusal}); on to the perturbation ladder");
432                            }
433                        }
434                    }
435                }
436            }
437            // Inside the isotropic-chart attempt the perturbation ladder is not
438            // run (the outer refusal reaches it if the attempt refuses).
439            if isotropic_chart::active() {
440                return Err(error);
441            }
442            // Perturbation-fallback lane (Simulation of Simplicity). The exact
443            // arrangement only errs on a DEGENERACY here (coincident /
444            // near-tangent carrier faces make it structurally inconsistent) —
445            // e.g. a partial torus whose equatorial circles lie exactly in a box
446            // face. Retry once on a rigidly perturbed second operand; accept only
447            // an oracle-clean, volume-consistent result. See
448            // `perturbation_retry`.
449            if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
450                || !error.class.perturbation_eligible()
451            {
452                return Err(error);
453            }
454            // OPERAND-CONSISTENCY GATE. A rigid nudge lifts a coincidence
455            // BETWEEN the operands; it cannot reconcile an operand with
456            // itself. A planar face whose straight boundary sits farther off
457            // its plane than the assembly weld — the shape the STEP importer's
458            // planar split repairs, so it reaches here only on a body built
459            // some other way — fails the exact arrangement for every rung
460            // alike: the 2026-09-12 mesh-import report paid twenty ~7 s rungs
461            // for one 3.4e-3 gap before the import split existed. Name the
462            // gap and stop. The predicate is deliberately the splitter's own,
463            // not a pcurve-error band: vendor bodies whose fitted edges stand
464            // a few 1e-4 off curved faces are legitimate input (per-entity
465            // tolerances) and keep every rung.
466            // OPERAND-CLOSURE GATE. A boolean of a body that is not a closed
467            // shell has no solid answer, exact or nudged: its inside is not
468            // defined, and its volume depends on the reference point. The
469            // slimmed fuzz fixtures (13, 14 and 15, operand A cut from a larger
470            // part by a box filter) carry 54, 97 and 66 edges that bound one
471            // face; every one of their 20 rungs refused on the exact lane, and
472            // 15's identity was read from an intersection with the open shell.
473            // Only consulted on the failure path, so nothing that succeeds
474            // today changes. Escape hatch: BREP_OPEN_OPERAND_GATE=0.
475            if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
476                if let Some((operand, open)) = [first, second]
477                    .iter()
478                    .enumerate()
479                    .find_map(|(operand, solid)| {
480                        let open = one_use_edges(solid);
481                        (open > 0).then_some((operand, open))
482                    })
483                {
484                    return Err(error.with_message(|message| format!(
485                        "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
486                         only one face, so no boolean of it encloses a solid and no perturbation \
487                         can close it"
488                    )));
489                }
490            }
491            if let Some((operand, face_id, deviation, weld)) =
492                planar_operand_off_its_plane(first, second, options)
493            {
494                return Err(error.with_message(|message| format!(
495                    "{message}; operand {operand} face {face_id} is a plane whose straight \
496                     boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
497                     no perturbation can reconcile — the body's planes must contain their \
498                     boundary before it can take part in an exact boolean"
499                )));
500            }
501            // INTERNAL-TANGENCY PINCH GATE. Perturbation is only legitimate
502            // where the exact arrangement is UNSTABLE but its ANSWER is not:
503            // the nearby transversal case must carry the same topology the
504            // degenerate one does. An internal tangency in a DIFFERENCE breaks
505            // exactly that premise — the exact `A − B` pinches to zero
506            // thickness along the contact, so an epsilon either tears the wall
507            // open (a through-slot where the exact answer has intact material)
508            // or leaves a sub-micron web. Both are within epsilon in Hausdorff
509            // distance and in volume, so neither the oracle (boundary skip
510            // band) nor the 1% CSG volume bound can see them, and the lane
511            // would ship the tolerant-kernel sliver this kernel refuses. Only
512            // consulted on the failure path, so nothing that succeeds today can
513            // change; the honest exact-path error is returned instead.
514            // Escape hatch for tamper-verification: BREP_PINCH_GATE=0.
515            if matches!(operation, BooleanOperation::Subtract)
516                && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
517                && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
518                    .unwrap_or(false)
519            {
520                // The exact answer exists where the contact only touches: see
521                // `subtract_through_the_common_part`. Not a perturbation.
522                if let Some(solid) = subtract_through_the_common_part(first, second, options) {
523                    return Ok(solid);
524                }
525                return Err(error.with_message(|message| format!(
526                    "{message}; internal tangency: the operands touch tangentially with \
527                     co-directed normals, so the exact difference pinches to zero thickness \
528                     (non-manifold, unrepresentable in a boundary model) — refusing rather \
529                     than returning a perturbed sliver"
530                )));
531            }
532            // TANGENT-NODE GATE, same doctrine as the pinch gate above and for
533            // the same reason. A 4-valent tangent node is refused because the
534            // kernel cannot imprint it, and perturbation is only legitimate
535            // where the exact arrangement is UNSTABLE but its ANSWER is not:
536            // the nudged configuration resolves the kiss one way or the other
537            // and the kernel has no claim on which. Until 2026-09-13 the ladder
538            // could not produce a candidate here at all; with `fit_polyline`
539            // measuring its own result the equal-radius torus pair's LAST rung
540            // (3.0e-3 of scale) assembles, validates, and passes the semantic
541            // oracle at 399 samples with a zero disagreement rate, reading
542            // 299.4998500 against the ideal union's 299.6 — a 0.03% error that
543            // is the nudge's, not the kernel's answer. Shipping that would
544            // answer a question this class exists to decline, so the class does
545            // not take the ladder. Escape hatch for measuring it:
546            // BREP_TANGENT_NODE_GATE=0.
547            if matches!(error.class, RefusalClass::TangentNodeSingularity)
548                && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
549            {
550                return Err(error);
551            }
552            // The union of two bodies tangent inside one another has an exact
553            // answer the arrangement of the difference reaches: see
554            // `union_through_the_difference`. Not a perturbation.
555            if matches!(operation, BooleanOperation::Union) {
556                if let Some(solid) = union_through_the_difference(first, second, options) {
557                    return Ok(solid);
558                }
559            }
560            // The ladder itself: not under `without_perturbation`.
561            if WITHOUT_PERTURBATION.with(|cell| cell.get()) {
562                return Err(error);
563            }
564            match perturbation_retry(first, second, operation, options) {
565                Ok(solid) => Ok(solid),
566                Err(refused) if refused.is_empty() => Err(error),
567                Err(refused) => {
568                    Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
569                }
570            }
571        }
572    }
573}
574
575/// Grid resolution (per parameter direction, endpoints included) used to probe a
576/// face pair for a tangential contact. Endpoints and the midpoint are both
577/// sampled, so a contact sitting on a periodic seam (a cylinder's `u = 0`
578/// ruling) and one sitting at a face's parametric centre are both hit exactly.
579const PINCH_PROBE_STEPS: usize = 8;
580
581/// `|n_a × n_b|` bound below which two unit normals count as parallel — the same
582/// bound `csg::imprint`'s pair classifier uses (`PAIR_ANGULAR_TOLERANCE`).
583const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
584
585/// Parameter-space step (fraction of the domain span) taken around a contact
586/// sample to prove the contact is LOWER-DIMENSIONAL — a tangency curve/point
587/// rather than a cosurface patch.
588const PINCH_SEPARATION_STEP: f64 = 1e-2;
589
590/// `first − second` as `first − (first ∩ second)`, on the exact lane only, for a
591/// difference the pinch gate is about to refuse (`BREP_PINCH_COMMON_RETRY`,
592/// default on; `=0` leaves the refusal).
593///
594/// The two are the same set, and the second form is often the arrangement the
595/// exact lane can build where the first is not. A cylinder cut by a smaller one
596/// tangent to it inside along a ruling, the cutter running on past both caps
597/// (a crescent; brep-bench probe 2026-11-12): each cap's section circle is
598/// tangent to the cap's own rim, the cap's loops do not close, and the cut
599/// refused; with the cutter flush with the caps it built, exact. The common part
600/// IS the cutter made flush, it is built without trouble (it has no thin wall),
601/// and cutting it away meets the first operand only in faces they share.
602///
603/// Nothing is nudged, so the pinch gate's reason for refusing a PERTURBED
604/// answer does not apply; what is accepted is an exact-lane body that validates
605/// and whose volume is `V(first) − V(first ∩ second)` to the drift bar. Any
606/// other outcome returns `None` and the gate's refusal stands.
607fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
608    // With the tangent imprint switched off the caller has asked for the
609    // recorded-only lane, whose answer to a pinch is its refusal.
610    if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
611        return None;
612    }
613    let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
614    if common.shells.iter().all(|shell| shell.faces.is_empty()) {
615        return None;
616    }
617    let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
618    if !cut.validate().is_empty() {
619        return None;
620    }
621    let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
622    let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
623    ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
624}
625
626/// `first ∪ second` as `second ∪ (first − second)`, on the exact lane only, for
627/// a union that failed where the operands touch tangentially with co-directed
628/// normals (`BREP_TANGENT_UNION_DIFFERENCE_RETRY`, default on; `=0` leaves the
629/// union to the paths it had).
630///
631/// The two are the same set. A cylinder holding a smaller one tangent to it
632/// inside along a ruling, the smaller running on past a cap: the union's
633/// arrangement leaves the cap's section circle tangent to the cap's own rim and
634/// the shell does not close, while the difference builds (the crescent) and the
635/// smaller body joins it along faces the two share. Accepted only when it
636/// validates and its volume is `V(first − second) + V(second)` to the drift bar;
637/// any other outcome returns `None` and the union goes on as before.
638fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
639    if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
640        return None;
641    }
642    let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
643    if !pinches(first, second) && !pinches(second, first) {
644        return None;
645    }
646    let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
647        Ok(outcome) => outcome.value,
648        Err(_) => subtract_through_the_common_part(first, second, options)?,
649    };
650    if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
651        return None;
652    }
653    let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
654    if !union.validate().is_empty() {
655        return None;
656    }
657    let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
658    let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
659    ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
660}
661
662/// Would the exact `first − second` PINCH to zero thickness at a tangential
663/// contact?
664///
665/// True when some face of `first` and some face of `second` touch tangentially
666/// (surfaces within the contact band, normals parallel) with CO-DIRECTED outward
667/// normals, at a contact that is lower-dimensional (the surfaces separate as you
668/// step away from it).
669///
670/// Co-directed outward normals at a tangency mean one solid lies locally INSIDE
671/// the other: subtracting leaves material on both sides of the contact that
672/// meets there at zero thickness — a non-manifold pinch no boundary model can
673/// represent. Anti-directed normals are the harmless EXTERNAL tangency (a
674/// cylinder resting against a wall): the difference simply keeps `first` intact.
675/// The lower-dimensionality requirement excludes a CO-SURFACE contact (a pocket
676/// wall flush with an outer wall — co-directed normals, but the surfaces stay
677/// coincident in every direction), where the difference is perfectly well
678/// behaved.
679///
680/// Conservative by construction: it only reports a pinch it can actually witness
681/// on the probe grid, and a miss just leaves the perturbation lane to its
682/// existing gates.
683pub fn subtract_pinches_at_internal_tangency(
684    first: &BrepSolid,
685    second: &BrepSolid,
686    tolerance: f64,
687) -> Result<bool, KernelRefusal> {
688    // Same contact band the imprint pair classifier uses for its sampled
689    // "these carriers touch" verdict.
690    let contact = (tolerance * 100.0).max(1e-12);
691    let probes_a = first
692        .shells
693        .iter()
694        .flat_map(|shell| &shell.faces)
695        .map(PinchProbe::of)
696        .collect::<Result<Vec<_>, _>>()?;
697    let probes_b = second
698        .shells
699        .iter()
700        .flat_map(|shell| &shell.faces)
701        .map(PinchProbe::of)
702        .collect::<Result<Vec<_>, _>>()?;
703    for probe_a in &probes_a {
704        for probe_b in &probes_b {
705            // Sampled-hull cull, so the (failure-path-only) cost stays linear in
706            // the faces that actually touch rather than quadratic in every face.
707            // The hull is built from the probe grid, so it can under-cover a
708            // curved carrier between samples: pad it by a percent of the pair's
709            // size before culling. Over-keeping a pair only costs a probe that
710            // finds nothing.
711            let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
712            if probe_a.separation(probe_b) > contact + pad {
713                continue;
714            }
715            // CO-SURFACE contacts are 2-dimensional, not tangencies: two flush
716            // walls (a pocket's side coincident with an outer wall, a cylinder
717            // cap lying in a box face) have co-directed normals wherever the
718            // solids nest, yet the difference there is perfectly well behaved.
719            // Only a LOWER-dimensional contact pinches, so drop the pair the
720            // pair classifier calls cosurface before probing it.
721            if classify_surface_pair(
722                &probe_a.face.surface,
723                &probe_b.face.surface,
724                tolerance,
725                PINCH_ANGULAR_TOLERANCE,
726            ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
727            .relation
728                == SurfacePairRelation::Cosurface
729            {
730                continue;
731            }
732            if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
733                return Ok(true);
734            }
735        }
736    }
737    Ok(false)
738}
739
740/// A face's probe grid plus the grid's bounding box, built once per face so the
741/// pair loop only pays for a hull comparison.
742struct PinchProbe<'a> {
743    face: &'a FaceRecord,
744    /// `(u, v, point)` on the face's carrier surface.
745    samples: Vec<(f64, f64, Vec3)>,
746    minimum: [f64; 3],
747    maximum: [f64; 3],
748}
749
750impl<'a> PinchProbe<'a> {
751    fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
752        let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
753        let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
754        let steps = PINCH_PROBE_STEPS as f64;
755        let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
756        let mut minimum = [f64::INFINITY; 3];
757        let mut maximum = [f64::NEG_INFINITY; 3];
758        for i in 0..=PINCH_PROBE_STEPS {
759            let u = u0 + (u1 - u0) * i as f64 / steps;
760            for j in 0..=PINCH_PROBE_STEPS {
761                let v = v0 + (v1 - v0) * j as f64 / steps;
762                let Ok(point) = face.surface.evaluate(u, v) else {
763                    continue;
764                };
765                for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
766                    minimum[axis] = minimum[axis].min(value);
767                    maximum[axis] = maximum[axis].max(value);
768                }
769                samples.push((u, v, point));
770            }
771        }
772        Ok(Self {
773            face,
774            samples,
775            minimum,
776            maximum,
777        })
778    }
779
780    /// Largest side of the sampled hull (0 when nothing sampled).
781    fn extent(&self) -> f64 {
782        (0..3)
783            .map(|axis| self.maximum[axis] - self.minimum[axis])
784            .fold(0.0f64, f64::max)
785    }
786
787    /// Axis-aligned gap between the two sampled hulls (0 when they overlap).
788    fn separation(&self, other: &Self) -> f64 {
789        let mut gap: f64 = 0.0;
790        for axis in 0..3 {
791            gap = gap.max(self.minimum[axis] - other.maximum[axis]);
792            gap = gap.max(other.minimum[axis] - self.maximum[axis]);
793        }
794        gap
795    }
796}
797
798/// One face pair of [`subtract_pinches_at_internal_tangency`]: probe both
799/// surfaces on a grid, keep samples that land on the other surface inside BOTH
800/// trims with parallel co-directed outward normals, and accept only where the
801/// contact provably separates nearby.
802fn faces_touch_with_codirected_normals(
803    probe_a: &PinchProbe<'_>,
804    probe_b: &PinchProbe<'_>,
805    contact: f64,
806) -> Result<bool, KernelRefusal> {
807    for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
808        let source = probe.face;
809        let target = other.face;
810        for &(u, v, point) in &probe.samples {
811            let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
812            if projection.distance > contact {
813                continue;
814            }
815            // A pole (collapsed du × dv) has no reliable orientation here;
816            // skipping it keeps the predicate conservative.
817            let (Ok(source_normal), Ok(target_normal)) = (
818                source.surface.normal(u, v),
819                target.surface.normal(projection.u, projection.v),
820            ) else {
821                continue;
822            };
823            let source_outward = outward_normal(source_normal, source.same_sense);
824            let target_outward = outward_normal(target_normal, target.same_sense);
825            if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
826                || source_outward.dot(target_outward) <= 0.0
827            {
828                continue;
829            }
830            if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
831                == PolygonClass::Outside
832                || parameter_point_in_face(
833                    target,
834                    Vec2 {
835                        x: projection.u,
836                        y: projection.v,
837                    },
838                    1e-6,
839                ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
840            {
841                continue;
842            }
843            if contact_separates_locally(source, target, u, v, contact)? {
844                return Ok(true);
845            }
846        }
847    }
848    Ok(false)
849}
850
851fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
852    if same_sense {
853        normal
854    } else {
855        normal.scale(-1.0)
856    }
857}
858
859/// Does the contact at `source(u, v)` LEAVE the contact band when you step away
860/// from it in parameter space? A tangency curve or point does (stepping across
861/// the tangency separates the surfaces quadratically); a cosurface patch does
862/// not (it stays coincident in every direction). Steps are clamped into the
863/// domain, so a sample on a seam or a domain edge probes only inward.
864fn contact_separates_locally(
865    source: &FaceRecord,
866    target: &FaceRecord,
867    u: f64,
868    v: f64,
869    contact: f64,
870) -> Result<bool, KernelRefusal> {
871    let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
872    let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
873    let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
874    let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
875    for (probe_u, probe_v) in [
876        ((u + step_u).min(u1), v),
877        ((u - step_u).max(u0), v),
878        (u, (v + step_v).min(v1)),
879        (u, (v - step_v).max(v0)),
880    ] {
881        if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
882            continue;
883        }
884        let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
885            continue;
886        };
887        // A generous multiple of the band: the step must clear it decisively,
888        // never on projection noise.
889        if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
890            return Ok(true);
891        }
892    }
893    Ok(false)
894}
895
896/// Deterministic perturbation-fallback (Simulation of Simplicity), the textbook
897/// CAD answer to an exact/near-tangent arrangement degeneracy, adopted after six
898/// incremental arrangement/imprint/fragment fixes for the near-tangent class were
899/// each falsified, rather than attempting a seventh. Rigidly TRANSLATE the second operand by a tiny
900/// epsilon so the degenerate contact becomes a clean transversal crossing, redo
901/// the boolean, and accept the result ONLY if it is (a) topologically valid —
902/// guaranteed by `assemble`'s own gate returning `Ok` — (b) semantically equal to
903/// the exact CSG of the ORIGINAL operands (the point-classification oracle), and
904/// (c) volume-consistent with the CSG inequality bounds. A wrong perturbed result
905/// is rejected on (b)/(c), so this lane preserves the engine's fail-safe property:
906/// it can only turn a degeneracy-error into a CORRECT solid, never a wrong one.
907///
908/// INVARIANT — no recursion: this calls `boolean_operation_with_diagnostics`
909/// (the EXACT path), never `boolean_operation`, so the fallback can never
910/// re-enter itself. A future refactor must preserve that.
911///
912/// (d) THE IDENTITY. Where the exact lane answers one of the other operations
913/// on the same operands, inclusion–exclusion names the volume this result
914/// must have, and a rung that misses it by more than the case gate's own drift
915/// band (`VOLUME_DRIFT_REL` of that volume, `VOLUME_DRIFT_ABS` floor) is
916/// refused by name. (c)'s 1% of the operands' total cannot see an error in a
917/// small removed volume: on the helmet's cutter − helmet (2026-09-15) the rung
918/// at fraction 3e-4 moved the helmet 5.2e-3, 2.3% of its size, passed the
919/// oracle at 1 in 336, and read 999.999899266 against V(cutter) − V(cutter ∩
920/// helmet) = 999.999905792: 6.9% too much material removed. Where no other
921/// operation clears on the exact lane there is no identity to hold, and the
922/// rung is held to (e) instead. Escape hatch for measuring it:
923/// BREP_PERTURB_IDENTITY=0 (which also lifts (e)).
924///
925/// (e) THE MIRROR. Where no exact-lane boolean of the operands clears in
926/// either order, the rung is held to itself moved the other way: the same
927/// operation, or failing that any sibling reading, on the second operand moved
928/// by −offset, with V(first) and V(second) from the mass integrator and the
929/// operation's sign, names the volume the mirrored rung encloses. A rigid
930/// translation changes the answer to first order in the offset, so half the
931/// difference between the rung's body and its mirror is the body's
932/// first-order translation error, and it must clear the same drift band. A
933/// rung whose mirror clears no boolean at all has nothing to check it and is
934/// refused by name. On 22_sag_boundary_identity_t164 (2026-09-15) the four
935/// shipped rescues at offset 9.7e-4 disagreed with each other through V(∩) by
936/// 4.3e-2 (the difference moves the part; the others move the sphere), against
937/// a bar of 5e-6. Escape hatch: BREP_PERTURB_MIRROR=0.
938///
939/// (d) and (e) run before (b), the oracle, which costs more than either.
940///
941/// (f) THE EARLY EXIT. Along one direction the mirror's error grows with the
942/// offset (`MirrorTrend` states the law and its measurement), so a direction
943/// whose two refused rungs read one sign, growing, is not tried at larger
944/// offsets, and the refusal names it. booleanIssue's refusal walked 20 rungs,
945/// each with its mirror, in 40.5 s against the case's 30 s. Escape hatch:
946/// BREP_MIRROR_EARLY_EXIT=0.
947///
948/// `Err` carries one sentence per rung refused on (d), empty when none was.
949fn perturbation_retry(
950    first: &BrepSolid,
951    second: &BrepSolid,
952    operation: BooleanOperation,
953    options: &BooleanOptions,
954) -> Result<BrepSolid, Vec<String>> {
955    // Generic translation directions: each has a substantial component on ALL
956    // three axes, so whatever axis the coincidence normal lies along (an
957    // equatorial plane flush with a box face, a cap plane flush with a side
958    // face, …) at least one direction has a component that lifts the contact off
959    // exact tangency. Axis-aligned directions are deliberately excluded — a nudge
960    // parallel to the coincident plane leaves the degeneracy in place (verified:
961    // pure ±X / ±Z never rescue the flush-torus case). Fixed, not hash-seeded
962    // as the lane was first sketched: the seeding's only purpose was to rule out
963    // RNG/clock nondeterminism, which fixed vectors already satisfy, and four
964    // diverse directions cover any axis-aligned normal.
965    const DIRECTIONS: [[f64; 3]; 4] = [
966        [0.4034, 0.7973, 0.4491],
967        [0.7973, 0.4491, 0.4034],
968        [0.4491, 0.4034, 0.7973],
969        [0.5774, -0.5774, 0.5774],
970    ];
971    // Fractions of operand scale, ordered SMALLEST-FIRST so the accepted solid
972    // carries the least geometric offset. Sized above the near-tangent sliver
973    // dead zone and below local feature size; the ladder + accept-gate make the
974    // exact magnitude non-critical (a rung that lands in a dead zone simply fails
975    // the gate and the next rung is tried).
976    const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
977
978    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
979    let scale = crate::solid_tolerance::solid_scale(first)
980        .max(crate::solid_tolerance::solid_scale(second))
981        .max(1.0);
982
983    // Original operand volumes for the CSG inequality backstop (the oracle skips
984    // points near boundaries, so a wrong thin shell hugging the flush face is
985    // invisible to it but shows up here).
986    let _caller = crate::mass_caller("boolean.perturbation_rescue");
987    let va = solid_signed_volume(first).ok().map(f64::abs);
988    let vb = solid_signed_volume(second).ok().map(f64::abs);
989    let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
990    // (e) is held only with (d): `BREP_PERTURB_MIRROR=0` alone ships a rung
991    // with no identity on (a)–(c), as before.
992    let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
993    // (f) A direction whose mirror errors say no larger offset can clear is
994    // closed. Escape hatch: `BREP_MIRROR_EARLY_EXIT=0` walks every rung.
995    let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
996    let mut trends = [MirrorTrend::default(); 4];
997    // Measured once, on the first rung that clears (a)–(c).
998    let mut identity: Option<Option<InclusionExclusion>> = None;
999    let mut refused = Vec::new();
1000    // `BREP_DEBUG_PERTURB_LADDER=1`: every rung's disposition on stderr, and
1001    // for every rung that builds, its miss against the identity, measured
1002    // before the ladder starts. Changes no decision.
1003    let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
1004    let ladder_start = web_time::Instant::now();
1005    if ladder {
1006        let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1007        match &measured {
1008            Some(identity) => eprintln!(
1009                "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
1010                identity.formula, identity.expected, identity.reading, identity.read, va, vb
1011            ),
1012            None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
1013        }
1014        identity = Some(measured);
1015    }
1016    let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
1017        let volume = body_volume(candidate);
1018        match (identity, volume) {
1019            (Some(Some(identity)), Some(volume)) => format!(
1020                "volume {volume:.9} miss {:+.3e} bar {:.3e}",
1021                volume - identity.expected,
1022                crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
1023            ),
1024            (_, Some(volume)) => format!("volume {volume:.9}"),
1025            _ => "no volume".to_string(),
1026        }
1027    };
1028
1029    for &fraction in &FRACTIONS {
1030        let magnitude = scale * fraction;
1031        for (direction, dir) in DIRECTIONS.iter().enumerate() {
1032            if trends[direction].closed {
1033                if ladder {
1034                    eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
1035                }
1036                continue;
1037            }
1038            let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
1039            let translate = match AffineTransform::new([
1040                1.0, 0.0, 0.0, offset[0], //
1041                0.0, 1.0, 0.0, offset[1], //
1042                0.0, 0.0, 1.0, offset[2], //
1043                0.0, 0.0, 0.0, 1.0,
1044            ]) {
1045                Ok(transform) => transform,
1046                Err(_) => continue,
1047            };
1048            let moved = match crate::transform_brep(second, translate, false) {
1049                Ok(solid) => solid,
1050                Err(_) => continue,
1051            };
1052            let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
1053            let rung_start = web_time::Instant::now();
1054            let candidate =
1055                match boolean_operation_with_diagnostics(first, &moved, operation, options) {
1056                    Ok(outcome) => outcome.value,
1057                    Err(error) => {
1058                        if ladder {
1059                            eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
1060                        }
1061                        continue;
1062                    }
1063                };
1064            let built = rung_start.elapsed();
1065            // A perturbation must not "rescue" a case into emptiness.
1066            if candidate.shells.is_empty() {
1067                if ladder {
1068                    eprintln!("[ladder] {rung}: empty");
1069                }
1070                continue;
1071            }
1072            // (c) Volume must satisfy the CSG inequality for the ORIGINAL
1073            // operands (generous 1% relative slack: catches gross wrongness —
1074            // doubled/halved bodies, missing lobes — without rejecting the
1075            // legitimate sub-micron offset).
1076            if let (Some(va), Some(vb)) = (va, vb) {
1077                if let Ok(vr) = solid_signed_volume(&candidate) {
1078                    if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
1079                        if ladder {
1080                            eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
1081                        }
1082                        continue;
1083                    }
1084                }
1085            }
1086            // (d) and (e) run before (b): each costs a volume, and (e) one
1087            // exact-lane boolean, where the oracle classifies 400 points. A
1088            // rung ships only when every gate clears, so the order decides
1089            // which gate names a refusal, never which rung ships.
1090            let bounded = rung_start.elapsed();
1091            // (d) The exact lane's inclusion–exclusion identity.
1092            if hold_identity {
1093                let identity = identity.get_or_insert_with(|| {
1094                    let identity =
1095                        inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1096                    if debug && identity.is_none() {
1097                        eprintln!(
1098                            "[perturb] no exact-lane boolean of these operands clears in either \
1099                             order; no identity to hold"
1100                        );
1101                    }
1102                    identity
1103                });
1104                if let Some(identity) = identity {
1105                    let expected = identity.expected;
1106                    let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
1107                    let volume = body_volume(&candidate);
1108                    let miss = volume.map(|volume| (volume - expected).abs());
1109                    if !miss.is_some_and(|miss| miss <= bar) {
1110                        let sentence = format!(
1111                            "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1112                             (offset {magnitude:.3e}) refused: its body reads {} against the \
1113                             inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
1114                             {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
1115                            volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
1116                            identity.formula,
1117                            identity.reading,
1118                            identity.read,
1119                            miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
1120                        );
1121                        if debug {
1122                            eprintln!("[perturb] {sentence}");
1123                        }
1124                        if ladder {
1125                            eprintln!(
1126                                "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1127                                volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1128                                volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1129                            );
1130                        }
1131                        refused.push(sentence);
1132                        continue;
1133                    }
1134                } else if hold_mirror {
1135                    // (e) No exact reading of these operands: the rung's
1136                    // mirror.
1137                    let mirror_start = web_time::Instant::now();
1138                    let mirrored = AffineTransform::new([
1139                        1.0, 0.0, 0.0, -offset[0], //
1140                        0.0, 1.0, 0.0, -offset[1], //
1141                        0.0, 0.0, 1.0, -offset[2], //
1142                        0.0, 0.0, 0.0, 1.0,
1143                    ])
1144                    .ok()
1145                    .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1146                    let mirror = mirrored.as_ref().and_then(|mirrored| {
1147                        inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1148                    });
1149                    let mirror_time = mirror_start.elapsed();
1150                    let volume = body_volume(&candidate);
1151                    let mut measured = None;
1152                    let verdict = match (&mirror, volume) {
1153                        (Some(mirror), Some(volume)) => {
1154                            let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1155                            let miss = 0.5 * (volume - mirror.expected).abs();
1156                            measured = Some((0.5 * (volume - mirror.expected), bar));
1157                            if ladder {
1158                                eprintln!(
1159                                    "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1160                                    mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1161                                );
1162                            }
1163                            (miss > bar).then(|| format!(
1164                                "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1165                                 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1166                                 operands clears, so the rung is held to its mirror: its body reads \
1167                                 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1168                                 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1169                                 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1170                                mirror.formula, mirror.expected, mirror.reading, mirror.read
1171                            ))
1172                        }
1173                        _ => Some(format!(
1174                            "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1175                             (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1176                             clears, and none clears with the second operand moved −offset either, \
1177                             so nothing checks the rung's body{}",
1178                            volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1179                        )),
1180                    };
1181                    match verdict {
1182                        None => trends[direction].cleared(),
1183                        Some(sentence) => {
1184                            if debug {
1185                                eprintln!("[perturb] {sentence}");
1186                            }
1187                            if ladder {
1188                                eprintln!(
1189                                    "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1190                                    rung_start.elapsed().as_secs_f64() * 1e3,
1191                                    built.as_secs_f64() * 1e3,
1192                                    (bounded - built).as_secs_f64() * 1e3,
1193                                    mirror_time.as_secs_f64() * 1e3,
1194                                    ladder_start.elapsed().as_secs_f64()
1195                                );
1196                            }
1197                            refused.push(sentence);
1198                            // (f) Two refused rungs of one sign, growing, close
1199                            // the direction.
1200                            let closure = measured.and_then(|(error, bar)| {
1201                                let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1202                                Some((earlier, error, bar))
1203                            });
1204                            if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1205                                let closed = format!(
1206                                    "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1207                                     rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1208                                     {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1209                                     growing, so no larger offset along it comes back to the volume drift bar \
1210                                     {bar:.3e}"
1211                                );
1212                                if debug {
1213                                    eprintln!("[perturb] {closed}");
1214                                }
1215                                if ladder {
1216                                    eprintln!("[ladder] {closed}");
1217                                }
1218                                refused.push(closed);
1219                            }
1220                            continue;
1221                        }
1222                    }
1223                }
1224            }
1225            // (b) Semantic agreement with the exact CSG of the ORIGINAL
1226            // operands. Reject a vacuous verdict (skip-band swallowed every
1227            // sample so nothing was actually checked).
1228            match crate::oracle::boolean_semantic_disagreement(
1229                first, second, operation, &candidate, 400,
1230            ) {
1231                Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1232                    if ladder {
1233                        eprintln!(
1234                            "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1235                            report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1236                        );
1237                    }
1238                    if debug {
1239                        eprintln!(
1240                            "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1241                             magnitude={magnitude:.3e} offset={offset:?} \
1242                             (oracle considered={} rate={:.4})",
1243                            report.considered, report.disagreement_rate
1244                        );
1245                    }
1246                    return Ok(candidate);
1247                }
1248                report => {
1249                    if ladder {
1250                        let verdict = match &report {
1251                            Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1252                            Err(error) => format!("oracle error {error:?}"),
1253                        };
1254                        eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1255                    }
1256                    continue;
1257                }
1258            }
1259        }
1260    }
1261    if debug {
1262        eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1263    }
1264    Err(refused)
1265}
1266
1267/// The perturbation ladder's offsets, as fractions of the operands' scale,
1268/// smallest first.
1269pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1270
1271/// (f) One ladder direction's rungs refused by their mirrors.
1272///
1273/// Along one direction a rung's signed first-order translation error, half
1274/// its body less its mirror's reading, reads s(δ) = kδ + r: a slope k from the
1275/// translation, and a remainder r from the degeneracy the rung steps over,
1276/// which does not grow with the offset. Two refused rungs at δ₁ < δ₂ with one
1277/// sign and |s(δ₂)| ≥ |s(δ₁)| fix k's sign as theirs, so every larger offset
1278/// reads farther from zero than s(δ₂), which is already beyond the drift bar:
1279/// the direction is closed. Rungs of one sign that shrink toward zero, or that
1280/// change sign, say nothing about k, and the direction stays open; a rung whose
1281/// mirror clears starts the direction's record again.
1282///
1283/// Measured 2026-09-15 (`BREP_DEBUG_PERTURB_LADDER=1` prints s). On
1284/// 22_sag_boundary_identity_t164, all four operations and all four
1285/// directions, s/δ keeps one sign and holds to 3.6% over the ladder's 100× of
1286/// offset (r ≈ 0; −22.23 .. −22.34 on the intersection's first direction). On
1287/// booleanIssue's flush partial torus union, s/δ holds to 0.5% and 8.5% on two
1288/// directions, and to 1.2% on a third past its smallest rung, whose remainder
1289/// reads −43.4 against the slope's −24.5. The first direction's smallest rung
1290/// reads −1.891e-2 where its slope, +2.3 .. +2.6, gives +3.5e-3 (r ≈ −2.2e-2),
1291/// and its next measured rung +3.510e-2: a change of sign, which keeps it open.
1292/// A closed direction's skipped rung would have had to fall to the bar, 8.3e2 ..
1293/// 1.5e6 times below the smallest refused |s| on those rows, to have cleared.
1294#[derive(Clone, Copy, Default)]
1295pub struct MirrorTrend {
1296    /// The last rung refused by its mirror: its offset and signed error.
1297    last: Option<(f64, f64)>,
1298    pub closed: bool,
1299}
1300
1301impl MirrorTrend {
1302    /// Records a rung refused by its mirror at `offset` with signed error
1303    /// `error`. When it and the direction's last refused rung close the
1304    /// direction, and `close` allows it, the direction is closed and the
1305    /// earlier rung's (offset, signed error) returned.
1306    pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1307        let earlier = self
1308            .last
1309            .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1310            .filter(|_| close);
1311        self.last = Some((offset, error));
1312        self.closed |= earlier.is_some();
1313        earlier
1314    }
1315
1316    /// A rung whose mirror clears: the direction's record starts again.
1317    pub fn cleared(&mut self) {
1318        self.last = None;
1319    }
1320}
1321
1322/// Non-degenerate edges a solid's faces use exactly once.
1323/// BELOW-TOLERANCE REFUSAL (`BREP_BELOW_TOLERANCE_REFUSAL`, default on, `=0` off). Two
1324/// planar faces, one of each operand, that are nearly parallel and stand no
1325/// farther apart over their shared extent than [`BELOW_TOLERANCE_BAND`] but not
1326/// exactly on one another are a configuration the kernel cannot resolve: its
1327/// weld floor is 1e-5 and its face arrangements resolve a few 1e-5, so the
1328/// slivers between such faces fall under the modelling tolerance. A cube
1329/// against a copy turned 1e-4 deg moves its corners 1.2e-5 to 2.5e-5: the exact
1330/// arrangement failed, and the perturbation ladder then answered a nudged pair
1331/// 8.5e-5 out in volume; at 1e-6 deg the face pairs read as coincident and the
1332/// difference came back empty. Consulted only where the exact lane failed or
1333/// returned an empty difference or common part, so nothing that answers today
1334/// changes; the refusal names the pair and the modelling tolerance instead of
1335/// shipping a nudged or empty solid.
1336pub fn below_tolerance_refusal_enabled() -> bool {
1337    crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1338}
1339
1340/// `BREP_BELOW_TOLERANCE_SLIVERS` (default on; `=0` refuses or keeps the exact
1341/// lane's answer as before): where the below-tolerance
1342/// refusal would name a pair, an operand whose difference from the other is
1343/// all sliver ([`difference_all_sliver`]) is read as lying inside it, and the
1344/// boolean answers by that inclusion: `first - second` is empty when it is all
1345/// sliver; `first ∪ second` is the operand the other lies inside; `first ∩
1346/// second` is the operand lying inside the other. A box less a copy of itself
1347/// moved 5.4e-6 and turned 8e-7 rad holds 1.1e-4 against a bar of 1.6e-4 and
1348/// was refused (the exact lane had no boundary face left to write); a box
1349/// united with a copy whose top stands 1e-5 under its own and whose other
1350/// faces stand within 2e-7 of its own came back with open loops where the
1351/// 1e-5 strips of the side faces welded shut. A union or common part the
1352/// exact lane did write over such a pair takes the inclusion's answer too: the
1353/// common part of that box and copy read 8e-5 apart in the two orders, both
1354/// above the copy's own volume. Anything else still refuses by name, or keeps
1355/// the exact lane's answer.
1356pub fn below_tolerance_slivers_enabled() -> bool {
1357    crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1358}
1359
1360/// The most faces an operand of [`below_tolerance_answer`] may have: the
1361/// polyhedral reads are quadratic in the faces.
1362const SLIVER_ANSWER_FACES: usize = 64;
1363
1364fn face_count(solid: &BrepSolid) -> usize {
1365    solid.shells.iter().map(|shell| shell.faces.len()).sum()
1366}
1367
1368/// The answer [`below_tolerance_slivers_enabled`] gives `operation`, if any.
1369fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1370    if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1371        return None;
1372    }
1373    if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1374        return None;
1375    }
1376    let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1377    if matches!(operation, BooleanOperation::Subtract) {
1378        return inside(first, second).then(empty_solid);
1379    }
1380    let (first_in, second_in) = (inside(first, second), inside(second, first));
1381    // Each inside the other: both answers hold at the tolerance; the union
1382    // takes the larger and the common part the smaller, whichever comes first.
1383    let first_larger = || match (body_volume(first), body_volume(second)) {
1384        (Some(a), Some(b)) => a >= b,
1385        _ => true,
1386    };
1387    let outer_is_first = match (first_in, second_in) {
1388        (false, false) => return None,
1389        (true, false) => false,
1390        (false, true) => true,
1391        (true, true) => first_larger(),
1392    };
1393    let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1394    Some(match operation {
1395        BooleanOperation::Union => outer.clone(),
1396        _ => inner.clone(),
1397    })
1398}
1399
1400/// One shell of a solid, every proper edge used by exactly two coedges.
1401fn closed_single_shell(solid: &BrepSolid) -> bool {
1402    if !solid.kind.is_solid() || solid.shells.len() != 1 {
1403        return false;
1404    }
1405    let mut uses: HashMap<u64, usize> = HashMap::default();
1406    for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1407        *uses.entry(coedge.edge_id).or_default() += 1;
1408    }
1409    !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1410}
1411
1412/// Whether `first - second` is all sliver: `second` a convex polyhedron and
1413/// `first` a polyhedron (planar faces, straight edges) standing past no face
1414/// plane of `second` by more than [`BELOW_TOLERANCE_BAND`], and the part of
1415/// `first` beyond `second`'s face planes, summed plane by plane (an upper bound
1416/// on V(first - second), since `second` is the intersection of their inner
1417/// half-spaces), at most `first`'s area times the coincidence distance
1418/// (1e-6): spread over the boundary, the material is thinner than two faces
1419/// the kernel reads as one surface. Each plane's part is exact: `first`'s face
1420/// polygons clipped to the plane's outer side, their volume read about a
1421/// point of the plane, where the cut's own cap adds nothing.
1422fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1423    let Some(bounds) = difference_bounds(first, second) else {
1424        return false;
1425    };
1426    let Ok(properties) = crate::solid_mass_properties(first) else {
1427        return false;
1428    };
1429    bounds.out <= BELOW_TOLERANCE_BAND
1430        && bounds.upper.is_finite()
1431        && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1432}
1433
1434/// Bounds on V(first - second) for a polyhedral `first` and a convex
1435/// polyhedral `second`, from `first`'s parts beyond each face plane of
1436/// `second` (exact, see [`difference_all_sliver`]): each part lies in the
1437/// difference, so the largest is a lower bound, and the difference is their
1438/// union, so their sum is an upper one.
1439struct DifferenceBounds {
1440    lower: f64,
1441    upper: f64,
1442    /// How far `first` stands past `second`'s face planes at most.
1443    out: f64,
1444}
1445
1446fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
1447    let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1448    let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1449    let vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1450    let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1451    let flat = 1e-9 * scale;
1452    let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1453    for polygon in &polygons_b {
1454        let (origin, normal) = polygon_plane(polygon)?;
1455        // Convex: every vertex of `second` on the inner side of its face plane.
1456        if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1457            return None;
1458        }
1459        let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1460        bounds.out = bounds.out.max(out);
1461        if out <= 0.0 {
1462            continue;
1463        }
1464        let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1465        bounds.lower = bounds.lower.max(part);
1466        bounds.upper += part;
1467    }
1468    Some(bounds)
1469}
1470
1471/// `BREP_BELOW_TOLERANCE_RESCALE` (default off): a
1472/// boolean the below-tolerance refusal would name, over two closed convex
1473/// polyhedra, is run again on both operands scaled up 100 (then 1000) times, so that faces a
1474/// weld floor apart (1e-5) stand clear of it, and the answer scaled back is
1475/// kept when its volume and area are the exact ones of the two convex
1476/// polyhedra ([`convex_pair_measures`]) to a part in 1e9: a cube less a copy
1477/// turned 1e-4 degrees came back right in volume but 1e-3 over in area (a
1478/// sliver's face too many), and refuses. A box less a copy whose top stands 1e-5 under its own
1479/// leaves a slab 1e-5 thick, a valid body: refused, it came back exact.
1480pub fn below_tolerance_rescale_enabled() -> bool {
1481    crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1482}
1483
1484fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1485    if !below_tolerance_rescale_enabled()
1486        || options.tolerances.is_some()
1487        || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1488    {
1489        return None;
1490    }
1491    let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1492    let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1493    let area_slack = 1e-9 * area_exact.max(1.0);
1494    for factor in [100.0, 1000.0] {
1495        let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1496        let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1497            continue;
1498        };
1499        let mut scaled_options = options.clone();
1500        scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1501        let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1502            continue;
1503        };
1504        let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1505            continue;
1506        };
1507        let Ok(properties) = crate::solid_mass_properties(&answer) else {
1508            continue;
1509        };
1510        if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1511            && (properties.surface_area - area_exact).abs() <= area_slack
1512            && !answer.validate().iter().any(|issue| issue.severity == "error")
1513        {
1514            return Some(answer);
1515        }
1516    }
1517    None
1518}
1519
1520/// The exact volume and area of `operation` on two convex polyhedra: each
1521/// face polygon clipped to the other's inner half-spaces is the part of it
1522/// inside the other, the common part is closed by those parts of both, and
1523/// the union and difference follow from the parts inside and the rest. `None`
1524/// unless both are convex polyhedra.
1525fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1526    let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1527    let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1528    let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1529    let zero = Vec3::new(0.0, 0.0, 0.0);
1530    // (volume of the cones over the parts inside, area of the polygons, area of the parts inside)
1531    let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1532        let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1533        for polygon in polygons {
1534            area += vector_area(polygon, zero).length();
1535            let mut inside = polygon.clone();
1536            for &(origin, normal) in planes {
1537                inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1538                if inside.len() < 3 {
1539                    break;
1540                }
1541            }
1542            if inside.len() >= 3 {
1543                let vector = vector_area(&inside, zero);
1544                cone += inside[0].dot(vector) / 3.0;
1545                inside_area += vector.length();
1546            }
1547        }
1548        (cone, area, inside_area)
1549    };
1550    let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1551    let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1552    let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1553    let common = cone_a + cone_b;
1554    Some(match operation {
1555        BooleanOperation::Intersect => (common, inside_a + inside_b),
1556        BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1557        BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1558    })
1559}
1560
1561/// A convex polyhedron's face planes (a point and the outward unit normal),
1562/// `None` when some vertex stands outside one of them.
1563fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1564    let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1565    let flat = 1e-9 * scale;
1566    let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1567    convex.then_some(planes)
1568}
1569
1570/// The part of `polygon` on the side of the plane through `origin` that
1571/// `normal` points to (Sutherland-Hodgman).
1572fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1573    let side = |point: Vec3| point.sub(origin).dot(normal);
1574    let mut kept = Vec::with_capacity(polygon.len() + 2);
1575    for (index, &point) in polygon.iter().enumerate() {
1576        let next = polygon[(index + 1) % polygon.len()];
1577        let (here, there) = (side(point), side(next));
1578        if here >= 0.0 {
1579            kept.push(point);
1580        }
1581        if (here >= 0.0) != (there >= 0.0) {
1582            let t = here / (here - there);
1583            kept.push(point.add(next.sub(point).scale(t)));
1584        }
1585    }
1586    kept
1587}
1588
1589/// Every loop of `solid` as a polygon of its vertices, ordered so the
1590/// polygons' vector areas point out of the solid; `None` unless every face is
1591/// a plane and every edge a straight segment.
1592fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1593    let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1594    let mut polygons = Vec::new();
1595    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1596        if !face.surface.is_affine().ok()? {
1597            return None;
1598        }
1599        for lp in &face.loops {
1600            let mut polygon = Vec::with_capacity(lp.coedges.len());
1601            for coedge in &lp.coedges {
1602                let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1603                let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1604                let chord = end.sub(start);
1605                let length = chord.length();
1606                if edge.degenerate || length <= 1e-12 * scale {
1607                    return None;
1608                }
1609                for control in &edge.curve.control_points {
1610                    let offset = control.point().ok()?.sub(start);
1611                    if offset.cross(chord).length() / length > 1e-9 * scale {
1612                        return None;
1613                    }
1614                }
1615                polygon.push(if coedge.forward { start } else { end });
1616            }
1617            polygons.push(polygon);
1618        }
1619    }
1620    // Orient by the enclosed volume's sign.
1621    let volume: f64 = polygons.iter().map(|polygon| clipped_cone_volume(polygon, Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0))).sum();
1622    if !(volume.abs() > 0.0) {
1623        return None;
1624    }
1625    if volume < 0.0 {
1626        for polygon in &mut polygons {
1627            polygon.reverse();
1628        }
1629    }
1630    Some(polygons)
1631}
1632
1633/// A polygon's plane: a point of it and its unit outward normal.
1634fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1635    let origin = *polygon.first()?;
1636    Some((origin, vector_area(polygon, origin).normalized().ok()?))
1637}
1638
1639fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1640    let mut area = Vec3::new(0.0, 0.0, 0.0);
1641    for (index, point) in polygon.iter().enumerate() {
1642        let next = polygon[(index + 1) % polygon.len()];
1643        area = area.add(point.sub(origin).cross(next.sub(origin)));
1644    }
1645    area.scale(0.5)
1646}
1647
1648/// The volume of the cone from `origin` over the part of `polygon` on the
1649/// outer side of the plane through `origin` with `normal` (all of it for a
1650/// zero normal). Summed over a closed polyhedron's polygons, it is the volume
1651/// of the polyhedron beyond that plane: the cut's cap lies in the plane and
1652/// adds nothing about a point of it.
1653fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1654    let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1655    if clipped.len() < 3 {
1656        return 0.0;
1657    }
1658    clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1659}
1660
1661/// Ten weld floors: the separation under which two near-coincident planar faces
1662/// are read as below the modelling tolerance.
1663const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1664
1665/// UNRESOLVED-MERGE REFUSAL (`BREP_UNRESOLVED_MERGE_REFUSAL`, default off). A
1666/// union or common part that SUCCEEDS over two planar faces, one of each
1667/// operand, standing farther apart than the coincidence band (1e-6: closer
1668/// faces are one surface by the kernel's definition) but no farther than the
1669/// weld floor (1e-5) has welded the two faces into one: a unit cube united
1670/// with a copy raised 3e-6 came back as the cube, valid, 2e-6 out in volume,
1671/// where the difference of the same pair already refuses by this name. The
1672/// step between such faces is neither a coincidence nor resolvable, so the
1673/// answer is the refusal.
1674pub fn unresolved_merge_refusal_enabled() -> bool {
1675    crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1676}
1677
1678/// SLIVER SHELLS (`BREP_SLIVER_SHELL_DROP`, default on, `=0` off). A solid
1679/// result of several shells, one of which is closed and encloses no material
1680/// (its volume over its area, the thickness of the slab it would be, under
1681/// [`SLIVER_SHELL_THICKNESS`] of the body's size: round-off), carries a sheet the arrangement could not
1682/// resolve, left closed on itself: a measure-zero set, not a void. A cylinder
1683/// of radius 5 with a coaxial one of radius 4.99999 between the same end
1684/// planes gave their common part the inner cylinder plus 64 closed sheets
1685/// over the 1e-5 rings at its ends, 6e-4 over in area and refused by STEP
1686/// export ("a void shell lies inside no outward shell"). Such shells are
1687/// dropped, with the edges and vertices only they used; the point set is
1688/// unchanged. Sheet and other non-solid bodies, open shells, and a body whose
1689/// every shell would go are left as they are.
1690pub fn sliver_shell_drop_enabled() -> bool {
1691    crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1692}
1693
1694/// The thickness, as a fraction of the body's size, under which a closed shell
1695/// encloses nothing: round-off. The sheets read 0 and 7e-17 thick; a real
1696/// slab 1e-7 thick beside a unit cube is material and stays.
1697const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1698
1699/// `BREP_SLIVER_SHELL_FAST` (on by default; `=0` reads every shell in full):
1700/// a shell is kept without its full
1701/// mass properties when its volume, read for its sign against the floor
1702/// times an upper bound on its area ([`face_area_upper_bound`]), proves it
1703/// thicker than the floor (only where every face's trim lies within its
1704/// carrier's knot domain). The reading's verdict is the exact check's, and
1705/// an area above the shell's makes the bar higher than the exact one, so a
1706/// shell kept this way is one the exact reading keeps. Everything else (a void,
1707/// whose volume is negative, a real sliver, a face without a bound) is read
1708/// in full as before. The reading reuses the face terms the assembly's sign
1709/// check retained: on a screw wall crossed by a box, the check of four shells
1710/// fell from about 300 ms to a few. `BREP_SLIVER_SHELL_FAST_CHECK` reads both
1711/// and counts the shells whose verdicts differ
1712/// ([`sliver_shell_fast_check_take`]), keeping the full reading's.
1713pub fn sliver_shell_fast_on() -> bool {
1714    crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1715}
1716
1717fn sliver_shell_fast_check_on() -> bool {
1718    crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1719}
1720
1721thread_local! {
1722    static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1723}
1724
1725/// (shells read both ways, verdicts that differed, shells the fast reading
1726/// kept) on this thread since the last call.
1727pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1728    SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1729}
1730
1731fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1732    SLIVER_FAST_CHECK.with(|cell| {
1733        let (a, b, c) = cell.get();
1734        cell.set((a + compared, b + differed, c + kept));
1735    });
1736}
1737
1738/// An upper bound on the area of `surface` over its whole parameter domain
1739/// (so on any face trimmed from it). `|S_u × S_v| ≤ |S_u| |S_v|`, and with
1740/// `S = P / w` (homogeneous `P`, weight `w`) `|S_u| ≤ (|P_u| w_max + |P|
1741/// |w_u|) / w_min²`. Each factor is bounded by the convex hull of its control
1742/// net: `|P|` and the weights by the control points, `P_u` and `w_u` by the
1743/// hodograph's points `p (Q_{i+1} − Q_i) / (u_{i+p+1} − u_{i+1})`. `None`
1744/// for a weight that is not positive or a bound that is not finite.
1745fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1746    let net = &surface.control_points;
1747    let rows = net.len();
1748    let columns = net.first()?.len();
1749    if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1750        return None;
1751    }
1752    let (p, q) = (surface.degree_u, surface.degree_v);
1753    let (us, vs) = (&surface.knots_u, &surface.knots_v);
1754    if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1755        return None;
1756    }
1757    let mut w_min = f64::INFINITY;
1758    let mut w_max = 0.0f64;
1759    let mut point_max = 0.0f64;
1760    for c in net.iter().flatten() {
1761        if !(c.w > 0.0) {
1762            return None;
1763        }
1764        w_min = w_min.min(c.w);
1765        w_max = w_max.max(c.w);
1766        point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1767    }
1768    // (max |P_u|, max |w_u|) over the hodograph in one direction.
1769    let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1770        let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1771        let (mut dp, mut dw) = (0.0f64, 0.0f64);
1772        for i in 0..count - 1 {
1773            let span = knots[i + degree + 1] - knots[i + 1];
1774            if !(span > 0.0) {
1775                continue;
1776            }
1777            let scale = degree as f64 / span;
1778            let others = if along_u { columns } else { rows };
1779            for j in 0..others {
1780                let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1781                let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1782                dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1783                dw = dw.max(scale * (b.w - a.w).abs());
1784            }
1785        }
1786        Some((dp, dw))
1787    };
1788    let (pu, wu) = hodograph(true)?;
1789    let (pv, wv) = hodograph(false)?;
1790    let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1791    let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1792    let extent_u = us[us.len() - 1] - us[0];
1793    let extent_v = vs[vs.len() - 1] - vs[0];
1794    let bound = su * sv * extent_u * extent_v;
1795    bound.is_finite().then_some(bound)
1796}
1797
1798/// [`face_area_upper_bound`] of `face`'s carrier, when its trim lies within
1799/// the carrier's knot domain: every pcurve control point (whose convex hull
1800/// holds the pcurve) inside it, to `1e-12` of the domain's own extent (a circle's
1801/// corner points land a rounding outside). A trim reaching further is
1802/// measured on the carrier's extension, which the control net does not
1803/// bound: `None`. The bound is doubled to cover that rounding's sliver of
1804/// extension (the carrier's own polynomial continued).
1805pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1806    let s = &face.surface;
1807    let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1808    let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1809    // (relative to the domain alone: a tiny chart's allowance stays tiny)
1810    let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1811    if !(du > 0.0 && dv > 0.0) {
1812        return None;
1813    }
1814    for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1815        for c in &coedge.pcurve.control_points {
1816            if !(c.w > 0.0) {
1817                return None;
1818            }
1819            let (u, v) = (c.x / c.w, c.y / c.w);
1820            if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1821                return None;
1822            }
1823        }
1824    }
1825    face_area_upper_bound(s).map(|bound| 2.0 * bound)
1826}
1827
1828/// Drops the sliver shells of `solid` (see [`sliver_shell_drop_enabled`]) and
1829/// returns how many went.
1830fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1831    if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1832        return 0;
1833    }
1834    let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1835    let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1836    let mut drop = vec![false; solid.shells.len()];
1837    for (index, shell) in solid.shells.iter().enumerate() {
1838        if shell.faces.is_empty() {
1839            continue;
1840        }
1841        // Closed: every proper edge the shell uses, used exactly twice by it.
1842        let mut uses: HashMap<u64, usize> = HashMap::default();
1843        for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1844            if !degenerate.contains(&coedge.edge_id) {
1845                *uses.entry(coedge.edge_id).or_default() += 1;
1846            }
1847        }
1848        if uses.is_empty() || uses.values().any(|&count| count != 2) {
1849            continue;
1850        }
1851        let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1852        let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1853        let kept_fast = (fast || check)
1854            && shell
1855                .faces
1856                .iter()
1857                .map(trimmed_face_area_upper_bound)
1858                .sum::<Option<f64>>()
1859                .map(|area| floor * area)
1860                .filter(|bar| bar.is_finite() && *bar > 0.0)
1861                .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1862                .unwrap_or(false);
1863        if kept_fast && !check {
1864            sliver_fast_record(0, 0, 1);
1865            continue;
1866        }
1867        let Ok(mass) = crate::solid_mass_properties(&alone) else {
1868            continue;
1869        };
1870        let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1871        if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1872            eprintln!(
1873                "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1874                solid.shells.len(),
1875                mass.volume,
1876                mass.surface_area
1877            );
1878        }
1879        drop[index] = thickness < floor;
1880        if check {
1881            sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1882        }
1883    }
1884    let dropped = drop.iter().filter(|&&d| d).count();
1885    if dropped == 0 || dropped == solid.shells.len() {
1886        return 0;
1887    }
1888    let mut index = 0;
1889    solid.shells.retain(|_| {
1890        let keep = !drop[index];
1891        index += 1;
1892        keep
1893    });
1894    let used_edges: std::collections::HashSet<u64> = solid
1895        .shells
1896        .iter()
1897        .flat_map(|shell| &shell.faces)
1898        .flat_map(|face| &face.loops)
1899        .flat_map(|lp| &lp.coedges)
1900        .map(|coedge| coedge.edge_id)
1901        .collect();
1902    solid.edges.retain(|edge| used_edges.contains(&edge.id));
1903    let used_vertices: std::collections::HashSet<u64> =
1904        solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1905    solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1906    solid.mass_properties_cache = Default::default();
1907    // A dropped shell may have carried handles: the genus is read again.
1908    refresh_derived_genus(solid);
1909    dropped
1910}
1911
1912fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1913    let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1914    let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1915    Some(KernelRefusal::unsupported(
1916        KernelStage::Intersect,
1917        "below_modelling_tolerance",
1918        format!(
1919            "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1920             another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1921             ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1922             welded away"
1923        ),
1924    ))
1925}
1926
1927fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1928    let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1929    let message = format!(
1930        "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1931         another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1932         modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1933        error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1934    );
1935    Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1936}
1937
1938/// The first pair of planar faces (one per operand) whose planes are nearly
1939/// parallel and whose boundaries stand within [`BELOW_TOLERANCE_BAND`] of the
1940/// other's plane, with overlapping extents, but which are not one plane.
1941fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1942    let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1943    planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1944}
1945
1946/// The first pair of nearly parallel planar faces (one per operand) with
1947/// overlapping extents whose largest separation is above `lower` and at most
1948/// `upper`.
1949fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1950    struct Planar {
1951        id: u64,
1952        origin: Vec3,
1953        normal: Vec3,
1954        corners: Vec<Vec3>,
1955        bounds: crate::spatial::Aabb,
1956    }
1957    let read = |solid: &BrepSolid| -> Vec<Planar> {
1958        let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1959        solid
1960            .shells
1961            .iter()
1962            .flat_map(|shell| &shell.faces)
1963            .filter_map(|face| {
1964                if !face.surface.is_affine().ok()? {
1965                    return None;
1966                }
1967                let origin = face.surface.control_points[0][0].point().ok()?;
1968                let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1969                let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1970                let normal = a.cross(b).normalized().ok()?;
1971                let corners: Vec<Vec3> = face
1972                    .loops
1973                    .iter()
1974                    .flat_map(|lp| &lp.coedges)
1975                    .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1976                    .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1977                    .flatten()
1978                    .collect();
1979                if corners.is_empty() {
1980                    return None;
1981                }
1982                let bounds = crate::spatial::Aabb::from_points(corners.clone());
1983                Some(Planar { id: face.id, origin, normal, corners, bounds })
1984            })
1985            .collect()
1986    };
1987    let (faces_a, faces_b) = (read(first), read(second));
1988    for a in &faces_a {
1989        for b in &faces_b {
1990            if a.normal.cross(b.normal).length() > 1e-3 {
1991                continue;
1992            }
1993            if !a.bounds.intersects(b.bounds, upper) {
1994                continue;
1995            }
1996            let separation = a
1997                .corners
1998                .iter()
1999                .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
2000                .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
2001                .fold(0.0f64, f64::max);
2002            if separation > lower && separation <= upper {
2003                return Some((a.id, b.id, separation));
2004            }
2005        }
2006    }
2007    None
2008}
2009
2010pub fn one_use_edges(solid: &BrepSolid) -> usize {
2011    let mut uses: HashMap<u64, usize> = HashMap::default();
2012    for coedge in solid
2013        .shells
2014        .iter()
2015        .flat_map(|shell| &shell.faces)
2016        .flat_map(|face| &face.loops)
2017        .flat_map(|loop_record| &loop_record.coedges)
2018    {
2019        *uses.entry(coedge.edge_id).or_default() += 1;
2020    }
2021    solid
2022        .edges
2023        .iter()
2024        .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
2025        .count()
2026}
2027
2028/// A body's enclosed volume, zero for an empty one.
2029fn body_volume(solid: &BrepSolid) -> Option<f64> {
2030    if solid.shells.is_empty() {
2031        return Some(0.0);
2032    }
2033    solid_signed_volume(solid).ok().map(f64::abs)
2034}
2035
2036/// What the exact lane's other operations say `operation` on these operands
2037/// must enclose.
2038struct InclusionExclusion {
2039    /// The rescued operation's volume in terms of V(first), V(second) and
2040    /// V(first ∩ second).
2041    formula: &'static str,
2042    /// The exact-lane boolean that supplied V(first ∩ second).
2043    reading: &'static str,
2044    /// That boolean's enclosed volume.
2045    read: f64,
2046    /// The volume `formula` gives.
2047    expected: f64,
2048}
2049
2050/// Whether a rescaled-chart boolean's body (`isotropic_chart.rs`) is admitted:
2051/// its volume inside the CSG bound and on the inclusion-exclusion identity the
2052/// perturbation ladder holds its rungs to, the identity read from an exact-lane
2053/// boolean of the original operands or, when none of them clears, of the
2054/// rescaled ones (a volume does not depend on the chart). With no identity
2055/// readable the body is not admitted. A sound body is not enough: on the slab
2056/// corner wedge (`slab_corner_wedge`, wedge lane off) the rescaled union built
2057/// sound at 0.5831 against the identity's 0.5298.
2058fn isotropic_chart_identity(
2059    first: &BrepSolid,
2060    second: &BrepSolid,
2061    rescaled_first: &BrepSolid,
2062    rescaled_second: &BrepSolid,
2063    operation: BooleanOperation,
2064    options: &BooleanOptions,
2065    result: &BrepSolid,
2066) -> Result<(), String> {
2067    let _caller = crate::mass_caller("boolean.isotropic_chart_identity");
2068    let va = solid_signed_volume(first).ok().map(f64::abs);
2069    let vb = solid_signed_volume(second).ok().map(f64::abs);
2070    let volume = body_volume(result).ok_or("its body has no volume")?;
2071    if let (Some(va), Some(vb)) = (va, vb) {
2072        if !volume_within_csg_bounds(operation, va, vb, volume) {
2073            return Err(format!("volume {volume:.9} outside the CSG bound of {va:.9} and {vb:.9}"));
2074        }
2075    }
2076    let identity = inclusion_exclusion_volume(first, second, operation, options, va, vb, false)
2077        .or_else(|| isotropic_chart::with_active(|| inclusion_exclusion_volume(rescaled_first, rescaled_second, operation, options, va, vb, false)))
2078        .ok_or("no exact-lane boolean of the operands clears to read the inclusion-exclusion identity")?;
2079    let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs());
2080    if (volume - identity.expected).abs() > bar {
2081        return Err(format!(
2082            "volume {volume:.9} against the identity {} = {:.9} (the {} reads {:.9}), bar {bar:.3e}",
2083            identity.formula, identity.expected, identity.reading, identity.read
2084        ));
2085    }
2086    Ok(())
2087}
2088
2089/// The volume `operation` on these operands must have, by inclusion–exclusion.
2090/// Any one exact-lane boolean of the same two operands fixes V(first ∩ second),
2091/// and with the operands' own volumes that fixes all four operations. The
2092/// readings are tried intersection, union, then difference, each in both
2093/// operand orders: the exact lane is not order-symmetric (the helmet's cutter
2094/// ∩ helmet refuses where helmet ∩ cutter clears). The rescued operation itself,
2095/// in its own order, is skipped, since it is the one that refused, unless
2096/// `own_first` asks for it to be read first (a rung's mirror, where it is a
2097/// different pair of operands). `None` when no reading clears or an operand has
2098/// no volume.
2099fn inclusion_exclusion_volume(
2100    first: &BrepSolid,
2101    second: &BrepSolid,
2102    operation: BooleanOperation,
2103    options: &BooleanOptions,
2104    va: Option<f64>,
2105    vb: Option<f64>,
2106    own_first: bool,
2107) -> Option<InclusionExclusion> {
2108    use BooleanOperation::{Intersect, Subtract, Union};
2109    let (va, vb) = (va?, vb?);
2110    let own = match operation {
2111        Intersect => (Intersect, false, "first ∩ second"),
2112        Union => (Union, false, "first ∪ second"),
2113        Subtract => (Subtract, false, "first − second"),
2114    };
2115    let readings = [
2116        (Intersect, false, "first ∩ second"),
2117        (Intersect, true, "second ∩ first"),
2118        (Union, false, "first ∪ second"),
2119        (Union, true, "second ∪ first"),
2120        (Subtract, false, "first − second"),
2121        (Subtract, true, "second − first"),
2122    ];
2123    let own_reading = own_first.then_some(own);
2124    let leading = usize::from(own_first);
2125    for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
2126        if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
2127            continue;
2128        }
2129        let (x, y) = if swapped { (second, first) } else { (first, second) };
2130        let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
2131            .ok()
2132            .and_then(|outcome| body_volume(&outcome.value))
2133        else {
2134            continue;
2135        };
2136        let intersection = match (other, swapped) {
2137            (Intersect, _) => read,
2138            (Union, _) => va + vb - read,
2139            (Subtract, false) => va - read,
2140            (Subtract, true) => vb - read,
2141        };
2142        let (formula, expected) = match operation {
2143            Intersect => ("V(first ∩ second)", intersection),
2144            Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
2145            Subtract => ("V(first) − V(first ∩ second)", va - intersection),
2146        };
2147        return Some(InclusionExclusion { formula, reading, read, expected });
2148    }
2149    None
2150}
2151
2152/// The worst planar face of either operand whose STRAIGHT boundary sits
2153/// farther off its plane than the assembly weld radius:
2154/// `(operand index, face id, gap, weld)`. Mirrors the STEP importer's planar
2155/// split predicate (`step_import::builder::planar_split`) on a finished
2156/// solid: a plane, a single loop of straight non-degenerate edges, and a
2157/// boundary vertex beyond the weld. `None` means no such face, so a failure
2158/// may still be a genuine degeneracy worth a perturbation rung. Only
2159/// consulted on the failure path.
2160fn planar_operand_off_its_plane(
2161    first: &BrepSolid,
2162    second: &BrepSolid,
2163    options: &BooleanOptions,
2164) -> Option<(u8, u64, f64, f64)> {
2165    let policy = options
2166        .tolerances
2167        .clone()
2168        .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2169    let weld = crate::tolerance::assembler_weld(policy.model);
2170    let mut worst: Option<(u8, u64, f64)> = None;
2171    for (operand, solid) in [(0u8, first), (1u8, second)] {
2172        let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2173        for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2174            let Some(crate::AnalyticSurface::Plane {
2175                origin,
2176                u_dir,
2177                v_dir,
2178                ..
2179            }) = face.surface.analytic()
2180            else {
2181                continue;
2182            };
2183            let [loop_record] = face.loops.as_slice() else {
2184                continue;
2185            };
2186            let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2187                continue;
2188            };
2189            let mut off_plane = 0.0f64;
2190            let mut straight = true;
2191            for coedge in &loop_record.coedges {
2192                let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2193                    straight = false;
2194                    break;
2195                };
2196                let (Some(start), Some(end)) =
2197                    (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2198                else {
2199                    straight = false;
2200                    break;
2201                };
2202                let chord = end.sub(start);
2203                let length = chord.length();
2204                if edge.degenerate || length <= weld {
2205                    straight = false;
2206                    break;
2207                }
2208                let direction = chord.scale(1.0 / length);
2209                for fraction in [0.25, 0.5, 0.75] {
2210                    let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2211                        straight = false;
2212                        break;
2213                    };
2214                    let delta = point.sub(start);
2215                    let along = delta.dot(direction);
2216                    if delta.sub(direction.scale(along)).length() > weld
2217                        || along < -weld
2218                        || along > length + weld
2219                    {
2220                        straight = false;
2221                        break;
2222                    }
2223                }
2224                if !straight {
2225                    break;
2226                }
2227                off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2228            }
2229            if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2230                worst = Some((operand, face.id, off_plane));
2231            }
2232        }
2233    }
2234    worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2235}
2236
2237/// CSG volume inequality bounds (no extra boolean needed) with 1% relative slack.
2238/// `va`, `vb`, `vr` are absolute volumes of operand A, operand B, and the result.
2239fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2240    let slack = 1e-2 * (va + vb).max(1.0);
2241    match operation {
2242        // max(A,B) ≤ A∪B ≤ A+B
2243        BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2244        // A−B ≤ A (and ≥ 0)
2245        BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2246        // A∩B ≤ min(A,B)
2247        BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2248    }
2249}
2250
2251// ---------------------------------------------------------------------------
2252// N-ary booleans (Golovanov T4.4)
2253//
2254// Union / intersect / subtract of N solids in ONE imprint+fragment pass.  This
2255// is a NEW ADDITIVE entry point: the binary `boolean_operation` above is left
2256// byte-identical.  The pipeline mirrors the binary one but generalizes the two
2257// operand-specific stages to N operands:
2258//
2259//   1. Imprint EVERY unordered pair (i, j) so every mutual intersection edge is
2260//      present on both operands' faces, and accumulate all pairs into ONE global
2261//      imprint (operand indices remapped to 0..N, piece/vertex ids made globally
2262//      unique, per-face piece lists and per-edge split parameters merged).
2263//   2. Split + fragment each operand by that single global imprint, so each
2264//      operand's faces are cut by ALL of its intersections at once.
2265//   3. Select fragments in one pass: the per-fragment keep decision generalizes
2266//      from "vs one other solid" to "vs the SET of other solids" (see
2267//      `nary_keep`).  Because every pair is imprinted, a fragment's interior lies
2268//      wholly inside or wholly outside each other operand, so a single interior
2269//      test point per (fragment, other-solid) is an exact membership verdict.
2270//   4. Assemble with the same machinery (`assemble_fragments`), then merge and
2271//      validate exactly as the binary path does.
2272// ---------------------------------------------------------------------------
2273
2274/// Reverse a fragment's orientation (surface sense + every coedge), the same
2275/// transform the binary Subtract path applies to the second operand's kept
2276/// fragments.  Extracted so the n-ary selector can reuse it verbatim.
2277fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2278    fragment.same_sense = !fragment.same_sense;
2279    for loop_record in &mut fragment.loops {
2280        loop_record.coedges.reverse();
2281        for coedge in &mut loop_record.coedges {
2282            coedge.forward = !coedge.forward;
2283            coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2284        }
2285    }
2286    Ok(())
2287}
2288
2289/// Imprint every unordered pair of operands and fold the pairwise
2290/// `ImprintResultRecord`s into ONE global imprint whose operand indices are the
2291/// operands' global positions (0..N).  Piece and vertex ids are re-based to be
2292/// globally unique; `by_face` piece lists and `edge_splits` parameter lists are
2293/// MERGED per key so `fragment_face` (which takes the first `by_face` match) and
2294/// `apply_edge_splits` (which collects one entry per edge) see every cut.
2295/// Also returns every pair's cosurface reading in global operand numbers,
2296/// which the record itself does not carry (read by the touch census only).
2297fn build_nary_imprint(
2298    operands: &[BrepSolid],
2299    options: &ImprintOptions,
2300) -> Result<(ImprintResultRecord, Vec<(FaceKey, FaceKey)>), KernelRefusal> {
2301    let mut section_evidence = false;
2302    let mut cosurface: Vec<(FaceKey, FaceKey)> = Vec::new();
2303    let mut vertices: Vec<ImprintVertex> = Vec::new();
2304    let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2305    let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2306    let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2307    let mut next_vertex_id: u64 = 1;
2308    let mut next_piece_id: u64 = 1;
2309
2310    // Profile only: the pairs whose imprint came back empty, and their cost.
2311    let profile = crate::profile::profile_enabled();
2312    let (mut empty_pairs, mut empty_ms, mut full_pairs, mut full_ms) = (0usize, 0.0f64, 0usize, 0.0f64);
2313    for i in 0..operands.len() {
2314        for j in (i + 1)..operands.len() {
2315            let pair_started = profile.then(web_time::Instant::now);
2316            let pair = build_imprints(&operands[i], &operands[j], options)?;
2317            if let Some(started) = pair_started {
2318                let ms = started.elapsed().as_secs_f64() * 1000.0;
2319                if pair.pieces.is_empty() && pair.vertices.is_empty() && pair.edge_splits.is_empty() {
2320                    empty_pairs += 1;
2321                    empty_ms += ms;
2322                } else {
2323                    full_pairs += 1;
2324                    full_ms += ms;
2325                }
2326            }
2327            let remap = |operand: u8| -> u8 {
2328                if operand == 0 {
2329                    i as u8
2330                } else {
2331                    j as u8
2332                }
2333            };
2334
2335            section_evidence = section_evidence || pair.section_evidence;
2336            for (first, second) in &pair.cosurface_pairs {
2337                let global = |key: &FaceKey| FaceKey { operand: remap(key.operand), face_id: key.face_id };
2338                cosurface.push((global(first), global(second)));
2339            }
2340            let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2341            for vertex in &pair.vertices {
2342                let global = next_vertex_id;
2343                next_vertex_id += 1;
2344                vertex_map.insert(vertex.id, global);
2345                vertices.push(ImprintVertex {
2346                    id: global,
2347                    point: vertex.point,
2348                });
2349            }
2350
2351            let mut piece_map: HashMap<u64, u64> = HashMap::default();
2352            for piece in &pair.pieces {
2353                let global = next_piece_id;
2354                next_piece_id += 1;
2355                piece_map.insert(piece.id, global);
2356                let mut mapped = piece.clone();
2357                mapped.id = global;
2358                mapped.start_vertex_id = *vertex_map
2359                    .get(&piece.start_vertex_id)
2360                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2361                mapped.end_vertex_id = *vertex_map
2362                    .get(&piece.end_vertex_id)
2363                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2364                for pcurve in &mut mapped.pcurves {
2365                    pcurve.operand = remap(pcurve.operand);
2366                }
2367                mapped.support_faces = [
2368                    FaceKey {
2369                        operand: remap(piece.support_faces[0].operand),
2370                        face_id: piece.support_faces[0].face_id,
2371                    },
2372                    FaceKey {
2373                        operand: remap(piece.support_faces[1].operand),
2374                        face_id: piece.support_faces[1].face_id,
2375                    },
2376                ];
2377                pieces.push(mapped);
2378            }
2379
2380            for entry in &pair.by_face {
2381                let list = by_face
2382                    .entry((remap(entry.operand), entry.face_id))
2383                    .or_default();
2384                for piece_id in &entry.piece_ids {
2385                    let global = *piece_map.get(piece_id).ok_or_else(|| {
2386                        KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2387                    })?;
2388                    list.push(global);
2389                }
2390            }
2391
2392            for split in &pair.edge_splits {
2393                edge_splits
2394                    .entry((remap(split.operand), split.edge_id))
2395                    .or_default()
2396                    .extend(split.parameters.iter().copied());
2397            }
2398        }
2399    }
2400    if profile {
2401        profile_line!("boolean.nary.imprint_pairs empty={empty_pairs} empty_ms={empty_ms:.2} full={full_pairs} full_ms={full_ms:.2}");
2402    }
2403
2404    Ok((ImprintResultRecord {
2405        faces_in_unproved_pairs: None,
2406        vertices,
2407        pieces,
2408        tangent_nodes: Vec::new(),
2409        barrier_edges: Vec::new(),
2410        section_evidence,
2411        cosurface_pairs: Vec::new(),
2412        operand_sliver_regions: Vec::new(),
2413        tangent_sections: Vec::new(),
2414        by_face: by_face
2415            .into_iter()
2416            .map(|((operand, face_id), piece_ids)| FaceImprints {
2417                operand,
2418                face_id,
2419                piece_ids,
2420            })
2421            .collect(),
2422        edge_splits: edge_splits
2423            .into_iter()
2424            .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2425                operand,
2426                edge_id,
2427                parameters,
2428            })
2429            .collect(),
2430    }, cosurface))
2431}
2432
2433/// N-ary union / intersect / subtract of `operands` in ONE imprint+fragment
2434/// pass (Golovanov T4.4).  Additive: does not touch the binary path.
2435///
2436/// - `Union`   : the boundary of `∪ operands`.
2437/// - `Intersect`: the boundary of `∩ operands`.
2438/// - `Subtract`: `operands[0]` minus the union of `operands[1..]`.
2439///
2440/// `N = 1` returns the sole operand; `N = 2` runs the same general pipeline and
2441/// reproduces the binary result (same volume, valid).  Returns a clear `Err`
2442/// when the operands cannot assemble into a closed, valid solid.
2443pub fn boolean_operation_nary(
2444    operands: &[BrepSolid],
2445    operation: BooleanOperation,
2446) -> Result<BrepSolid, KernelRefusal> {
2447    boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2448}
2449
2450/// [`boolean_operation_nary`] under the caller's [`BooleanOptions`]: the
2451/// tolerance, the coplanar-face merge and its `keep_unmerged_name_substrs`
2452/// list are honoured exactly as the binary path honours them, so a caller that
2453/// falls back from a sequence of binary unions to one arrangement (the sheet
2454/// metal walk with adjacent bends) keeps the same face partition contract.
2455pub fn boolean_operation_nary_with_options(
2456    operands: &[BrepSolid],
2457    operation: BooleanOperation,
2458    options: &BooleanOptions,
2459) -> Result<BrepSolid, KernelRefusal> {
2460    // More operands than one arrangement takes (255): folded a chunk at a
2461    // time, the result so far the next chunk's first operand. Union and
2462    // intersection are associative, and a difference takes the first operand
2463    // less all the rest, so the answer is the one arrangement's would be.
2464    let most = nary_chunk();
2465    if operands.len() > most && nary_chunks_on() {
2466        let mut whole = boolean_operation_nary_with_options(&operands[..most], operation, options)?;
2467        for chunk in operands[most..].chunks(most - 1) {
2468            // A last chunk of one operand is the binary boolean of the two
2469            // (as every two-operand call is answered by the pairwise path).
2470            if let [only] = chunk {
2471                whole = boolean_operation(&whole, only, operation, options)?;
2472                continue;
2473            }
2474            let mut next = Vec::with_capacity(chunk.len() + 1);
2475            next.push(whole);
2476            next.extend_from_slice(chunk);
2477            whole = boolean_operation_nary_with_options(&next, operation, options)?;
2478        }
2479        return Ok(whole);
2480    }
2481    let arranged = boolean_operation_nary_arranged(operands, operation, options);
2482    match arranged {
2483        Err(error) if nary_sequential_fallback_enabled() && operands.len() > 2 && error.message.contains("boolean assembly") => {
2484            // The binary path, operand by operand: each step is the pairwise
2485            // boolean every other caller makes.
2486            let mut whole = operands[0].clone();
2487            for operand in &operands[1..] {
2488                whole = match boolean_operation(&whole, operand, operation, options) {
2489                    Ok(solid) => solid,
2490                    Err(_) => return Err(error),
2491                };
2492            }
2493            Ok(whole)
2494        }
2495        other => other,
2496    }
2497}
2498
2499/// `BREP_NARY_SEQUENTIAL_FALLBACK` (default on; `=0` refuses as before): an n-ary boolean whose single
2500/// arrangement fails to assemble is answered by the binary boolean applied
2501/// operand by operand, and refuses as before only if that fails too. A disc
2502/// less a counterbore, a hole and a countersink whose tops lie on the
2503/// counterbore's floor (three faces on one plane, the countersink's rim
2504/// crossing the counterbore wall's foot) left an open loop as one arrangement
2505/// and builds cut by cut.
2506/// The operands one n-ary arrangement takes.
2507const NARY_MOST: usize = 255;
2508
2509/// The operands a fold takes a chunk at a time: `NARY_MOST` (a test may set
2510/// fewer on its thread).
2511fn nary_chunk() -> usize {
2512    NARY_MOST
2513}
2514
2515
2516/// `BREP_NARY_CHUNKS` (on unless =0): an n-ary boolean of more operands than
2517/// one arrangement takes is folded a chunk at a time instead of refused.
2518fn nary_chunks_on() -> bool {
2519    crate::switch!("BREP_NARY_CHUNKS", true)
2520}
2521
2522/// `BREP_NARY_SCOPED` (default on, `=0` reads the whole result): the n-ary arrangement's inherited-trim
2523/// challenger reads only the faces its operands touched (a piece, a split
2524/// edge or a cosurface partner) and their ring, instead of the whole result;
2525/// the weld and every other assembly pass still read the whole solid. An
2526/// inherited trim on a face no operand touched is handed on as its operand
2527/// held it, unrefit. (Scoping every pass, as `touched_assembly` does, moved
2528/// an untouched triple-junction vertex 1.7e-9 on the benchy's glyph cut: the
2529/// whole-solid junction polish puts it back, a scoped one never reaches it.) The benchy's
2530/// body is cut and joined some forty times, and each call re-read every one
2531/// of its thousand faces. Promoted 2026-11-28: the benchy STEP, the split
2532/// census (140 rows) and the manifest census (98 cases, 352 bodies) read the
2533/// same with it on and off.
2534fn nary_scoped_on() -> bool {
2535    crate::switch!("BREP_NARY_SCOPED", true)
2536}
2537
2538fn nary_sequential_fallback_enabled() -> bool {
2539    crate::switch!("BREP_NARY_SEQUENTIAL_FALLBACK", true)
2540}
2541
2542fn boolean_operation_nary_arranged(
2543    operands: &[BrepSolid],
2544    operation: BooleanOperation,
2545    options: &BooleanOptions,
2546) -> Result<BrepSolid, KernelRefusal> {
2547    if operands.len() > 1 {
2548        if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2549            return scaled.run(
2550                || boolean_operation_nary_with_options(operands, operation, options),
2551                || boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2552                    .map_err(|error| scaled.refusal(error))
2553                    .and_then(|solid| scaled.back(&solid)),
2554            );
2555        }
2556    }
2557    if operands.is_empty() {
2558        return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2559    }
2560    if operands.len() == 1 {
2561        return Ok(operands[0].clone());
2562    }
2563    if operands.len() > nary_chunk() {
2564        return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2565    }
2566    // Each whole ball turned onto the one line the others cut it about
2567    // (`ball_align`); the turned set runs once more and is then left as it is.
2568    if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2569        return boolean_operation_nary_with_options(&aligned, operation, options);
2570    }
2571    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2572
2573    // One tolerance policy for the whole set: the largest-scale operand's policy
2574    // dominates (every derived band is monotonic in scale), matching how the
2575    // binary path takes `for_pair` = max of the two scales.
2576    let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2577    for operand in &operands[1..] {
2578        let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2579        if candidate.sew_search > policy.sew_search {
2580            policy = candidate;
2581        }
2582    }
2583    policy.check().or_input(KernelStage::Collect, "tolerances")?;
2584    let tolerance = policy.model;
2585
2586    // Per-operand fuse-first healing, exactly as the binary path (a no-op on
2587    // clean input, so clean operands are untouched).
2588    let nary_clock = NaryClock::start();
2589    let mut healed = operands.to_vec();
2590    // NARY SCOPED (`BREP_NARY_SCOPED_REFIT=0` leaves the refit whole for an
2591    // A/B): each operand's refit reads only its faces that are not
2592    // separated (exact control hulls, past the search band) from every other
2593    // operand; a separated face carries no section and keeps its trims.
2594    let refit_scopes: Option<Vec<std::collections::HashSet<u64>>> = (nary_scoped_on() && crate::switch!("BREP_NARY_SCOPED_REFIT", true)).then(|| {
2595        let bounds: Vec<Option<crate::Aabb>> = operands
2596            .iter()
2597            .map(|operand| crate::fragment::bounded_carriers(operand).then(|| operand_bounds(operand)))
2598            .collect();
2599        operands
2600            .iter()
2601            .enumerate()
2602            .map(|(index, operand)| {
2603                operand
2604                    .shells
2605                    .iter()
2606                    .flat_map(|shell| &shell.faces)
2607                    .filter(|face| {
2608                        !bounds.iter().enumerate().filter(|(other, _)| *other != index).all(|(_, other)| {
2609                            other.as_ref().is_some_and(|other| crate::fragment::face_separated(face, *other, policy.sew_search))
2610                        })
2611                    })
2612                    .map(|face| face.id)
2613                    .collect()
2614            })
2615            .collect()
2616    });
2617    for (index, operand) in healed.iter_mut().enumerate() {
2618        crate::heal::heal_operands(operand, &policy)?;
2619        nary_clock.lap("nary.heal.operands_ms");
2620        // Then refit any inherited trim off the pcurve construction contract
2621        // whose edge lies on every carrier (a no-op without one).
2622        match &refit_scopes {
2623            Some(scopes) => crate::heal::with_refit_face_scope(scopes[index].clone(), || crate::heal::refit_inherited_trims_reused(operand, &policy))?,
2624            None => crate::heal::refit_inherited_trims_reused(operand, &policy)?,
2625        }
2626        nary_clock.lap("nary.heal.refit_ms");
2627        // Same operand normalization as the binary path: seam edges for
2628        // seamless full-period band faces.
2629        normalize_operand_band_seams(operand)?;
2630        nary_clock.lap("nary.heal.seams_ms");
2631    }
2632
2633    // 1. Imprint every pair into one global imprint.
2634    let mut imprint_options = options.imprint.clone();
2635    imprint_options.tolerance = tolerance;
2636    let (imprint, cosurface) = build_nary_imprint(&healed, &imprint_options)?;
2637    nary_clock.lap("nary.imprint_ms");
2638
2639    // 2. Split every operand's edges, then fragment its faces, by that imprint.
2640    let mut split = Vec::with_capacity(healed.len());
2641    for (index, operand) in healed.iter().enumerate() {
2642        split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2643    }
2644    let mut fragments = Vec::with_capacity(split.len());
2645    for (index, solid) in split.iter().enumerate() {
2646        fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2647    }
2648    nary_clock.lap("nary.split_fragment_ms");
2649
2650    // 3. Select fragments in one pass against the set of other operands.
2651    let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2652    nary_clock.lap("nary.select_ms");
2653
2654    // 4. Assemble + normalize + validate, mirroring the binary tail.
2655    let solids: HashMap<u8, &BrepSolid> = split
2656        .iter()
2657        .enumerate()
2658        .map(|(index, solid)| (index as u8, solid))
2659        .collect();
2660    let solid = if nary_scoped_on() {
2661        // NARY SCOPED: the inherited-trim challenger reads the faces the
2662        // operation touched and their ring only; every other pass reads the
2663        // whole result as before.
2664        let prepared: Vec<&BrepSolid> = healed.iter().collect();
2665        let touch = touch::TouchCensus::build_all(&prepared, &imprint, &cosurface);
2666        assemble::assemble_fragments_inherited_scoped(selected, &solids, &imprint, tolerance, &touch)?
2667    } else {
2668        assemble_fragments(selected, &solids, &imprint, tolerance)?
2669    };
2670    nary_clock.lap("nary.assemble_ms");
2671    let solid = if options.merge_coplanar_faces
2672        && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2673    {
2674        let merged = merge_same_surface_faces_excluding(
2675            &solid,
2676            tolerance,
2677            &options.keep_unmerged_name_substrs,
2678        )?;
2679        let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2680        rejoin::rejoin_unless_referenced(merged, options, tolerance)
2681    } else {
2682        solid
2683    };
2684    nary_clock.lap("nary.merge_ms");
2685    let validation = solid.validate_detailed(&policy);
2686    nary_clock.lap("nary.validate_ms");
2687    if !validation.issues.is_empty() {
2688        return Err(KernelRefusal::new(
2689            RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2690            KernelStage::Validate,
2691            format!(
2692            "boolean_operation_nary: invalid result: {:?}",
2693            validation.issues
2694        )));
2695    }
2696    if debug {
2697        if let Ok(report) =
2698            crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2699        {
2700            if report.is_flagged() {
2701                eprintln!(
2702                    "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2703                    report.disagreement_rate,
2704                    report.disagreements.len(),
2705                    report.considered,
2706                    report.sample_disagreement()
2707                );
2708            }
2709        }
2710    }
2711    Ok(solid)
2712}
2713
2714/// TANGENT-NODE ATTRIBUTION.
2715///
2716/// The imprint's second-order filter decides which tangential contacts are
2717/// isolated NODES the arrangement can carve, and marches those instead of
2718/// refusing. It cannot decide a THIRD-order singularity — where the transverse
2719/// branch is tangent to a contact curve, every second-order quantity vanishes
2720/// together and the contact reads as a clean saddle at every stopping rule
2721/// (`imprint/tangent_contact.rs`). The assembly is the authority on whether an
2722/// admitted node was really imprintable, so a tear downstream of one is
2723/// reported AGAINST THE NODE rather than as an anonymous degeneracy: same
2724/// refusal class the whole tangent-node family carries, naming the point.
2725///
2726/// Only classes that are ALREADY perturbation-eligible are re-attributed, so a
2727/// refusal that could never take the ladder still cannot. The stage's own
2728/// message — the one-use edges, the genus — is NOT carried into the refusal:
2729/// `tangent_node_assembly` and `torus_torus_singular_refusal` hold the
2730/// tangent-node refusal to naming its cause without the arrangement's
2731/// symptom text ("open between", "genus", "pcurve"), the policy the class
2732/// exists for. It is printed under `BREP_DEBUG_BOOL` instead, so what the
2733/// assembly actually read is still there for a reader of the trace.
2734///
2735/// It does decide WHICH refusals are retried, though, and since 2026-09-13 that
2736/// matters: `boolean_operation`'s failure arm gates `TangentNodeSingularity` out
2737/// of the perturbation ladder (the TANGENT-NODE GATE there) and reads the class
2738/// AFTER this rewrite. So a tear downstream of an ADMITTED node — whatever class
2739/// the pipeline actually raised — declines the ladder along with the tangent-node
2740/// family proper. That is the conservative direction and the same claim the class
2741/// makes (a tear after a node is the node proving unimprintable). Anything added
2742/// to this rewrite widens that gate: read the gate when you touch the
2743/// attribution.
2744fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2745    let Some(node) = nodes.first() else {
2746        return error;
2747    };
2748    if !error.class.perturbation_eligible()
2749        || matches!(error.class, RefusalClass::TangentNodeSingularity)
2750    {
2751        return error;
2752    }
2753    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2754        eprintln!(
2755            "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2756            node.x, node.y, node.z, error.message
2757        );
2758    }
2759    KernelRefusal::new(
2760        RefusalClass::TangentNodeSingularity,
2761        error.stage,
2762        format!(
2763            "boolean: unsupported singular/tangent-node surface intersection \
2764             at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2765             assemble into a closed shell",
2766            node.x, node.y, node.z
2767        ),
2768    )
2769}
2770
2771/// The tangent-curve lane's attribution: an ASSEMBLY refusal whose faces the
2772/// imprint found touching along a CURVE is reported against that contact, by
2773/// its faces and its ends, in the tangent-node class — the arrangement's own
2774/// message (an open loop, a one-use edge) is the symptom, the contact is the
2775/// cause, and the class keeps the refusal out of the perturbation ladder
2776/// exactly as an admitted node's tear is kept out
2777/// (`attribute_to_tangent_node`). The original message is carried along so
2778/// nothing the stage said is hidden.
2779///
2780/// REACH: the faces the refusal names, and only those. `origins` maps the
2781/// assembled result's face ids (minted one per selected fragment, from 1, in
2782/// order) back to operand faces; the ids are read off the message's
2783/// `face <id>` (validate's open-loop issues) and `on faces [<id> '…`
2784/// (one-use edges) entries, and the rewrite happens only when one of them is
2785/// a face the section INVOLVES (`TangentSectionRecord::faces`: the carriers'
2786/// faces and the faces across the edges its ends lie on). A refusal naming no
2787/// face, or only faces the contact does not touch — a model with a benign
2788/// recorded contact (a blind pocket touching a wall) that fails elsewhere —
2789/// keeps its class and enters the ladder as it always did. With
2790/// `ImprintOptions::tangent_curve_lane` off the sections are empty and
2791/// nothing is rewritten.
2792pub fn attribute_to_tangent_section(
2793    error: KernelRefusal,
2794    sections: &[crate::imprint::TangentSectionRecord],
2795    origins: &[FaceKey],
2796) -> KernelRefusal {
2797    if sections.is_empty()
2798        || !error.class.perturbation_eligible()
2799        || matches!(error.class, RefusalClass::TangentNodeSingularity)
2800    {
2801        return error;
2802    }
2803    let named = refusal_result_faces(&error.message)
2804        .into_iter()
2805        .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2806        .collect::<Vec<FaceKey>>();
2807    // A record the lane's own sites minted before one the grazing-pierce
2808    // path minted (`TangentSectionRecord::grazing`): the sprocket slit star's
2809    // cutter names its traced contact, not the pierce of a neighbouring pair.
2810    let involving = |fallback: bool| {
2811        sections.iter().find(|section| {
2812            section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2813        })
2814    };
2815    let Some(section) = involving(false).or_else(|| involving(true)) else {
2816        return error;
2817    };
2818    // A clipped end sits on a trim at round-off, and `-0.000000` names no
2819    // place: print what six decimals can show.
2820    let at = |point: Vec3| {
2821        let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2822        format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2823    };
2824    // The grazing pierces (`imprint/driver.rs`, 2026-10-17): trim edges that
2825    // pierce the other carrier inside both trims below the seed gate while
2826    // the pair marched nothing. A record the lane built stands on its contact
2827    // and carries them as a note; a record standing on the pierces ALONE
2828    // (its `start` IS the first pierce) is named by them.
2829    let pierces = (!section.grazing.is_empty()).then(|| {
2830        let shown = section.grazing.len().min(4);
2831        let mut listed = section.grazing[..shown]
2832            .iter()
2833            .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2834            .collect::<Vec<_>>()
2835            .join(", ");
2836        if section.grazing.len() > shown {
2837            listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2838        }
2839        listed
2840    });
2841    let pierce_only = section.pierce_only();
2842    let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2843        format!(
2844            "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2845             trims at {pierces}, below the marcher's start gate, and no transverse section was \
2846             marched between the pierces — a near-tangent crossing born on a tangent contact \
2847             (a third-order singularity) the imprint does not build yet"
2848        )
2849    } else if section.planar {
2850        format!(
2851            "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2852             imprint does not build yet",
2853            at(section.start),
2854            at(section.end),
2855            section.length,
2856            section.stations,
2857            if section.closed { ", closed" } else { "" }
2858        )
2859    } else {
2860        format!(
2861            "touch along a curve through {} with neither carrier planar, a curved/curved \
2862             tangent contact the lane does not trace yet",
2863            at(section.start)
2864        )
2865    };
2866    let shape = match (pierce_only, pierces) {
2867        (false, Some(pierces)) => format!(
2868            "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2869             below the marcher's start gate, with no transverse section marched"
2870        ),
2871        _ => shape,
2872    };
2873    let involved = named
2874        .iter()
2875        .filter(|face| section.faces.contains(face))
2876        .map(|face| format!("{}/{}", face.operand, face.face_id))
2877        .collect::<Vec<_>>()
2878        .join(", ");
2879    KernelRefusal::new(
2880        RefusalClass::TangentNodeSingularity,
2881        error.stage,
2882        format!(
2883            "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2884             the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2885            section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2886            error.message
2887        ),
2888    )
2889}
2890
2891/// The RESULT face ids an assembly refusal names: every `face <id>` (the
2892/// validator's "loop … of face `<id>` is open …") and every `<id> '` entry of an
2893/// `on faces [...]` list (the one-use edge census). Nothing else in the
2894/// message is read.
2895pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2896    let mut ids = Vec::new();
2897    let digits_after = |text: &str| -> Option<u64> {
2898        let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2899        text[..end].parse().ok()
2900    };
2901    for (index, _) in message.match_indices("face ") {
2902        if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2903            ids.push(id);
2904        }
2905    }
2906    if let Some(start) = message.find("on faces [") {
2907        let rest = &message[start + "on faces [".len()..];
2908        let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2909        for entry in list.split(", ") {
2910            let entry = entry.trim_start();
2911            if let Some(id) = digits_after(entry) {
2912                if entry[id.to_string().len()..].starts_with(" '") {
2913                    ids.push(id);
2914                }
2915            }
2916        }
2917    }
2918    ids.sort_unstable();
2919    ids.dedup();
2920    ids
2921}
2922
2923pub fn boolean_operation_with_diagnostics(
2924    first: &BrepSolid,
2925    second: &BrepSolid,
2926    operation: BooleanOperation,
2927    options: &BooleanOptions,
2928) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2929    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2930        return scaled.run(
2931            || boolean_operation_with_diagnostics(first, second, operation, options),
2932            || {
2933                let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2934                    .map_err(|error| scaled.refusal(error))?;
2935                outcome.value = scaled.back(&outcome.value)?;
2936                outcome.diagnostics.count_n("working_scale.fired", 1);
2937                outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2938                Ok(outcome)
2939            },
2940        );
2941    }
2942    let _account = profile::Scope::new("boolean.other");
2943    // A whole ball turned onto the line the other operand cuts it about
2944    // (`ball_align`): its sections become latitudes.
2945    let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2946    let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2947    let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2948    if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2949        let started = Instant::now();
2950        let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2951        profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2952        return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2953    }
2954    // CYLINDER CONTACTS (`reseat::seam_reseat_cylinders_mode`): with no later
2955    // references stated, only the cylinder-against-cylinder re-seat runs.
2956    let cylinders = reseat::seam_reseat_cylinders_mode();
2957    if reseat::seam_reseat_enabled() && cylinders != crate::env_read::Mode::Off {
2958        let kinds = reseat::ContactKinds { planes: false, cylinders: true };
2959        let volume = |result: &Result<KernelOutcome<BrepSolid>, KernelRefusal>| {
2960            result.as_ref().ok().and_then(|outcome| crate::solid_mass_properties(&outcome.value).ok()).map(|mass| mass.volume)
2961        };
2962        if reseat::seam_reseat_retry_enabled() {
2963            // RETRY: the operands as given first; the re-seated ones (with the
2964            // tangent-cylinder cosurface exchange) only when that refuses, so a
2965            // body built without a re-seat stays the operand of the next cut as
2966            // it would be without the switch. `check` reports what the retry
2967            // would give and returns the first attempt.
2968            let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2969            if plain.is_ok() {
2970                return plain;
2971            }
2972            let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2973            let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2974            if !moved {
2975                return plain;
2976            }
2977            let reseated = crate::imprint::driver::with_tangent_cylinder_filter(|| {
2978                boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells)
2979            });
2980            if cylinders == crate::env_read::Mode::Check {
2981                eprintln!(
2982                    "boolean.seam_reseat_cylinders check: plain refused, reseated retry {} volume {:?}",
2983                    if reseated.is_ok() { "built" } else { "refused" },
2984                    volume(&reseated)
2985                );
2986                return plain;
2987            }
2988            return match reseated {
2989                Ok(mut outcome) => {
2990                    outcome.diagnostics.count_n("seam_reseat_cylinders.retry_built", 1);
2991                    Ok(outcome)
2992                }
2993                Err(_) => plain,
2994            };
2995        }
2996        let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2997        let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2998        if moved {
2999            let reseated = boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells);
3000            if cylinders == crate::env_read::Mode::On {
3001                return reseated;
3002            }
3003            let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
3004            eprintln!(
3005                "boolean.seam_reseat_cylinders check: plain {} volume {:?}, reseated {} volume {:?}",
3006                if plain.is_ok() { "built" } else { "refused" },
3007                volume(&plain),
3008                if reseated.is_ok() { "built" } else { "refused" },
3009                volume(&reseated)
3010            );
3011            return plain;
3012        }
3013    }
3014    boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
3015}
3016
3017/// [`drop_sliver_shells`] on a boolean's outcome, counted in its diagnostics.
3018fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
3019    let dropped = drop_sliver_shells(&mut outcome.value);
3020    if dropped > 0 {
3021        outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
3022    }
3023    outcome
3024}
3025
3026pub fn boolean_operation_with_diagnostics_impl(
3027    first: &BrepSolid,
3028    second: &BrepSolid,
3029    operation: BooleanOperation,
3030    options: &BooleanOptions,
3031    closed_inputs: bool,
3032) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3033    // One coedge-check memo per operation: the
3034    // assembly, face-merge and closing validations re-read coedges unchanged.
3035    let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
3036    // Plan 1.6: only a declared Sheet enters the trim path. The unchanged
3037    // Solid path continues below; no kind is inferred from failed closure.
3038    if matches!(operation, BooleanOperation::Intersect)
3039        && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
3040        && match std::env::var("BREP_SHEET_TRIM").as_deref() {
3041            Ok("1") => true,
3042            Ok("0") => false,
3043            _ => options.sheet_trim,
3044        }
3045    {
3046        return sheet::trim(first, second, options);
3047    }
3048    // OPERAND-KIND GATE. A body that DECLARES itself a Sheet has no
3049    // inside, so a union or subtract with it has no solid answer; the
3050    // survey (record 2026-10-12, table 2) measured the arrangement
3051    // returning a validating solid of volume 3.5 when the sheet's opening
3052    // lay outside the other operand. Read from the declaration only,
3053    // before any arrangement work (nothing infers a kind from the edge
3054    // census; an undeclared open body is the closure gate's below).
3055    // Intersect is not gated here.
3056    if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
3057        if let Some(operand) = [first, second]
3058            .iter()
3059            .position(|solid| solid.kind == crate::BodyKind::Sheet)
3060        {
3061            return Err(KernelRefusal::input(
3062                KernelStage::Collect,
3063                "sheet_operand",
3064                format!(
3065                    "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
3066                     subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
3067                ),
3068            ));
3069        }
3070    }
3071    // Inside/outside is undefined for an open operand, even if its opening
3072    // misses the other operand and the constructed result happens to validate.
3073    // Count existing edge uses, without modifying/healing either operand.
3074    // Keep failures on their original path and preserve their class/evidence;
3075    // the existing perturbation gate already diagnoses open failed operands.
3076    let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
3077    let closure_started = closed_inputs.then(Instant::now);
3078    if closed_inputs {
3079        for (operand, solid) in [first, second].into_iter().enumerate() {
3080            let open = one_use_edges(solid);
3081            if open > 0 {
3082                return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
3083                    "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
3084                )));
3085            }
3086        }
3087    }
3088    if let Some(started) = closure_started {
3089        let ms = started.elapsed().as_secs_f64() * 1000.0;
3090        profile_stage("operand_closure_ms", ms);
3091        outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
3092    }
3093    Ok(outcome)
3094}
3095
3096fn boolean_operation_with_diagnostics_core(
3097    first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
3098) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3099
3100    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`):
3101    // the outermost entry runs the operation on translated operands.
3102    if let Some(offset) = crate::recentre::control_offset_at_entry() {
3103        return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
3104    }
3105    // The recentre guard: operands far from the origin in their own
3106    // units run at the origin.
3107    let mut bounds = operand_bounds(first);
3108    bounds.include(operand_bounds(second));
3109    if let Some(offset) = crate::recentre::guard_offset(bounds) {
3110        crate::recentre::profile_fired("boolean", offset, bounds);
3111        let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
3112        outcome.diagnostics.count_n("recentre.fired", 1);
3113        outcome.diagnostics.measure_max("recentre.distance", offset.length());
3114        return Ok(outcome);
3115    }
3116    let mut tangent_nodes = Vec::new();
3117    let (mut outcome, soundness_candidates) =
3118        boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
3119            .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
3120    // The assembly's single exit. A boolean can hand back a body whose walls
3121    // pass through each other while `validate()` is silent and the volume
3122    // measures right, which is exactly the failure a regularized boolean must
3123    // not report as success. A crossing the OPERANDS already had is theirs and
3124    // passes through — the defect came in with the input and refusing it here
3125    // would blame the wrong operation — so the operands are only scanned when
3126    // the result is flagged, and the common case pays for one scan. The
3127    // acceptance's refusal is typed at its origin (an `UnsoundResult` naming
3128    // the defect and the faces); it was classed `Internal` here while
3129    // `accept_sound_against` still returned text. Timed as its own stage: the
3130    // record's phase split read only the pipeline's `timing.*` measures, and
3131    // on a 108-face disjoint union this scan was 185 of 226 ms end to end.
3132    let stage_started = Instant::now();
3133    let accepted = match &soundness_candidates {
3134        // Pass-through: the faces the operation touched, their
3135        // neighbours and every face whose box reaches the other operand.
3136        Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
3137        None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
3138    };
3139    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3140    profile_stage("soundness_ms", stage_ms);
3141    outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
3142    outcome.value = accepted?;
3143    Ok(outcome)
3144}
3145
3146/// [`boolean_operation_with_diagnostics`] with both operands translated by
3147/// `offset` for the operation and the result translated back. Refusal
3148/// messages name the translated coordinates.
3149pub fn boolean_operation_with_diagnostics_at_offset(
3150    first: &BrepSolid,
3151    second: &BrepSolid,
3152    operation: BooleanOperation,
3153    options: &BooleanOptions,
3154    offset: Vec3,
3155) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3156    boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
3157}
3158
3159/// The translated run behind the control and the guard.
3160fn boolean_translated(
3161    first: &BrepSolid,
3162    second: &BrepSolid,
3163    operation: BooleanOperation,
3164    options: &BooleanOptions,
3165    offset: Vec3,
3166    kind: crate::recentre::EntryKind,
3167) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3168    let _entry = crate::recentre::TranslatedEntry::open(kind);
3169    let translate = |solid: &BrepSolid, offset: Vec3| {
3170        crate::recentre::translate_solid(solid, offset).map_err(|message| {
3171            KernelRefusal::internal(
3172                KernelStage::Collect,
3173                "translation_control",
3174                format!("boolean: the translation control could not move an operand: {message}"),
3175            )
3176        })
3177    };
3178    let moved_first = translate(first, offset)?;
3179    let moved_second = translate(second, offset)?;
3180    let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
3181    let value = translate(&outcome.value, offset.scale(-1.0))?;
3182    Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
3183}
3184
3185/// The n-ary arrangement's stage clock: a `boolean.nary.*_ms` line per stage
3186/// under `BREP_PROFILE`, and no clock read without it.
3187struct NaryClock(Option<std::cell::Cell<web_time::Instant>>);
3188
3189impl NaryClock {
3190    fn start() -> Self {
3191        Self(crate::profile::profile_enabled().then(|| std::cell::Cell::new(web_time::Instant::now())))
3192    }
3193
3194    fn lap(&self, code: &str) {
3195        if let Some(cell) = &self.0 {
3196            let now = web_time::Instant::now();
3197            profile_stage(code, (now - cell.get()).as_secs_f64() * 1000.0);
3198            cell.set(now);
3199        }
3200    }
3201}
3202
3203/// Stage wall-clock line on stderr when `BREP_PROFILE` is set — the same switch
3204/// `imprint.profile` and `assemble.*_ms` use — so a REFUSED boolean, whose
3205/// `KernelDiagnostics` never reach a caller, still shows where its time went.
3206fn profile_stage(code: &str, ms: f64) {
3207    let row = match code {
3208        "heal_ms" => Some("boolean.operand_prepare"),
3209        "imprint_ms" => Some("boolean.imprint"),
3210        "edge_split_ms" => Some("boolean.edge_split"),
3211        "fragment_ms" => Some("boolean.fragment"),
3212        "select_ms" => Some("boolean.select"),
3213        "assemble_ms" => Some("boolean.assemble"),
3214        "face_merge_ms" => Some("boolean.face_merge"),
3215        "soundness_ms" => Some("boolean.soundness"),
3216        "operand_closure_ms" => Some("boolean.operand_closure"),
3217        "seam_prepare_ms" => Some("boolean.seam_prepare"),
3218        "final_validate_ms" => Some("boolean.final_validate"),
3219        _ => None,
3220    };
3221    if let Some(row) = row { profile::record(row, ms); }
3222    if crate::profile::profile_enabled() {
3223        profile_line!("boolean.{code}={ms:.2}");
3224    }
3225}
3226
3227/// `BREP_BOOLEAN_DUMP` names a directory. Every binary boolean then writes its
3228/// stages there as JSON — the two split operands, the selected fragments, the
3229/// assembled solid and the merged one — numbered per process, so a probe can
3230/// read a face's loops at each stage without replaying the document.
3231struct BooleanStageDump {
3232    directory: std::path::PathBuf,
3233    serial: usize,
3234}
3235
3236impl BooleanStageDump {
3237    fn open() -> Option<Self> {
3238        static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3239        let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
3240        let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3241        Some(Self { directory: directory.into(), serial })
3242    }
3243
3244    fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
3245        let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
3246        match serde_json::to_string(value) {
3247            Ok(text) => {
3248                if let Err(error) = std::fs::write(&path, text) {
3249                    eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
3250                }
3251            }
3252            Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
3253        }
3254    }
3255}
3256
3257/// The tolerance policy a binary boolean of `first` and `second` runs under.
3258pub fn boolean_policy(
3259    first: &BrepSolid,
3260    second: &BrepSolid,
3261    options: &BooleanOptions,
3262) -> Result<KernelTolerances, KernelRefusal> {
3263    let policy = options
3264        .tolerances
3265        .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
3266    policy.check().or_input(KernelStage::Collect, "tolerances")?;
3267    Ok(policy)
3268}
3269
3270/// The operands as the imprint reads them: healed, with their band seams
3271/// normalized.
3272fn prepared_operands(
3273    first: &BrepSolid,
3274    second: &BrepSolid,
3275    policy: &KernelTolerances,
3276) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3277    // Fuse-first operand healing (Lever A): before any intersection touches the
3278    // operands, snap each one's near-coincident / off-plane vertices to exact
3279    // and re-anchor the incident edge curves onto them, so noisy
3280    // near-degenerate input (points that should coincide but drifted, vertices
3281    // a few microns off a planar face) cannot tip a fixed downstream band over
3282    // the edge.  Healing is per-operand, validate-gated, and — because a clean
3283    // operand has no vertices within `heal_tol` and none off its planes — a
3284    // no-op that leaves the boolean output byte-identical on clean inputs.
3285    let stage_started = Instant::now();
3286    let mut first_owned = first.clone();
3287    let mut second_owned = second.clone();
3288    crate::heal::heal_operands(&mut first_owned, policy)?;
3289    crate::heal::heal_operands(&mut second_owned, policy)?;
3290    profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3291    // Then refit, on each operand's own carriers, any inherited trim off the
3292    // pcurve construction contract whose edge lies on every incident carrier
3293    // (`heal::refit_inherited_trims`; a byte-identical no-op without one).
3294    let refit_started = Instant::now();
3295    crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
3296    crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
3297    profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
3298    if crate::profile::profile_enabled() {
3299        let (hits, misses) = crate::reading_memo::counts();
3300        profile_line!("boolean.reading_memo hits={hits} misses={misses}");
3301        let (served, stored) = crate::heal::refit_memo_counts_served_stored();
3302        profile_line!("boolean.refit_memo served={served} stored={stored}");
3303        let (served, stored, mismatches) = crate::heal::claim_record_memo_counts();
3304        profile_line!("boolean.claim_record_memo served={served} stored={stored} check_mismatches={mismatches}");
3305    }
3306    profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3307    // Seamless full-period band faces (STEP import) break the seam-aware
3308    // imprint/arrangement machinery; normalize them to the seam-carrying
3309    // topology native periodic faces use. No-op on operands without such
3310    // faces. See `insert_periodic_band_seam_edges`.
3311    normalize_operand_band_seams(&mut first_owned)?;
3312    normalize_operand_band_seams(&mut second_owned)?;
3313    Ok((first_owned, second_owned))
3314}
3315
3316fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
3317    let mut imprint_options = options.imprint.clone();
3318    imprint_options.tolerance = tolerance;
3319    imprint_options
3320}
3321
3322/// The two operands a binary boolean's arrangement reads: prepared as the
3323/// boolean prepares them, with every boundary edge split where the imprint's
3324/// sections meet it. These are the `NNN-first` and `NNN-second` stages
3325/// `BREP_BOOLEAN_DUMP` writes, not the operands at the boolean's entry.
3326///
3327/// A boolean must read the same on these as on the operands it split them
3328/// from: the splits are vertices its own imprint puts on those edges anyway.
3329/// Where it does not, an imprint lane is deciding on what the input happens to
3330/// have split, and that is a defect.
3331pub fn boolean_split_operands(
3332    first: &BrepSolid,
3333    second: &BrepSolid,
3334    options: &BooleanOptions,
3335) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3336    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
3337        return scaled.run(
3338            || boolean_split_operands(first, second, options),
3339            || {
3340                let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
3341                    .map_err(|error| scaled.refusal(error))?;
3342                Ok((scaled.back(&split_first)?, scaled.back(&split_second)?))
3343            },
3344        );
3345    }
3346    let policy = boolean_policy(first, second, options)?;
3347    let (first, second) = prepared_operands(first, second, &policy)?;
3348    let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
3349    let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
3350    let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
3351    Ok((split_first, split_second))
3352}
3353
3354/// Conservative bounds of an operand: its vertices and every face's control
3355/// net (a NURBS lies in the hull of its controls). A control net that cannot
3356/// be read bounds everything, so nothing is left out for want of a reading.
3357fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
3358    let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
3359    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3360        match crate::Aabb::from_surface_controls(&face.surface) {
3361            Ok(face_bounds) => bounds.include(face_bounds),
3362            Err(_) => {
3363                return crate::Aabb {
3364                    minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
3365                    maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
3366                }
3367            }
3368        }
3369    }
3370    bounds
3371}
3372
3373/// Row 12's gate: the boxes are separated or touch exactly in at least two
3374/// axes. A trimmed face lies in its carrier's control-net box when every
3375/// weight is positive, so a point interior to both operands would lie
3376/// strictly inside both boxes in every axis; two such axes leave a line or a
3377/// point of contact, which has no area to merge.
3378fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3379    apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
3380}
3381
3382/// One apart axis: no point can be interior to both operands (see
3383/// [`line_or_point_contact`]), though the boxes may share a face's area.
3384fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3385    apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
3386}
3387
3388/// The axes in which the boxes are separated or touch exactly (no band).
3389fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
3390    let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
3391    [
3392        apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
3393        apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
3394        apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
3395    ]
3396    .into_iter()
3397    .filter(|&apart| apart)
3398    .count()
3399}
3400
3401/// A plain solid whose faces lie in their control-net boxes: every weight positive.
3402fn plain_hull_solid(solid: &BrepSolid) -> bool {
3403    solid.kind == crate::BodyKind::Solid
3404        && solid.cells.is_empty()
3405        && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
3406            face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
3407        })
3408}
3409
3410/// `BREP_SCOPE_PROVED_APART` (default on since the 2026-11-19 promotion;
3411/// `=0` scans every face whose box reaches the other operand): see
3412/// [`soundness_candidates`].
3413fn scope_proved_apart_on() -> bool {
3414    switch!(live "BREP_SCOPE_PROVED_APART", true)
3415}
3416
3417/// The result faces the soundness scan reads under pass-through: the
3418/// examined faces (touched and their neighbours) and every other face whose
3419/// control-net box reaches the OTHER operand's bounds within `band`. A face
3420/// outside both is an operand's own, clear of everything the operation added.
3421///
3422/// PROVED APART (`BREP_SCOPE_PROVED_APART`): with `unproved` (the imprint's
3423/// [`crate::ImprintResultRecord::faces_in_unproved_pairs`]) and both operands
3424/// plain hull solids, a face whose box reaches the other operand is still
3425/// left out when the imprint PROVED it clear of every face of the other
3426/// operand (its box met none, or each pair it met was classified `Disjoint`
3427/// or proved apart by span hulls). A pair the imprint skipped, marched to
3428/// nothing, or could not prove keeps the face in. A whole-body scan of a body
3429/// nested inside the other operand's box (a closed hollow: the source less
3430/// its inward offset, untouched) read every face of both for that alone.
3431fn soundness_candidates(
3432    solid: &BrepSolid,
3433    scope: &AssemblyScope,
3434    bounds: [crate::Aabb; 2],
3435    band: f64,
3436    unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3437) -> HashSet<u64> {
3438    let mut candidates = HashSet::default();
3439    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3440        if scope.examined.contains(&face.id) {
3441            candidates.insert(face.id);
3442            continue;
3443        }
3444        let Some(&operand) = scope.operand_of.get(&face.id) else {
3445            candidates.insert(face.id);
3446            continue;
3447        };
3448        let other = bounds[usize::from(operand == 0)];
3449        match crate::Aabb::from_surface_controls(&face.surface) {
3450            Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3451            _ => {
3452                let proved_clear = unproved.is_some_and(|unproved| {
3453                    scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3454                });
3455                if !proved_clear {
3456                    candidates.insert(face.id);
3457                }
3458            }
3459        }
3460    }
3461    candidates
3462}
3463
3464
3465/// `BREP_TOUCHING_EMPTY` (default on; =0 refuses as before): an intersection
3466/// or difference of operands that only touch, which selects no fragment,
3467/// returns the empty solid on the sample witnesses and an inclusion-exclusion
3468/// volume of zero (`boolean_pipeline`). brep-conformance's touching families
3469/// (boxes face to face, flush pockets, contact along a line) refused with
3470/// "operation produced no boundary faces" where the regularized result is
3471/// empty.
3472fn touching_empty_enabled() -> bool {
3473    switch!("BREP_TOUCHING_EMPTY", true)
3474}
3475
3476thread_local! {
3477    /// Set while a touching-empty proof reads another boolean of its pair, so
3478    /// that reading cannot itself be rescued as empty.
3479    static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3480}
3481
3482/// Whether a cylinder face of `first` and one of `second`, or a ball of each,
3483/// reach into each other by more than `tolerance`: the closed-form depth of
3484/// their lens (radii against the closest distance of the axes, at any angle,
3485/// or of the centres; outer or nested), counted only where the two faces'
3486/// boxes overlap by more than `tolerance` along every axis (two cylinders
3487/// meeting end to end through their caps do not count).
3488fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3489    use crate::AnalyticSurface as A;
3490    fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface, &crate::FaceRecord)> {
3491        solid
3492            .shells
3493            .iter()
3494            .flat_map(|shell| &shell.faces)
3495            .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface, face)))
3496            .collect()
3497    }
3498    // A face's extent along `axis`: its control points' (the hull holds it).
3499    let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3500        surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3501            let at = point.dot(axis);
3502            (low.min(at), high.max(at))
3503        })
3504    };
3505    let crossing = |distance: f64, ra: f64, rb: f64| {
3506        let outer = ra + rb - distance;
3507        let nested = distance - (ra - rb).abs();
3508        outer > tolerance && nested > tolerance
3509    };
3510    let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3511        (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3512            && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3513            && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3514    };
3515    for (a, box_a, surface_a, face_a) in faces(first) {
3516        for (b, box_b, surface_b, face_b) in faces(second) {
3517            if !boxes_overlap(&box_a, &box_b) {
3518                continue;
3519            }
3520            match (a, b) {
3521                (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3522                    if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3523                {
3524                    let offset = fb.origin.sub(fa.origin);
3525                    let normal = fa.axis.cross(fb.axis);
3526                    // Parallel walls meet only where their extents along the
3527                    // axis overlap (two cylinders end to end touch at a cap).
3528                    if normal.length() <= 1e-12 {
3529                        let (low_a, high_a) = along(surface_a, fa.axis);
3530                        let (low_b, high_b) = along(surface_b, fa.axis);
3531                        if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3532                            continue;
3533                        }
3534                    }
3535                    let apart = if normal.length() <= 1e-12 {
3536                        offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3537                    } else {
3538                        offset.dot(normal).abs() / normal.length()
3539                    };
3540                    if crossing(apart, a0.abs(), b0.abs()) {
3541                        return true;
3542                    }
3543                }
3544                (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3545                    // The two balls' lens meets the faces only along the
3546                    // circle where the spheres cross; a face that circle is
3547                    // proven off (a part of a cavity the circle passes
3548                    // beside) holds no lens, however deep the carriers' is.
3549                    if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb)
3550                        && !circle_off_face(face_a, first, (fa.origin, *ra), (fb.origin, *rb), tolerance)
3551                        && !circle_off_face(face_b, second, (fb.origin, *rb), (fa.origin, *ra), tolerance)
3552                    {
3553                        return true;
3554                    }
3555                }
3556                _ => {}
3557            }
3558        }
3559    }
3560    false
3561}
3562
3563/// Whether the circle where the sphere `own` (centre, radius), carrying
3564/// `face`, crosses the sphere `other` is proven to lie off `face`: every edge
3565/// of the face stands clear of `other` by more than `tolerance` (its control
3566/// hull, halved where it does not decide, wholly inside or wholly outside),
3567/// so the circle, which lies on `other`, never meets the face's boundary and
3568/// is wholly on the face or wholly off it; and one point of it is outside the
3569/// face's trim. A face with no trim, or anything unproven, is not off.
3570fn circle_off_face(face: &crate::FaceRecord, solid: &BrepSolid, own: (Vec3, f64), other: (Vec3, f64), tolerance: f64) -> bool {
3571    use crate::classification::{parameter_point_in_face, PolygonClass};
3572    let ((ca, ra), (cb, rb)) = (own, other);
3573    if face.loops.iter().all(|lp| lp.coedges.is_empty()) {
3574        return false;
3575    }
3576    // A curve's points on [t0, t1] all inside or all outside the other ball:
3577    // its control points (positive weights: the hull holds the curve) all
3578    // within `rb - tolerance` of the centre, or their box farther than
3579    // `rb + tolerance` from it; otherwise each half, a few times over.
3580    fn clear(curve: &crate::NurbsCurve, depth: u32, centre: Vec3, radius: f64, tolerance: f64) -> bool {
3581        let points: Option<Vec<Vec3>> = curve.control_points.iter().map(|control| if control.w > 0.0 { control.point().ok() } else { None }).collect();
3582        let Some(points) = points else { return false };
3583        if points.iter().all(|point| point.sub(centre).length() < radius - tolerance) {
3584            return true;
3585        }
3586        let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
3587        for point in &points {
3588            low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
3589            high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
3590        }
3591        let near = Vec3::new(centre.x.clamp(low.x, high.x), centre.y.clamp(low.y, high.y), centre.z.clamp(low.z, high.z));
3592        if near.sub(centre).length() > radius + tolerance {
3593            return true;
3594        }
3595        if depth == 0 {
3596            return false;
3597        }
3598        let Ok([t0, t1]) = curve.domain() else { return false };
3599        match curve.split(0.5 * (t0 + t1)) {
3600            Ok((left, right)) => clear(&left, depth - 1, centre, radius, tolerance) && clear(&right, depth - 1, centre, radius, tolerance),
3601            Err(_) => false,
3602        }
3603    }
3604    for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
3605        let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false };
3606        let Ok([d0, d1]) = edge.curve.domain() else { return false };
3607        // The edge's own span of its curve.
3608        let mut span = edge.curve.clone();
3609        if edge.t1 < d1 {
3610            match span.split(edge.t1) {
3611                Ok((left, _)) => span = left,
3612                Err(_) => return false,
3613            }
3614        }
3615        if edge.t0 > d0 {
3616            match span.split(edge.t0) {
3617                Ok((_, right)) => span = right,
3618                Err(_) => return false,
3619            }
3620        }
3621        if !clear(&span, 10, cb, rb, tolerance) {
3622            return false;
3623        }
3624    }
3625    let axis = cb.sub(ca);
3626    let distance = axis.length();
3627    let Ok(n) = axis.normalized() else { return false };
3628    let along = (distance * distance + ra * ra - rb * rb) / (2.0 * distance);
3629    let across = ra * ra - along * along;
3630    let Ok(side) = n.perpendicular() else { return false };
3631    if !(across > 0.0) {
3632        return false;
3633    }
3634    let point = ca.add(n.scale(along)).add(side.scale(across.sqrt()));
3635    let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false };
3636    matches!(parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9), Ok(PolygonClass::Outside))
3637}
3638
3639
3640/// The empty solid a legitimately empty boolean returns.
3641fn empty_solid() -> BrepSolid {
3642    BrepSolid {
3643        mass_properties_cache: Default::default(),
3644        cells: Default::default(),
3645        id: 0,
3646        vertices: Vec::new(),
3647        edges: Vec::new(),
3648        shells: Vec::new(),
3649        genus: 0,
3650        kind: crate::BodyKind::Solid,
3651    }
3652}
3653
3654/// The two operands as one solid, shell by shell: ids minted afresh in the
3655/// assembler's order (the first operand's faces, then the second's), the
3656/// second operand's face names suffixed where they clash with the first's
3657/// as the assembler suffixes a split face, geometry copied byte for byte,
3658/// genus the sum. Nothing is welded: the operands are disjoint.
3659fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3660    let mut vertices = Vec::new();
3661    let mut edges = Vec::new();
3662    let mut shells = Vec::new();
3663    let mut used_face_names = HashSet::<String>::default();
3664    let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3665    for operand in [first, second] {
3666        let vertex_base = vertices.len() as u64;
3667        let edge_base = edges.len() as u64;
3668        let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3669        for (index, vertex) in operand.vertices.iter().enumerate() {
3670            let id = vertex_base + index as u64 + 1;
3671            vertex_ids.insert(vertex.id, id);
3672            vertices.push(VertexRecord { id, point: vertex.point });
3673        }
3674        let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3675        for (index, edge) in operand.edges.iter().enumerate() {
3676            let id = edge_base + index as u64 + 1;
3677            edge_ids.insert(edge.id, id);
3678            edges.push(EdgeRecord {
3679                id,
3680                curve: edge.curve.clone(),
3681                t0: edge.t0,
3682                t1: edge.t1,
3683                start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3684                end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3685                degenerate: edge.degenerate,
3686                name: edge.name.clone(),
3687            });
3688        }
3689        for shell in &operand.shells {
3690            let mut faces = Vec::with_capacity(shell.faces.len());
3691            for face in &shell.faces {
3692                let loops = face
3693                    .loops
3694                    .iter()
3695                    .map(|loop_record| {
3696                        let coedges = loop_record
3697                            .coedges
3698                            .iter()
3699                            .map(|coedge| {
3700                                let id = next_coedge_id;
3701                                next_coedge_id += 1;
3702                                CoedgeRecord {
3703                                    id,
3704                                    edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3705                                    forward: coedge.forward,
3706                                    pcurve: coedge.pcurve.clone(),
3707                                }
3708                            })
3709                            .collect();
3710                        let id = next_loop_id;
3711                        next_loop_id += 1;
3712                        LoopRecord { id, coedges }
3713                    })
3714                    .collect();
3715                let name = face.name.clone().map(|base| {
3716                    if used_face_names.insert(base.clone()) {
3717                        base
3718                    } else {
3719                        let mut suffix = 1usize;
3720                        loop {
3721                            let candidate = format!("{base}_{suffix}");
3722                            if used_face_names.insert(candidate.clone()) {
3723                                break candidate;
3724                            }
3725                            suffix += 1;
3726                        }
3727                    }
3728                });
3729                faces.push(FaceRecord {
3730                    id: next_face_id,
3731                    surface: face.surface.clone(),
3732                    same_sense: face.same_sense,
3733                    loops,
3734                    name,
3735                });
3736                next_face_id += 1;
3737            }
3738            shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3739        }
3740    }
3741    BrepSolid {
3742        mass_properties_cache: Default::default(),
3743        cells: Default::default(),
3744        id: 1,
3745        vertices,
3746        edges,
3747        shells,
3748        genus: first.genus + second.genus,
3749        kind: crate::BodyKind::Solid,
3750    }
3751}
3752
3753/// The binary boolean. The second value is the soundness scan's candidate
3754/// faces under pass-through (`None` reads the whole result).
3755fn boolean_pipeline(
3756    first: &BrepSolid,
3757    second: &BrepSolid,
3758    operation: BooleanOperation,
3759    options: &BooleanOptions,
3760    tangent_nodes: &mut Vec<Vec3>,
3761) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3762    let _work = crate::imprint::work_profile::Scope::open("boolean");
3763    let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3764    let (first, second) = match &replaced_operands {
3765        Some((first, second)) => (first, second),
3766        None => (first, second),
3767    };
3768    let policy = boolean_policy(first, second, options)?;
3769    let tolerance = policy.model;
3770    // DISJOINT FAST PATH. A box test on the control-net hulls, not "no
3771    // section evidence": a tool inside the other operand also leaves no
3772    // evidence and must stay on the pipeline, where a union is the outer
3773    // operand, a subtract the outer with a void shell and an intersect the
3774    // tool. Operands clear of each other by more than the search band can
3775    // touch nothing, so nothing is prepared, imprinted, assembled or
3776    // scanned: a union is the two operands side by side, a subtract the
3777    // first operand, an intersect the legitimate-empty result below. The
3778    // soundness scan is skipped as well (an empty candidate set): the
3779    // operands cannot cross each other, and a crossing an operand carried in
3780    // passes through the full acceptance unrepaired exactly the same.
3781    //
3782    // CONTACT FAST PATH (row 12): boxes that only meet along a line or at a
3783    // point, read exactly; see `line_or_point_contact`.
3784    let bounds = [operand_bounds(first), operand_bounds(second)];
3785    let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3786    let contact = !disjoint
3787        && contact_fast_path(options)
3788        && options.seam_reseat_later_references.is_some()
3789        && line_or_point_contact(first, second, bounds);
3790    // One apart axis already leaves no common interior, so an intersect is
3791    // empty even where the boxes share a face's area (which is why a union or
3792    // a subtract stays on the pipeline). Nothing survives to carry an id, so
3793    // no caller has to say what follows.
3794    let contact = contact
3795        || (!disjoint
3796            && matches!(operation, BooleanOperation::Intersect)
3797            && contact_fast_path(options)
3798            && boxes_share_no_interior(first, second, bounds));
3799    if disjoint || contact {
3800        let operation_started = Instant::now();
3801        let mut diagnostics = KernelDiagnostics::default();
3802        diagnostics.count_n(
3803            "collect.faces",
3804            first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3805        );
3806        diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3807        diagnostics.measure_max("tolerance.model", policy.model);
3808        diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3809        let value = match operation {
3810            BooleanOperation::Union => concatenate_disjoint(first, second),
3811            BooleanOperation::Subtract => first.clone(),
3812            BooleanOperation::Intersect => {
3813                diagnostics.event(
3814                    DiagnosticSeverity::Info,
3815                    KernelStage::Select,
3816                    "boolean.empty_result",
3817                    format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3818                );
3819                empty_solid()
3820            }
3821        };
3822        let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3823        profile_stage("disjoint_fast_path_ms", stage_ms);
3824        diagnostics.measure_max("timing.total_ms", stage_ms);
3825        return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3826    }
3827    let heal_started = Instant::now();
3828    let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3829    let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3830    let first = &first_owned;
3831    let second = &second_owned;
3832
3833    let mut diagnostics = KernelDiagnostics::default();
3834    // Operand preparation ran before `timing.total_ms` opens and was absent
3835    // from every phase split; it is 1.6 of a disjoint box union's 7.2 ms.
3836    diagnostics.measure_max("timing.heal_ms", heal_ms);
3837    // Every pcurve fit made while this scope is open — the imprint's sections,
3838    // the assembler's rebuilt trims, the merge's re-fits — is tallied, so the
3839    // outcome can say whether every curved trim reached its floor instead of
3840    // letting a sample-ceiling exit pass for a met one (`pcurve.unmet_floor`).
3841    let fit_scope = crate::PcurveFitScope::open();
3842    // And every POLYLINE fit: a marched section's interpolant is measured
3843    // against the tolerance it was given, so `fit.polyline.unmet_tolerance`
3844    // reports a section that could not reach it (`geometry/fit.rs`).
3845    let polyline_scope = crate::PolylineFitScope::open();
3846    let operation_started = Instant::now();
3847    diagnostics.count_n(
3848        "collect.faces",
3849        first
3850            .shells
3851            .iter()
3852            .chain(&second.shells)
3853            .map(|shell| shell.faces.len() as u64)
3854            .sum(),
3855    );
3856    diagnostics.measure_max("tolerance.model", policy.model);
3857    diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3858
3859    let imprint_options = boolean_imprint_options(options, tolerance);
3860    let stage_started = Instant::now();
3861    let imprint = build_imprints(first, second, &imprint_options)?;
3862    tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3863    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3864        for piece in &imprint.pieces {
3865            let start = piece.curve.evaluate(piece.t0);
3866            let end = piece.curve.evaluate(piece.t1);
3867            eprintln!(
3868                "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3869                piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3870            );
3871        }
3872        for entry in &imprint.by_face {
3873            eprintln!(
3874                "by_face operand={} face={} pieces={:?}",
3875                entry.operand, entry.face_id, entry.piece_ids
3876            );
3877        }
3878        for split in &imprint.edge_splits {
3879            eprintln!(
3880                "edge_split operand={} edge={} params={:?}",
3881                split.operand, split.edge_id, split.parameters
3882            );
3883        }
3884    }
3885    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3886    profile_stage("imprint_ms", stage_ms);
3887    diagnostics.measure_max("timing.imprint_ms", stage_ms);
3888    diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3889    diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3890    diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3891    let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3892    diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3893    diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3894    let touch = TouchCensus::build([first, second], &imprint);
3895    touch.report(&mut diagnostics);
3896    let stage_started = Instant::now();
3897    let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3898    let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3899    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3900    profile_stage("edge_split_ms", stage_ms);
3901    diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3902    let stage_started = Instant::now();
3903    crate::classification::classify_profile_begin();
3904    let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3905    let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3906    crate::classification::classify_profile_report("fragment");
3907    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3908    profile_stage("fragment_ms", stage_ms);
3909    diagnostics.measure_max("timing.fragment_ms", stage_ms);
3910    diagnostics.count_n(
3911        "fragment.candidates",
3912        (fragments_a.len() + fragments_b.len()) as u64,
3913    );
3914    touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3915    // Operand surface samples for the LEGITIMATE-EMPTY adjudication below:
3916    // every fragment test point is a 3D point ON its operand's boundary and
3917    // inside its face trim, so they witness where the operands' materials sit
3918    // relative to each other without extra geometry work.
3919    let a_surface_samples: Vec<Vec3> = fragments_a
3920        .iter()
3921        .flat_map(|fragment| {
3922            std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3923        })
3924        .collect();
3925    let b_surface_samples: Vec<Vec3> = fragments_b
3926        .iter()
3927        .flat_map(|fragment| {
3928            std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3929        })
3930        .collect();
3931    let stage_started = Instant::now();
3932    let mut barrier_edges: HashSet<(u8, u64)> = imprint
3933        .pieces
3934        .iter()
3935        .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
3936        .collect();
3937    barrier_edges.extend(imprint.barrier_edges.iter().copied());
3938    // The barrier set is keyed on ORIGINAL edge ids, but a barrier edge the
3939    // imprint also SPLIT (rotated equator-tangency: the overlapped cap ring
3940    // gains a junction at the sphere-seam crossing) reaches fragment
3941    // selection as its minted sub-edge ids. Remap the barrier through the
3942    // split ledger — keeping the originals too for unsplit references.
3943    for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
3944        let minted: Vec<(u8, u64)> = barrier_edges
3945            .iter()
3946            .filter(|(barrier_operand, _)| *barrier_operand == operand)
3947            .filter_map(|(_, edge_id)| split_map.get(edge_id))
3948            .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
3949            .collect();
3950        barrier_edges.extend(minted);
3951    }
3952    crate::classification::classify_profile_begin();
3953    let coincident = coincident_pairs(
3954        &fragments_a,
3955        &fragments_b,
3956        first,
3957        second,
3958        &imprint.cosurface_pairs,
3959        tolerance,
3960    )?;
3961    let sector_mode = sector::sector_mode(options);
3962    let mut select_census = sector::SelectCensus::default();
3963    let mut selected = select_fragments(
3964        fragments_a,
3965        fragments_b,
3966        first,
3967        second,
3968        operation,
3969        tolerance,
3970        &barrier_edges,
3971        &imprint,
3972        &coincident,
3973        sector_mode,
3974        &mut select_census,
3975    )?;
3976    let resewn = resew_coincident_rims(
3977        &mut selected,
3978        [&split_first, &split_second],
3979        [first, second],
3980        &imprint.cosurface_pairs,
3981        operation,
3982        tolerance,
3983    )?;
3984    diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
3985    diagnostics.count_n("select.rims_resewn", resewn as u64);
3986    crate::classification::classify_profile_report("select");
3987    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3988    profile_stage("select_ms", stage_ms);
3989    diagnostics.measure_max("timing.select_ms", stage_ms);
3990    diagnostics.count_n("select.fragments", selected.len() as u64);
3991    // One census line per selection as well.
3992    diagnostics.count_n("select.sector_eligible", select_census.eligible);
3993    diagnostics.count_n("select.sector_primary", select_census.sector_primary);
3994    diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
3995    diagnostics.count_n("select.sector_disagree", select_census.disagree);
3996    diagnostics.count_n("select.ray_casts", select_census.ray_casts);
3997    diagnostics.count_n("select.on_votes", select_census.on_votes);
3998    diagnostics.count_n("select.overturns", select_census.overturns);
3999    if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
4000        sector::sector_census_line(|| {
4001            format!(
4002                "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
4003                selected.len(),
4004                select_census.eligible,
4005                select_census.sector_primary,
4006                select_census.sector_fallback,
4007                select_census.disagree,
4008                select_census.ray_casts,
4009                select_census.on_votes,
4010                select_census.overturns
4011            )
4012        });
4013    }
4014    // LEGITIMATE-EMPTY RESULTS: an intersect of DISJOINT operands (or a
4015    // subtract whose left operand is entirely CONSUMED by the right) selects
4016    // zero fragments, and assembly used to refuse with "operation produced no
4017    // boundary faces" — 384 of the 474 post-wrapped-band pool errors were
4018    // this, not bugs. Empty is only blessed on TWO independent proofs:
4019    //   (a) the imprint recorded NO section evidence (no accepted pierce
4020    //       seed, no traced SSI branch, no minted piece) — a silently-lost
4021    //       section (the trial-489 class) always leaves upstream evidence
4022    //       even when every downstream sub-segment is clipped away, while
4023    //       pure material disjointness leaves none (verified: 489's
4024    //       recreated silent-miss state keeps erroring; per-face surface
4025    //       samples ALONE missed its 235 mm³ pocket, which is why (a) is
4026    //       required and sampling alone was rejected);
4027    //   (b) the operands' surface samples agree (every fragment test point
4028    //       classified against the other solid):
4029    //       intersect — no sample of either operand strictly inside the
4030    //       other; subtract — no left-operand sample strictly outside the
4031    //       right.
4032    // Contact/graze pairs (evidence exists, material still disjoint) stay
4033    // errors — conservative by design. Escape hatch: BREP_EMPTY_BOOLEAN=0
4034    // restores the unconditional error.
4035    if selected.is_empty()
4036        && !imprint.section_evidence
4037        && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
4038    {
4039        let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
4040            for &sample in samples {
4041                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
4042                    return Ok(true);
4043                }
4044            }
4045            Ok(false)
4046        };
4047        let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
4048            for &sample in samples {
4049                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
4050                    return Ok(true);
4051                }
4052            }
4053            Ok(false)
4054        };
4055        let legitimate = match operation {
4056            BooleanOperation::Intersect => {
4057                !strictly_inside(&a_surface_samples, second)?
4058                    && !strictly_inside(&b_surface_samples, first)?
4059            }
4060            BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
4061            BooleanOperation::Union => false,
4062        };
4063        if legitimate {
4064            diagnostics.event(
4065                DiagnosticSeverity::Info,
4066                KernelStage::Select,
4067                "boolean.empty_result",
4068                format!("{operation:?} of witnessed-non-overlapping operands is empty"),
4069            );
4070            fit_scope.close().report_into(&mut diagnostics);
4071            polyline_scope.close().report_into(&mut diagnostics);
4072            diagnostics.measure_max(
4073                "timing.total_ms",
4074                operation_started.elapsed().as_secs_f64() * 1_000.0,
4075            );
4076            return Ok((
4077                KernelOutcome {
4078                    value: empty_solid(),
4079                    diagnostics,
4080                },
4081                None,
4082            ));
4083        }
4084    }
4085    // TOUCHING-EMPTY RESULTS (`BREP_TOUCHING_EMPTY`): operands that only
4086    // touch (faces in contact, a flush pocket's tool inside its block) leave
4087    // section evidence, so the legitimate-empty proof above does not apply,
4088    // and the regularized intersection or difference is empty all the same.
4089    // Empty is blessed here on two independent proofs: the same surface-sample
4090    // witnesses as above, and inclusion-exclusion over another exact-lane
4091    // boolean of the same pair, which must put this one's volume at zero to
4092    // a billionth of the larger operand's.
4093    if selected.is_empty()
4094        && imprint.section_evidence
4095        && !matches!(operation, BooleanOperation::Union)
4096        && touching_empty_enabled()
4097        && !TOUCHING_PROOF.with(std::cell::Cell::get)
4098    {
4099        let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
4100            for &sample in samples {
4101                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
4102                    return Ok(true);
4103                }
4104            }
4105            Ok(false)
4106        };
4107        let witnessed = match operation {
4108            BooleanOperation::Intersect => {
4109                !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
4110            }
4111            BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
4112            BooleanOperation::Union => false,
4113        };
4114        // Two cylinders, or two balls, can meet in a lens a hair deep
4115        // (parallel cylinders 1.8e-6 into each other) that the
4116        // imprint misses and every other boolean of the pair also reads as a
4117        // touch. Their depth is closed form; one beyond the model tolerance
4118        // is a real body, which is not empty.
4119        let overlap_free = !hair_deep_overlap(first, second, tolerance);
4120        if witnessed && overlap_free {
4121            TOUCHING_PROOF.with(|flag| flag.set(true));
4122            let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
4123            TOUCHING_PROOF.with(|flag| flag.set(false));
4124            // Touching operands read zero to rounding (about 1e-13 here); a
4125            // band in model tolerances over the area would also bless a
4126            // genuine overlap by a hair (parallel cylinders a few microns
4127            // deep), so it is a billionth of the larger operand's volume.
4128            let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
4129            let band = 1e-9 * volume(first).max(volume(second));
4130            if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
4131                diagnostics.event(
4132                    DiagnosticSeverity::Info,
4133                    KernelStage::Select,
4134                    "boolean.empty_touching",
4135                    format!(
4136                        "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
4137                        proof.formula, proof.expected, proof.reading
4138                    ),
4139                );
4140                fit_scope.close().report_into(&mut diagnostics);
4141                polyline_scope.close().report_into(&mut diagnostics);
4142                diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
4143                return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
4144            }
4145        }
4146    }
4147    let solids = [(0, &split_first), (1, &split_second)]
4148        .into_iter()
4149        .collect::<HashMap<_, _>>();
4150    let dump = BooleanStageDump::open();
4151    if let Some(dump) = &dump {
4152        dump.write("first", &split_first);
4153        dump.write("second", &split_second);
4154        dump.write("selected", &selected);
4155    }
4156    let stage_started = Instant::now();
4157    // Result face `k` is minted from `selected[k - 1]` (one face per fragment,
4158    // ids from 1 in order): the map the tangent-section attribution reads a
4159    // refusal's face ids through.
4160    let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
4161        Vec::new()
4162    } else {
4163        selected
4164            .iter()
4165            .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
4166            .collect()
4167    };
4168    // A record the grazing-pierce path minted (`TangentSectionRecord::
4169    // grazing` non-empty, whether or not the lane then found a contact to
4170    // name) yields to a tangent NODE the imprint classified: the node is the
4171    // nearer cause and `attribute_to_tangent_node` names it on the way out
4172    // (the G1 elbow over its own-radius arm: the arm's cap circle also
4173    // pierces the elbow under the seed gate, and the lane sees the join).
4174    let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
4175        .tangent_sections
4176        .iter()
4177        .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
4178        .cloned()
4179        .collect();
4180    let attribute = |error: KernelRefusal| {
4181        attribute_to_tangent_section(error, &attributable, &assembled_origins)
4182    };
4183    let cellular_result = matches!(operation, BooleanOperation::Union)
4184        && cellular::enabled(options)
4185        && cellular::complete_contact(first, second, &selected, tolerance);
4186    let (solid, scope) = if cellular_result {
4187        (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
4188            .map_err(attribute)?, None)
4189    } else if untouched_passthrough(options) {
4190        assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
4191            .map_err(attribute)?
4192    } else {
4193        (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
4194    };
4195    if let Some(scope) = &scope {
4196        diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
4197    }
4198    if let Some(dump) = &dump {
4199        dump.write("assembled", &solid);
4200    }
4201    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4202    profile_stage("assemble_ms", stage_ms);
4203    diagnostics.measure_max("timing.assemble_ms", stage_ms);
4204    let stage_started = Instant::now();
4205    let declines_before = crate::face_merge::declines_served();
4206    let area_checks_before = crate::face_merge::boundary_area_checks();
4207    if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
4208        let issues = solid.validate();
4209        eprintln!(
4210            "pre-merge validation: {} issue(s){}",
4211            issues.len(),
4212            issues
4213                .first()
4214                .map(|issue| format!(" — first: {}", issue.message))
4215                .unwrap_or_default()
4216        );
4217    }
4218    let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
4219        && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
4220    {
4221        let merged = match &scope {
4222            // Every pair merges as before (an operand's own coplanar
4223            // neighbours included); the closing validation reads the
4224            // examined faces and the merged ones.
4225            Some(scope) => merge_same_surface_faces_scoped(
4226                &solid,
4227                tolerance,
4228                &options.keep_unmerged_name_substrs,
4229                &scope.examined,
4230            )?,
4231            None => merge_same_surface_faces_excluding(
4232                &solid,
4233                tolerance,
4234                &options.keep_unmerged_name_substrs,
4235            )?,
4236        };
4237        // Face merging can make previously separate collinear boundary
4238        // segments incident to the same pair of faces. Run continuation
4239        // cleanup again, matching the post-merge normalization performed by
4240        // the former assembly pipeline.
4241        let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
4242        rejoin::rejoin_unless_referenced(merged, options, tolerance)
4243    } else {
4244        solid
4245    };
4246    if let Some(dump) = &dump {
4247        dump.write("merged", &solid);
4248    }
4249    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4250    profile_stage("face_merge_ms", stage_ms);
4251    if crate::profile::profile_enabled() {
4252        profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
4253        let area_checks = crate::face_merge::boundary_area_checks();
4254        if area_checks != area_checks_before {
4255            profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
4256        }
4257    }
4258    diagnostics.measure_max("timing.face_merge_ms", stage_ms);
4259    let validation_started = Instant::now();
4260    let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
4261    profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
4262    diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4263    diagnostics.count_n(
4264        "validate.wire_warnings",
4265        validation.wire_warnings.len() as u64,
4266    );
4267    diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4268    for warning in &validation.wire_warnings {
4269        diagnostics.event(
4270            DiagnosticSeverity::Warning,
4271            KernelStage::Validate,
4272            "validate.uv_wire",
4273            warning.message.clone(),
4274        );
4275    }
4276    for issue in &validation.issues {
4277        diagnostics.event(
4278            DiagnosticSeverity::Error,
4279            KernelStage::Validate,
4280            "validate.brep",
4281            issue.message.clone(),
4282        );
4283    }
4284    fit_scope.close().report_into(&mut diagnostics);
4285    polyline_scope.close().report_into(&mut diagnostics);
4286    diagnostics.measure_max(
4287        "timing.total_ms",
4288        operation_started.elapsed().as_secs_f64() * 1_000.0,
4289    );
4290    if !validation.issues.is_empty() {
4291        return Err(KernelRefusal::new(
4292            RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
4293            KernelStage::Validate,
4294            format!(
4295            "boolean_operation: invalid result: {:?}",
4296            validation.issues
4297        )));
4298    }
4299    // Optional semantic oracle (off by default, no perf hit): under
4300    // BREP_DEBUG_BOOL, cross-check the well-formed result against the CSG
4301    // point-membership expectation and scan for residual coincident-but-unwelded
4302    // geometry. Purely diagnostic and NON-rejecting — a statistical check must
4303    // never fail a valid op (see oracle.rs) — so it only ever warns.
4304    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
4305        if let Ok(report) =
4306            crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
4307        {
4308            if report.is_flagged() {
4309                eprintln!(
4310                    "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
4311                    report.disagreement_rate,
4312                    report.disagreements.len(),
4313                    report.considered,
4314                    report.sample_disagreement()
4315                );
4316            }
4317        }
4318        let fusable_band = crate::tolerance::assembler_weld(policy.model);
4319        let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
4320        if !fusables.is_empty() {
4321            eprintln!(
4322                "[oracle] {} residual fusable(s) after weld; sample {:?}",
4323                fusables.len(),
4324                fusables.first()
4325            );
4326        }
4327    }
4328    let candidates = scope.as_ref().map(|scope| {
4329        let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
4330            .then(|| imprint.faces_in_unproved_pairs.as_ref())
4331            .flatten()
4332            .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
4333        let candidates = soundness_candidates(
4334            &solid,
4335            scope,
4336            [operand_bounds(first), operand_bounds(second)],
4337            policy.sew_search,
4338            unproved.as_ref(),
4339        );
4340        diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
4341        crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
4342        candidates
4343    });
4344    Ok((
4345        KernelOutcome {
4346            value: solid,
4347            diagnostics,
4348        },
4349        candidates,
4350    ))
4351}
4352
4353