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