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