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