Skip to main content

brep_boolean/csg/imprint/
driver.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse, RefusalClass, MAX_FIT_STATIONS};
2
3// Fit-split instrumentation: where the section
4// fit's time goes, read only under BREP_PROFILE and printed once per
5// `build_imprints` as `imprint.fit_split`. Zero behaviour: timers only.
6#[derive(Clone, Copy)]
7pub(super) enum FitSplitLane { InitialFit, EvenSliverTotal, RefineTotal, Consistency, Midspan, MidspanRefine, CarrierUpper, Representatives, Seeded, FullRefit, CarrierReadings }
8const FIT_SPLIT_LANES: usize = 11;
9const FIT_SPLIT_NAMES: [&str; FIT_SPLIT_LANES] = ["initial_fit", "even_sliver_total", "refine_total", "consistency", "midspan", "midspan_refine", "carrier_upper", "representatives", "seeded", "full_refit", "carrier_readings"];
10thread_local! {
11    static FIT_SPLIT: std::cell::RefCell<([f64; FIT_SPLIT_LANES], [u64; FIT_SPLIT_LANES])> = const { std::cell::RefCell::new(([0.0; FIT_SPLIT_LANES], [0; FIT_SPLIT_LANES])) };
12}
13pub(super) fn fit_split_started() -> Option<Instant> { crate::profile::profile_enabled().then(Instant::now) }
14pub(super) fn fit_split_add(lane: FitSplitLane, started: Option<Instant>, calls: u64) {
15    if let Some(started) = started {
16        FIT_SPLIT.with(|cell| { let mut cell = cell.borrow_mut(); cell.0[lane as usize] += started.elapsed().as_secs_f64() * 1e3; cell.1[lane as usize] += calls; });
17    }
18}
19pub(super) fn fit_split_timed<T>(lane: FitSplitLane, run: impl FnOnce() -> T) -> T {
20    let started = fit_split_started();
21    let out = run();
22    fit_split_add(lane, started, 1);
23    out
24}
25pub(super) fn fit_split_report() {
26    let (ms, calls) = FIT_SPLIT.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
27    let line = FIT_SPLIT_NAMES.iter().enumerate().map(|(i, name)| format!("{name}={:.2}/{}", ms[i], calls[i])).collect::<Vec<_>>().join(" ");
28    profile_line!("imprint.fit_split {line}");
29    let (calls, stations, points, params_ms, interpolate_ms, measure_ms) = crate::fit::station_set_split_take();
30    profile_line!("imprint.station_set calls={calls} stations={stations} points={points} params_ms={params_ms:.2} interpolate_ms={interpolate_ms:.2} measure_ms={measure_ms:.2}");
31}
32
33/// The degree a marched section is interpolated at (2026-09-27). The march
34/// puts every station on both carriers; the fit decides how far the curve
35/// strays BETWEEN them, and a cubic's O(h^4) there left `BadBoolean`'s
36/// sphere×bore rim 2.5e-7 off the bore with a mean bias of −1.2e-8 that both
37/// trims inherited (+1.14e-6 on the solid). A quintic through the same
38/// stations reads 8.5e-9 and +6e-11 with the same knots and control-point
39/// count. More stations bought the same accuracy on 2026-09-26 and were
40/// reverted for their cost: the watertight tessellator samples every interior
41/// knot, so every scan downstream scales with station count, and a degree does
42/// not add knots. `BREP_SECTION_FIT_DEGREE=3` restores the cubic. The gate on
43/// the mid-span refinement, as a multiple of the fit tolerance (2026-09-27): a
44/// marched section whose unrefined fit misses a carrier between stations by
45/// more than this is UNDERSAMPLED — the 20° cylinder crossing of
46/// `fillet-skew-cylinder-seam-split-20deg` sits 4e-5..8e-5 off, 470 times the
47/// tolerance, at any degree — and only such a section is given true
48/// intersection points until its mid-spans hold. Refining every section cost
49/// more downstream than it returned (the tessellator samples every knot).
50/// `BREP_SECTION_REFINE_GATE` sets the multiple (`on` for
51/// [`SECTION_REFINE_GATE`]). OFF BY DEFAULT: at k = 100 the sequential
52/// blend/direct_edit/imprint/boolean lib set costs +64 % and
53/// `oblique_multi_rim_cone_cap_tearing_push_refuses` goes red; k = 1000 costs
54/// +32 % and leaves the skew union +5.3e-4 off. This global switch stays off.
55/// Independently, a pair of grazing crossings on one trim edge requests a
56/// fit-floor check for that face pair below: those two nearby junctions and
57/// the intervening cap must survive the fit.
58fn section_refine_gate() -> Option<f64> {
59    static GATE: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
60    *GATE.get_or_init(|| match std::env::var("BREP_SECTION_REFINE_GATE") {
61        Ok(value) if value == "on" => Some(SECTION_REFINE_GATE),
62        Ok(value) => value.parse::<f64>().ok().filter(|gate| *gate >= 0.0),
63        Err(_) => None,
64    })
65}
66
67/// Why a section goes to `refine_section_against_carriers`.
68#[derive(Clone, Copy, Debug, PartialEq)]
69pub enum SectionRefineRoute {
70    /// `BREP_SECTION_REFINE_GATE`: every section, at the variable's multiple.
71    Global,
72    /// A recovered fit reproduces its march points; check it between them.
73    Recovered,
74    /// A pair of grazing crossings on one trim edge.
75    Grazing,
76    /// The standing fit missed the tolerance it was asked for. The polyline
77    /// deviation can overstate the carrier miss (a band-raised floor reads the
78    /// input's noise), so the refiner's own carrier measure decides: a section
79    /// whose mid-spans already hold the gate leaves at round 0 as `BelowGate`,
80    /// unchanged. Measured 2026-10-04: the StationCeiling fits it reaches ship
81    /// 4.7e-5 to 2.1e-4 off the true section; the refiner brings them to
82    /// 1e-8..3e-8.
83    UnmetRequest,
84    /// A standing fit that MET its request on no other route, whose kept
85    /// stations all lie on both carriers within the fit tolerance, but whose
86    /// curve stands further off the carriers BETWEEN them than the local gate
87    /// ([`carrier_miss_route`]). The polyline it met is the march's chords; an
88    /// interpolant through consistent stations can still ring between them.
89    /// Measured 2026-10-04 (94 cases): 23 of 285 fast-path sections,
90    /// 13 distinct pairs, read their mid-spans up to 6.03e-6 off while every
91    /// kept station read within 1e-7; fixture 28 t217 pair 118x474 read 1.59e-6
92    /// between stations 1.8e-9 off.
93    CarrierMiss,
94}
95
96/// The carrier-miss route for a fit that met its request on no other route:
97/// refine at the local gate when its mid-spans miss the carriers by more than
98/// the fit tolerance WHILE every kept station is within it. Stations off a
99/// carrier are the input's (moving them is the reserved relocation ruling),
100/// so such a section keeps the fast path and is not reported as refined. An
101/// unreadable reading (NaN) never routes.
102pub fn carrier_miss_route(station_upper: f64, midspan_upper: f64, fit_tolerance: f64) -> Option<(f64, SectionRefineRoute)> {
103    (station_upper.is_finite() && midspan_upper.is_finite() && station_upper <= fit_tolerance && midspan_upper > fit_tolerance)
104        .then_some((1.0, SectionRefineRoute::CarrierMiss))
105}
106
107/// The carrier readings [`carrier_miss_route`] decides on: the worst of both
108/// carriers over EVERY point of the section's run (the march's original
109/// stations, kept or dropped by the fit, so a fit through consistent kept
110/// stations cannot hide an inconsistent dropped one), and at the fit's
111/// mid-spans. Projector distances, so upper readings; NaN as soon as any is
112/// unreadable. The mid-span read is the route's TRIGGER, not a bound on the
113/// curve's maximum; [`knot_interior_carrier_upper`] is the finer read.
114pub fn fast_path_carrier_readings(fit: &PolylineFit, run: &[Vec3], first: &NurbsSurface, second: &NurbsSurface) -> (f64, f64) {
115    let read = |surface: &NurbsSurface, point: Vec3| project_point_to_surface(surface, point).map_or(f64::NAN, |projection| projection.distance);
116    let mut station = 0.0f64;
117    for point in run {
118        let (a, b) = (read(first, *point), read(second, *point));
119        station = if a.is_nan() || b.is_nan() || station.is_nan() { f64::NAN } else { station.max(a).max(b) };
120    }
121    (station, midspan_carrier_upper(fit, first, second))
122}
123
124/// `BREP_PLANAR_ISO_TANGENT_TOUCH` (default on; `=0` restores): see
125/// PLANAR-ISO TANGENT TOUCH in the pair loop.
126fn planar_iso_tangent_touch_enabled() -> bool {
127    switch!("BREP_PLANAR_ISO_TANGENT_TOUCH", true)
128}
129
130/// SECTION-REFINE READ MEMO (`BREP_SECTION_REFINE_READ_MEMO`, default on, =0 restores).
131/// One section refine reads the carrier distance of
132/// the SAME points several times: a representative round reads every mid-span
133/// in [`midspan_misses`], again in [`midspan_carrier_upper`], and, once a
134/// representative has run, the mid-spans and knot interiors a second time on
135/// the unchanged fit. In wasm the planter's carrier upper reads were 103 ms of
136/// its 395 ms section fit. This keeps each `(carrier, point bits)` reading for
137/// one `refine_section_against_carriers_inner` call, error included, so every
138/// caller sees exactly the value (or error) the first read returned. Off, it
139/// is the projector itself.
140pub struct CarrierReads {
141    memo: Option<HashMap<(usize, [u64; 3]), Result<f64, String>>>,
142}
143impl CarrierReads {
144    pub fn off() -> Self {
145        Self { memo: None }
146    }
147    pub fn open() -> Self {
148        Self { memo: switch!(live "BREP_SECTION_REFINE_READ_MEMO", true).then(HashMap::default) }
149    }
150    /// The carrier distance at `point` on carrier `side` (0 first, 1 second).
151    pub fn distance(&mut self, side: usize, surface: &NurbsSurface, point: Vec3) -> Result<f64, String> {
152        let Some(memo) = self.memo.as_mut() else {
153            return project_point_to_surface(surface, point).map(|projection| projection.distance);
154        };
155        memo.entry((side, [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()]))
156            .or_insert_with(|| project_point_to_surface(surface, point).map(|projection| projection.distance))
157            .clone()
158    }
159}
160
161/// The worst of BOTH carriers at the fit's mid-spans, each carrier read on its
162/// own and checked finite BEFORE any max (`f64::max` would drop a NaN from one
163/// carrier and pass the other's reading): NaN as soon as either is unreadable.
164pub(super) fn midspan_carrier_upper(fit: &PolylineFit, first: &NurbsSurface, second: &NurbsSurface) -> f64 {
165    midspan_carrier_upper_read(fit, first, second, &mut CarrierReads::off())
166}
167
168/// [`midspan_carrier_upper`] through a section-refine round's [`CarrierReads`].
169fn midspan_carrier_upper_read(fit: &PolylineFit, first: &NurbsSurface, second: &NurbsSurface, reads: &mut CarrierReads) -> f64 {
170    let mut read = |side: usize, surface: &NurbsSurface, point: Vec3| reads.distance(side, surface, point).unwrap_or(f64::NAN);
171    let mut worst = 0.0f64;
172    for span in 0..fit.parameters.len().saturating_sub(1) {
173        let mid = 0.5 * (fit.parameters[span] + fit.parameters[span + 1]);
174        let (a, b) = match fit.curve.evaluate(mid) {
175            Ok(point) => (read(0, first, point), read(1, second, point)),
176            Err(_) => (f64::NAN, f64::NAN),
177        };
178        if !(a.is_finite() && b.is_finite()) || worst.is_nan() {
179            return f64::NAN;
180        }
181        worst = worst.max(a).max(b);
182    }
183    worst
184}
185
186/// The curve's worst distance from both carriers at the quarter points of
187/// every one of its own knot spans (its native pieces, where an interpolant
188/// is extremal between knots), NaN as soon as any read is unreadable. Sampled
189/// and projector-based: an upper reading at its points, not a certified
190/// maximum of the curve.
191pub fn knot_interior_carrier_upper(curve: &NurbsCurve, first: &NurbsSurface, second: &NurbsSurface) -> f64 {
192    knot_interior_carrier_upper_read(curve, first, second, &mut CarrierReads::off())
193}
194
195/// [`knot_interior_carrier_upper`] through a section-refine round's [`CarrierReads`].
196fn knot_interior_carrier_upper_read(curve: &NurbsCurve, first: &NurbsSurface, second: &NurbsSurface, reads: &mut CarrierReads) -> f64 {
197    let mut read = |side: usize, surface: &NurbsSurface, point: Vec3| reads.distance(side, surface, point).unwrap_or(f64::NAN);
198    let Ok([t0, t1]) = curve.domain() else { return f64::NAN };
199    let mut knots: Vec<f64> = curve.knots.iter().copied().filter(|knot| *knot >= t0 && *knot <= t1).collect();
200    knots.dedup();
201    let mut worst = 0.0f64;
202    for pair in knots.windows(2) {
203        if pair[1] <= pair[0] {
204            continue;
205        }
206        for fraction in [0.25, 0.5, 0.75] {
207            let value = match curve.evaluate(pair[0] + (pair[1] - pair[0]) * fraction) {
208                Ok(point) => {
209                    let (a, b) = (read(0, first, point), read(1, second, point));
210                    if a.is_finite() && b.is_finite() { a.max(b) } else { f64::NAN }
211                }
212                Err(_) => f64::NAN,
213            };
214            worst = if worst.is_nan() || !value.is_finite() { f64::NAN } else { worst.max(value) };
215        }
216    }
217    worst
218}
219
220/// The refine route and its gate (a multiple of the fit tolerance) for one
221/// section, or `None` for the fast path.
222///
223/// A standing fit that MET its request takes exactly the routes that existed
224/// before: the global gate alone when set, else a recovered fit, else a grazing
225/// pair (read lazily, only when the first two do not apply), else nothing — it
226/// goes straight to `process_curve`, untouched.
227///
228/// A fit that MISSED its request is always refined, at the local gate 1, or at
229/// a tighter global gate. A looser global gate does not mask the miss: seam 60
230/// was a recovered fit missing its 1e-7 request, and `BREP_SECTION_REFINE_GATE`
231/// above 1 used to let it through. Its route stays `UnmetRequest` under any
232/// global gate, so its cost reads apart from the global gate's.
233pub fn section_refine_route(
234    global: Option<f64>,
235    recovered: bool,
236    grazing: impl FnOnce() -> bool,
237    met_requested: bool,
238) -> Option<(f64, SectionRefineRoute)> {
239    if !met_requested {
240        return Some((global.map_or(1.0, |gate| gate.min(1.0)), SectionRefineRoute::UnmetRequest));
241    }
242    global
243        .map(|gate| (gate, SectionRefineRoute::Global))
244        .or_else(|| recovered.then_some((1.0, SectionRefineRoute::Recovered)))
245        .or_else(|| grazing().then_some((1.0, SectionRefineRoute::Grazing)))
246}
247
248/// The multiple `BREP_SECTION_REFINE_GATE=on` uses: the smallest measured
249/// that trips the skew union's undersampled sections and leaves fixture 22 as
250/// it was (k = 10 flips it).
251const SECTION_REFINE_GATE: f64 = 100.0;
252
253/// The axis-aligned box of a curve's control points (rational ones read at
254/// their Cartesian position), grown by `margin` on every side: a box the
255/// curve cannot leave, since a NURBS curve with positive weights lies in its
256/// control hull.
257pub fn control_hull_box(curve: &NurbsCurve, margin: f64) -> [Vec3; 2] {
258    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
259    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
260    for control in &curve.control_points {
261        let w = if control.w.abs() > 1e-300 { control.w } else { 1.0 };
262        let point = Vec3::new(control.x / w, control.y / w, control.z / w);
263        low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
264        high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
265    }
266    [
267        Vec3::new(low.x - margin, low.y - margin, low.z - margin),
268        Vec3::new(high.x + margin, high.y + margin, high.z + margin),
269    ]
270}
271
272/// Whether two closed boxes share a point.
273pub fn boxes_overlap(a: &[Vec3; 2], b: &[Vec3; 2]) -> bool {
274    a[0].x <= b[1].x && b[0].x <= a[1].x && a[0].y <= b[1].y && b[0].y <= a[1].y && a[0].z <= b[1].z && b[0].z <= a[1].z
275}
276
277/// A clipped run's END span can be a sliver: the clip endpoint lands beside a
278/// march station, a spacing ratio to the run's median of 0.011 on
279/// `anotherBooleanFail`, and a global interpolant rings next to such a jump —
280/// the mid-spans near the ends miss their carriers by 1e-3, and bisecting them
281/// only makes the spacing more uneven (2026-09-27). The reduced witness
282/// (`imprint/tests.rs` `sliver_end_evening`) says what makes the jump ring: a
283/// sliver end ON both carriers fits to 3e-8, while the same end 2.7e-4 off
284/// the torus — the vendor's edge curves sit that far off the tori they
285/// bound, and the run's end is solved on such an edge — rings at 2e-3 with
286/// the interior at 3e-13 (2026-09-30). Below
287/// `SLIVER_END_FRACTION` of the median spacing the station beside the
288/// endpoint is RE-SOLVED at the middle of the merged gap as a fresh
289/// intersection point (the default, `BREP_SECTION_SLIVER_END=resolve`) or
290/// dropped (`drop`); `off` restores the unevened fit for a before/after
291/// reading. Returns how many ends were evened.
292///
293/// ON BY DEFAULT since 2026-09-30 (lane K6), behind the measurement in
294/// [`even_sliver_ends_measured`]: only a section whose fit shows the ringing signature
295/// ([`ringing_signature`]) is evened, and the evened fit stands only where it reads closer to
296/// the carriers by [`SLIVER_END_GAIN`]. The ringing is what a marched section carries into the
297/// result: on `anotherBooleanFail` the sphere sections leave the analytic vendor torus by
298/// 3.1e-3 within 1% of their span (measured against the STEP file's own `TOROIDAL_SURFACE`,
299/// not the projector), the cut torus faces depart from their edges by 2.6e-4 and the result
300/// shell's vector-area closure reads 1.88e-4 against a 3.83e-5 bar. Evened, the sections sit
301/// 5e-8 off, the shell closes at 1.7e-6 and the boolean takes 2.3 s instead of 9.1 s. The
302/// 2026-09-27 shelving reason was three fixture-25 exact-value pins moving under a blanket
303/// `resolve`; a blanket default also refused fixture 28's reversed subtract and broke fixture
304/// 26's idempotence, which is why the signature gates it. Fixture 25's sections do not show
305/// the signature at the shipped contrast and its pins stand.
306fn even_sliver_ends(
307    section: &mut Vec<Vec3>,
308    first: &NurbsSurface,
309    second: &NurbsSurface,
310    tolerance: f64,
311) -> Result<usize, String> {
312    static MODE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
313    let mode = MODE.get_or_init(|| {
314        std::env::var("BREP_SECTION_SLIVER_END").unwrap_or_else(|_| "resolve".to_string())
315    });
316    if !(mode == "drop" || mode == "resolve") {
317        return Ok(0);
318    }
319    let mut evened = 0;
320    // One sliver at a time: each removal changes the spans it sits between.
321    for _ in 0..SLIVER_END_ROUNDS {
322        let count = section.len();
323        if count < 6 {
324            break;
325        }
326        let mut chords: Vec<f64> = section.windows(2).map(|pair| pair[1].sub(pair[0]).length()).collect();
327        let lengths = chords.clone();
328        chords.sort_by(f64::total_cmp);
329        let median = chords[chords.len() / 2];
330        let spans = lengths.len();
331        let near_ends = [0, 1, 2, spans - 3, spans - 2, spans - 1];
332        let Some(&sliver) = near_ends
333            .iter()
334            .filter(|&&span| lengths[span] < sliver_end_fraction() * median)
335            .min_by(|a, b| lengths[**a].total_cmp(&lengths[**b]))
336        else {
337            break;
338        };
339        // The sliver's bounding stations are `sliver` and `sliver + 1`; a run
340        // endpoint is never moved. Of the interior ones, remove the one whose
341        // removal leaves the shorter merged span.
342        let mut candidates = Vec::new();
343        for station in [sliver, sliver + 1] {
344            if station == 0 || station == count - 1 {
345                continue;
346            }
347            let merged = section[station + 1].sub(section[station - 1]).length();
348            candidates.push((station, merged));
349        }
350        let Some(&(station, _)) = candidates.iter().min_by(|a, b| a.1.total_cmp(&b.1)) else {
351            break;
352        };
353        if mode == "resolve" {
354            let (before, after) = (section[station - 1], section[station + 1]);
355            let seed = before.add(after).scale(0.5);
356            let reach = 0.5 * after.sub(before).length();
357            match crate::surface_surface_intersection::refine_to_intersection(first, second, seed, tolerance, reach)? {
358                Some(point) => section[station] = point,
359                None => {
360                    section.remove(station);
361                }
362            }
363        } else {
364            section.remove(station);
365        }
366        evened += 1;
367    }
368    Ok(evened)
369}
370
371/// At 0.25 six of `anotherBooleanFail`'s eight sections stay NoProgress
372/// (worst miss 2.7e-4); at 0.5 all eight are evened and fall below the
373/// refinement gate (worst miss 2.8e-3 -> 5.4e-8).
374const SLIVER_END_FRACTION: f64 = 0.5;
375
376/// How many sliver spans one section may lose, at most, over both ends. Every
377/// `anotherBooleanFail` section reaches this cap (the march lands several
378/// closely spaced stations beside each clip end), and the evened fits read
379/// 2.2e-8..5.4e-8 against the carriers under it; whether a higher cap would
380/// read differently was not measured (lane K6, 2026-09-30).
381const SLIVER_END_ROUNDS: usize = 4;
382
383/// `BREP_SECTION_SLIVER_FRACTION` overrides [`SLIVER_END_FRACTION`] for the
384/// measurement that picks it.
385fn sliver_end_fraction() -> f64 {
386    static FRACTION: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
387    *FRACTION.get_or_init(|| {
388        std::env::var("BREP_SECTION_SLIVER_FRACTION")
389            .ok()
390            .and_then(|value| value.parse::<f64>().ok())
391            .filter(|fraction| *fraction > 0.0 && *fraction < 1.0)
392            .unwrap_or(SLIVER_END_FRACTION)
393    })
394}
395
396fn section_fit_degree() -> usize {
397    static DEGREE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
398    *DEGREE.get_or_init(|| {
399        std::env::var("BREP_SECTION_FIT_DEGREE")
400            .ok()
401            .and_then(|value| value.parse::<usize>().ok())
402            .filter(|degree| (1..=7).contains(degree))
403            .unwrap_or(5)
404    })
405}
406
407/// `BREP_SPAN_BUDGET`, read once: unset leaves [`ImprintOptions::span_budget`]
408/// in charge; `off` forces none; `fit` is the pair's `intersection_fit` at the
409/// operands' scale; a number is an absolute budget.
410#[derive(Clone, Copy, Debug, PartialEq)]
411enum SpanBudgetSwitch {
412    Unset,
413    Off,
414    Fit,
415    Absolute(f64),
416}
417
418fn span_budget_switch() -> SpanBudgetSwitch {
419    static SWITCH: std::sync::OnceLock<SpanBudgetSwitch> = std::sync::OnceLock::new();
420    *SWITCH.get_or_init(|| match std::env::var("BREP_SPAN_BUDGET") {
421        Ok(value) if value == "fit" => SpanBudgetSwitch::Fit,
422        Ok(value) if value == "off" || value == "0" => SpanBudgetSwitch::Off,
423        Ok(value) => value
424            .parse::<f64>()
425            .ok()
426            .filter(|budget| *budget > 0.0)
427            .map_or(SpanBudgetSwitch::Unset, SpanBudgetSwitch::Absolute),
428        Err(_) => SpanBudgetSwitch::Unset,
429    })
430}
431
432/// The span budget every march of this imprint carries: the option under
433/// its environment override. `fit` is what the catalogue names as the
434/// budget a lane may carry, the imprint's `intersection_fit`
435/// (`KernelTolerances::for_scale`), never the corrector's `tolerance`.
436pub(super) fn span_budget(options: &ImprintOptions, scale: f64) -> Option<f64> {
437    match span_budget_switch() {
438        SpanBudgetSwitch::Unset => options.span_budget,
439        SpanBudgetSwitch::Off => None,
440        SpanBudgetSwitch::Fit => Some(crate::KernelTolerances::for_scale(scale, options.tolerance).intersection_fit),
441        SpanBudgetSwitch::Absolute(budget) => Some(budget),
442    }
443}
444
445/// [`ImprintOptions::hermite_sections`] under its environment override.
446fn hermite_sections(options: &ImprintOptions) -> bool {
447    match std::env::var("BREP_HERMITE_SECTIONS").as_deref() {
448        Ok("0") => false,
449        Ok(_) => true,
450        Err(_) => options.hermite_sections,
451    }
452}
453
454/// [`ImprintOptions::exact_iso_pcurves`] under its environment override
455/// (`BREP_EXACT_ISO_PCURVES`: `0`/`off`, `check`, anything else on).
456#[derive(Clone, Copy, Debug, PartialEq, Eq)]
457pub(super) enum ExactIsoPcurves {
458    Off,
459    On,
460    /// The fit lane runs; the exact pcurve is built beside it and compared
461    /// (`ImprintBuilder::exact_pcurve_check`).
462    Check,
463}
464
465fn exact_iso_pcurves(options: &ImprintOptions) -> ExactIsoPcurves {
466    match mode_switch!(live "BREP_EXACT_ISO_PCURVES", options.exact_iso_pcurves) {
467        crate::env_read::Mode::Off => ExactIsoPcurves::Off,
468        crate::env_read::Mode::Check => ExactIsoPcurves::Check,
469        crate::env_read::Mode::On => ExactIsoPcurves::On,
470    }
471}
472
473thread_local! {
474    /// Set by `build_imprints_impl` as it returns, read by the boolean
475    /// right after ([`take_rescue_firings`]) into
476    /// `intersect.march_swap_rescue` and `intersect.clip_swap_rescue`; a
477    /// thread-local rather than a field so the shared record's eight
478    /// literals stay as they are.
479    static RESCUE_FIRINGS: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
480}
481
482/// `(march-order swap rescues, clip-order swap rescues)` of the last imprint
483/// built on this thread, cleared by the read.
484pub fn take_rescue_firings() -> (u64, u64) {
485    RESCUE_FIRINGS.with(|cell| cell.replace((0, 0)))
486}
487
488/// [`ImprintOptions::march_starts`] under its environment override, as
489/// `(ordered_starts, consume_starts, tree_seeds)` for every march this
490/// imprint runs. `BREP_MARCH_STARTS`: `0`/`off`; `order` (A3's ordering
491/// alone); `snap` (the ordering with run-through starts consumed); `tree`
492/// (A4 alone); `order+tree`; anything else all three.
493fn march_starts(options: &ImprintOptions, carrier_tree_seeds: bool) -> (bool, bool, bool) {
494    match std::env::var("BREP_MARCH_STARTS").as_deref() {
495        Ok("0") | Ok("off") => (false, false, false),
496        Ok("order") => (true, false, false),
497        Ok("snap") => (true, true, false),
498        Ok("tree") => (false, false, true),
499        Ok("order+tree") => (true, false, true),
500        Ok(_) => (true, true, true),
501        Err(_) => (options.march_starts, options.march_starts, options.march_starts || carrier_tree_seeds),
502    }
503}
504
505/// `BREP_SPAN_CENSUS=<file>`: one line per clipped section, appended, so a
506/// corpus replay can be read for station growth and refine-route firings
507/// under a budget. `BREP_CENSUS_LABEL` names the run on every line.
508fn span_census(line: impl FnOnce() -> String) {
509    if let Ok(path) = std::env::var("BREP_SPAN_CENSUS") {
510        use std::io::Write;
511        if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
512            let label = std::env::var("BREP_CENSUS_LABEL").unwrap_or_default();
513            let _ = writeln!(file, "span-budget census: label {label} {}", line());
514        }
515    }
516}
517
518/// A marched section is held to the fit tolerance against the CARRIERS, not
519/// only against the polyline it was fitted through (2026-09-26). The march
520/// refines every station onto both surfaces to `tolerance * 0.01`, but the
521/// cubic interpolant between stations is measured by `fit_polyline` against the
522/// polyline's own chords, which are further from the true curve than the
523/// interpolant is — so a systematic bias of the interpolant (2.8e-8 mean,
524/// 4.7e-7 worst, inside the bore on `BadBoolean`'s sphere/bore rim at 135
525/// stations) passed every check the fit could make, and both trims inherited it
526/// (+1.14e-6 on the solid's volume, against two independent readings agreeing
527/// to 1e-8). The check below evaluates the fitted curve at every mid-span,
528/// measures it against both carriers, and where it misses `fit tolerance *
529/// SECTION_MIDSPAN_FRACTION` inserts a TRUE intersection point there and
530/// refits. The interpolant's bias falls as h^4, so one round usually suffices.
531/// A round that neither halves the worst miss nor lowers the count of spans
532/// missing is not in that regime — a carrier's C0 crease puts a corner in the
533/// section (fixture 25's pierce solid), where every round only doubles the
534/// stations — so that round is discarded and the loop stops. It is also capped
535/// in rounds and stations, and names how it left.
536/// `BREP_SECTION_REFINE_GATE=off` switches it off, for the before/after reading
537/// and nothing else.
538pub(super) const SECTION_MIDSPAN_FRACTION: f64 = 0.1;
539const SECTION_MIDSPAN_ROUNDS: usize = 4;
540/// A round earns another if it cuts the worst mid-span miss by this factor
541/// (h^4 promises 16 for a halved spacing) OR lowers the count of spans
542/// missing: near the floor a few isolated spans hold the worst while the count
543/// falls, and on a corner the count GROWS round on round.
544const SECTION_MIDSPAN_PROGRESS: f64 = 0.5;
545
546/// Squared distance from `point` to the segment `from`-`to`.
547fn distance_to_segment_sq(point: Vec3, from: Vec3, to: Vec3) -> f64 {
548    point.distance_to_segment_squared(from, to)
549}
550
551/// The carrier miss, in fit tolerances, past which a section the mid-span
552/// refiner left unconverged goes to the 3-D Hermite lane
553/// (`BREP_SECTION_HERMITE_3D`). Measured on the lane's cases: a section that
554/// stalls near its floor (crossing cylinders, a tangent cone: 1.2e-8 to
555/// 1.3e-7 at a 1e-7 tolerance) keeps its fit; the swept rim walls' hairpin
556/// sections miss by 0.1 to 4.4e2.
557const HERMITE_3D_GROSS_MISS: f64 = 1e3;
558
559/// How a mid-span refinement left (`SECTION_MIDSPAN_*`), for the pair trace.
560#[derive(Clone, Copy, Debug, PartialEq)]
561pub enum MidspanExit {
562    /// Every mid-span within the floor of both carriers.
563    Converged,
564    /// The unrefined fit's worst mid-span is within the gate: the section is
565    /// sampled well enough that its degree carries it, and stations would
566    /// cost more downstream than they return.
567    BelowGate,
568    /// Some mid-span still misses and no inserted point could improve it
569    /// (the Newton failed, wandered off the span, or landed on a station
570    /// already present).
571    Stalled,
572    /// A round neither halved the worst miss nor lowered the count of spans
573    /// missing: not the h^4 regime, so the section has a corner the
574    /// interpolant cannot follow. That round's fit is discarded.
575    NoProgress,
576    RoundBudget,
577    StationCeiling,
578}
579
580/// Measure `fit` at every mid-span against both carriers; return the worst
581/// distance, the count of spans that miss `floor` and, for each of them the
582/// Newton could place, the refined intersection point to insert (with the
583/// span's index).
584fn midspan_misses(
585    fit: &PolylineFit,
586    first: &NurbsSurface,
587    second: &NurbsSurface,
588    floor: f64,
589    tolerance: f64,
590    reads: &mut CarrierReads,
591) -> Result<(f64, usize, Vec<(usize, Vec3)>), String> {
592    let mut worst = 0.0f64;
593    let mut missing = 0usize;
594    let mut inserts = Vec::new();
595    for span in 0..fit.parameters.len().saturating_sub(1) {
596        let mid = 0.5 * (fit.parameters[span] + fit.parameters[span + 1]);
597        let point = fit.curve.evaluate(mid)?;
598        let off = reads.distance(0, first, point)?.max(reads.distance(1, second, point)?);
599        worst = worst.max(off);
600        if off <= floor {
601            continue;
602        }
603        missing += 1;
604        // The refined point must stay on THIS span: half its chord is the reach.
605        let reach = 0.5 * fit.kept[span + 1].sub(fit.kept[span]).length();
606        if let Some(refined) = fit_split_timed(FitSplitLane::MidspanRefine, || crate::surface_surface_intersection::refine_to_intersection(
607            first, second, point, tolerance, reach,
608        ))? {
609            inserts.push((span, refined));
610        }
611    }
612    Ok((worst, missing, inserts))
613}
614
615/// Every mid-span miss of `fit` against both carriers, measured and nothing
616/// else: what [`even_sliver_ends_measured`] reads before and after evening.
617/// It refines nothing, so a section without a sliver end pays only the
618/// projections.
619fn midspan_misses_only(fit: &PolylineFit, first: &NurbsSurface, second: &NurbsSurface) -> Result<Vec<f64>, String> {
620    let mut misses = Vec::with_capacity(fit.parameters.len());
621    for span in 0..fit.parameters.len().saturating_sub(1) {
622        let mid = 0.5 * (fit.parameters[span] + fit.parameters[span + 1]);
623        let point = fit.curve.evaluate(mid)?;
624        let off = project_point_to_surface(first, point)?
625            .distance
626            .max(project_point_to_surface(second, point)?.distance);
627        misses.push(off);
628    }
629    Ok(misses)
630}
631
632/// The signature of a global interpolant ringing on a sliver end span: the
633/// worst mid-span miss sits in one of the [`SLIVER_END_SPANS`] spans at either
634/// end, is over the fit `floor`, AND stands [`SLIVER_RING_CONTRAST`] times
635/// above the median of the interior spans. A section sampled too coarsely for the carriers misses
636/// everywhere at once and does not show this; a section with fewer than two
637/// interior spans offers no evidence either way. Returns the end-span worst
638/// and the interior median when the signature is present.
639fn ringing_signature(misses: &[f64], floor: f64) -> Option<(f64, f64)> {
640    let spans = misses.len();
641    if spans < 2 * SLIVER_END_SPANS + 2 {
642        return None;
643    }
644    let ends = misses[..SLIVER_END_SPANS]
645        .iter()
646        .chain(&misses[spans - SLIVER_END_SPANS..])
647        .copied()
648        .fold(0.0f64, f64::max);
649    let mut interior: Vec<f64> = misses[SLIVER_END_SPANS..spans - SLIVER_END_SPANS].to_vec();
650    interior.sort_by(f64::total_cmp);
651    let median = interior[interior.len() / 2];
652    let worst = misses.iter().copied().fold(0.0f64, f64::max);
653    // Below the fit floor there is nothing to even: a 1e-8 miss on a planar
654    // section passed the contrast on fixture 26 and flipped its idempotence
655    // reading while changing nothing a bar could see.
656    (ends > floor.max(sliver_min_miss()) && ends >= worst && ends > sliver_ring_contrast() * median.max(f64::MIN_POSITIVE))
657        .then_some((ends, median))
658}
659
660/// How many spans at each end of a section [`even_sliver_ends`] may even —
661/// the same three it inspects — and where [`ringing_signature`] looks.
662const SLIVER_END_SPANS: usize = 3;
663
664/// The ringing signature's contrast: the end spans' worst mid-span miss over
665/// the interior spans' median. A converged march leaves its interior at
666/// 1e-9 and a sliver end rings at 1e-4..1e-3, so the ratio is 1e5 and up:
667/// `anotherBooleanFail`'s eight sections read 1.3e5..2.2e6 (interior
668/// 6e-10..2.6e-9, ends 1.6e-4..2.8e-3). A section whose interior itself
669/// misses is under-sampled rather than ringing, and evening its end moves a
670/// junction the assembler then cannot repair: fixture 28's pair 822×118
671/// (interior 1.5e-6, ends 1.4e-3, contrast 930) refused the reversed
672/// subtract whenever it was evened, while its pairs 474×118 (1.7e4) and
673/// 842×118 (1.4e5) are evened and build. Fixture 25's two sections read
674/// 2.2e3 and 5.9e3 (interior 2e-8) and keep their stations and their pins.
675/// 3e4 sits at least 4× from the nearest reading on either side
676/// (2026-09-30).
677const SLIVER_RING_CONTRAST: f64 = 3.0e4;
678
679/// `BREP_SECTION_SLIVER_CONTRAST` overrides [`SLIVER_RING_CONTRAST`] for the
680/// measurement that picks it.
681fn sliver_ring_contrast() -> f64 {
682    static CONTRAST: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
683    *CONTRAST.get_or_init(|| {
684        std::env::var("BREP_SECTION_SLIVER_CONTRAST")
685            .ok()
686            .and_then(|value| value.parse::<f64>().ok())
687            .filter(|contrast| *contrast >= 1.0)
688            .unwrap_or(SLIVER_RING_CONTRAST)
689    })
690}
691
692/// `BREP_SECTION_SLIVER_MIN_MISS` raises the absolute floor under the end
693/// spans' worst miss, for measurement only (the shipped floor is the fit
694/// tolerance).
695fn sliver_min_miss() -> f64 {
696    static MIN: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
697    *MIN.get_or_init(|| {
698        std::env::var("BREP_SECTION_SLIVER_MIN_MISS")
699            .ok()
700            .and_then(|value| value.parse::<f64>().ok())
701            .filter(|miss| *miss >= 0.0)
702            .unwrap_or(0.0)
703    })
704}
705
706/// How a sliver-end evening left, for the census line.
707#[derive(Clone, Copy, Debug, PartialEq)]
708pub enum SliverEvening {
709    /// No end span was shorter than the fraction, or the hatch is `off`.
710    NoSliver,
711    /// A sliver end exists but the unevened fit does not show the ringing
712    /// signature ([`ringing_signature`]): its stations stand.
713    NotRinging { slivers: usize, worst: f64 },
714    /// The evened section's fit reads at least [`SLIVER_END_GAIN`] times
715    /// closer to the carriers at its worst mid-span: the evened fit stands.
716    Accepted { slivers: usize, before: f64, after: f64, interior: f64 },
717    /// Evening did not earn its keep: the unevened fit stands, the stations
718    /// untouched.
719    Rejected { slivers: usize, before: f64, after: f64, interior: f64 },
720}
721
722/// A sliver-end evening must earn its keep: the evened fit stands only when
723/// its worst mid-span miss against both carriers falls by at least this
724/// factor. Measured on 2026-09-30 against the blanket default: `resolve` on
725/// every section that HAS a sliver end refused the reversed subtract of
726/// fixture 28 (`march_swap_rescue_recovers_reversed_subtract_t217`, an open
727/// loop) and made fixture 26's union read differently before and after
728/// operand splitting, while on `anotherBooleanFail` (2.8e-3 → 5e-8) and
729/// fixture 25 (2.0e-5 / 3.4e-5 → 9.2e-7) it cut the miss by 20× to 5e4×. A
730/// section whose evened fit is not clearly better keeps its stations.
731const SLIVER_END_GAIN: f64 = 2.0;
732
733/// [`even_sliver_ends`] with the measurement that decides whether it stands:
734/// fit the section as marched; if its mid-spans show the ringing signature
735/// ([`ringing_signature`]), even its sliver ends, fit again, and keep the
736/// evened fit only when its worst mid-span wins by [`SLIVER_END_GAIN`].
737/// Returns the section, its fit, the recovery flag of the fit that stands and
738/// the outcome.
739pub fn even_sliver_ends_measured(
740    section: Vec<Vec3>,
741    first: &NurbsSurface,
742    second: &NurbsSurface,
743    tolerance: f64,
744    fit_tolerance: f64,
745    maximum_fit_points: usize,
746    local_fit: bool,
747) -> Result<(Vec<Vec3>, PolylineFit, bool, SliverEvening), String> {
748    fit_split_timed(FitSplitLane::EvenSliverTotal, || even_sliver_ends_measured_inner(section, first, second, tolerance, fit_tolerance, maximum_fit_points, local_fit))
749}
750
751fn even_sliver_ends_measured_inner(
752    section: Vec<Vec3>,
753    first: &NurbsSurface,
754    second: &NurbsSurface,
755    tolerance: f64,
756    fit_tolerance: f64,
757    maximum_fit_points: usize,
758    local_fit: bool,
759) -> Result<(Vec<Vec3>, PolylineFit, bool, SliverEvening), String> {
760    let (fit, recovered) = fit_split_timed(FitSplitLane::InitialFit, || crate::fit::fit_polyline_of_degree_with_recovery(
761        &section,
762        fit_tolerance,
763        maximum_fit_points,
764        local_fit,
765        section_fit_degree(),
766    ))?;
767    let mut evened = section.clone();
768    let slivers = even_sliver_ends(&mut evened, first, second, tolerance)?;
769    if slivers == 0 {
770        return Ok((section, fit, recovered, SliverEvening::NoSliver));
771    }
772    let misses = midspan_misses_only(&fit, first, second)?;
773    let Some((before, interior)) = ringing_signature(&misses, fit_tolerance) else {
774        let worst = misses.iter().copied().fold(0.0f64, f64::max);
775        return Ok((section, fit, recovered, SliverEvening::NotRinging { slivers, worst }));
776    };
777    let (evened_fit, evened_recovered) = crate::fit::fit_polyline_of_degree_with_recovery(
778        &evened,
779        fit_tolerance,
780        maximum_fit_points,
781        local_fit,
782        section_fit_degree(),
783    )?;
784    let after_misses = midspan_misses_only(&evened_fit, first, second)?;
785    let after = after_misses.iter().copied().fold(0.0f64, f64::max);
786    if let Ok(path) = std::env::var("BREP_SECTION_SLIVER_CENSUS") {
787        use std::io::Write;
788        if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
789            let chords = |points: &[Vec3]| points.windows(2).map(|pair| format!("{:.4e}", pair[1].sub(pair[0]).length())).collect::<Vec<_>>().join(" ");
790            let fmt = |values: &[f64]| values.iter().map(|value| format!("{value:.2e}")).collect::<Vec<_>>().join(" ");
791            let _ = writeln!(file, "sliver-end detail: stations {} -> {} kept {} -> {}", section.len(), evened.len(), fit.kept.len(), evened_fit.kept.len());
792            let _ = writeln!(file, "sliver-end detail: chords before: {}", chords(&section));
793            let _ = writeln!(file, "sliver-end detail: chords after:  {}", chords(&evened));
794            let _ = writeln!(file, "sliver-end detail: misses before: {}", fmt(&misses));
795            let _ = writeln!(file, "sliver-end detail: misses after:  {}", fmt(&after_misses));
796            let _ = writeln!(file, "sliver-end detail: ends before: {:?} {:?}", section[0], section[section.len() - 1]);
797            let _ = writeln!(file, "sliver-end detail: ends after:  {:?} {:?}", evened[0], evened[evened.len() - 1]);
798        }
799    }
800    if after * SLIVER_END_GAIN <= before {
801        Ok((evened, evened_fit, evened_recovered, SliverEvening::Accepted { slivers, before, after, interior }))
802    } else {
803        Ok((section, fit, recovered, SliverEvening::Rejected { slivers, before, after, interior }))
804    }
805}
806
807/// Refit `section` until its mid-spans sit within `floor` of both carriers,
808/// inserting true intersection points where they do not. Returns the fit that
809/// stands, the worst mid-span miss it still carries, the unrefined fit's worst
810/// (what the gate read), the rounds spent and the exit.
811/// Keep the single best measured refiner state (root grant 2026-10-04,
812/// accepted-representative sections only): replaced when `worst` is finite and
813/// no larger than the kept one (ties go to the later state). An unreadable
814/// reading is never kept. At most one snapshot is held.
815pub fn keep_best_state<S>(best: &mut Option<(S, f64)>, state: impl FnOnce() -> S, worst: f64) {
816    if worst.is_finite() && best.as_ref().is_none_or(|(_, kept)| worst <= *kept) {
817        *best = Some((state(), worst));
818    }
819}
820
821/// The rollback a budget-type exit (RoundBudget, StationCeiling, Stalled)
822/// takes: on a section where an ACCEPTED representative round ran, the kept
823/// best state when its COMMON reading is strictly lower than the current
824/// state's common reading on the same instrument (both carriers, finite, at the
825/// fit's mid-spans and its own knot-span quarter points). Otherwise `None`:
826/// the exit returns the current state exactly as before, with nothing cloned.
827/// An unreadable current reading never rolls back (it is not hidden).
828pub fn take_rollback<S>(best: &mut Option<(S, f64)>, current_common: f64, representative_ran: bool) -> Option<(S, f64)> {
829    let lower = matches!(best, Some((_, kept)) if representative_ran && current_common.is_finite() && *kept < current_common);
830    if lower { best.take() } else { None }
831}
832
833/// Which fit a refinement RETURNED: a receipt for controls, deciding nothing.
834#[derive(Clone, Copy, Debug, PartialEq)]
835pub enum RefinedFitSource {
836    /// The standing fit the caller passed in.
837    Standing,
838    /// The original full refit of the run, made directly (`full-unmatched`,
839    /// or the retry after an unreadable representative or a seeded stall).
840    FullRefit,
841    /// The seeded (forced-station) call and its own path: a `Fallback` path
842    /// IS the original full refit.
843    Seeded(crate::fit::SeededPath),
844    /// The representative candidate call and its own path: a `Fallback` path
845    /// IS the original full refit.
846    Representatives(crate::fit::SeededPath),
847    /// The best measured state the budget-exit rollback restored.
848    Rollback,
849}
850
851/// The refiner's receipt: whether the run took the representative route at
852/// all, and which fit it returned (None on an error return). Production
853/// callers discard it; only controls read it.
854#[allow(dead_code)]
855#[derive(Clone, Copy, Debug, Default, PartialEq)]
856pub struct RefineReceipt {
857    pub original_consistent: bool,
858    pub returned: Option<RefinedFitSource>,
859}
860
861
862/// `refine_section_against_carriers` with the representative switch passed
863/// in (the env hatch's value, so a control can take the seeded route without
864/// touching the process environment) and a receipt of the fit returned.
865#[allow(clippy::too_many_arguments)]
866pub fn refine_section_against_carriers_with(
867    section: &mut Vec<Vec3>,
868    fit: PolylineFit,
869    first: &NurbsSurface,
870    second: &NurbsSurface,
871    fit_tolerance: f64,
872    tolerance: f64,
873    local_fit: bool,
874    gate: f64,
875    representatives: bool,
876    receipt: &mut RefineReceipt,
877) -> Result<(PolylineFit, f64, f64, usize, MidspanExit), String> {
878    let started = fit_split_started();
879    let out = refine_section_against_carriers_inner(section, fit, first, second, fit_tolerance, tolerance, local_fit, gate, representatives, receipt);
880    fit_split_add(FitSplitLane::RefineTotal, started, 1);
881    out
882}
883
884#[allow(clippy::too_many_arguments)]
885fn refine_section_against_carriers_inner(
886    section: &mut Vec<Vec3>,
887    fit: PolylineFit,
888    first: &NurbsSurface,
889    second: &NurbsSurface,
890    fit_tolerance: f64,
891    tolerance: f64,
892    local_fit: bool,
893    gate: f64,
894    representatives: bool,
895    receipt: &mut RefineReceipt,
896) -> Result<(PolylineFit, f64, f64, usize, MidspanExit), String> {
897    // A reused receipt starts clean, so an error return leaves `returned`
898    // None as documented, never a previous call's value.
899    *receipt = RefineReceipt::default();
900    // Which fit `fit` currently is, and which fit `previous` holds.
901    let mut fit_source = RefinedFitSource::Standing;
902    let mut previous_source = RefinedFitSource::Standing;
903    let floor = fit_tolerance * SECTION_MIDSPAN_FRACTION;
904    let mut unrefined = f64::NAN;
905    let mut fit = fit;
906    let mut rounds = 0usize;
907    let mut previous: Option<(PolylineFit, f64, usize)> = None;
908    // Every true intersection point inserted so far: the residual-driven bend
909    // witnesses, which the refit must keep as stations.
910    let mut inserted_points: Vec<Vec3> = Vec::new();
911    // `BREP_SECTION_REFINE_CENSUS`: one `section-refine round:` line per round,
912    // bound to its section by the run's head and tail, so a stall can be read
913    // round by round (debug only; nothing below reads it).
914    let round_census = std::env::var("BREP_SECTION_REFINE_CENSUS").ok();
915    let (head, tail) = (section[0], section[section.len() - 1]);
916    // Whether EVERY original point of the run lies on both carriers within the
917    // fit tolerance (projector upper readings, NaN = no): only such a run takes
918    // the refiner-specific representative candidate below. A run with any
919    // point off a carrier keeps the existing seeded path exactly (moving or
920    // discounting input points is the reserved relocation ruling).
921    // `representatives` false (the `BREP_SECTION_REPRESENTATIVES=0` hatch)
922    // restores the seeded path everywhere for an attribution A/B only.
923    let consistency_started = fit_split_started();
924    let original_consistent = representatives
925        && section.iter().all(|point| {
926            let a = project_point_to_surface(first, *point).map_or(f64::NAN, |projection| projection.distance);
927            let b = project_point_to_surface(second, *point).map_or(f64::NAN, |projection| projection.distance);
928            a.is_finite() && b.is_finite() && a <= fit_tolerance && b <= fit_tolerance
929        });
930    receipt.original_consistent = original_consistent;
931    fit_split_add(FitSplitLane::Consistency, consistency_started, 1);
932    let mut refit_path = String::from("standing");
933    let mut refit_seeds = 0usize;
934    let mut refit_seeds_kept = 0usize;
935    let mut refit_seeds_outside_pool = 0usize;
936    let mut refit_pool = 0usize;
937    let mut refit_pool_discarded = 0usize;
938    let mut refit_pool_floor = f64::NAN;
939    let mut refit_seed_min_chord = f64::NAN;
940    // Trace only: what the closest seed pair is made of (kept station or
941    // refiner insert at each end), to place the near pair upstream.
942    let mut refit_seed_min_pair = "n/a";
943    // Trace only: every seed the full refit's pool rejects, by ORIGIN (a march
944    // station of the run, or a refiner insert) and by REASON (dropped by
945    // `station_pool`'s simplification, or kept by it and then conditioned
946    // away as a near-duplicate): [march simplified, march conditioned,
947    // insert simplified, insert conditioned].
948    let mut refit_rejected = [0usize; 4];
949    // Fits made for the round being judged (2 when its seeded fit stalled and
950    // the full refit was tried as well), and that retry's own cost.
951    let mut refit_trials = 1usize;
952    let mut retry_ms = 0.0f64;
953    // Whether the fit judged this round is an ACCEPTED seeded fit (not merely
954    // a seeded call: a seeded call that fell back already IS the full refit).
955    let mut seeded_refit = false;
956    // Whether the fit judged this round is an ACCEPTED representative
957    // candidate, and what that candidate call spent (its own interpolations
958    // and whether it ended on the full refit), kept apart from the fit's
959    // report, which on a fallback must stay the full refit's to the bit.
960    let mut representative_fit = false;
961    let mut refit_cost = crate::fit::RepresentativeCost::default();
962    // Whether an ACCEPTED representative round ran on this section, and the one
963    // best measured (fit, section) state kept for its budget exits.
964    let mut representative_ran = false;
965    let mut best_state: Option<((PolylineFit, Vec<Vec3>), f64)> = None;
966    let mut reads = CarrierReads::open();
967    loop {
968        // On an accepted representative candidate a read or refinement ERROR is
969        // not a refusal: the section takes the original full refit of the same
970        // run instead, as an unreadable read does below.
971        let (mut worst, missing, inserts) = match fit_split_timed(FitSplitLane::Midspan, || midspan_misses(&fit, first, second, floor, tolerance, &mut reads)) {
972            Ok(reading) => reading,
973            Err(_) if representative_fit => {
974                representative_fit = false;
975                seeded_refit = false;
976                let maximum_points = section.len().min(MAX_FIT_STATIONS);
977                fit = fit_split_timed(FitSplitLane::FullRefit, || fit_polyline_of_degree(section, fit_tolerance, maximum_points, local_fit, section_fit_degree()))?;
978                fit_source = RefinedFitSource::FullRefit;
979                refit_path = String::from("full-after-unreadable-representative");
980                refit_trials += 1;
981                refit_cost.full_refit = true;
982                continue;
983            }
984            Err(error) => return Err(error),
985        };
986        // An ACCEPTED representative candidate is judged on more than its
987        // mid-spans: both carriers must read finite at every mid-span and at
988        // the quarter points of the curve's own knot spans, and its worst is
989        // the worse of the two reads (sampled, projector upper readings; the
990        // carrier target is unchanged). An unreadable read never passes: the
991        // section takes the original full refit of the same run instead.
992        if representative_fit {
993            let interior = fit_split_timed(FitSplitLane::CarrierUpper, || knot_interior_carrier_upper_read(&fit.curve, first, second, &mut reads));
994            let midspans = fit_split_timed(FitSplitLane::CarrierUpper, || midspan_carrier_upper_read(&fit, first, second, &mut reads));
995            if interior.is_finite() && midspans.is_finite() {
996                worst = worst.max(interior).max(midspans);
997            } else {
998                representative_fit = false;
999                seeded_refit = false;
1000                let maximum_points = section.len().min(MAX_FIT_STATIONS);
1001                fit = fit_split_timed(FitSplitLane::FullRefit, || fit_polyline_of_degree(section, fit_tolerance, maximum_points, local_fit, section_fit_degree()))?;
1002                fit_source = RefinedFitSource::FullRefit;
1003                refit_path = String::from("full-after-unreadable-representative");
1004                refit_trials += 1;
1005                refit_cost.full_refit = true;
1006                continue;
1007            }
1008        }
1009        if let Some(path) = &round_census {
1010            use std::io::Write;
1011            if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
1012                let _ = writeln!(
1013                    file,
1014                    "section-refine round: head ({:.9}, {:.9}, {:.9}) tail ({:.9}, {:.9}, {:.9}) round {rounds} fit {refit_path} trials {refit_trials} retry_ms {retry_ms:.3} kept {} seeds {refit_seeds} seeds_kept {refit_seeds_kept} seeds_outside_pool {refit_seeds_outside_pool} seed_min_chord {refit_seed_min_chord:.3e} seed_min_pair {refit_seed_min_pair} rejected_march_simplified {} rejected_march_conditioned {} rejected_insert_simplified {} rejected_insert_conditioned {} pool {refit_pool} pool_discarded {refit_pool_discarded} pool_floor {refit_pool_floor:.3e} exit {:?} deviation {:.3e} floor {:.3e} run {} worst {:.3e} missing {} inserts_offered {} representatives {} witnesses {} candidate_fits {} candidate_full_refit {} candidate_end_offsets {:.3e}/{:.3e} seed_role {}",
1015                    head.x, head.y, head.z, tail.x, tail.y, tail.z,
1016                    fit.kept.len(),
1017                    refit_rejected[0], refit_rejected[1], refit_rejected[2], refit_rejected[3], fit.report.exit, fit.report.deviation, fit.report.floor, section.len(), worst, missing, inserts.len(),
1018                    refit_cost.representatives, refit_cost.witnesses, refit_cost.candidate_fits, refit_cost.full_refit,
1019                    refit_cost.start_offset, refit_cost.end_offset,
1020                    // On the representative path the seeds counted above are
1021                    // WITNESSES (not forced); on the seeded path they are forced.
1022                    if original_consistent { "witness" } else { "forced" }
1023                );
1024                // Trace only: where the full refit's band-raised floor comes
1025                // from on THIS run, and whether the run's own points are on
1026                // the carriers (input-consistent) or not. The band is
1027                // `dropped_band`'s reading (largest distance of a point the
1028                // pool drops from the segment between its surviving
1029                // neighbours); its point is classified as simplified away or
1030                // conditioned away, with its carrier distance and its gap to
1031                // the nearest run neighbour. Projector distances are upper
1032                // readings.
1033                let pool = crate::fit::polyline_station_pool(section, fit_tolerance);
1034                let simplified = crate::fit::simplify_polyline_indices(section, fit_tolerance);
1035                let mut band = (0.0f64, usize::MAX);
1036                for pair in pool.windows(2) {
1037                    for index in pair[0] + 1..pair[1] {
1038                        let off = distance_to_segment_sq(section[index], section[pair[0]], section[pair[1]]).sqrt();
1039                        if off > band.0 {
1040                            band = (off, index);
1041                        }
1042                    }
1043                }
1044                let carrier = |point: Vec3| -> f64 {
1045                    let a = project_point_to_surface(first, point).map_or(f64::NAN, |projection| projection.distance);
1046                    let b = project_point_to_surface(second, point).map_or(f64::NAN, |projection| projection.distance);
1047                    if a.is_nan() || b.is_nan() { f64::NAN } else { a.max(b) }
1048                };
1049                let mut run_carrier = 0.0f64;
1050                for point in section.iter() {
1051                    let off = carrier(*point);
1052                    run_carrier = if off.is_nan() || run_carrier.is_nan() { f64::NAN } else { run_carrier.max(off) };
1053                }
1054                let (kind, band_carrier, gap) = if band.1 == usize::MAX {
1055                    ("none", f64::NAN, f64::NAN)
1056                } else {
1057                    let index = band.1;
1058                    let kind = if simplified.binary_search(&index).is_ok() { "conditioned" } else { "simplified" };
1059                    let mut gap = f64::INFINITY;
1060                    if index > 0 {
1061                        gap = gap.min(section[index].sub(section[index - 1]).length());
1062                    }
1063                    if index + 1 < section.len() {
1064                        gap = gap.min(section[index + 1].sub(section[index]).length());
1065                    }
1066                    (kind, carrier(section[index]), gap)
1067                };
1068                let _ = writeln!(
1069                    file,
1070                    "section-refine band: head ({:.9}, {:.9}, {:.9}) tail ({:.9}, {:.9}, {:.9}) round {rounds} run {} pool {} tolerance {:.3e} band {:.3e} band_index {} of {} band_kind {kind} band_point_carrier_upper {band_carrier:.3e} band_point_gap {gap:.3e} run_carrier_upper {run_carrier:.3e}",
1071                    head.x, head.y, head.z, tail.x, tail.y, tail.z,
1072                    section.len(), pool.len(), fit_tolerance, band.0,
1073                    if band.1 == usize::MAX { -1 } else { band.1 as i64 }, section.len()
1074                );
1075            }
1076        }
1077        if rounds == 0 {
1078            unrefined = worst;
1079        }
1080        // The rollback path's COMMON reading, only once an accepted
1081        // representative round has run and only on a run the refit can hold
1082        // (<= MAX_FIT_STATIONS): both carriers, finite, at the fit's mid-spans
1083        // and its own knot-span quarter points, for EVERY state compared
1084        // (representative, standing or full alike). One snapshot, the fit and
1085        // the run it was measured on as one coherent pair: its payload is one
1086        // PolylineFit and at most MAX_FIT_STATIONS points. Off this path
1087        // nothing is read or cloned.
1088        let mut current_common = f64::NAN;
1089        if representative_ran && section.len() <= MAX_FIT_STATIONS {
1090            let interior = fit_split_timed(FitSplitLane::CarrierUpper, || knot_interior_carrier_upper_read(&fit.curve, first, second, &mut reads));
1091            let midspans = fit_split_timed(FitSplitLane::CarrierUpper, || midspan_carrier_upper_read(&fit, first, second, &mut reads));
1092            current_common = if interior.is_finite() && midspans.is_finite() { interior.max(midspans) } else { f64::NAN };
1093            keep_best_state(&mut best_state, || (fit.clone(), section.clone()), current_common);
1094        }
1095        if worst <= floor {
1096            receipt.returned = Some(fit_source);
1097            return Ok((fit, worst, unrefined, rounds, MidspanExit::Converged));
1098        }
1099        if rounds == 0 && worst <= gate {
1100            receipt.returned = Some(fit_source);
1101            return Ok((fit, worst, unrefined, rounds, MidspanExit::BelowGate));
1102        }
1103        if let Some((earlier, earlier_worst, earlier_missing)) = previous.take() {
1104            // A round that did not earn its keep is discarded whole: the fit
1105            // of the last round that did stands (on a corner, the unrefined
1106            // fit), not whichever of the two happens to read a smaller max.
1107            if worst > earlier_worst * SECTION_MIDSPAN_PROGRESS && missing >= earlier_missing {
1108                // A SEEDED round that did not earn its keep is refitted once
1109                // with the original full refit of the same denser run, and
1110                // that is judged against the same earlier round before the
1111                // section stops. The seeded fit keeps fewer stations; on the
1112                // helmet's 2036x3009 section that gave back the whole of the
1113                // full refit's gain (6.335e-6 stood where 5.596e-7 was
1114                // reached). The full refit is the round the refiner made
1115                // before the seeded entry existed; only a round that fails
1116                // both ends the section, exactly as before.
1117                if seeded_refit {
1118                    seeded_refit = false;
1119                    let maximum_points = section.len().min(MAX_FIT_STATIONS);
1120                    let retry_started = round_census.is_some().then(Instant::now);
1121                    fit = fit_split_timed(FitSplitLane::FullRefit, || fit_polyline_of_degree(section, fit_tolerance, maximum_points, local_fit, section_fit_degree()))?;
1122                    fit_source = RefinedFitSource::FullRefit;
1123                    // Trace: one more fit for the SAME round, its cost, and no
1124                    // seed counters carried over from the rejected seeded fit.
1125                    refit_path = String::from("full-after-seeded-stall");
1126                    // Every fit this round made: the candidate's (or the seeded
1127                    // call's one) plus this retry.
1128                    refit_trials += 1;
1129                    retry_ms = retry_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1e3);
1130                    refit_seeds = 0;
1131                    refit_seeds_kept = 0;
1132                    refit_seeds_outside_pool = 0;
1133                    refit_seed_min_chord = f64::NAN;
1134                    refit_seed_min_pair = "n/a";
1135                    refit_rejected = [0; 4];
1136                    representative_fit = false;
1137                    // Keep the candidate's own counts; the retry is the full refit.
1138                    refit_cost.full_refit = true;
1139                    previous = Some((earlier, earlier_worst, earlier_missing));
1140                    continue;
1141                }
1142                receipt.returned = Some(previous_source);
1143                return Ok((earlier, earlier_worst, unrefined, rounds, MidspanExit::NoProgress));
1144            }
1145        }
1146        if inserts.is_empty() {
1147            if let Some(((kept_fit, kept_run), kept_common)) = take_rollback(&mut best_state, current_common, representative_ran) {
1148                *section = kept_run;
1149                receipt.returned = Some(RefinedFitSource::Rollback);
1150                return Ok((kept_fit, kept_common, unrefined, rounds, MidspanExit::Stalled));
1151            }
1152            receipt.returned = Some(fit_source);
1153            return Ok((fit, worst, unrefined, rounds, MidspanExit::Stalled));
1154        }
1155        if rounds >= SECTION_MIDSPAN_ROUNDS {
1156            if let Some(((kept_fit, kept_run), kept_common)) = take_rollback(&mut best_state, current_common, representative_ran) {
1157                *section = kept_run;
1158                receipt.returned = Some(RefinedFitSource::Rollback);
1159                return Ok((kept_fit, kept_common, unrefined, rounds, MidspanExit::RoundBudget));
1160            }
1161            receipt.returned = Some(fit_source);
1162            return Ok((fit, worst, unrefined, rounds, MidspanExit::RoundBudget));
1163        }
1164        if section.len() + inserts.len() > MAX_FIT_STATIONS {
1165            if let Some(((kept_fit, kept_run), kept_common)) = take_rollback(&mut best_state, current_common, representative_ran) {
1166                *section = kept_run;
1167                receipt.returned = Some(RefinedFitSource::Rollback);
1168                return Ok((kept_fit, kept_common, unrefined, rounds, MidspanExit::StationCeiling));
1169            }
1170            receipt.returned = Some(fit_source);
1171            return Ok((fit, worst, unrefined, rounds, MidspanExit::StationCeiling));
1172        }
1173        // Insert each refined point into the run between its span's stations,
1174        // on the nearest segment of the run there. Positions are located
1175        // against the run BEFORE any insertion of this round, then applied
1176        // from the back so earlier indices stay valid. The kept stations are
1177        // found by a FORWARD search from the previous one: a closed section
1178        // ends on its first station, and a search from the start would put
1179        // the last span's far end at index 0 and skip that span forever.
1180        let station_index = |point: Vec3, from: usize| -> Option<usize> {
1181            section[from..]
1182                .iter()
1183                .position(|p| p.sub(point).length() <= 1e-15 * (1.0 + point.length()))
1184                .map(|offset| from + offset)
1185        };
1186        let mut placed: Vec<(usize, Vec3)> = Vec::new();
1187        for (span, point) in inserts {
1188            let Some(lo) = station_index(fit.kept[span], 0) else {
1189                continue;
1190            };
1191            let Some(hi) = station_index(fit.kept[span + 1], lo + 1) else {
1192                continue;
1193            };
1194            if hi <= lo {
1195                continue;
1196            }
1197            if section[lo..=hi].iter().any(|p| p.sub(point).length() <= floor) {
1198                continue; // already a station: inserting it again refines nothing
1199            }
1200            let mut best = (lo, f64::INFINITY);
1201            for index in lo..hi {
1202                let d2 = distance_to_segment_sq(point, section[index], section[index + 1]);
1203                if d2 < best.1 {
1204                    best = (index, d2);
1205                }
1206            }
1207            placed.push((best.0 + 1, point));
1208        }
1209        if placed.is_empty() {
1210            if let Some(((kept_fit, kept_run), kept_common)) = take_rollback(&mut best_state, current_common, representative_ran) {
1211                *section = kept_run;
1212                receipt.returned = Some(RefinedFitSource::Rollback);
1213                return Ok((kept_fit, kept_common, unrefined, rounds, MidspanExit::Stalled));
1214            }
1215            receipt.returned = Some(fit_source);
1216            return Ok((fit, worst, unrefined, rounds, MidspanExit::Stalled));
1217        }
1218        placed.sort_by(|a, b| b.0.cmp(&a.0));
1219        for (at, point) in placed {
1220            section.insert(at, point);
1221            inserted_points.push(point);
1222        }
1223        // The refit keeps the stations the current fit kept and every point
1224        // inserted so far as SEEDS, and grows only where it is measured to
1225        // miss (`fit_polyline_seeded_with_path`). It is no longer the whole denser run
1226        // from the run's own count: that interpolated every march station the
1227        // standing fit had dropped as well, 3x the controls on the skew-cylinder
1228        // loop for the same carrier floor. The ceiling is the one the full refit
1229        // derives from the same `maximum_points`, and a seeded fit that cannot
1230        // meet the floor, or cannot be read, IS the full refit. The carrier
1231        // measure above still decides every round.
1232        let same = |a: &Vec3, b: &Vec3| a.x.to_bits() == b.x.to_bits() && a.y.to_bits() == b.y.to_bits() && a.z.to_bits() == b.z.to_bits();
1233        let mut seeds = Vec::with_capacity(fit.kept.len() + inserted_points.len());
1234        // The previous fit's kept stations alone: the representative candidate's
1235        // starting set (inserts are its witnesses, not forced stations).
1236        let mut kept_seeds = Vec::with_capacity(fit.kept.len());
1237        // The refiner's own inserted true-carrier points: the representative
1238        // candidate's TIGHT witnesses, held to this refiner's carrier floor.
1239        let mut insert_indices = Vec::with_capacity(inserted_points.len());
1240        let mut next_kept = 0usize;
1241        for (index, point) in section.iter().enumerate() {
1242            // The kept stations are a subsequence of the run, in run order
1243            // (insertion only adds points), so a closed run's two equal ends
1244            // each match their own station.
1245            // An inserted point is a tight witness whether or not the previous
1246            // fit also kept it as a station (membership is independent).
1247            let inserted = inserted_points.iter().any(|candidate| same(point, candidate));
1248            if inserted {
1249                insert_indices.push(index);
1250            }
1251            if next_kept < fit.kept.len() && same(point, &fit.kept[next_kept]) {
1252                seeds.push(index);
1253                kept_seeds.push(index);
1254                next_kept += 1;
1255            } else if inserted {
1256                seeds.push(index);
1257            }
1258        }
1259        let maximum_points = section.len().min(MAX_FIT_STATIONS);
1260        // Every standing station must be found as a seed; if the pass missed
1261        // one, the seeded refit would silently lose it, so the section takes the
1262        // original full refit instead.
1263        refit_trials = 1;
1264        retry_ms = 0.0;
1265        let refit_source;
1266        let refit = if next_kept == fit.kept.len() {
1267            let (refit, path) = if original_consistent {
1268                let (refit, path, cost) = fit_split_timed(FitSplitLane::Representatives, || crate::fit::fit_polyline_representatives_with_witnesses(
1269                    section,
1270                    &kept_seeds,
1271                    &insert_indices,
1272                    floor,
1273                    fit_tolerance,
1274                    maximum_points,
1275                    local_fit,
1276                    section_fit_degree(),
1277                ))?;
1278                // MIXED UNITS, named as such: the candidate's own
1279                // `fit_station_set` interpolations plus one per call of the
1280                // full refit `fit_polyline_of_degree`, which may itself run
1281                // several ladder and recovery interpolations that are NOT
1282                // counted here. Whole-job cost is the matched timing.
1283                refit_cost = cost;
1284                refit_trials = cost.candidate_fits + usize::from(cost.full_refit);
1285                (refit, path)
1286            } else {
1287                refit_cost = crate::fit::RepresentativeCost::default();
1288                fit_split_timed(FitSplitLane::Seeded, || crate::fit::fit_polyline_seeded_with_path(
1289                    section,
1290                    &seeds,
1291                    fit_tolerance,
1292                    maximum_points,
1293                    local_fit,
1294                    section_fit_degree(),
1295                ))?
1296            };
1297            // Only an ACCEPTED seeded fit can be retried in full: a fallback
1298            // already is the full refit, and retrying it would repeat it.
1299            seeded_refit = matches!(path, crate::fit::SeededPath::Accepted { .. });
1300            representative_fit = original_consistent && seeded_refit;
1301            refit_source = if original_consistent { RefinedFitSource::Representatives(path) } else { RefinedFitSource::Seeded(path) };
1302            representative_ran |= representative_fit;
1303            if round_census.is_some() {
1304                refit_path = if original_consistent { format!("representatives-call:{path:?}") } else { format!("seeded-call:{path:?}") };
1305            }
1306            refit
1307        } else {
1308            seeded_refit = false;
1309            representative_fit = false;
1310            refit_cost = crate::fit::RepresentativeCost::default();
1311            refit_path = String::from("full-unmatched");
1312            refit_source = RefinedFitSource::FullRefit;
1313            fit_split_timed(FitSplitLane::FullRefit, || fit_polyline_of_degree(section, fit_tolerance, maximum_points, local_fit, section_fit_degree()))?
1314        };
1315        if round_census.is_some() {
1316            // Trace only: how many seeds the refit kept. This does NOT tell an
1317            // accepted seeded fit from the fallback (a full refit can keep
1318            // every seed too); the returned `SeededPath`, traced as `fit`, does.
1319            refit_seeds = seeds.len();
1320            refit_seeds_kept = seeds.iter().filter(|&&index| refit.kept.iter().any(|kept| same(kept, &section[index]))).count();
1321            // Seeds the full refit's pool would NOT interpolate (simplified
1322            // or conditioned away): forced stations only the seeded fit keeps.
1323            let pool = crate::fit::polyline_station_pool(section, fit_tolerance);
1324            refit_pool = pool.len();
1325            refit_pool_discarded = section.len() - pool.len();
1326            refit_pool_floor = crate::fit::polyline_station_pool_floor(section, fit_tolerance);
1327            refit_seeds_outside_pool = seeds.iter().filter(|index| !pool.contains(index)).count();
1328            // Seeds are in run order; the closest consecutive pair is what a
1329            // near-duplicate conditioning floor would act on.
1330            refit_seed_min_chord = seeds
1331                .windows(2)
1332                .map(|pair| section[pair[1]].sub(section[pair[0]]).length())
1333                .fold(f64::INFINITY, f64::min);
1334            let is_insert = |index: usize| inserted_points.iter().any(|inserted| same(inserted, &section[index]));
1335            refit_seed_min_pair = seeds
1336                .windows(2)
1337                .min_by(|a, b| {
1338                    section[a[1]].sub(section[a[0]]).length().total_cmp(&section[b[1]].sub(section[b[0]]).length())
1339                })
1340                .map_or("n/a", |pair| match (is_insert(pair[0]), is_insert(pair[1])) {
1341                    (false, false) => "station-station",
1342                    (false, true) => "station-insert",
1343                    (true, false) => "insert-station",
1344                    (true, true) => "insert-insert",
1345                });
1346            // Every rejected seed, classified. `station_pool` starts from this
1347            // same simplification, so a non-member that is not in it was
1348            // simplified away, and one that is in it was conditioned away.
1349            let simplified = crate::fit::simplify_polyline_indices(section, fit_tolerance);
1350            refit_rejected = [0; 4];
1351            for &index in seeds.iter().filter(|index| !pool.contains(index)) {
1352                let conditioned = simplified.binary_search(&index).is_ok();
1353                refit_rejected[2 * usize::from(is_insert(index)) + usize::from(conditioned)] += 1;
1354            }
1355        }
1356        previous = Some((std::mem::replace(&mut fit, refit), worst, missing));
1357        previous_source = std::mem::replace(&mut fit_source, refit_source);
1358        rounds += 1;
1359    }
1360}
1361use super::*;
1362use super::gate_census::{census_pair, fit_census_enabled};
1363
1364fn preserves_branch_prefix(
1365    original: &[crate::SurfaceIntersectionCurve],
1366    completed: &[crate::SurfaceIntersectionCurve],
1367) -> bool {
1368    let same_points = |a: &[Vec3], b: &[Vec3]| {
1369        a.len() == b.len() && a.iter().zip(b).all(|(a, b)| {
1370            a.x.to_bits() == b.x.to_bits() && a.y.to_bits() == b.y.to_bits() && a.z.to_bits() == b.z.to_bits()
1371        })
1372    };
1373    completed.len() >= original.len() && original.iter().zip(completed).all(|(a, b)| {
1374        let same_tangents = match (&a.tangents, &b.tangents) {
1375            (Some(a), Some(b)) => same_points(a, b),
1376            (None, None) => true,
1377            _ => false,
1378        };
1379        same_points(&a.points, &b.points) && a.params_a == b.params_a && a.params_b == b.params_b
1380            && a.closed == b.closed && same_tangents
1381            && a.span_deviation == b.span_deviation && a.tangent == b.tangent
1382    })
1383}
1384
1385pub fn build_imprints(
1386    solid_a: &BrepSolid,
1387    solid_b: &BrepSolid,
1388    options: &ImprintOptions,
1389) -> Result<ImprintResultRecord, KernelRefusal> {
1390    build_imprints_impl(solid_a, solid_b, options, false, super::pcurve_cache::enabled())
1391}
1392
1393/// Imprint temporary open offset sheets. A section riding one sheet's trim
1394/// still cuts the other sheet when no boundary copy supplied that section.
1395pub fn build_carrier_imprints(
1396    solid_a: &BrepSolid,
1397    solid_b: &BrepSolid,
1398    options: &ImprintOptions,
1399    tree_seeds: bool,
1400) -> Result<ImprintResultRecord, KernelRefusal> {
1401    build_imprints_with_carrier_seeds(
1402        solid_a, solid_b, options, true, super::pcurve_cache::enabled(), tree_seeds, None,
1403    )
1404}
1405
1406/// Lane P3b row 6 (2026-10-26): imprint the faces of ONE open sheet solid
1407/// against each other in a single call. `solid` is both operands (operand 0
1408/// and 1 tag the same faces); a face pair is processed once, as
1409/// (first index, second index) in the solid's face order with first < second,
1410/// and only when `admit(first, second)` says so. Every post-pass then runs
1411/// once over the whole piece set instead of once per pair.
1412pub fn build_carrier_imprints_within(
1413    solid: &BrepSolid,
1414    admit: &dyn Fn(usize, usize) -> bool,
1415    options: &ImprintOptions,
1416    tree_seeds: bool,
1417) -> Result<ImprintResultRecord, KernelRefusal> {
1418    build_imprints_with_carrier_seeds(
1419        solid, solid, options, true, super::pcurve_cache::enabled(), tree_seeds, Some(admit),
1420    )
1421}
1422
1423/// `BREP_IMPRINT_PLANE_POINT_SKIP` (lane X row 5): skip the march for two
1424/// exact parallelogram faces whose contact is one point
1425/// ([`super::support::planar_point_contact`]) once their seeds are accepted.
1426/// On by default; `0`/`off` disables it.
1427pub(super) fn plane_point_skip_enabled() -> bool {
1428    switch!(live "BREP_IMPRINT_PLANE_POINT_SKIP", true)
1429}
1430
1431thread_local! {
1432    static PLANE_POINT_SKIPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
1433}
1434
1435
1436
1437pub(super) fn build_imprints_impl(
1438    solid_a: &BrepSolid,
1439    solid_b: &BrepSolid,
1440    options: &ImprintOptions,
1441    open_carriers: bool,
1442    pcurve_cache: bool,
1443) -> Result<ImprintResultRecord, KernelRefusal> {
1444    build_imprints_with_carrier_seeds(solid_a, solid_b, options, open_carriers, pcurve_cache, false, None)
1445}
1446
1447// A carved offset can have a narrow transverse section beside its fold.
1448// Seed its knot spans without enabling ordered/consumed starts on other paths.
1449fn build_imprints_with_carrier_seeds(
1450    solid_a: &BrepSolid,
1451    solid_b: &BrepSolid,
1452    options: &ImprintOptions,
1453    open_carriers: bool,
1454    pcurve_cache: bool,
1455    carrier_tree_seeds: bool,
1456    // `Some`: `solid_a` IS `solid_b` and only face pairs (first < second) the
1457    // predicate admits are processed ([`build_carrier_imprints_within`]).
1458    self_pairs: Option<&dyn Fn(usize, usize) -> bool>,
1459) -> Result<ImprintResultRecord, KernelRefusal> {
1460    let _wall = crate::wall_profile::Stage::open("imprint");
1461    let _profile_sink = ProfileSink::open();
1462    let _work = super::work_profile::Scope::open("imprint");
1463    let classify_before = crate::pair_classification::classify_reads();
1464    let setup_started = profile_enabled().then(Instant::now);
1465    let windows_before = window_reads();
1466    let _pcurve_cache = super::pcurve_cache::FitCacheScope::open(pcurve_cache);
1467    let _edge_hulls = super::support::EdgeHullScope::open(super::support::edge_hull_memo_enabled());
1468    let _intersection_cache = super::intersection_cache::Scope::open();
1469    let reuse_whole_miss = open_carriers &&
1470        std::env::var("BREP_OFFSET_IMPRINT_READINGS").map_or(true, |v| v != "0" && v != "off");
1471    let mut section_evidence = false;
1472    let edges = edge_map(solid_a, solid_b);
1473    // FEATURE SCALE (`BREP_FEATURE_SCALE_IMPRINT`, default on, `=0` off):
1474    // the slivers between almost parallel plane faces of the two operands,
1475    // measured before any section is processed so that every band the
1476    // imprint applies sees them. A sliver a quarter of which is under the
1477    // tolerance cannot be resolved by any band, so the boolean refuses
1478    // rather than merge it away.
1479    let feature_scale = if crate::feature_scale::imprint_enabled() {
1480        let scale = crate::feature_scale::FeatureScale::between(solid_a, solid_b, options.tolerance)
1481            .or_refuse(KernelStage::Intersect, "feature_scale")?;
1482        if let Some(thinnest) = scale.thinnest() {
1483            if crate::feature_scale::FRACTION * thinnest < options.tolerance {
1484                return Err(KernelRefusal::new(
1485                    RefusalClass::IllPosed { what: "feature size".into() },
1486                    KernelStage::Intersect,
1487                    format!(
1488                        "boolean: a sliver {thinnest:.3e} thick between almost parallel faces is smaller than the \
1489                         section's resolution (tolerance {:.1e})",
1490                        options.tolerance
1491                    ),
1492                ));
1493            }
1494        }
1495        scale
1496    } else {
1497        Default::default()
1498    };
1499    // The tail passes (coincident-piece merge, junction canonicalisation)
1500    // run after the builder is consumed; they read the same scale.
1501    let tail_feature_scale = feature_scale.clone();
1502    let mut builder = ImprintBuilder {
1503        feature_scale,
1504        open_carriers,
1505        edges,
1506        tolerance: options.tolerance,
1507        barrier_edges: HashSet::default(),
1508        overlap_ridden_edges: HashSet::default(),
1509        scale: solid_scale(solid_a).max(solid_scale(solid_b)),
1510        vertices: Vec::new(),
1511        vertex_radii: HashMap::default(),
1512        vertex_sources: HashMap::default(),
1513        pieces: Vec::new(),
1514        section_end_seeds: Vec::new(),
1515        section_end_evidence: Default::default(),
1516        // Open offset carriers do not have a closed solid's wall/cap incidence.
1517        record_planar_sections: !open_carriers && (switch!("BREP_PLANAR_SECTION_END_DISCOVERY", true)
1518            || switch!("BREP_PLANAR_SECTION_END_DISCOVERY_CHECK", false)),
1519        planar_sections: Vec::new(),
1520        marched_section: false,
1521        exchanged_rides: Vec::new(),
1522        exchanged_rides_mode: crate::env_read::Mode::Off,
1523        by_face: HashMap::default(),
1524        edge_splits: HashMap::default(),
1525        marched_pieces: HashSet::default(),
1526        exact_section: false,
1527        pending_ruling: None,
1528        external_touch_only: false,
1529        emitted_pcurves: HashSet::default(),
1530        exact_pcurve_check: false,
1531        next_id: 1,
1532    };
1533    let requested_hermite_lane = hermite_sections(options);
1534    let hermite_lane = requested_hermite_lane || super::hermite::carried_uv_enabled();
1535    let hermite_min_stations = if hermite_lane { super::hermite::carried_uv_min_stations() } else { 2 };
1536    let exact_iso = exact_iso_pcurves(options);
1537    let (ordered_starts, consume_starts, tree_seeds) = march_starts(options, carrier_tree_seeds);
1538    builder.exact_pcurve_check = exact_iso == ExactIsoPcurves::Check;
1539    // The Hermite lane needs the march's span test; with no budget asked for
1540    // it carries the one the catalogue names, the pair's `intersection_fit`.
1541    let march_span_budget = span_budget(options, builder.scale)
1542        .or_else(|| requested_hermite_lane.then(|| crate::KernelTolerances::for_scale(builder.scale, options.tolerance).intersection_fit));
1543    // UV reuse must never request a different trace. Its stricter emission
1544    // check is applied after clipping; an unqualified run keeps the fit route.
1545    let emission_budget = super::hermite::carried_uv_emission_budget(march_span_budget,
1546        crate::KernelTolerances::for_scale(builder.scale, options.tolerance).intersection_fit);
1547    let mut first_faces = faces(solid_a, 0);
1548    let mut second_faces = faces(solid_b, 1);
1549    // Per-face trim-window carriers, computed once: tighter BVH bounds, and
1550    // the seed/march stages walk the window instead of the full carrier
1551    // (identical geometry and parameterization inside the window).
1552    //
1553    // A window LIFTED across a closed direction's seam (`restricted_carrier`)
1554    // is the exception to "same parameterization": it is the trim's frame, a
1555    // period off the carrier's on one side. Its face carries it as its
1556    // `chart`, and every uv the imprint reads for that face — the clip's
1557    // containment, the sections' pcurves, a seed's normal — is read there.
1558    let first_restricted: Vec<Option<MarchWindow>> = first_faces
1559        .iter()
1560        .map(|tagged| restricted_carrier_memoized(tagged.face))
1561        .collect();
1562    let second_restricted: Vec<Option<MarchWindow>> = second_faces
1563        .iter()
1564        .map(|tagged| restricted_carrier_memoized(tagged.face))
1565        .collect();
1566    for (tagged, window) in first_faces.iter_mut().zip(&first_restricted) {
1567        tagged.lifted = window.as_ref().filter(|window| window.lifted).map(|window| &window.surface);
1568    }
1569    for (tagged, window) in second_faces.iter_mut().zip(&second_restricted) {
1570        tagged.lifted = window.as_ref().filter(|window| window.lifted).map(|window| &window.surface);
1571    }
1572    let first_faces = first_faces;
1573    let second_faces = second_faces;
1574    // The lifted charts, by key, for the post-passes that rebuild a pcurve
1575    // after the mint (junction canonicalization, the origin dissolve, the
1576    // truncation bridge). A face absent here is read on its own carrier.
1577    let charts: FaceCharts<'_> = first_faces
1578        .iter()
1579        .chain(second_faces.iter())
1580        .filter_map(|tagged| tagged.lifted.map(|surface| (tagged.key(), surface)))
1581        .collect();
1582    let first_bounds = first_faces
1583        .iter()
1584        .zip(&first_restricted)
1585        .map(|(tagged, restricted)| {
1586            face_bounds(
1587                tagged.face,
1588                restricted.as_ref().map(|window| &window.surface),
1589                &builder.edges,
1590                tagged.operand,
1591                options.tolerance,
1592            )
1593        })
1594        .collect::<Result<Vec<_>, _>>()?;
1595    let second_bounds = second_faces
1596        .iter()
1597        .zip(&second_restricted)
1598        .map(|(tagged, restricted)| {
1599            face_bounds(
1600                tagged.face,
1601                restricted.as_ref().map(|window| &window.surface),
1602                &builder.edges,
1603                tagged.operand,
1604                options.tolerance,
1605            )
1606        })
1607        .collect::<Result<Vec<_>, _>>()?;
1608    let second_bvh = Bvh::build(&second_bounds);
1609    // Per-face classifier data and edge lists/subcurves, computed once and
1610    // reused across every pair the face participates in.
1611    let first_classify = first_faces
1612        .iter()
1613        .map(|tagged| SurfaceClassifyData::memoized(&tagged.face.surface, options.tolerance))
1614        .collect::<Result<Vec<_>, _>>().or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
1615    let second_classify = second_faces
1616        .iter()
1617        .map(|tagged| SurfaceClassifyData::memoized(&tagged.face.surface, options.tolerance))
1618        .collect::<Result<Vec<_>, _>>().or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
1619    // Per-face span hulls for the separation prefilter, built on first use.
1620    let first_hulls: Vec<std::cell::OnceCell<Option<crate::SpanHullSet>>> =
1621        (0..first_faces.len()).map(|_| std::cell::OnceCell::new()).collect();
1622    let second_hulls: Vec<std::cell::OnceCell<Option<crate::SpanHullSet>>> =
1623        (0..second_faces.len()).map(|_| std::cell::OnceCell::new()).collect();
1624    let mut face_edge_lists: HashMap<FaceKey, Vec<&EdgeRecord>> = HashMap::default();
1625    for tagged in first_faces.iter().chain(second_faces.iter()) {
1626        face_edge_lists.insert(tagged.key(), face_edges(*tagged, &builder.edges)?);
1627    }
1628    let mut subcurves: HashMap<(u8, u64), NurbsCurve> = HashMap::default();
1629    for (&key, edge) in &builder.edges {
1630        if !edge.degenerate {
1631            // Failures fall through: the use sites recompute and surface the
1632            // original error exactly where the uncached code did.
1633            if let Ok(curve) = edge_subcurve(edge) {
1634                subcurves.insert(key, curve);
1635            }
1636        }
1637    }
1638    let cached_subcurve = |operand: u8, edge: &EdgeRecord| -> Result<NurbsCurve, KernelRefusal> {
1639        match subcurves.get(&(operand, edge.id)) {
1640            Some(curve) => Ok(curve.clone()),
1641            None => edge_subcurve(edge),
1642        }
1643    };
1644    if let Some(started) = setup_started { profile_line!("imprint.setup ms={:.3} faces={} classify_reads={} windows_built={}", started.elapsed().as_secs_f64()*1000.0, first_faces.len()+second_faces.len(), crate::pair_classification::classify_reads()-classify_before, window_reads()-windows_before); }
1645    let mut profile = ImprintProfile::new();
1646    let mut march_swap_rescues = 0_u64;
1647    let mut clip_swap_rescues = 0_u64;
1648    // `imprint.fits`: the pcurve fits the pairs record, read through a nested
1649    // scope that folds into the operation's own ledger on close.
1650    let pairs_fits = profile.enabled.then(crate::PcurveFitScope::open);
1651    let mut tangent_nodes: Vec<Vec3> = Vec::new();
1652    let mut tangent_sections: Vec<TangentSectionRecord> = Vec::new();
1653    // Planar tangent runs to IMPRINT once every pair has minted its pieces
1654    // (`ImprintOptions::tangent_curve_imprint`): (section index, run, pair).
1655    let mut tangent_imprint_candidates: Vec<(usize, Vec<Vec3>, TaggedFace<'_>, TaggedFace<'_>)> = Vec::new();
1656    let mut cosurface_pairs: Vec<(FaceKey, FaceKey)> = Vec::new();
1657    let mut deferred_boundary_spans = Vec::new();
1658    let mut work_pairs = super::work_profile::Pairs::new(first_faces.len() * second_faces.len());
1659    let mut paired = Vec::new();
1660    // Every cross-operand pair whose face boxes met, and those of them the
1661    // imprint PROVED apart (`ImprintResultRecord::faces_in_unproved_pairs`).
1662    let mut visited_pairs: Vec<(usize, usize)> = Vec::new();
1663    let mut proved_apart_pairs: HashSet<(usize, usize)> = HashSet::default();
1664    // Sections between nonplanar walls supply the endpoints that split a
1665    // later planar section. Keep face storage and admission indices intact;
1666    // only visit the planar pairs after their incident wall pairs.
1667    let section_end_order = switch!("BREP_PLANAR_SECTION_END_JUNCTIONS", false);
1668    let check_section_end_order = switch!("BREP_PLANAR_SECTION_END_JUNCTIONS_CHECK", false);
1669    let order_sections = |indices: &mut Vec<usize>, faces: &[TaggedFace<'_>], side: &str| {
1670        if !(section_end_order || check_section_end_order) { return; }
1671        let mut ordered = indices.clone();
1672        ordered.sort_by_key(|&index| matches!(faces[index].face.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })));
1673        if check_section_end_order && ordered != *indices {
1674            eprintln!("planar section end order {side}: {:?} -> {:?}, enabled={section_end_order}", indices, ordered);
1675        }
1676        if section_end_order { *indices = ordered; }
1677    };
1678    let first_order = if section_end_order || check_section_end_order {
1679        let mut indices: Vec<_> = (0..first_faces.len()).collect();
1680        order_sections(&mut indices, &first_faces, "first");
1681        Some(indices)
1682    } else { None };
1683    for position in 0..first_faces.len() {
1684        let first_index = first_order.as_ref().map_or(position, |order| order[position]);
1685        let first = first_faces[first_index];
1686        paired.clear();
1687        second_bvh.overlapping(
1688            first_bounds[first_index],
1689            options.tolerance * 100.0,
1690            &mut paired,
1691        );
1692        paired.sort_unstable();
1693        order_sections(&mut paired, &second_faces, "second");
1694        let debug_pairs = std::env::var("BREP_DEBUG_PAIRS").is_ok();
1695        if debug_pairs {
1696            eprintln!(
1697                "bvh first_face={} -> {} candidate pairs {:?}",
1698                first.face.id,
1699                paired.len(),
1700                paired
1701                    .iter()
1702                    .map(|&index| second_faces[index].face.id)
1703                    .collect::<Vec<_>>()
1704            );
1705        }
1706        for &second_index in &paired {
1707            if let Some(admit) = self_pairs {
1708                if second_index <= first_index || !admit(first_index, second_index) {
1709                    continue;
1710                }
1711            }
1712            let second = second_faces[second_index];
1713            visited_pairs.push((first_index, second_index));
1714            profile.pairs += 1;
1715            let _work_pair = super::work_profile::Pair::open(&mut work_pairs, first.face, second.face);
1716            // Set when this pair's section passes through an isolated TANGENT
1717            // NODE inside both trims (see the classification below). The march
1718            // is attempted anyway — that is the whole point — but a marcher
1719            // that cannot get through a node must refuse in the tangent-node
1720            // class naming the node, not leak its own step-budget message.
1721            let mut tangent_node: Option<Vec3> = None;
1722            // The pair's branches came from the sub-gate re-march below: a
1723            // run end that stalls in the tangency band then lands on a trim
1724            // edge the carriers share exactly as a tangent-node pair's does.
1725            let mut grazing_march = false;
1726            let mut lap_start = None;
1727            profile.lap(&mut lap_start);
1728            let pair_classification = classify_surface_pair_cached(
1729                &first.face.surface,
1730                &first_classify[first_index],
1731                &second.face.surface,
1732                &second_classify[second_index],
1733                options.tolerance,
1734                PAIR_ANGULAR_TOLERANCE,
1735            ).or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
1736            profile.classify += profile.lap(&mut lap_start);
1737            // A proof recorded, not acted on (the pair is imprinted as
1738            // before): two exact concentric analytic carriers whose surfaces
1739            // cannot meet (the walls of a closed hollow of a revolved solid).
1740            let concentric_apart = concentric_carriers_apart(&first.face.surface, &second.face.surface, options.tolerance * 10.0);
1741            if concentric_apart {
1742                proved_apart_pairs.insert((first_index, second_index));
1743            }
1744            if pair_classification.relation == SurfacePairRelation::Disjoint {
1745                // A proof: the control hulls' boxes, or two parallel planes,
1746                // apart by more than the contact band.
1747                proved_apart_pairs.insert((first_index, second_index));
1748                if debug_pairs {
1749                    eprintln!(
1750                        "pair {}x{}: DISJOINT-cull sep={:.4e}",
1751                        first.face.id, second.face.id, pair_classification.minimum_separation
1752                    );
1753                }
1754                continue;
1755            }
1756            // Coincident carriers are never marched: their true intersection
1757            // is a 2D region, not a curve, so anything the marcher traces on
1758            // them is noise ("similar faces we do not intersect" — Golovanov
1759            // §6.2).  The sampled classification catches coincident pairs
1760            // the strict reconstruction test misses (partial overlaps,
1761            // differing parameterizations); both route to the boundary-curve
1762            // exchange below.
1763            // `BREP_COSURFACE_EXACT_APART` (default on, `=0` off): two exact
1764            // concentric carriers proved apart by more than the On band
1765            // (coaxial cylinders 2.1e-6 apart in radius) are two surfaces,
1766            // whatever the sampled reading's band (1e-5) says, unless their
1767            // boundaries run within twice the weld floor of each other (one
1768            // end plane, rims 5e-6 apart): the assembly welds such rims as
1769            // one, and only the cosurface exchange keeps that weld closed.
1770            // A complete finite profile crossing cover excludes a shared
1771            // profile arc. Unlike a sampled off-carrier point, it cannot veto
1772            // a genuinely coincident trimmed portion elsewhere on a carrier.
1773            let certified_on = crate::switch!("BREP_EXTRUSION_CERTIFIED_CROSSINGS", true);
1774            let certified_check = crate::switch!("BREP_EXTRUSION_CERTIFIED_CROSSINGS_CHECK", false);
1775            let certified_sections = if certified_on || certified_check {
1776                match (first.face.surface.linear_extrusion(),second.face.surface.linear_extrusion()) {
1777                    (Some(a),Some(b)) if a.profile.degree>1 && b.profile.degree>1 =>
1778                        brep_geometry::analytic_surface::certified_parallel_extrusion_sections(a,b,options.tolerance),
1779                    _=>None,
1780                }
1781            } else {None};
1782            let ruling_on = crate::switch!("BREP_SECTOR_EXTRUSION_RULING_SIDE", true);
1783            let ruling_check = crate::switch!("BREP_SECTOR_EXTRUSION_RULING_SIDE_CHECK", false);
1784            let rulings = if (ruling_on || ruling_check) && certified_on {
1785                match (first.face.surface.linear_extrusion(), second.face.surface.linear_extrusion()) {
1786                    (Some(a), Some(b)) if a.profile.degree > 1 && b.profile.degree > 1 =>
1787                        brep_geometry::certified_planar::ruling::sections(first.chart(), second.chart(), options.tolerance),
1788                    _ => None,
1789                }
1790            } else { None };
1791            if ruling_check {
1792                eprintln!("SECTOR_EXTRUSION_RULING_SIDE pair={}x{} old={:?} certified={:?} applied={}",
1793                    first.face.id, second.face.id, certified_sections.as_ref().map(Vec::len),
1794                    rulings.as_ref().map(Vec::len), ruling_on && rulings.is_some());
1795            }
1796            let rulings = if ruling_on { rulings } else { None };
1797            let certified_sections = rulings.as_ref().map(|rs| rs.iter().map(|r| r.curve().clone()).collect())
1798                .or(certified_sections);
1799            let witness_apart = certified_on && certified_sections.is_some();
1800            if certified_check {
1801                if let Some(sections)=&certified_sections {
1802                    eprintln!("EXTRUSION_CERTIFIED_CROSSINGS pair={}x{} sections={} sampled={:?} enabled={}",
1803                        first.face.id,second.face.id,sections.len(),pair_classification.relation,certified_on);
1804                }
1805            }
1806            // OPERAND SLIVERS (`BREP_FEATURE_SCALE_OPERAND_SLIVERS`): two
1807            // planes FeatureScale measured a resolvable sliver apart are two
1808            // surfaces, whatever the pair reading's band says; read as one,
1809            // the sliver's two caps were dropped as coincident copies.
1810            let operand_sliver = {
1811                let (zero, one) = if first.operand == 0 { (first.face.id, second.face.id) } else { (second.face.id, first.face.id) };
1812                first.operand != second.operand && tail_feature_scale.operand_sliver(zero, one)
1813            };
1814            let is_cosurface = !operand_sliver
1815                && !(concentric_apart
1816                    && crate::switch!("BREP_COSURFACE_EXACT_APART", true)
1817                    && !boundaries_within(&face_edge_lists[&first.key()], &face_edge_lists[&second.key()], 2.0 * crate::tolerance::WELD_FLOOR))
1818                && !witness_apart
1819                && (pair_classification.relation == SurfacePairRelation::Cosurface
1820                    || cosurface_pair(&first.face.surface, &second.face.surface, options.tolerance)?);
1821            profile.cosurface += profile.lap(&mut lap_start);
1822            if is_cosurface {
1823                if debug_pairs {
1824                    eprintln!("pair {}x{}: cosurface", first.face.id, second.face.id);
1825                }
1826                cosurface_pairs.push((first.key(), second.key()));
1827                let tangent_mode = tangent_cylinders_off_carrier_mode();
1828                let tangent_cylinders = tangent_mode != crate::env_read::Mode::Off
1829                    && distinct_cylinder_carriers(&first.face.surface, &second.face.surface, options.tolerance);
1830                let off_carrier = |edge: &EdgeRecord, target: TaggedFace<'_>| -> Result<bool, KernelRefusal> {
1831                    if !tangent_cylinders {
1832                        return Ok(false);
1833                    }
1834                    let off = edge_interior_off_carrier(edge, &target.face.surface, options.tolerance)?;
1835                    if off && (debug_pairs || tangent_mode == crate::env_read::Mode::Check) {
1836                        eprintln!(
1837                            "pair {}x{}: tangent cylinders read cosurface: edge {} lies off face {}:{}'s carrier, {}",
1838                            first.face.id, second.face.id, edge.id, target.operand, target.face.id,
1839                            if tangent_mode == crate::env_read::Mode::On { "not exchanged" } else { "exchanged (check)" }
1840                        );
1841                    }
1842                    Ok(off && tangent_mode == crate::env_read::Mode::On)
1843                };
1844                for edge in &face_edge_lists[&second.key()] {
1845                    if !edge.degenerate && !off_carrier(edge, first)? {
1846                        builder.process_curve(
1847                            cached_subcurve(second.operand, edge)?,
1848                            first,
1849                            second,
1850                            &[first],
1851                            &[first],
1852                            false,
1853                            None,
1854                        )?;
1855                    }
1856                }
1857                for edge in &face_edge_lists[&first.key()] {
1858                    if !edge.degenerate && !off_carrier(edge, second)? {
1859                        builder.process_curve(
1860                            cached_subcurve(first.operand, edge)?,
1861                            first,
1862                            second,
1863                            &[second],
1864                            &[second],
1865                            false,
1866                            None,
1867                        )?;
1868                    }
1869                }
1870                profile.process_curve += profile.lap(&mut lap_start);
1871                continue;
1872            }
1873
1874            // Exact lanes discard sections riding an ordinary trim boundary:
1875            // that face already owns the edge, but the other face still needs
1876            // the overlapping span as a cut. Keep the existing whole-edge
1877            // exchange order, and append missing partial spans after all pairs
1878            // have run so duplicate sections retain their established IDs and
1879            // fragment names. Seams are retained by the exact lane itself.
1880            // OPERAND WEDGES (`BREP_FEATURE_SCALE_OPERAND_WEDGES`): a tilted
1881            // pair FeatureScale registered is sectioned below the usual angle.
1882            let operand_wedge = crate::feature_scale::operand_wedges_mode() == crate::env_read::Mode::On && {
1883                let (zero, one) = if first.operand == 0 { (first.face.id, second.face.id) } else { (second.face.id, first.face.id) };
1884                first.operand != second.operand && tail_feature_scale.operand_wedge(zero, one)
1885            };
1886            let planar_iso = super::support::with_operand_wedge_pair(operand_wedge, || planar_iso_section(
1887                &first.face.surface,
1888                &second.face.surface,
1889                options.tolerance,
1890            ))?;
1891            profile.planar_iso += profile.lap(&mut lap_start);
1892            let analytic = if witness_apart { certified_sections } else { crate::intersect_analytic_pair(
1893                &first.face.surface,
1894                &second.face.surface,
1895                options.tolerance,
1896            ) };
1897            profile.analytic += profile.lap(&mut lap_start);
1898            let exact_section = planar_iso.is_some() || analytic.is_some();
1899            // The pieces this pair's lies-on exchange mints (each its curve's
1900            // own range), for `BREP_MARCH_RIDES_EXCHANGED_SPAN` to read the pair's
1901            // marched runs against. A span the exchange processes but mints
1902            // nothing from, or defers, is not one.
1903            let exchanged_mode = exchanged_span_mode();
1904            let mut exchanged_spans: Vec<(NurbsCurve, f64, f64)> = Vec::new();
1905
1906            for (source, target) in [(first, second), (second, first)] {
1907                for edge in &face_edge_lists[&source.key()] {
1908                    if edge.degenerate {
1909                        continue;
1910                    }
1911                    let curve = cached_subcurve(source.operand, edge)?;
1912                    let spans = curve_spans_on_face(
1913                        curve.clone(), target.face, &face_edge_lists[&target.key()],
1914                        options.tolerance, exact_section,
1915                    )?;
1916                    let seam = source.face.loops.iter().flat_map(|loop_record| &loop_record.coedges)
1917                        .filter(|coedge| coedge.edge_id == edge.id).count() >= 2;
1918                    if spans.is_empty() && exact_section && !seam {
1919                        // The whole-only call above returned empty: its exact
1920                        // curve/carrier reading was false. Nothing has mutated.
1921                        let partial = if reuse_whole_miss {
1922                            profile.whole_reading_reuses += 1;
1923                            curve_spans_after_whole_miss(
1924                                curve, target.face, &face_edge_lists[&target.key()], options.tolerance,
1925                            )?
1926                        } else {
1927                            curve_spans_on_face(
1928                                curve, target.face, &face_edge_lists[&target.key()], options.tolerance, false,
1929                            )?
1930                        };
1931                        for span in partial {
1932                            deferred_boundary_spans.push((span, first, second, target));
1933                        }
1934                    }
1935                    for span in spans {
1936                        let minted_before = builder.pieces.len();
1937                        builder.process_curve(span, first, second, &[target], &[target], false, None)?;
1938                        if exchanged_mode != crate::env_read::Mode::Off {
1939                            exchanged_spans.extend(builder.pieces[minted_before..].iter().map(|piece| (piece.curve.clone(), piece.t0, piece.t1)));
1940                        }
1941                    }
1942                }
1943            }
1944            profile.lies_on += profile.lap(&mut lap_start);
1945            // CENSUS ONLY (`BREP_FIT_CENSUS=1`): the lane this pair takes under
1946            // the count-keyed and the geometry-keyed gates, and — when it is
1947            // marched here and answered exactly there — the point-set comparison
1948            // of the two, printed when `pair_census` is dropped. `imprint/gate_census.rs`.
1949            let mut pair_census = if fit_census_enabled() {
1950                census_pair(first, second, options.tolerance)?
1951            } else {
1952                None
1953            };
1954            if let Some(IsoSection { curve, pcurves, own_lane }) = planar_iso {
1955                if debug_pairs {
1956                    eprintln!("pair {}x{}: planar_iso", first.face.id, second.face.id);
1957                }
1958                // Slice 1: the exact pcurves ride along with the curve when
1959                // the lane is on (or checked). A face read in a lifted chart
1960                // declines: the iso line is in the carrier's own frame, and
1961                // the lifted chart's period is not the carrier's.
1962                let exact_iso = if own_lane { ExactIsoPcurves::On } else { exact_iso };
1963                let exact_pcurves = match (exact_iso, pcurves) {
1964                    (ExactIsoPcurves::Off, _) => None,
1965                    (_, Some(pcurves)) if first.lifted.is_none() && second.lifted.is_none() => {
1966                        profile.exact_iso_sections += 1;
1967                        Some(pcurves)
1968                    }
1969                    _ => {
1970                        profile.exact_iso_declined += 1;
1971                        None
1972                    }
1973                };
1974                let lane_fits = profile.enabled.then(crate::PcurveFitScope::open);
1975                // PLANAR-ISO TANGENT TOUCH (`BREP_PLANAR_ISO_TANGENT_TOUCH`,
1976                // default on, =0 restores): the plane's iso circle is as exact
1977                // as the analytic lane's, so it is processed as an exact
1978                // section and an EXTERNAL touch of an edge in passing becomes
1979                // a junction (TANGENT TOUCH in `process_curve`). A plate already holding
1980                // two holes, less a third tangent to both: the third circle
1981                // touched the two hole rims and stayed one piece, whose
1982                // midpoint lay on one of the touches and read On the boundary,
1983                // so the circle was dropped and the disc kept.
1984                builder.exact_section = planar_iso_tangent_touch_enabled();
1985                builder.external_touch_only = true;
1986                let processed = builder.process_curve(
1987                    curve,
1988                    first,
1989                    second,
1990                    &[first, second],
1991                    &[first, second],
1992                    true,
1993                    exact_pcurves,
1994                );
1995                builder.exact_section = false;
1996                builder.external_touch_only = false;
1997                processed?;
1998                if let Some(scope) = lane_fits {
1999                    profile.exact_lane_fits += scope.close().fits;
2000                }
2001                profile.process_curve += profile.lap(&mut lap_start);
2002                continue;
2003            }
2004
2005            // Recognized analytic pairs produce their exact intersection
2006            // curves (lines, circles, ellipses) directly — no marching, no
2007            // polyline fitting, no chord-sag drift. An empty result is a
2008            // proof of non-intersection and also skips the marcher. (Read
2009            // above, with the planar-iso curve.)
2010            if let Some(curves) = analytic {
2011                if debug_pairs {
2012                    eprintln!(
2013                        "pair {}x{}: analytic x{}",
2014                        first.face.id,
2015                        second.face.id,
2016                        curves.len()
2017                    );
2018                }
2019                // TANGENT-CURVE LANE. An exact lane's "provably empty" is a
2020                // proof about TRANSVERSE curves: a plane at exactly the
2021                // cylinder's radius from its axis has no generatrix pair, and
2022                // the pair would be dropped here without a word while the
2023                // carriers touch along a whole line. Where the classification
2024                // read the pair as near-tangent, the lane looks for the
2025                // extended contact and records it typed.
2026                if curves.is_empty()
2027                    && options.tangent_curve_lane
2028                    && pair_classification.relation == SurfacePairRelation::NearTangent
2029                {
2030                    if let Some((section, run)) = tangent_curve_section(
2031                        first, second, options, &first_faces, &second_faces, &face_edge_lists, debug_pairs,
2032                    )? {
2033                        if options.tangent_curve_imprint && section.planar && run.len() >= 2 {
2034                            tangent_imprint_candidates.push((tangent_sections.len(), run, first, second));
2035                        }
2036                        tangent_sections.push(section);
2037                    }
2038                }
2039                let lane_fits = profile.enabled.then(crate::PcurveFitScope::open);
2040                builder.exact_section = true;
2041                for (index, curve) in curves.into_iter().enumerate() {
2042                    builder.pending_ruling = rulings.as_ref().and_then(|rs| rs.get(index)).cloned();
2043                    let processed = builder.process_curve(
2044                        curve,
2045                        first,
2046                        second,
2047                        &[first, second],
2048                        &[first, second],
2049                        true,
2050                        None,
2051                    );
2052                    if processed.is_err() {
2053                        builder.exact_section = false;
2054                    }
2055                    processed?;
2056                }
2057                builder.exact_section = false;
2058                if let Some(scope) = lane_fits {
2059                    profile.exact_lane_fits += scope.close().fits;
2060                }
2061                profile.process_curve += profile.lap(&mut lap_start);
2062                continue;
2063            }
2064
2065            // A pair whose every touching sample is TANGENTIAL cannot
2066            // contain a transverse intersection curve: the marcher would
2067            // walk the tangency band's noise, which neither closes nor
2068            // reaches a boundary (the distance-0 glue-extrude runaway).
2069            // Shared topology at a tangential contact comes from the
2070            // boundary-curve exchange above ("similar faces we do not
2071            // intersect" extended to tangential contacts — Golovanov §6.2;
2072            // where surfaces CROSS through a tangency, off-line samples
2073            // have non-parallel normals and the pair still marches).
2074            if pair_classification.relation == SurfacePairRelation::NearTangent
2075                && pair_classification.tangential_only
2076            {
2077                // The coarse 5×5 classifier can flag `tangential_only` off an
2078                // incidental tangential KISS between two curved carriers and
2079                // miss the transverse loop where they actually cross (two
2080                // overlapping tori: their tubes cross while their inner walls
2081                // just touch). Before honouring the skip, a GATED supplemental
2082                // detector (denser two-sided seeding, tangency-band seeds
2083                // rejected, trace-exhaustion swallowed, transverse-only
2084                // branches) checks whether a genuine transverse curve of
2085                // meaningful length lies inside BOTH trims.
2086                //
2087                // Such a pair's intersection is SINGULAR where a tangency
2088                // sits on it, and what the imprint can do about that depends
2089                // entirely on the SHAPE of the tangency — see
2090                // `imprint/tangent_contact.rs`. An isolated NODE (two branches
2091                // crossing, as every equal-radius pair produces) is already
2092                // assembled correctly by the ordinary march plus the 2D
2093                // arrangement's pinch carving; an EXTENDED contact along a
2094                // whole curve has no section to imprint at all and tears the
2095                // shell. Both are classified below and only the second is
2096                // refused. Skipping either silently would DROP the
2097                // intersection (torus∪torus double-counts; torus−torus removes
2098                // nothing — the two structural bugs the semantic oracle
2099                // found), so nothing here ever falls through quietly.
2100                let first_march = first_restricted[first_index]
2101                    .as_ref()
2102                    .map(|window| &window.surface)
2103                    .unwrap_or(&first.face.surface);
2104                let second_march = second_restricted[second_index]
2105                    .as_ref()
2106                    .map(|window| &window.surface)
2107                    .unwrap_or(&second.face.surface);
2108                let supplemental = super::work_profile::supplemental(
2109                    first_march,
2110                    second_march,
2111                    &SurfaceIntersectionOptions {
2112                        tolerance: options.tolerance,
2113                        maximum_step: options.maximum_ssi_step,
2114                        span_budget: march_span_budget,
2115                        ..Default::default()
2116                    },
2117                ).or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
2118                let mut dropped_length = 0.0f64;
2119                let mut clipped: Vec<Vec<Vec3>> = Vec::new();
2120                for branch in &supplemental {
2121                    for run in clip_branch_to_trims(&branch.points, first, second)? {
2122                        if run.len() < 2 {
2123                            continue;
2124                        }
2125                        let length: f64 = run
2126                            .windows(2)
2127                            .map(|pair| pair[1].sub(pair[0]).length())
2128                            .sum();
2129                        dropped_length = dropped_length.max(length);
2130                        clipped.push(run);
2131                    }
2132                }
2133                if dropped_length <= options.tolerance * 100.0 {
2134                    if debug_pairs {
2135                        eprintln!(
2136                            "pair {}x{}: tangential-only contact, march skipped",
2137                            first.face.id, second.face.id
2138                        );
2139                    }
2140                    // TANGENT-CURVE LANE: the skip is right for a transverse
2141                    // march, which has nothing to walk here, but the contact
2142                    // may still be a CURVE inside both trims (the same
2143                    // generatrix on a carrier no exact lane recognises).
2144                    // Recognise and record it, typed, rather than lose it.
2145                    if options.tangent_curve_lane {
2146                        if let Some((section, run)) = tangent_curve_section(
2147                            first, second, options, &first_faces, &second_faces, &face_edge_lists, debug_pairs,
2148                        )? {
2149                            if options.tangent_curve_imprint && section.planar && run.len() >= 2 {
2150                                tangent_imprint_candidates.push((tangent_sections.len(), run, first, second));
2151                            }
2152                            tangent_sections.push(section);
2153                        }
2154                    }
2155                    // RIM BRIDGE (`BREP_RIM_BRIDGE`, default on, `=0` off). A pair
2156                    // tangent along one stretch (two swept walls along the
2157                    // join of the sweeps) can still cross elsewhere along a
2158                    // section shorter than the march can see: where a rim of
2159                    // each operand passes the other at a grazing angle, each
2160                    // rim pierces the other operand's face a few
2161                    // `tol / |tan·n|` from the other's pierce, and the section
2162                    // between the two pierces lies on both faces of this pair.
2163                    // Its neighbours end at the two pierces; without it the
2164                    // shell tears there. The bridge is the straight segment
2165                    // between a crossing pierce of each operand inside both
2166                    // trims, mutual nearest and within the grazing reach.
2167                    if rim_bridge_enabled() {
2168                        rim_bridge(&mut builder, first, second, first_march, second_march, &face_edge_lists, options, debug_pairs)?;
2169                    }
2170                    continue;
2171                }
2172                // A transverse curve EXISTS. What would make it unimprintable is
2173                // a tangent NODE on it — and the node need not lie inside the
2174                // trims. Two equal-radius pipe arms are tangent to each other
2175                // where their axes' common perpendicular leaves the junction,
2176                // and a joint ball wider than the arms trims that crotch off
2177                // both faces; what is left inside the trims is an ordinary
2178                // crossing. So the question is not "does a transverse curve
2179                // exist" but "does the curve INSIDE BOTH TRIMS reach a
2180                // tangency". Only the latter is the checkerboard case.
2181                let mut tangency_inside_trims = false;
2182                let mut tangency_witness = Vec3::default();
2183                'clipped: for run in &clipped {
2184                    for (index, &point) in run.iter().enumerate() {
2185                        if pair_normals_parallel_at(first, second, point)? {
2186                            tangency_inside_trims = true;
2187                            tangency_witness = point;
2188                            if debug_pairs {
2189                                eprintln!(
2190                                    "pair {}x{}: TANGENCY at run index {}/{} ({:.6},{:.6},{:.6}) dropped_len={:.4e}",
2191                                    first.face.id, second.face.id, index, run.len(),
2192                                    point.x, point.y, point.z, dropped_length
2193                                );
2194                            }
2195                            break 'clipped;
2196                        }
2197                    }
2198                }
2199                if tangency_inside_trims {
2200                    // WHAT SHAPE is the tangency? The witness is only a marched
2201                    // sample within the transverse-seed angular gate, so it is
2202                    // REFINED onto the contact before being classified — at the
2203                    // raw witness a G1 cylinder/torus join and a genuine
2204                    // equal-radius node are eighteen-fold apart, which would be
2205                    // a band; at the refined contact they are thirty orders
2206                    // apart, which is a rank question. See
2207                    // `imprint/tangent_contact.rs`.
2208                    let contact = classify_tangent_contact(
2209                        &first.face.surface,
2210                        &second.face.surface,
2211                        tangency_witness,
2212                        options.tolerance,
2213                    )?;
2214                    if debug_pairs {
2215                        eprintln!(
2216                            "pair {}x{}: contact classification {:?}",
2217                            first.face.id, second.face.id, contact
2218                        );
2219                    }
2220                    match contact {
2221                        // An isolated node: the section is a curve everywhere
2222                        // but that one point, so the ordinary march below runs
2223                        // and the 2D arrangement carves the pinch on both
2224                        // faces. `tangent_node` records it so a march that
2225                        // cannot get through still refuses in THIS class rather
2226                        // than leaking the marcher's own message.
2227                        Some(contact) if contact.is_isolated_node() => {
2228                            tangent_node = Some(contact.point);
2229                            tangent_nodes.push(contact.point);
2230                        }
2231                        // An extended contact (rank-deficient) or a witness we
2232                        // could not refine onto any contact at all (None — so
2233                        // nothing is proven and the pre-classification refusal
2234                        // stands). Neither has a section curve the imprint can
2235                        // represent.
2236                        // The witness's refinement held on an open edge of a
2237                        // carrier, short of a contact: the contact lies off
2238                        // the carrier, so within both the pair only nears
2239                        // tangency at that edge and its section is an ordinary
2240                        // curve (`BREP_IMPRINT_TANGENCY_OFF_CARRIER`).
2241                        None if super::tangent_contact::tangency_off_carrier_on()
2242                            && super::tangent_contact::tangency_runs_off_carrier(
2243                                &first.face.surface,
2244                                &second.face.surface,
2245                                tangency_witness,
2246                                options.tolerance,
2247                            )?
2248                            && every_other_tangency_admitted(first, second, &clipped, options.tolerance)? =>
2249                        {
2250                            if debug_pairs {
2251                                eprintln!(
2252                                    "pair {}x{}: tangency witness refines off the carrier, marched as a section",
2253                                    first.face.id, second.face.id
2254                                );
2255                            }
2256                        }
2257                        other => {
2258                            let shape = match other {
2259                                Some(contact) => contact.describe(),
2260                                None => format!(
2261                                    "the tangency near ({:.6},{:.6},{:.6}) could not be refined \
2262                                     onto a contact, so its shape is unproven",
2263                                    tangency_witness.x, tangency_witness.y, tangency_witness.z
2264                                ),
2265                            };
2266                            return Err(KernelRefusal::new(
2267                                RefusalClass::TangentNodeSingularity,
2268                                KernelStage::Intersect,
2269                                format!(
2270                                    "boolean: unsupported singular/tangent-node surface intersection \
2271                                     between faces {} and {}: {shape}",
2272                                    first.face.id, second.face.id
2273                                ),
2274                            ));
2275                        }
2276                    }
2277                }
2278                if debug_pairs && tangent_node.is_none() {
2279                    // Transverse the whole way inside both trims: the coarse
2280                    // 5x5 classifier only saw the tangency the trims cut away.
2281                    eprintln!(
2282                        "pair {}x{}: classified tangential-only, but the curve inside both \
2283                         trims is transverse ({dropped_length:.4}) — marching",
2284                        first.face.id, second.face.id
2285                    );
2286                }
2287            }
2288
2289            // The trim-window carriers: same surface and parameterization
2290            // over the window, so hit (u, v) values remain valid on the
2291            // originals; out-of-window intersections could never survive
2292            // clip_branch_to_trims and are not walked at all.
2293            let first_march = first_restricted[first_index]
2294                .as_ref()
2295                .map(|window| &window.surface)
2296                .unwrap_or(&first.face.surface);
2297            let second_march = second_restricted[second_index]
2298                .as_ref()
2299                .map(|window| &window.surface)
2300                .unwrap_or(&second.face.surface);
2301            // Trim-window carriers PROVED apart by their span hulls
2302            // (`BREP_SSI_SEPARATION_PREFILTER`) have nothing to seed or march:
2303            // every cheaper lane above has had the pair, and only the pairs
2304            // that reach the march pay for the proof (each face's hulls are
2305            // built once).
2306            let proved_apart = crate::separation_prefilter_enabled() && {
2307                let hulls_a = first_hulls[first_index].get_or_init(|| crate::SpanHullSet::of(first_march));
2308                let hulls_b = second_hulls[second_index].get_or_init(|| crate::SpanHullSet::of(second_march));
2309                matches!((hulls_a, hulls_b), (Some(a), Some(b)) if crate::hull_sets_proved_apart(a, b, options.tolerance * 10.0))
2310            };
2311            if proved_apart {
2312                proved_apart_pairs.insert((first_index, second_index));
2313                profile.seeds += profile.lap(&mut lap_start);
2314                if debug_pairs {
2315                    eprintln!("pair {}x{}: trim-window carriers proved apart, not marched", first.face.id, second.face.id);
2316                }
2317                continue;
2318            }
2319            let pair_hermite_lane = hermite_lane && super::hermite::refinement_carriers_eligible(
2320                &first.face.surface, &second.face.surface,
2321            );
2322            let mut seed_points = Vec::new();
2323            // Smallest |edge_tangent · surface_normal| over accepted seeds — the
2324            // local grazing measure at the trim crossings (near 0 = the edge
2325            // pierces the other surface tangentially). Gates the near-tangent
2326            // clip-order rescue below to genuinely grazing pairs.
2327            let mut min_seed_tangency = f64::INFINITY;
2328            // Two grazing crossings of one trim edge bound a real, narrow
2329            // interval. It cannot tolerate a section fit that misses either
2330            // crossing, even when a coarse whole-model distance looks small.
2331            let mut paired_grazing_crossings = false;
2332            // Every hit the seed gate rejected, for the whole pair: the
2333            // point, its `|tan·n|`, the edge (its operand, its id) and the
2334            // parameter on it, and whether that edge belongs to `first`.
2335            // Read only when the march comes back empty, below, where the
2336            // genuine crossings among them are told from lies-on samples.
2337            let mut grazing_hits: Vec<(Vec3, f64, u8, u64, f64, bool)> = Vec::new();
2338            for (face, other_march, other) in
2339                [(first, second_march, second), (second, first_march, first)]
2340            {
2341                for edge in &face_edge_lists[&face.key()] {
2342                    if edge.degenerate {
2343                        continue;
2344                    }
2345                    let mut grazing_crossings: Vec<Vec3> = Vec::new();
2346                    // LIES-ON SKIP (2026-10-17, the shelled-box report's
2347                    // offset bore against the offset blend walls): an edge
2348                    // that LIES ON the other carrier — the test the exchange
2349                    // stage above already trusted to hand the whole edge over
2350                    // as a shared span — returns a hit per sample from
2351                    // `intersect_curve_surface`, every one grazing (|tan.n| = 0
2352                    // on a curve in the surface) and every one rejected: three
2353                    // such edges answered 8 580 of that pair's 8 586 seed hits
2354                    // at 0.36 s. Such an edge contributes no seed, no tangency
2355                    // minimum and no section evidence; its one effect is the
2356                    // paired-grazing flag, set when two of its grazing points
2357                    // sit more than the weld apart, which is reproduced here
2358                    // from the edge's own extent. `BREP_IMPRINT_LIES_ON_SEED_SKIP=0`
2359                    // runs the solve as before.
2360                    if lies_on_seed_skip_enabled() {
2361                        let subcurve = cached_subcurve(face.operand, edge)?;
2362                        if super::support::curve_lies_on_surface(&subcurve, other_march, options.tolerance)? {
2363                            let [start, end] = subcurve.domain().or_refuse(KernelStage::Intersect, "domain")?;
2364                            let mut probes = Vec::with_capacity(5);
2365                            for fraction in [0.0, 0.25, 0.5, 0.75, 1.0] {
2366                                probes.push(subcurve.evaluate(start + (end - start) * fraction).or_refuse(KernelStage::Intersect, "evaluate")?);
2367                            }
2368                            let weld = assembler_weld(options.tolerance);
2369                            if probes.iter().any(|a| probes.iter().any(|b| a.sub(*b).length() > weld)) {
2370                                paired_grazing_crossings = true;
2371                            }
2372                            if debug_pairs {
2373                                eprintln!(
2374                                    "pair {}x{}: seed edge {} lies on the other carrier — seed solve skipped",
2375                                    first.face.id, second.face.id, edge.id
2376                                );
2377                            }
2378                            continue;
2379                        }
2380                    }
2381                    for hit in intersect_curve_surface(&edge.curve, other_march, options.tolerance).or_refuse(KernelStage::Intersect, "intersect_curve_surface")?
2382                    {
2383                        if hit.t < edge.t0 - 1e-9 || hit.t > edge.t1 + 1e-9 {
2384                            continue;
2385                        }
2386                        let derivative = edge.curve.derivatives(hit.t, 1).or_refuse(KernelStage::Intersect, "derivatives")?[1];
2387                        // A STATIONARY POINT on the edge curve is not a reason
2388                        // to refuse the boolean. An involute flank starts at
2389                        // the base circle with an exactly zero tangent, so a
2390                        // gear tooth's profile carries one cusp per flank, and
2391                        // a hit landing on that parameter used to propagate
2392                        // "Vec3.normalized: zero-length vector" out of the
2393                        // whole union (the 2026-09-14 herringbone report: the
2394                        // second tooth band's z=0 cap edge meets the first
2395                        // band's flank exactly at the cusp). The direction is
2396                        // still defined as the one-sided limit, so read it from
2397                        // just inside the edge's own range; an edge with no
2398                        // direction at all simply contributes no seed, exactly
2399                        // as a hit whose face normal is unavailable already
2400                        // does two lines below. Seeds are marcher hints, so a
2401                        // dropped one costs a hint, never an answer.
2402                        // Escape hatch for tamper-verification:
2403                        // BREP_CUSP_TANGENT_RESCUE=0 restores the refusal.
2404                        let tangent = match derivative.normalized() {
2405                            Ok(tangent) => tangent,
2406                            Err(error) => {
2407                                if std::env::var("BREP_CUSP_TANGENT_RESCUE").as_deref() == Ok("0") {
2408                                    return Err(error)
2409                                        .or_refuse(KernelStage::Intersect, "normalized");
2410                                }
2411                                match edge.curve.stationary_tangent_rescue(hit.t, edge.t0, edge.t1)
2412                                {
2413                                    Some(tangent) => tangent,
2414                                    None => continue,
2415                                }
2416                            }
2417                        };
2418                        // `hit` was solved on the other face's MARCH WINDOW, so
2419                        // its uv is in that face's chart — a period off the
2420                        // carrier's where the window is lifted, and `normal`
2421                        // clamps a parameter past its domain.
2422                        let normal = match other.chart().normal(hit.u, hit.v) {
2423                            Ok(normal) => normal,
2424                            Err(_) => continue,
2425                        };
2426                        if debug_pairs {
2427                            eprintln!(
2428                                "pair {}x{}: seed edge {} t={:.6} p=({:.5},{:.5},{:.5}) |tan.n|={:.4} {}",
2429                                first.face.id,
2430                                second.face.id,
2431                                edge.id,
2432                                hit.t,
2433                                hit.point.x,
2434                                hit.point.y,
2435                                hit.point.z,
2436                                tangent.dot(normal).abs(),
2437                                if tangent.dot(normal).abs() >= 0.1 { "ACCEPT" } else { "reject" }
2438                            );
2439                        }
2440                        if tangent.dot(normal).abs() >= 0.1 {
2441                            seed_points.push(hit.point);
2442                            min_seed_tangency = min_seed_tangency.min(tangent.dot(normal).abs());
2443                            section_evidence = true;
2444                        } else {
2445                            if grazing_crossings.iter().any(|point| {
2446                                point.sub(hit.point).length() > assembler_weld(options.tolerance)
2447                            }) {
2448                                paired_grazing_crossings = true;
2449                            }
2450                            grazing_crossings.push(hit.point);
2451                            grazing_hits.push((
2452                                hit.point,
2453                                tangent.dot(normal).abs(),
2454                                face.operand,
2455                                edge.id,
2456                                hit.t,
2457                                face.operand == first.operand && face.face.id == first.face.id,
2458                            ));
2459                        }
2460                    }
2461                }
2462            }
2463            profile.seeds += profile.lap(&mut lap_start);
2464            // POINT CONTACT (`BREP_IMPRINT_PLANE_POINT_SKIP`, lane X row 5):
2465            // two exact parallelograms meeting at one point have no section
2466            // curve. Once a seed is accepted the pair's contact evidence is
2467            // already recorded and the march could only trace that point, so
2468            // it is skipped; an unseeded pair still marches.
2469            if !seed_points.is_empty()
2470                && plane_point_skip_enabled()
2471                && super::support::planar_point_contact(&first.face.surface, &second.face.surface, options.tolerance) == Some(true)
2472            {
2473                PLANE_POINT_SKIPS.with(|count| count.set(count.get() + 1));
2474                if debug_pairs {
2475                    eprintln!("pair {}x{}: planar point contact, march skipped", first.face.id, second.face.id);
2476                }
2477                continue;
2478            }
2479            // BOUNDARY TOUCH (`BREP_IMPRINT_BOUNDARY_TOUCH`, default off): a carrier
2480            // that meets a flat face's plane only along one of its own boundary
2481            // iso-curves ([`super::support::touches_plane_only_on_boundary`]) has
2482            // no section but that boundary, which the edge exchange imprints; the
2483            // march along it traced the rim in short branches a ULP decided.
2484            if super::support::boundary_touch_enabled()
2485                && (super::support::touches_plane_only_on_boundary(&first.face.surface, &second.face.surface, options.tolerance)
2486                    || super::support::touches_plane_only_on_boundary(&second.face.surface, &first.face.surface, options.tolerance))
2487            {
2488                if debug_pairs {
2489                    eprintln!("pair {}x{}: boundary touch on a flat face, march skipped", first.face.id, second.face.id);
2490                }
2491                continue;
2492            }
2493            profile.marched_pairs += 1;
2494            if debug_pairs {
2495                eprintln!(
2496                    "pair {}x{}: marching (relation {:?})...",
2497                    first.face.id, second.face.id, pair_classification.relation
2498                );
2499            }
2500            let marched = super::work_profile::trace(
2501                first_march,
2502                second_march,
2503                &SurfaceIntersectionOptions {
2504                    tolerance: options.tolerance,
2505                    maximum_step: march_maximum_step(
2506                        &pair_classification,
2507                        options.maximum_ssi_step,
2508                        builder.scale,
2509                    ),
2510                    seed_points: seed_points.clone(),
2511                    span_budget: march_span_budget,
2512                    ordered_starts,
2513                    consume_starts,
2514                    tree_seeds,
2515                    ..Default::default()
2516                },
2517            );
2518            // A pair carrying a tangent node keeps its OWN refusal class when
2519            // the march fails: the node is why the trace cannot close, and the
2520            // equal-radius torus pair depends on being told so rather than on
2521            // reading a step-budget message it cannot act on.
2522            let marched = match (marched, tangent_node) {
2523                (Err(error), Some(node)) => {
2524                    return Err(KernelRefusal::new(
2525                        RefusalClass::TangentNodeSingularity,
2526                        KernelStage::Intersect,
2527                        format!(
2528                            "boolean: unsupported singular/tangent-node surface intersection \
2529                             between faces {} and {}: the section through the tangent node at \
2530                             ({:.6},{:.6},{:.6}) could not be marched ({error})",
2531                            first.face.id, second.face.id, node.x, node.y, node.z
2532                        ),
2533                    ));
2534                }
2535                (marched, _) => marched,
2536            };
2537            let mut branches = marched
2538            .map_err(|error| {
2539                format!(
2540                    "{error} (marching faces {} and {})",
2541                    first.face.id, second.face.id
2542                )
2543            }).or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
2544            profile.march += profile.lap(&mut lap_start);
2545            let rescue_started = profile.enabled.then(Instant::now);
2546            // MARCH-ORDER SWAP RESCUE (hatch BREP_MARCH_SWAP_RESCUE=0).
2547            // `intersect_surfaces` is not order-symmetric: the coupled Newton
2548            // trace can fail to start/continue from a valid seed when the two
2549            // surfaces are presented in one operand order yet succeed in the
2550            // other. This is the sole reason t217's `subtract(sphere, step)`
2551            // fails while every other op passes — pair 118x842 (sphere-first)
2552            // marches ZERO branches, while 842x118 (step-first, the working
2553            // a\b order) marches the section from the IDENTICAL accepted pierce
2554            // seeds. When the forward order returns no branch AND an accepted
2555            // transverse pierce seed exists (so a real section provably crosses
2556            // both trims), retry the march with the surfaces swapped — i.e.
2557            // reproduce the exact call the working operand order makes for this
2558            // pair (measured: seed_only alone does NOT recover it — the section
2559            // is found from an auto-grid start, not from the near-tangent pierce
2560            // seeds, which the seed normal-cross gate rejects). The returned
2561            // branch points are 3D and therefore order-independent, so no
2562            // parameter remap is needed; they flow through the identical clip /
2563            // process_curve gates below, which drop any out-of-trim or
2564            // sub-length run exactly as today. The rescue only ever runs when
2565            // the forward order found NOTHING, so it cannot alter a pair that
2566            // already marched.
2567            if branches.is_empty()
2568                && !seed_points.is_empty()
2569                && pair_classification.relation == SurfacePairRelation::Candidate
2570                && std::env::var("BREP_MARCH_SWAP_RESCUE").as_deref() != Ok("0")
2571            {
2572                // FAIL-SOFT: the forward order already returned Ok(empty); a
2573                // swapped-march error (trace-exhaustion is a real error class —
2574                // `intersect_surfaces_supplemental` swallows it for exactly this
2575                // reason) must NOT convert that graceful empty into a hard error.
2576                // On Err, keep the (empty) forward result and carry on.
2577                let swapped = super::work_profile::trace(
2578                    second_march,
2579                    first_march,
2580                    &SurfaceIntersectionOptions {
2581                        tolerance: options.tolerance,
2582                        maximum_step: march_maximum_step(
2583                            &pair_classification,
2584                            options.maximum_ssi_step,
2585                            builder.scale,
2586                        ),
2587                        seed_points: seed_points.clone(),
2588                        span_budget: march_span_budget,
2589                        ordered_starts,
2590                        consume_starts,
2591                        tree_seeds,
2592                        ..Default::default()
2593                    },
2594                )
2595                .unwrap_or_default();
2596                if debug_pairs {
2597                    eprintln!(
2598                        "pair {}x{}: MARCH-SWAP RESCUE attempt -> {} branches, pts {:?}",
2599                        first.face.id,
2600                        second.face.id,
2601                        swapped.len(),
2602                        swapped.iter().map(|b| b.points.len()).collect::<Vec<_>>()
2603                    );
2604                }
2605                if !swapped.is_empty() {
2606                    branches = swapped;
2607                    march_swap_rescues += 1;
2608                }
2609            }
2610            // NEAR-TANGENT CLIP-ORDER RESCUE (hatch BREP_MARCH_SWAP_CLIP_RESCUE=0).
2611            // Companion to the empty-branch MARCH-SWAP RESCUE above:
2612            // `intersect_surfaces` is order-asymmetric not only in WHETHER it
2613            // marches, but in the exact sample positions of the section
2614            // polyline. On a NEAR-TANGENT graze, `clip_branch_to_trims`
2615            // classifies those samples against the mutual trims, and a sample
2616            // landing just past the near-tangent boundary is dropped as a
2617            // false-Outside that TRUNCATES the clipped section. The two operand
2618            // orders drop DIFFERENT near-tangent tail samples, so one order
2619            // yields a section ~0.1-0.2mm shorter at ONE endpoint (t660: b\a's
2620            // step-first order clips pairs 223x105/399x105 ~0.22/0.14mm short of
2621            // the section a\b's cyl-first order keeps, stranding edge 173
2622            // one-use). Near-tangent clip errors are almost exclusively
2623            // false-Outside (a point truly outside a trim rarely projects to an
2624            // in-trim uv), so the order with the LONGER clipped section suffered
2625            // fewer drops and is the more complete one. When the swapped order
2626            // marches the SAME branch structure with a meaningfully longer
2627            // clipped total, adopt its branches (3D points, so they flow through
2628            // the identical clip/process_curve gates below). Gated to Candidate
2629            // pairs (the near-tangent/ambiguous class; clean Transverse
2630            // crossings clip identically in both orders and never differ) with
2631            // an accepted GRAZING pierce seed (min |tan·n| < 0.5 — a real
2632            // section provably crosses, and does so near-tangentially, the only
2633            // regime where the clip wobbles; this also bounds the extra march to
2634            // grazing pairs), and requires a >0.1%-of-length margin so
2635            // raw-sampling jitter (t660: 0.02%) cannot flip a clean pair.
2636            // Fail-soft: any swapped-march or comparison-clip error keeps the
2637            // forward result.
2638            if !branches.is_empty()
2639                && !seed_points.is_empty()
2640                && min_seed_tangency < 0.5
2641                && pair_classification.relation == SurfacePairRelation::Candidate
2642                && std::env::var("BREP_MARCH_SWAP_CLIP_RESCUE").as_deref() != Ok("0")
2643            {
2644                let swapped = super::work_profile::trace(
2645                    second_march,
2646                    first_march,
2647                    &SurfaceIntersectionOptions {
2648                        tolerance: options.tolerance,
2649                        maximum_step: march_maximum_step(
2650                            &pair_classification,
2651                            options.maximum_ssi_step,
2652                            builder.scale,
2653                        ),
2654                        seed_points: seed_points.clone(),
2655                        span_budget: march_span_budget,
2656                        ordered_starts,
2657                        consume_starts,
2658                        tree_seeds,
2659                        ..Default::default()
2660                    },
2661                )
2662                .unwrap_or_default();
2663                // Only a swap that reproduces the SAME branch count — a
2664                // refined-endpoint variant of the same section, not a different
2665                // branch decomposition (guards against adopting a spurious
2666                // extra branch as "longer").
2667                if !swapped.is_empty() && swapped.len() == branches.len() {
2668                    let totals = (|| -> Result<(f64, f64), KernelRefusal> {
2669                        let mut fwd = 0.0;
2670                        for b in &branches {
2671                            let refined = insert_seed_points_into_branch(
2672                                &b.points,
2673                                &seed_points,
2674                                options.tolerance,
2675                            );
2676                            for run in clip_branch_to_trims(&refined, first, second)? {
2677                                fwd += run
2678                                    .windows(2)
2679                                    .map(|p| p[1].sub(p[0]).length())
2680                                    .sum::<f64>();
2681                            }
2682                        }
2683                        let mut swp = 0.0;
2684                        for b in &swapped {
2685                            let refined = insert_seed_points_into_branch(
2686                                &b.points,
2687                                &seed_points,
2688                                options.tolerance,
2689                            );
2690                            for run in clip_branch_to_trims(&refined, first, second)? {
2691                                swp += run
2692                                    .windows(2)
2693                                    .map(|p| p[1].sub(p[0]).length())
2694                                    .sum::<f64>();
2695                            }
2696                        }
2697                        Ok((fwd, swp))
2698                    })();
2699                    if let Ok((fwd_clip, swp_clip)) = totals {
2700                        let margin = fwd_clip.max(swp_clip) * 1.0e-3;
2701                        let adopt = swp_clip > fwd_clip + margin;
2702                        if debug_pairs {
2703                            eprintln!(
2704                                "pair {}x{}: CLIP-SWAP RESCUE fwd_clip={:.6} swp_clip={:.6} margin={:.6}{}",
2705                                first.face.id,
2706                                second.face.id,
2707                                fwd_clip,
2708                                swp_clip,
2709                                margin,
2710                                if adopt { " ADOPT" } else { "" }
2711                            );
2712                        }
2713                        if adopt {
2714                            branches = swapped;
2715                            clip_swap_rescues += 1;
2716                        }
2717                    }
2718                }
2719            }
2720            if let Some(started) = rescue_started {
2721                profile.rescue_march += started.elapsed();
2722            }
2723            // A surviving grid branch does not establish completeness. Append
2724            // proven trim pierces after the ordinary starts, retaining their
2725            // admission bound and every branch already returned by the march.
2726            // Seed ordering and consumption can alter earlier branches, so
2727            // those modes retain their existing behavior here.
2728            let complete_grazing = switch!("BREP_GRAZING_BRANCH_COMPLETION", true);
2729            let check_completion = switch!("BREP_GRAZING_BRANCH_COMPLETION_CHECK", false);
2730            if (complete_grazing || check_completion)
2731                && !branches.is_empty() && seed_points.is_empty() && !grazing_hits.is_empty()
2732                && options.tangent_curve_lane && !ordered_starts && !consume_starts
2733            {
2734                let completed = (|| -> Result<_, KernelRefusal> {
2735                    let mut pierces: Vec<Vec3> = Vec::new();
2736                    for &(point, _, _, edge_id, t, on_first) in &grazing_hits {
2737                        let (owner, other_march) = if on_first { (first, second_march) } else { (second, first_march) };
2738                        let Some(edge) = face_edge_lists[&owner.key()].iter().find(|edge| edge.id == edge_id) else {
2739                            continue;
2740                        };
2741                        if edge_crosses_carrier(edge, &face_edge_lists[&owner.key()], t, other_march, options.tolerance)?
2742                            && !(super::support::near_end_snap_enabled()
2743                                && pierce_is_end_contact(edge, t, point, other_march, options.tolerance)?)
2744                            && !pierces.iter().any(|seen| seen.sub(point).length() <= options.tolerance)
2745                            && inside_both_trims(point, first, second)?
2746                        {
2747                            pierces.push(point);
2748                        }
2749                    }
2750                    if pierces.is_empty() { return Ok(None); }
2751                    let bound = (options.tolerance / (2.0 * builder.scale.max(options.tolerance))).sqrt();
2752                    let extended = super::work_profile::trace(
2753                        first_march, second_march,
2754                        &SurfaceIntersectionOptions {
2755                            tolerance: options.tolerance,
2756                            maximum_step: march_maximum_step(&pair_classification, options.maximum_ssi_step, builder.scale),
2757                            seed_points: pierces.clone(),
2758                            seed_only: false,
2759                            seed_start_cross: Some(bound),
2760                            span_budget: march_span_budget,
2761                            ordered_starts,
2762                            consume_starts,
2763                            tree_seeds,
2764                            ..Default::default()
2765                        },
2766                    ).or_refuse(KernelStage::Intersect, "grazing branch completion")?;
2767                    Ok(Some((pierces, extended)))
2768                })();
2769                match completed {
2770                    Ok(Some((pierces, extended))) => {
2771                        let preserved = preserves_branch_prefix(&branches, &extended);
2772                        let added = extended.len().saturating_sub(branches.len());
2773                        if check_completion || debug_pairs {
2774                            eprintln!("grazing completion {}x{}: pierces={} branches={}->{} prefix_preserved={preserved} added={added} enabled={complete_grazing}",
2775                                first.face.id, second.face.id, pierces.len(), branches.len(), extended.len());
2776                        }
2777                        if complete_grazing && preserved && added > 0 {
2778                            branches = extended;
2779                            seed_points.extend(pierces);
2780                            grazing_march = true;
2781                        }
2782                    }
2783                    Ok(None) => {}
2784                    Err(error) => {
2785                        if check_completion || debug_pairs {
2786                            eprintln!("grazing completion {}x{}: retained original branches after {error}", first.face.id, second.face.id);
2787                        }
2788                    }
2789                }
2790            }
2791            // CROSSING-NODE SPLIT (`BREP_SSI_NODE_SPLIT`, default on, `=0` off;
2792            // `intersect/crossing_node.rs`): a branch the marcher carried
2793            // through a saddle tangent node is cut at every passage, so the
2794            // node is a vertex where the four half-branches meet.
2795            if crate::crossing_node_split_enabled() && !branches.is_empty() {
2796                let (split, nodes) = crate::split_at_crossing_nodes(
2797                    first_march,
2798                    second_march,
2799                    std::mem::take(&mut branches),
2800                    options.tolerance,
2801                )
2802                .or_refuse(KernelStage::Intersect, "csg.imprint.driver")?;
2803                branches = split;
2804                for node in nodes {
2805                    if debug_pairs {
2806                        eprintln!(
2807                            "pair {}x{}: crossing node ({:.9},{:.9},{:.9}) split the march",
2808                            first.face.id, second.face.id, node.x, node.y, node.z
2809                        );
2810                    }
2811                    tangent_node.get_or_insert(node);
2812                    if !tangent_nodes.iter().any(|known| known.sub(node).length() <= options.tolerance * 10.0) {
2813                        tangent_nodes.push(node);
2814                    }
2815                }
2816            }
2817            if branches.iter().any(|branch| branch.points.len() >= 2) {
2818                section_evidence = true;
2819            }
2820            if debug_pairs {
2821                eprintln!(
2822                    "pair {}x{}: MARCH {} branches, pts {:?}",
2823                    first.face.id,
2824                    second.face.id,
2825                    branches.len(),
2826                    branches.iter().map(|b| b.points.len()).collect::<Vec<_>>()
2827                );
2828            }
2829            // GRAZING PIERCE, NO SECTION (2026-10-17, the revolve-into-bore
2830            // report). A trim edge of one face pierces the other carrier at
2831            // an angle below the seed gate, inside BOTH trims, and the pair
2832            // marched nothing: the pierce proves a section crosses the faces
2833            // there, the empty march says the crossing is too near tangency
2834            // for the marcher's start gate to admit (the -4° revolve of a
2835            // bored box's top face about its back edge, unioned back: the
2836            // torus hole wall continues the bore tangentially along their
2837            // shared rim and crosses it again at 0.002 rad — a third-order
2838            // contact, `boolean::attribute_to_tangent_node`). Nothing is
2839            // imprinted here; the contact is RECORDED, with the faces across
2840            // the pierced edges, so a tear downstream of it is attributed to
2841            // the contact in the tangent-node class — which declines the
2842            // perturbation ladder — instead of leaking as an anonymous
2843            // open-edge arrangement and burning the ladder's rungs (12.5 s
2844            // on the report, every rung refused by its mirror). A pair whose
2845            // pierce the trims do not both contain is left alone, as is one
2846            // with an accepted seed: those pairs the march could and should
2847            // have answered. `BREP_GRAZING_PIERCE_RECORD=0` is the hatch.
2848            if branches.is_empty()
2849                && seed_points.is_empty()
2850                && !grazing_hits.is_empty()
2851                && options.tangent_curve_lane
2852                && std::env::var("BREP_GRAZING_PIERCE_RECORD").as_deref() != Ok("0")
2853            {
2854                let mut inside: Vec<(Vec3, f64, u8, u64)> = Vec::new();
2855                for &(point, tangency, operand, edge_id, t, on_first) in &grazing_hits {
2856                    // A pierce, not a lies-on sample: the edge must CROSS the
2857                    // carrier at the hit (a rim lying on the other carrier
2858                    // reads |tan·n| = 0 at every sample and never changes
2859                    // side) — and inside both trims.
2860                    let (owner, other_march) = if on_first { (first, second_march) } else { (second, first_march) };
2861                    let Some(edge) = face_edge_lists[&owner.key()].iter().find(|edge| edge.id == edge_id) else {
2862                        continue;
2863                    };
2864                    let crosses = edge_crosses_carrier(edge, &face_edge_lists[&owner.key()], t, other_march, options.tolerance)?
2865                        && !(super::support::near_end_snap_enabled() && pierce_is_end_contact(edge, t, point, other_march, options.tolerance)?);
2866                    // The two halves of a split edge report one pierce at
2867                    // their shared vertex: it is one section point, once.
2868                    if crosses && inside.iter().any(|(seen, ..)| seen.sub(point).length() <= options.tolerance) {
2869                        continue;
2870                    }
2871                    let contained = crosses && inside_both_trims(point, first, second)?;
2872                    if debug_pairs && crosses {
2873                        eprintln!(
2874                            "pair {}x{}: grazing pierce op={operand} edge={edge_id} ({:.6},{:.6},{:.6}) |tan.n|={tangency:.4} inside both trims: {contained}",
2875                            first.face.id, second.face.id, point.x, point.y, point.z
2876                        );
2877                    }
2878                    if contained {
2879                        inside.push((point, tangency, operand, edge_id));
2880                    }
2881                }
2882                // SUB-GATE RE-MARCH (2026-10-17, the same report, second
2883                // half). The pierces are PROVEN section points, so the march
2884                // is retried from them alone, admitted below the marcher's
2885                // start gate: the crossing is resolvable while its lateral
2886                // uncertainty `tol / α` fits inside the tangency band's
2887                // half-width `√(2 R tol)`, i.e. `α ≥ √(tol / 2R)`, and no
2888                // carrier is curved tighter than the model, so the bound is
2889                // taken at `R = scale`. Grid starts stay gated (their
2890                // tangency-band runaway is the gate's reason). A branch that
2891                // comes back is imprinted exactly as a marched one; only when
2892                // none does is the contact recorded for the attribution. The
2893                // retry is fail-soft like the swap rescue: an Err keeps the
2894                // empty forward result. Hatch: BREP_GRAZING_SEED_MARCH=0.
2895                if !inside.is_empty() && std::env::var("BREP_GRAZING_SEED_MARCH").as_deref() != Ok("0") {
2896                    let bound = (options.tolerance / (2.0 * builder.scale.max(options.tolerance))).sqrt();
2897                    let pierces: Vec<Vec3> = inside.iter().map(|(point, _, _, _)| *point).collect();
2898                    let rescued = super::work_profile::trace(
2899                        first_march,
2900                        second_march,
2901                        &SurfaceIntersectionOptions {
2902                            tolerance: options.tolerance,
2903                            maximum_step: march_maximum_step(
2904                                &pair_classification,
2905                                options.maximum_ssi_step,
2906                                builder.scale,
2907                            ),
2908                            seed_points: pierces.clone(),
2909                            seed_only: true,
2910                            seed_start_cross: Some(bound),
2911                            span_budget: march_span_budget,
2912                            ordered_starts,
2913                            consume_starts,
2914                            tree_seeds,
2915                            ..Default::default()
2916                        },
2917                    )
2918                    .unwrap_or_default();
2919                    if debug_pairs {
2920                        eprintln!(
2921                            "pair {}x{}: SUB-GATE MARCH from {} pierce(s) at bound {bound:.3e} -> {} branches, pts {:?}",
2922                            first.face.id,
2923                            second.face.id,
2924                            pierces.len(),
2925                            rescued.len(),
2926                            rescued.iter().map(|b| b.points.len()).collect::<Vec<_>>()
2927                        );
2928                    }
2929                    if !rescued.is_empty() {
2930                        branches = rescued;
2931                        grazing_march = true;
2932                        // The pierces are the branches' exact trim crossings,
2933                        // inserted below like any accepted seed.
2934                        seed_points.extend(pierces);
2935                        inside.clear();
2936                    }
2937                }
2938                if !inside.is_empty() {
2939                    if debug_pairs {
2940                        eprintln!(
2941                            "pair {}x{}: {} grazing pierce(s) inside both trims and no marched branch: {}",
2942                            first.face.id,
2943                            second.face.id,
2944                            inside.len(),
2945                            inside
2946                                .iter()
2947                                .map(|(point, tangency, operand, edge)| format!(
2948                                    "op={operand} edge={edge} ({:.6},{:.6},{:.6}) |tan.n|={tangency:.4}",
2949                                    point.x, point.y, point.z
2950                                ))
2951                                .collect::<Vec<_>>()
2952                                .join(", ")
2953                        );
2954                    }
2955                    // The extended contact the lane can name, when it finds
2956                    // one (the shared rim here); else the record stands on
2957                    // the pierces alone.
2958                    let mut section = match tangent_curve_section(
2959                        first, second, options, &first_faces, &second_faces, &face_edge_lists, debug_pairs,
2960                    )? {
2961                        Some((section, _run)) => section,
2962                        None => TangentSectionRecord {
2963                            first: first.key(),
2964                            second: second.key(),
2965                            start: inside[0].0,
2966                            end: inside[inside.len() - 1].0,
2967                            length: 0.0,
2968                            closed: false,
2969                            stations: 0,
2970                            planar: false,
2971                            faces: vec![first.key(), second.key()],
2972                            piece_ids: Vec::new(),
2973                            grazing: Vec::new(),
2974                        },
2975                    };
2976                    // The faces across each pierced edge: the pierce is where
2977                    // the missing section meets that edge, so those faces are
2978                    // the ones a tear downstream of it will name.
2979                    for (_, _, operand, edge_id) in &inside {
2980                        let siblings = if *operand == first.operand { &first_faces } else { &second_faces };
2981                        for sibling in siblings.iter() {
2982                            let shares = sibling
2983                                .face
2984                                .loops
2985                                .iter()
2986                                .flat_map(|loop_record| &loop_record.coedges)
2987                                .any(|coedge| coedge.edge_id == *edge_id);
2988                            if shares && !section.faces.contains(&sibling.key()) {
2989                                section.faces.push(sibling.key());
2990                            }
2991                        }
2992                    }
2993                    section.grazing = inside.iter().map(|(point, tangency, _, _)| (*point, *tangency)).collect();
2994                    tangent_sections.push(section);
2995                }
2996            }
2997            if profile.enabled {
2998                // Net metadata only: observing carriers must not warm their
2999                // recognition/projection caches before the section fitter.
3000                profile_line!("imprint.march_pair first={:?} second={:?} ids={}x{} degrees={}x{}/{}x{} nets={}x{}/{}x{} stations={:?}",
3001                    first.face.name, second.face.name, first.face.id, second.face.id,
3002                    first.face.surface.degree_u, first.face.surface.degree_v,
3003                    second.face.surface.degree_u, second.face.surface.degree_v,
3004                    first.face.surface.control_points.len(), first.face.surface.control_points.first().map_or(0, Vec::len),
3005                    second.face.surface.control_points.len(), second.face.surface.control_points.first().map_or(0, Vec::len),
3006                    branches.iter().map(|branch| branch.points.len()).collect::<Vec<_>>());
3007            }
3008            // GRAZING PIERCES BOUND CLIP INTERVALS TOO (hosted report
3009            // 2026-11-01, "Boolean seems to take way too long": the cage-box
3010            // union with the cylinder moved 0.165 off the cage's axis). The
3011            // seed gate rejects a pierce whose `|tan·n|` is under 0.1 as a
3012            // march START, but the point is still an exact section point on
3013            // a trim edge: the end of a trim interval. The cylinder's bottom
3014            // rim crosses the cage's flat-to-second-order side twice, 0.036
3015            // apart, at `|tan·n|` = 0.0035, so the disc keeps a 0.036-long
3016            // piece of the y = 0 section there. Marched from the accepted
3017            // seeds with ~0.9 stations, that interval held no station, the
3018            // clip dropped it, the disc's two lenses stayed unbounded and
3019            // the arrangement tore: an open-edge refusal that sent the union
3020            // up the perturbation ladder (64 imprints, ~39 s native, every
3021            // rung refused). Inserting the rejected hits — gated, like every
3022            // seed, to the ones lying on the branch — gives such an interval
3023            // its endpoints. Only a RESOLVABLE pierce is inserted: its
3024            // position along the edge is known to `tol / |tan·n|`, so the
3025            // same bound the sub-gate re-march below admits a start at,
3026            // `|tan·n| >= √(tol / 2·scale)`, keeps the lateral uncertainty
3027            // inside the tangency band. Below it the hits are lies-on
3028            // samples (an edge in the other carrier reads |tan·n| = 0 at
3029            // every sample) or near-tangent brushes whose along-edge
3030            // position is a guess: the 2026-10-25 offset-shell history
3031            // (`successive_fillet_history_shells_under_the_one_call_imprint`)
3032            // inserts 25 pairs' worth of such points at |tan·n| ≤ 1.1e-4 and
3033            // its O.S10 pcurve fit then misses its stations by 2.6e-3.
3034            // `BREP_GRAZING_CLIP_REFINE=0` restores the accepted seeds alone.
3035            let clip_points: std::borrow::Cow<'_, [Vec3]> = if grazing_hits.is_empty()
3036                || std::env::var("BREP_GRAZING_CLIP_REFINE").as_deref() == Ok("0")
3037            {
3038                std::borrow::Cow::Borrowed(&seed_points)
3039            } else {
3040                let resolvable = (options.tolerance / (2.0 * builder.scale.max(options.tolerance))).sqrt();
3041                // A crease fading to tangency along a rim brushes it at |tan.n|
3042                // around 1e-4 for its last stretch, and those hits cut the
3043                // section into micro-pieces whose ends disagree; the interval
3044                // this path exists for pierced at 3.5e-3. `BREP_GRAZING_CLIP_FLOOR=0`
3045                // restores the resolvable bound alone.
3046                let resolvable = if switch!("BREP_GRAZING_CLIP_FLOOR", true) { resolvable.max(1e-3) } else { resolvable };
3047                let mut points = seed_points.clone();
3048                points.extend(grazing_hits.iter().filter(|hit| hit.1 >= resolvable).map(|hit| hit.0));
3049                if debug_pairs && points.len() != seed_points.len() {
3050                    eprintln!(
3051                        "pair {}x{}: {} grazing pierce(s) at |tan.n| >= {resolvable:.3e} join the trim clip",
3052                        first.face.id, second.face.id, points.len() - seed_points.len()
3053                    );
3054                }
3055                std::borrow::Cow::Owned(points)
3056            };
3057            for branch in branches {
3058                // The pierce seeds are the section's exact trim-crossing
3059                // points — insert them so no trim interval shorter than the
3060                // march step is invisible to the point-classification clip.
3061                let refined_points =
3062                    insert_seed_points_into_branch(&branch.points, &clip_points, options.tolerance);
3063                let clip_started = profile.enabled.then(Instant::now);
3064                let mut runs = clip_branch_to_trims(&refined_points, first, second)?;
3065                // TANGENT-RIM LANDING: a run the march stalled short of a trim
3066                // edge the two carriers are tangent along ends ON that edge
3067                // (see `land_run_ends_on_tangent_rim`).
3068                // Reached for the pairs whose march can stall short: one
3069                // carrying an admitted node, one marched from sub-gate
3070                // pierces, or one the classifier read as near-tangent (the
3071                // −10° sibling: no node admitted, an ordinary march that
3072                // stops 4e-5 short of the rim it is tangent along).
3073                if tangent_node.is_some()
3074                    || grazing_march
3075                    || pair_classification.relation == SurfacePairRelation::NearTangent
3076                {
3077                    for run in runs.iter_mut() {
3078                        for (operand, edge_id, parameter, from, to) in land_run_ends_on_tangent_node(
3079                            run,
3080                            first,
3081                            second,
3082                            &face_edge_lists,
3083                            options.tolerance,
3084                        )? {
3085                            if debug_pairs {
3086                                eprintln!(
3087                                    "pair {}x{}: tangent-node landing: run end ({:.6},{:.6},{:.6}) -> \
3088                                     node ({:.9},{:.9},{:.9}) on operand {operand} edge {edge_id} at t={parameter:.9}",
3089                                    first.face.id, second.face.id, from.x, from.y, from.z, to.x, to.y, to.z
3090                                );
3091                            }
3092                            let edge = builder.edges[&(operand, edge_id)];
3093                            builder.add_edge_split(operand, edge, parameter)?;
3094                        }
3095                        for (operand, edge_id, parameter, from, to) in land_run_ends_on_tangent_rim(
3096                            run,
3097                            tangent_node,
3098                            first,
3099                            second,
3100                            &face_edge_lists,
3101                            options.tolerance,
3102                        )? {
3103                            if debug_pairs {
3104                                eprintln!(
3105                                    "pair {}x{}: tangent-rim landing: run end ({:.6},{:.6},{:.6}) -> \
3106                                     ({:.6},{:.6},{:.6}) on operand {operand} edge {edge_id} at t={parameter:.6}",
3107                                    first.face.id, second.face.id, from.x, from.y, from.z, to.x, to.y, to.z
3108                                );
3109                            }
3110                            let edge = builder.edges[&(operand, edge_id)];
3111                            builder.add_edge_split(operand, edge, parameter)?;
3112                        }
3113                    }
3114                }
3115                if debug_pairs {
3116                    let dups = |points: &[Vec3]| points.windows(2).enumerate().filter(|(_, pair)| pair[1].sub(pair[0]).length() <= options.tolerance).map(|(i, pair)| format!("{i}:{:.2e}", pair[1].sub(pair[0]).length())).collect::<Vec<_>>();
3117                    eprintln!(
3118                        "pair {}x{}: DUPS branch {:?} seeded {:?} runs {:?} seeds {} branch_pts {} seeded_pts {}",
3119                        first.face.id, second.face.id, dups(&branch.points), dups(&refined_points), runs.iter().map(|run| dups(run)).collect::<Vec<_>>(), seed_points.len(), branch.points.len(), refined_points.len()
3120                    );
3121                }
3122                if let Some(started) = clip_started {
3123                    profile.clip += started.elapsed();
3124                }
3125                for run in runs {
3126                    if debug_pairs {
3127                        eprintln!(
3128                            "pair {}x{}: clip run len_pts={} length={:.4e}",
3129                            first.face.id,
3130                            second.face.id,
3131                            run.len(),
3132                            run.windows(2)
3133                                .map(|pair| pair[1].sub(pair[0]).length())
3134                                .sum::<f64>()
3135                        );
3136                    }
3137                    if run.len() < 2 {
3138                        continue;
3139                    }
3140                    let length: f64 = run
3141                        .windows(2)
3142                        .map(|pair| pair[1].sub(pair[0]).length())
3143                        .sum();
3144                    if length <= options.tolerance * 100.0 {
3145                        continue;
3146                    }
3147                    let shared_started = profile.enabled.then(Instant::now);
3148                    let follows_shared = branch_follows_shared_boundary(
3149                        &run,
3150                        first,
3151                        second,
3152                        &builder.edges,
3153                        options.tolerance,
3154                        builder.scale,
3155                    )?;
3156                    if let Some(started) = shared_started {
3157                        profile.shared_boundary += started.elapsed();
3158                    }
3159                    if follows_shared {
3160                        if debug_pairs {
3161                            eprintln!(
3162                                "pair {}x{}: run dropped (follows shared boundary)",
3163                                first.face.id, second.face.id
3164                            );
3165                        }
3166                        continue;
3167                    }
3168                    if let Some(census) = pair_census.as_mut() {
3169                        census.record_stations(&run);
3170                    }
3171                    let pieces_before = builder.pieces.len();
3172                    let chunk_points = options.fit_chunk_points.unwrap_or(run.len()).max(2);
3173                    let mut start = 0;
3174                    while start + 1 < run.len() {
3175                        let end = (start + chunk_points - 1).min(run.len() - 1);
3176                        // HERMITE EMISSION (`imprint/hermite.rs`): with the lane on
3177                        // and every span of this run within the budget, the section
3178                        // is the march's own cubic Hermite with its two parameter
3179                        // Hermites, and the fit lane below is skipped.
3180                        let hermite_started = profile.enabled.then(Instant::now);
3181                        let hermite: Option<Result<super::hermite::HermiteSection, super::hermite::HermiteDecline>> = if pair_hermite_lane && end + 1 - start >= hermite_min_stations {
3182                            Some(match emission_budget {
3183                                Some(budget) => super::hermite::hermite_section(&run[start..=end], &branch, first_march, second_march, budget)
3184                                    .or_refuse(KernelStage::Intersect, "csg.imprint.driver.hermite")?,
3185                                None => Err(super::hermite::HermiteDecline::NoTangents),
3186                            })
3187                        } else {
3188                            None
3189                        };
3190                        if let Some(started) = hermite_started {
3191                            profile.hermite += started.elapsed();
3192                        }
3193                        let (section_curve, exact_pcurves) = match hermite {
3194                            Some(Ok(emitted)) => {
3195                                super::work_profile::add(|c| { c.carried_uv_curves += 2; c.carried_uv_stations += 2 * emitted.stations as u64; });
3196                                profile.hermite_runs += 1;
3197                                span_census(|| {
3198                                    format!(
3199                                        "pair {}x{} budget {} branch_stations {} run_stations {} kept {} span_deviation {:.3e} tangents true route None met_requested true lane hermite inserted {}",
3200                                        first.face.id,
3201                                        second.face.id,
3202                                        march_span_budget.map_or("none".to_string(), |budget| format!("{budget:.3e}")),
3203                                        branch.points.len(),
3204                                        emitted.stations,
3205                                        emitted.stations,
3206                                        emitted.deviation,
3207                                        emitted.inserted,
3208                                    )
3209                                });
3210                                (emitted.curve, Some([emitted.pcurve_a, emitted.pcurve_b]))
3211                            }
3212                            other => {
3213                        let hermite_decline = other.map(|lane| lane.err());
3214                        profile.fit_runs += 1;
3215                        let fit_started = profile.enabled.then(Instant::now);
3216                        let fit_tolerance = options.tolerance.max(1e-7);
3217                        let (mut section, mut fit, recovered, evening) = even_sliver_ends_measured(
3218                            run[start..=end].to_vec(),
3219                            &first.face.surface,
3220                            &second.face.surface,
3221                            options.tolerance,
3222                            fit_tolerance,
3223                            options.maximum_fit_points,
3224                            options.local_fit,
3225                        )
3226                        .or_refuse(KernelStage::Intersect, "csg.imprint.driver.sliver_end")?;
3227                        if evening != SliverEvening::NoSliver {
3228                            if let Ok(path) = std::env::var("BREP_SECTION_SLIVER_CENSUS") {
3229                                use std::io::Write;
3230                                if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
3231                                    let _ = writeln!(file, "sliver-end census: pair {}x{} {evening:?} stations {}", first.face.id, second.face.id, section.len());
3232                                }
3233                            }
3234                        }
3235                        // A recovered fit may reproduce every march point yet
3236                        // still wander off the carriers between sparse stations.
3237                        // Measure it against both supports before accepting that
3238                        // recovery, and use the existing bounded SSI refiner.
3239                        let met_requested = fit.report.met_requested_tolerance();
3240                        let refine_route = section_refine_route(
3241                            section_refine_gate(),
3242                            recovered,
3243                            || {
3244                                paired_grazing_crossings
3245                                    && std::env::var("BREP_GRAZE_SECTION_REFINE").as_deref() != Ok("0")
3246                            },
3247                            met_requested,
3248                        )
3249                        .or_else(|| {
3250                            // `BREP_SECTION_CARRIER_MISS=0` restores the fast path
3251                            // for an attribution A/B only (default on).
3252                            if std::env::var("BREP_SECTION_CARRIER_MISS").as_deref() == Ok("0") {
3253                                return None;
3254                            }
3255                            let (station_upper, midspan_upper) =
3256                                fit_split_timed(FitSplitLane::CarrierReadings, || fast_path_carrier_readings(&fit, &section, &first.face.surface, &second.face.surface));
3257                            carrier_miss_route(station_upper, midspan_upper, fit_tolerance)
3258                        });
3259                        let mut refine_unconverged = false;
3260                        let mut refine_worst = 0.0f64;
3261                        if let Some((gate, route)) = refine_route {
3262                            let stations_before = fit.kept.len();
3263                            let refine_census = std::env::var("BREP_SECTION_REFINE_CENSUS").ok();
3264                            let (census_head, census_tail) = (section[0], section[section.len() - 1]);
3265                            let refine_started = refine_census.is_some().then(Instant::now);
3266                            // The wrapper's own two lines, inlined so the receipt
3267                            // can be read (behaviour identical to
3268                            // `refine_section_against_carriers`).
3269                            let representatives = std::env::var("BREP_SECTION_REPRESENTATIVES").as_deref() != Ok("0");
3270                            let mut receipt = RefineReceipt::default();
3271                            let (refined, worst, unrefined, rounds, exit) = refine_section_against_carriers_with(
3272                                &mut section,
3273                                fit,
3274                                &first.face.surface,
3275                                &second.face.surface,
3276                                fit_tolerance,
3277                                options.tolerance,
3278                                options.local_fit,
3279                                gate * fit_tolerance,
3280                                representatives,
3281                                &mut receipt,
3282                            ).or_refuse(KernelStage::Intersect, "csg.imprint.driver.midspan")?;
3283                            let _ = &receipt;
3284                            // `BREP_SECTION_REFINE_CENSUS=<file>`: one line per section,
3285                            // appended, so a corpus replay (whose children's stderr is
3286                            // captured) can be read for trip counts and growth.
3287                            // The route, whether the standing fit met its request, and
3288                            // the refiner's own wall time close the line, so a run can
3289                            // total the UNMET-REQUEST route's cost apart from the
3290                            // global gate's (which reads every section).
3291                            if let Some(path) = refine_census {
3292                                use std::io::Write;
3293                                if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
3294                                    let _ = writeln!(
3295                                        file,
3296                                        "section-refine census: pair {}x{} exit {:?} rounds {} stations {} -> {} unrefined {:.3e} worst {:.3e} route {:?} met_requested {} ms {:.3} head ({:.9}, {:.9}, {:.9}) tail ({:.9}, {:.9}, {:.9})",
3297                                        first.face.id, second.face.id, exit, rounds, stations_before, refined.kept.len(), unrefined, worst,
3298                                        route, met_requested, refine_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1e3),
3299                                        census_head.x, census_head.y, census_head.z, census_tail.x, census_tail.y, census_tail.z
3300                                    );
3301                                }
3302                            }
3303                            if debug_pairs && (rounds > 0 || !matches!(exit, MidspanExit::Converged | MidspanExit::BelowGate)) {
3304                                eprintln!(
3305                                    "pair {}x{}: mid-span refinement {:?} after {} round(s): {} stations, worst {:.3e}",
3306                                    first.face.id, second.face.id, exit, rounds, section.len(), worst
3307                                );
3308                            }
3309                            refine_unconverged = !matches!(exit, MidspanExit::Converged | MidspanExit::BelowGate);
3310                            refine_worst = worst;
3311                            fit = refined;
3312                        }
3313                        span_census(|| {
3314                            format!(
3315                                "pair {}x{} budget {} branch_stations {} run_stations {} kept {} span_deviation {} tangents {} route {:?} met_requested {} lane fit hermite {}",
3316                                first.face.id,
3317                                second.face.id,
3318                                march_span_budget.map_or("none".to_string(), |budget| format!("{budget:.3e}")),
3319                                branch.points.len(),
3320                                section.len(),
3321                                fit.kept.len(),
3322                                branch.span_deviation.map_or("none".to_string(), |deviation| format!("{deviation:.3e}")),
3323                                branch.tangents.is_some(),
3324                                refine_route.map(|(_, route)| route),
3325                                met_requested,
3326                                hermite_decline.map_or("off".to_string(), |decline| decline.map_or("none".to_string(), |decline| format!("{decline:?}"))),
3327                            )
3328                        });
3329                        // `BREP_SECTION_OVERSHOOT_CENSUS=<file>` (debug only; nothing
3330                        // reads it): EVERY section's final fit, on any route, is read
3331                        // against both carriers at its kept stations and at its
3332                        // mid-spans, so a fit that stands further off the carriers
3333                        // between its stations than at them (fixture 28 t217: 5.07e-4
3334                        // shipped against a 1.32e-4 worst station) is counted, not
3335                        // guessed. Projector distances are upper readings; the line
3336                        // says so by its field names.
3337                        {
3338                            if let Ok(path) = std::env::var("BREP_SECTION_OVERSHOOT_CENSUS") {
3339                                // An unreadable station makes the whole reading NaN
3340                                // (f64::max would silently drop it).
3341                                let read = |surface: &NurbsSurface, point: Vec3| {
3342                                    project_point_to_surface(surface, point).map_or(f64::NAN, |projection| projection.distance)
3343                                };
3344                                let mut station_worst = 0.0f64;
3345                                for point in &fit.kept {
3346                                    let (a, b) = (read(&first.face.surface, *point), read(&second.face.surface, *point));
3347                                    station_worst = if a.is_nan() || b.is_nan() || station_worst.is_nan() { f64::NAN } else { station_worst.max(a).max(b) };
3348                                }
3349                                let (run_worst, _) = fast_path_carrier_readings(&fit, &section, &first.face.surface, &second.face.surface);
3350                                let interior_worst = knot_interior_carrier_upper(&fit.curve, &first.face.surface, &second.face.surface);
3351                                let misses = midspan_misses_only(&fit, &first.face.surface, &second.face.surface).unwrap_or_default();
3352                                let (worst_span, midspan_worst) = misses
3353                                    .iter()
3354                                    .copied()
3355                                    .enumerate()
3356                                    .fold((usize::MAX, 0.0f64), |best, (span, miss)| if miss > best.1 { (span, miss) } else { best });
3357                                let line = format!(
3358                                    "section-overshoot census: pair {}x{} route {:?} kept {} spans_read {} station_upper {:.3e} midspan_upper {:.3e} worst_span {} fit_tolerance {:.1e} ratio {:.3} run {} run_upper {run_worst:.3e} knot_interior_upper {interior_worst:.3e} head ({:.9}, {:.9}, {:.9}) tail ({:.9}, {:.9}, {:.9})\n",
3359                                    first.face.id, second.face.id, refine_route.map(|(_, route)| route), fit.kept.len(), misses.len(), station_worst, midspan_worst,
3360                                    if worst_span == usize::MAX { -1 } else { worst_span as i64 }, fit_tolerance,
3361                                    midspan_worst / station_worst.max(fit_tolerance),
3362                                    section.len(),
3363                                    section[0].x, section[0].y, section[0].z,
3364                                    section[section.len() - 1].x, section[section.len() - 1].y, section[section.len() - 1].z
3365                                );
3366                                use std::io::Write;
3367                                if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
3368                                    let _ = file.write_all(line.as_bytes());
3369                                }
3370                            }
3371                        }
3372                        if let Some(started) = fit_started {
3373                            profile.fit += started.elapsed();
3374                        }
3375                        if let Some(census) = pair_census.as_mut() {
3376                            census.record_fit(&fit);
3377                        }
3378                        // HERMITE 3-D LANE (`BREP_SECTION_HERMITE_3D`, default on;
3379                        // `imprint/hermite.rs`): a fit the refiner left unconverged and
3380                        // still missing a carrier by more than [`HERMITE_3D_GROSS_MISS`]
3381                        // fit tolerances, or one standing further from its own polyline
3382                        // between stations than half the run's longest chord (ringing,
3383                        // not chord sag), is
3384                        // replaced by the C1 cubic through the march stations and their
3385                        // tangents, bisected onto true intersection points until every
3386                        // span holds the fit tolerance on both carriers. A run the lane
3387                        // cannot bring within that keeps the fit.
3388                        let mut lane_pcurves = None;
3389                        if super::hermite::hermite_3d_enabled() {
3390                            let longest = section.windows(2).map(|pair| pair[1].sub(pair[0]).length()).fold(0.0f64, f64::max);
3391                            let ringing = !(fit.report.between_stations <= 0.5 * longest);
3392                            let gross = refine_unconverged && !(refine_worst <= HERMITE_3D_GROSS_MISS * fit_tolerance);
3393                            if gross || ringing {
3394                                let emitted = super::hermite::hermite_section_3d(
3395                                    &run[start..=end],
3396                                    &branch,
3397                                    &first.face.surface,
3398                                    &second.face.surface,
3399                                    fit_tolerance,
3400                                )
3401                                .or_refuse(KernelStage::Intersect, "csg.imprint.driver.hermite_3d")?;
3402                                if debug_pairs {
3403                                    eprintln!(
3404                                        "pair {}x{}: hermite 3-D lane (gross {gross}, unconverged {refine_unconverged} worst {refine_worst:.3e}, ringing {ringing} between {:.3e} longest {longest:.3e}): {}",
3405                                        first.face.id,
3406                                        second.face.id,
3407                                        fit.report.between_stations,
3408                                        emitted.as_ref().map_or("declined".to_string(), |(curve, _)| format!("{} controls", curve.control_points.len()))
3409                                    );
3410                                }
3411                                // `BREP_HERMITE_3D_CENSUS=<file>`: one line per section the
3412                                // lane is asked to take, appended (debug only).
3413                                if let Ok(path) = std::env::var("BREP_HERMITE_3D_CENSUS") {
3414                                    use std::io::Write;
3415                                    if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
3416                                        let _ = writeln!(
3417                                            file,
3418                                            "hermite-3d census: label {} pair {}x{} gross {gross} ringing {ringing} worst {refine_worst:.3e} between {:.3e} -> {}",
3419                                            std::env::var("BREP_CENSUS_LABEL").unwrap_or_default(),
3420                                            first.face.id,
3421                                            second.face.id,
3422                                            fit.report.between_stations,
3423                                            emitted.as_ref().map_or("declined".to_string(), |(curve, _)| format!("{} controls", curve.control_points.len()))
3424                                        );
3425                                    }
3426                                }
3427                                if let Some((curve, pcurves)) = emitted {
3428                                    fit.curve = curve;
3429                                    lane_pcurves = Some(pcurves);
3430                                }
3431                            }
3432                        }
3433                        (fit.curve, lane_pcurves)
3434                            }
3435                        };
3436                        let process_started = profile.enabled.then(Instant::now);
3437                        builder.marched_section = true;
3438                        if exchanged_mode != crate::env_read::Mode::Off {
3439                            builder.exchanged_rides = exchanged_spans.clone();
3440                            builder.exchanged_rides_mode = exchanged_mode;
3441                        }
3442                        builder.process_curve(
3443                            section_curve,
3444                            first,
3445                            second,
3446                            &[first, second],
3447                            &[first, second],
3448                            true,
3449                            exact_pcurves,
3450                        )?;
3451                        builder.marched_section = false;
3452                        builder.exchanged_rides.clear();
3453                        builder.exchanged_rides_mode = crate::env_read::Mode::Off;
3454                        if let Some(started) = process_started {
3455                            profile.process += started.elapsed();
3456                        }
3457                        start = end;
3458                    }
3459                    for piece in &builder.pieces[pieces_before..] {
3460                        builder.marched_pieces.insert(piece.id);
3461                    }
3462                    if debug_pairs {
3463                        eprintln!(
3464                            "pair {}x{}: run -> {} pieces",
3465                            first.face.id,
3466                            second.face.id,
3467                            builder.pieces.len() - pieces_before
3468                        );
3469                    }
3470                }
3471            }
3472            profile.clip_and_fit += profile.lap(&mut lap_start);
3473        }
3474    }
3475    for (span, first, second, target) in deferred_boundary_spans {
3476        builder.process_curve(span, first, second, &[target], &[target], false, None)?;
3477    }
3478    let discover = switch!("BREP_PLANAR_SECTION_END_DISCOVERY", true);
3479    let check_discovery = switch!("BREP_PLANAR_SECTION_END_DISCOVERY_CHECK", false);
3480    if !open_carriers && (discover || check_discovery) {
3481        let all_faces: Vec<_> = first_faces.iter().chain(&second_faces).copied().collect();
3482        if discover {
3483            builder.replay_planar_sections(&all_faces, check_discovery)?;
3484        } else {
3485            let mut probe = builder.clone();
3486            if let Err(error) = probe.replay_planar_sections(&all_faces, true) {
3487                eprintln!("planar local discovery: replay refused: {error}");
3488            }
3489        }
3490    }
3491    if let Some(scope) = pairs_fits {
3492        profile.pairs_fits = scope.close().fits;
3493    }
3494    super::work_profile::faces(first_faces.iter().chain(&second_faces)
3495        .map(|face| (face.face, builder.by_face.contains_key(&face.key()))));
3496    profile.report();
3497    let hull_culls = super::builder::take_hull_culls();
3498    if profile.enabled && super::builder::hull_cull_enabled() {
3499        profile_line!("imprint.hull_culls edges={hull_culls}");
3500    }
3501    // The row counters are drained only when they are printed, so a test
3502    // reading them after a whole operation sees every call's count.
3503    if profile.enabled && super::builder::pierce_cull_enabled() {
3504        profile_line!("imprint.pierce_culls edges={}", super::builder::take_pierce_culls());
3505    }
3506    if profile.enabled {
3507        let overlap_hull_skips = super::sections::take_overlap_hull_skips();
3508        if overlap_hull_skips > 0 {
3509            profile_line!("imprint.overlap_hull_skips stations={overlap_hull_skips}");
3510        }
3511        let exchange_hull_skips = super::builder::take_exchange_hull_skips();
3512        if exchange_hull_skips > 0 {
3513            profile_line!("imprint.exchange_hull_skips answered={exchange_hull_skips}");
3514        }
3515    }
3516    // SELF-TOUCH SPLIT: a face whose loops touch at an edge interior (a hole
3517    // tangent to a fillet setback) gets a vertex minted at the touch on BOTH
3518    // edges, so the fragment arrangement's pinch resolution assembles — see
3519    // `imprint/self_touch.rs`. Escape hatch: BREP_SELF_TOUCH_SPLIT=0.
3520    let mut tail_lap: Option<Instant> = None;
3521    // Beside each stage's time, the pcurve fits it recorded (a nested
3522    // `PcurveFitScope` per stage, folded into the operation's ledger).
3523    let mut tail_fits: Option<crate::PcurveFitScope> = None;
3524    let mut tail_ms = Vec::<(&str, f64, u64)>::new();
3525    let lap = |name: &'static str,
3526                   started: &mut Option<Instant>,
3527                   fits: &mut Option<crate::PcurveFitScope>,
3528                   tail_ms: &mut Vec<(&str, f64, u64)>| {
3529        if profile.enabled {
3530            let now = Instant::now();
3531            let recorded = fits.take().map_or(0, |scope| scope.close().fits);
3532            if let Some(previous) = *started {
3533                tail_ms.push((name, (now - previous).as_secs_f64() * 1_000.0, recorded));
3534            }
3535            *started = Some(now);
3536            *fits = Some(crate::PcurveFitScope::open());
3537        }
3538    };
3539    lap("pairs", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3540    if std::env::var("BREP_SELF_TOUCH_SPLIT").as_deref() != Ok("0") {
3541        let scans_before = super::self_touch::touch_scans();
3542        let pairs_before = super::self_touch::pair_reads();
3543        builder.split_self_touching_loops(&first_faces, &face_edge_lists, &cached_subcurve)?;
3544        builder.split_self_touching_loops(&second_faces, &face_edge_lists, &cached_subcurve)?;
3545        if profile.enabled {
3546            let pairs = super::self_touch::pair_reads();
3547            profile_line!("imprint.self_touch faces={} scanned={} pairs_served={} pairs_read={}", first_faces.len() + second_faces.len(), super::self_touch::touch_scans() - scans_before, pairs[0] - pairs_before[0], pairs[1] - pairs_before[1]);
3548        }
3549    }
3550    // PIECE-ENDPOINT EXCHANGE post-pass: with every pair's process_curve
3551    // done, the piece set is final for the ridden-edge class — imprint each
3552    // open riding piece's junction endpoints onto the ridden edges (see the
3553    // method doc; hatch BREP_OVERLAP_PIECE_ENDPOINT_SPLIT=0).
3554    builder.exchange_piece_endpoint_junctions()?;
3555    // TANGENT-SECTION IMPRINT (`ImprintOptions::tangent_curve_imprint`), after
3556    // every pair: whether a run splits a face is read against the face's trim
3557    // AND the pieces the other pairs minted on it, so the runs are minted
3558    // once the piece set is complete (the through-bore's contact ends on the
3559    // bore's cap circles, which the box's top and bottom minted).
3560    for (index, run, first, second) in std::mem::take(&mut tangent_imprint_candidates) {
3561        let closed = tangent_sections[index].closed;
3562        tangent_sections[index].piece_ids = imprint_tangent_run(
3563            &mut builder,
3564            &run,
3565            closed,
3566            first,
3567            second,
3568            &face_edge_lists,
3569            options,
3570            std::env::var("BREP_DEBUG_PAIRS").is_ok(),
3571        )?;
3572    }
3573    // TANGENT-SECTION T-JUNCTIONS (`ImprintOptions::tangent_curve_imprint`):
3574    // an imprinted contact ends on operand edges, which `process_curve` split,
3575    // and on earlier SECTIONS of the same carrier, which nothing splits — the
3576    // through-bore's contact line ends on the two cap circles the box's top
3577    // and bottom minted on the bore. Split those pieces at the contact's end
3578    // vertices so both faces of each circle carry the vertex the bore's
3579    // arrangement needs there (see `split_pieces_at_tangent_ends`).
3580    if tangent_sections.iter().any(|section| !section.piece_ids.is_empty()) {
3581        split_pieces_at_tangent_ends(
3582            &mut builder,
3583            &tangent_sections,
3584            &first_faces,
3585            &second_faces,
3586            options,
3587            std::env::var("BREP_DEBUG_PAIRS").is_ok(),
3588        )?;
3589    }
3590    lap("self_touch", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3591    let mut edge_splits = builder
3592        .edge_splits
3593        .into_iter()
3594        .map(|((operand, edge_id), mut parameters)| {
3595            parameters.sort_by(f64::total_cmp);
3596            EdgeSplitRecord {
3597                operand,
3598                edge_id,
3599                parameters,
3600            }
3601        })
3602        .collect::<Vec<_>>();
3603    edge_splits.sort_by_key(|record| (record.operand, record.edge_id));
3604    let mut by_face = builder
3605        .by_face
3606        .into_iter()
3607        .map(|(face, piece_ids)| FaceImprints {
3608            operand: face.operand,
3609            face_id: face.face_id,
3610            piece_ids,
3611        })
3612        .collect::<Vec<_>>();
3613    by_face.sort_by_key(|record| (record.operand, record.face_id));
3614    let section_evidence = section_evidence || !builder.pieces.is_empty();
3615    let marched_pieces = std::mem::take(&mut builder.marched_pieces);
3616    let mut emitted_pcurves = std::mem::take(&mut builder.emitted_pcurves);
3617    let junction_evidence = JunctionEvidence {
3618        radii: std::mem::take(&mut builder.vertex_radii),
3619        sources: std::mem::take(&mut builder.vertex_sources),
3620    };
3621    // Published for the plain two-operand loop only: a self-imprint's pairs
3622    // are within one solid and say nothing about the other operand.
3623    let faces_in_unproved_pairs = self_pairs.is_none().then(|| {
3624        let mut faces: HashSet<FaceKey> = HashSet::default();
3625        for pair in &visited_pairs {
3626            if !proved_apart_pairs.contains(pair) {
3627                faces.insert(first_faces[pair.0].key());
3628                faces.insert(second_faces[pair.1].key());
3629            }
3630        }
3631        let mut faces = faces.into_iter().collect::<Vec<_>>();
3632        faces.sort_by_key(|key| (key.operand, key.face_id));
3633        faces
3634    });
3635    let mut result = ImprintResultRecord {
3636        faces_in_unproved_pairs,
3637        tangent_nodes,
3638        tangent_sections,
3639        vertices: builder.vertices,
3640        pieces: builder.pieces,
3641        by_face,
3642        edge_splits,
3643        barrier_edges: builder.barrier_edges.into_iter().collect(),
3644        section_evidence,
3645        cosurface_pairs,
3646        operand_sliver_regions: tail_feature_scale
3647            .operand_sliver_regions
3648            .iter()
3649            .map(|region| ([region.minimum.x, region.minimum.y, region.minimum.z], [region.maximum.x, region.maximum.y, region.maximum.z]))
3650            .collect(),
3651    };
3652    RESCUE_FIRINGS.with(|cell| cell.set((march_swap_rescues, clip_swap_rescues)));
3653    if profile.enabled {
3654        profile_line!("imprint.rescues march_swap={march_swap_rescues} clip_swap={clip_swap_rescues}");
3655    }
3656    // COINCIDENT-PIECE MERGE (and the generic one-circle-from-many-pairs
3657    // class): the SAME section curve can be minted by several pairs — a
3658    // cosurface boundary-edge copy (the cylinder cap ring lying ON the
3659    // inscribed sphere) AND the cap-plane's analytic section ring are one
3660    // circle minted twice, each carrying only its own pair's
3661    // supports/pcurves. Assembly then builds duplicate edges that cannot both
3662    // be two-use → one-use strands. Merge pieces whose curves coincide along
3663    // their whole span (bidirectional max deviation within the weld band):
3664    // keep the first, union the supports/pcurves/by_face registrations of the
3665    // rest into it. Escape hatch: BREP_COINCIDENT_PIECE_MERGE=0.
3666    lap("collect", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3667    if std::env::var("BREP_COINCIDENT_PIECE_MERGE").as_deref() != Ok("0") {
3668        let weld = assembler_weld(options.tolerance).max(options.tolerance * 10.0);
3669        // Two pieces that coincide along their WHOLE spans (deviation within
3670        // the weld both ways) also have matching end points, up to direction
3671        // and a weld or two of overhang, so a piece whose ends are nowhere
3672        // near the other's needs no 33-station projection sweep. The sweep is
3673        // what made this pass quadratic in wall time: 630 pieces cost 3.2 s
3674        // of a 3.8 s imprint on the 2026-09-12 mesh-import report, all of it
3675        // rejecting pairs an end-point look already rules out.
3676        let mut ends: Vec<[Vec3; 2]> = Vec::with_capacity(result.pieces.len());
3677        for piece in &result.pieces {
3678            let [d0, d1] = piece.curve.domain().or_refuse(KernelStage::Intersect, "domain")?;
3679            ends.push([
3680                piece.curve.evaluate(d0).or_refuse(KernelStage::Intersect, "evaluate")?,
3681                piece.curve.evaluate(d1).or_refuse(KernelStage::Intersect, "evaluate")?,
3682            ]);
3683        }
3684        let end_band = 4.0 * weld;
3685        // CONTROL-HULL CULL (2026-10-10): the plate minus 36 cylinders mints 72
3686        // CLOSED rings, every one of which took the full sweep against every other —
3687        // 2 556 pairs, 230 of the imprint's 288 ms — although rings 16 units apart
3688        // cannot coincide. A NURBS curve lies in the convex hull of its control
3689        // points, so two curves within `weld` of each other along their whole spans
3690        // have control boxes that overlap once each is grown by `weld`; a pair whose
3691        // boxes do not is skipped before any projection. Exact, so the merged set is
3692        // the one the sweep alone found. `BREP_COINCIDENT_MERGE_BOX=0` restores the
3693        // unculled sweep for a before/after reading.
3694        let box_cull = std::env::var("BREP_COINCIDENT_MERGE_BOX").as_deref() != Ok("0");
3695        let mut boxes: Vec<[Vec3; 2]> = Vec::with_capacity(result.pieces.len());
3696        for piece in &result.pieces {
3697            boxes.push(control_hull_box(&piece.curve, weld));
3698        }
3699        // A CLOSED piece (a full ring) has no end points to speak of: two
3700        // rings of the same circle seamed at different azimuths coincide
3701        // along their whole spans while their domain ends sit anywhere on
3702        // the ring, so a closed piece always takes the full sweep.
3703        let ends_match = |a: &[Vec3; 2], b: &[Vec3; 2]| -> bool {
3704            let near = |p: Vec3, q: Vec3| p.sub(q).length() <= end_band;
3705            near(a[0], a[1])
3706                || near(b[0], b[1])
3707                || (near(a[0], b[0]) && near(a[1], b[1]))
3708                || (near(a[0], b[1]) && near(a[1], b[0]))
3709        };
3710        let mut removed: Vec<u64> = Vec::new();
3711        let mut index = 0;
3712        while index < result.pieces.len() {
3713            let mut other = index + 1;
3714            while other < result.pieces.len() {
3715                let coincide = (!box_cull || boxes_overlap(&boxes[index], &boxes[other]))
3716                    && ends_match(&ends[index], &ends[other])
3717                    && {
3718                        let a = &result.pieces[index];
3719                        let b = &result.pieces[other];
3720                        // FEATURE SCALE B2 (`BREP_FEATURE_SCALE_IMPRINT`):
3721                        // the weld (1e-6) equals the hairline slot's width,
3722                        // so the two walls' pieces read as one; beside a
3723                        // feature the weld is capped at a quarter of it.
3724                        let weld = if tail_feature_scale.is_empty() {
3725                            weld
3726                        } else {
3727                            tail_feature_scale.cap(ends[index][0], weld).min(tail_feature_scale.cap(ends[index][1], weld))
3728                        };
3729                        !distinct_exact_circles(&a.curve, &b.curve)?
3730                            && max_curve_deviation(&a.curve, &b.curve)? <= weld
3731                            && max_curve_deviation(&b.curve, &a.curve)? <= weld
3732                    };
3733                if coincide {
3734                    let absorbed = result.pieces.remove(other);
3735                    ends.remove(other);
3736                    boxes.remove(other);
3737                    removed.push(absorbed.id);
3738                    let keeper = &mut result.pieces[index];
3739                    for pcurve in absorbed.pcurves {
3740                        if !keeper
3741                            .pcurves
3742                            .iter()
3743                            .any(|existing| {
3744                                existing.operand == pcurve.operand
3745                                    && existing.face_id == pcurve.face_id
3746                            })
3747                        {
3748                            let key = FaceKey { operand: pcurve.operand, face_id: pcurve.face_id };
3749                            if emitted_pcurves.remove(&(absorbed.id, key)) {
3750                                emitted_pcurves.insert((keeper.id, key));
3751                            }
3752                            keeper.pcurves.push(pcurve);
3753                        }
3754                    }
3755                    let keeper_id = keeper.id;
3756                    for record in &mut result.by_face {
3757                        if let Some(position) =
3758                            record.piece_ids.iter().position(|&id| id == absorbed.id)
3759                        {
3760                            if record.piece_ids.contains(&keeper_id) {
3761                                record.piece_ids.remove(position);
3762                            } else {
3763                                record.piece_ids[position] = keeper_id;
3764                            }
3765                        }
3766                    }
3767                } else {
3768                    other += 1;
3769                }
3770            }
3771            index += 1;
3772        }
3773        if !removed.is_empty() && std::env::var("BREP_DEBUG_BOOL").is_ok() {
3774            eprintln!("coincident-piece merge: absorbed {:?}", removed);
3775        }
3776    }
3777    // Rescue near-tangent SSI truncations BEFORE canonicalization so the added
3778    // bridge pieces' endpoints (existing crossing/stub vertices) fold into the
3779    // same junction merges as every other section.
3780    lap("coincident_merge", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3781
3782    extend_truncated_sections(
3783        &mut result,
3784        &face_edge_lists,
3785        solid_a,
3786        solid_b,
3787        &charts,
3788        options.tolerance,
3789    )?;
3790    lap("extend_truncated", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3791
3792    canonicalize_imprint_junctions(
3793        &mut result,
3794        solid_a,
3795        solid_b,
3796        &charts,
3797        options.tolerance,
3798        &emitted_pcurves,
3799        &junction_evidence,
3800        junction_combine_mode(options),
3801        &tail_feature_scale,
3802        // The composite one-call carrier imprint keeps the per-pair contract:
3803        // no residual-evidence vertex merge across its admitted pairs (see
3804        // the parameter doc on `canonicalize_imprint_junctions`).
3805        self_pairs.is_none(),
3806    )?;
3807    lap("canonicalize", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3808
3809    // ONE RIM, ONE EDGE: with vertex identity final, dissolve the section
3810    // vertices that no operand edge passes through — the marcher's own
3811    // parameterization origin, which `process_curve` cannot tell from a
3812    // junction because it sees one pair at a time. See the method doc.
3813    let dissolved = dissolve_section_origin_vertices(
3814        &mut result,
3815        &marched_pieces,
3816        solid_a,
3817        solid_b,
3818        &charts,
3819        options.tolerance,
3820    )?;
3821    if dissolved > 0 && std::env::var("BREP_DEBUG_BOOL").is_ok() {
3822        eprintln!("origin-dissolve: {dissolved} parameterization vertex/vertices removed");
3823    }
3824    lap("origin_dissolve", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3825    // B2: reuse an existing boundary edge as the shared section edge wherever a
3826    // section coincides with one along its whole span (vertices are final after
3827    // canonicalization; `face_edge_lists` holds each face's boundary edges on
3828    // the healed operands). Runs here so both operands reference ONE edge.
3829    reuse_boundary_section_edges(
3830        &mut result,
3831        &face_edge_lists,
3832        solid_a,
3833        solid_b,
3834        options.tolerance,
3835    )?;
3836    // Capstone step 1 — instrumentation only, zero behavior change: report
3837    // every (section piece × boundary edge) contact where the piece runs
3838    // within the scale-derived band of the edge over a real span. Measuring
3839    // the bands here first validates the graze-contact model on the
3840    // acceptance suite before step 2's common-block machinery replaces a
3841    // grazed overlap with a shared edge.
3842    lap("reuse_boundary", &mut tail_lap, &mut tail_fits, &mut tail_ms);
3843    report_graze_contacts(&result, &face_edge_lists, solid_a, solid_b, options.tolerance)?;
3844    if profile.enabled {
3845        if let Some(scope) = tail_fits.take() {
3846            scope.close();
3847        }
3848        let line = tail_ms
3849            .iter()
3850            .map(|(name, ms, _)| format!("{name}={ms:.2}"))
3851            .collect::<Vec<_>>()
3852            .join(" ");
3853        profile_line!("imprint.stages {line}");
3854        let split = imprint_split_take();
3855        let ms = |d: Duration| d.as_secs_f64() * 1_000.0;
3856        profile_line!(
3857            "imprint.split pierce={:.3} pierce_edges={} overlap={:.3} overlap_edges={} crossing={:.3} crossing_edges={} recover={:.3} recover_pierces={} lies_whole={:.3} lies_whole_calls={} lies_whole_hits={} lies_span={:.3} lies_span_calls={} reuse_edges={}",
3858            ms(split.pierce), split.pierce_edges, ms(split.overlap), split.overlap_edges, ms(split.crossing), split.crossing_edges,
3859            ms(split.recover), split.recover_pierces, ms(split.lies_whole), split.lies_whole_calls, split.lies_whole_hits,
3860            ms(split.lies_span), split.lies_span_calls, split.reuse_edges,
3861        );
3862        let fits = tail_ms
3863            .iter()
3864            .map(|(name, _, fits)| format!("{name}={fits}"))
3865            .collect::<Vec<_>>()
3866            .join(" ");
3867        profile_line!("imprint.stage_fits {fits}");
3868    }
3869    if let Ok(path) = std::env::var("BREP_IMPRINT_SECTION_CENSUS") {
3870        use std::io::Write;
3871        // A private observation of the complete imprint, including section
3872        // curves, pcurves and junctions. Canonicalize only the set-valued
3873        // barrier list on a COPY; leave every returned record untouched.
3874        let mut observed = result.clone();
3875        observed.barrier_edges.sort_unstable();
3876        let bytes = serde_json::to_vec(&observed).expect("serialize imprint census");
3877        let digest = bytes.iter().fold(0xcbf29ce484222325_u64,
3878            |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3));
3879        let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path)
3880            .expect("open imprint section census");
3881        writeln!(file, "imprint.sections digest={digest:016x} bytes={} pieces={} vertices={}",
3882            bytes.len(), observed.pieces.len(), observed.vertices.len()).expect("append imprint section census");
3883    }
3884    Ok(result)
3885}
3886
3887/// Debug-only graze-contact survey (`BREP_DEBUG_GRAZE=1`): for each section
3888/// piece and each boundary edge of its support faces, sample the piece and
3889/// measure distance to the edge; report contacts whose in-band span exceeds
3890/// both the weld scale and 4× the minimum deviation (span-wise proximity, not
3891/// a point touch). `band_cap` reuses the residual-merge `sep_cap` ceiling —
3892/// measured, never grown. The output is the raw material for capstone step 2
3893/// (partial-span common-block): which contacts exist, their spans, and their
3894/// measured bands.
3895fn report_graze_contacts(
3896    result: &ImprintResultRecord,
3897    face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
3898    solid_a: &BrepSolid,
3899    solid_b: &BrepSolid,
3900    tolerance: f64,
3901) -> Result<(), KernelRefusal> {
3902    if std::env::var("BREP_DEBUG_GRAZE").as_deref() != Ok("1") {
3903        return Ok(());
3904    }
3905    let raw_extent = raw_solid_extent(solid_a).max(raw_solid_extent(solid_b));
3906    let (_, band_cap) = residual_merge_bands(raw_extent, tolerance);
3907    const SAMPLES: usize = 17;
3908    for piece in &result.pieces {
3909        let [t0, t1] = [piece.t0, piece.t1];
3910        if !(t1 > t0) {
3911            continue;
3912        }
3913        for key in piece.support_faces {
3914            let Some(edges) = face_edge_lists.get(&key) else {
3915                continue;
3916            };
3917            for edge in edges {
3918                if edge.degenerate {
3919                    continue;
3920                }
3921                let mut in_band = 0usize;
3922                let mut min_dev = f64::INFINITY;
3923                let mut max_dev_in_band = 0.0f64;
3924                let mut span = 0.0f64;
3925                let mut prev: Option<(bool, Vec3)> = None;
3926                for k in 0..SAMPLES {
3927                    let t = t0 + (t1 - t0) * k as f64 / (SAMPLES - 1) as f64;
3928                    let point = piece.curve.evaluate(t).or_refuse(KernelStage::Intersect, "evaluate")?;
3929                    let deviation = project_point_to_curve(&edge.curve, point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?.distance;
3930                    min_dev = min_dev.min(deviation);
3931                    let inside = deviation <= band_cap;
3932                    if inside {
3933                        in_band += 1;
3934                        max_dev_in_band = max_dev_in_band.max(deviation);
3935                        if let Some((true, prev_point)) = prev {
3936                            span += point.sub(prev_point).length();
3937                        }
3938                    }
3939                    prev = Some((inside, point));
3940                }
3941                // Span-wise contact: several consecutive samples in band and a
3942                // span that dwarfs the closest-approach (not a transversal
3943                // crossing, which dips in and out at one sample).
3944                if in_band >= 3 && span > (4.0 * min_dev).max(assembler_weld(tolerance)) {
3945                    eprintln!(
3946                        "graze: piece {} sup=[{}:{},{}:{}] ~ edge {}:{} span={:.3e} band=[{:.3e},{:.3e}] samples_in_band={}/{}",
3947                        piece.id,
3948                        piece.support_faces[0].operand,
3949                        piece.support_faces[0].face_id,
3950                        piece.support_faces[1].operand,
3951                        piece.support_faces[1].face_id,
3952                        key.operand,
3953                        edge.id,
3954                        span,
3955                        min_dev,
3956                        max_dev_in_band,
3957                        in_band,
3958                        SAMPLES
3959                    );
3960                }
3961            }
3962        }
3963    }
3964    Ok(())
3965}
3966
3967/// `BREP_RIM_BRIDGE` (default on, `=0` off): see RIM BRIDGE in the pair loop.
3968fn rim_bridge_enabled() -> bool {
3969    crate::switch!("BREP_RIM_BRIDGE", true)
3970}
3971
3972/// The rim pierces of a tangential-only pair, bridged (see RIM BRIDGE in the
3973/// pair loop): every edge of each face that CROSSES the other carrier at a
3974/// grazing angle (`|tan·n|` under the seed gate) inside both trims, and for
3975/// each pierce of the first operand whose nearest pierce of the second is
3976/// mutually nearest, farther apart than the assembler weld and within
3977/// `4 tol / |tan·n|` (capped at 1e-3), the segment between them is imprinted.
3978#[allow(clippy::too_many_arguments)]
3979fn rim_bridge(
3980    builder: &mut ImprintBuilder<'_>,
3981    first: TaggedFace<'_>,
3982    second: TaggedFace<'_>,
3983    first_march: &NurbsSurface,
3984    second_march: &NurbsSurface,
3985    face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
3986    options: &ImprintOptions,
3987    debug_pairs: bool,
3988) -> Result<(), KernelRefusal> {
3989    let mut pierces: [Vec<(Vec3, f64)>; 2] = [Vec::new(), Vec::new()];
3990    for (side, (face, other, other_march)) in [(first, second, second_march), (second, first, first_march)].into_iter().enumerate() {
3991        let edges = &face_edge_lists[&face.key()];
3992        for edge in edges {
3993            if edge.degenerate {
3994                continue;
3995            }
3996            // An edge lying ON the other carrier (the rims along the join the
3997            // pair is tangent across) reads a grazing hit per sample and
3998            // crosses nowhere: skip its solve, as the seed loop does.
3999            if super::support::curve_lies_on_surface(&edge_subcurve(edge)?, other_march, options.tolerance)? {
4000                continue;
4001            }
4002            for hit in intersect_curve_surface(&edge.curve, other_march, options.tolerance).or_refuse(KernelStage::Intersect, "intersect_curve_surface")? {
4003                if hit.t <= edge.t0 || hit.t >= edge.t1 {
4004                    continue;
4005                }
4006                let Ok(tangent) = edge.curve.derivatives(hit.t, 1).or_refuse(KernelStage::Intersect, "derivatives")?[1].normalized() else {
4007                    continue;
4008                };
4009                let Ok(normal) = other.chart().normal(hit.u, hit.v) else {
4010                    continue;
4011                };
4012                let tangency = tangent.dot(normal).abs();
4013                if !(tangency > 0.0 && tangency < 0.1) {
4014                    continue;
4015                }
4016                if !edge_crosses_carrier(edge, edges, hit.t, other_march, options.tolerance)? {
4017                    continue;
4018                }
4019                if !inside_both_trims(hit.point, first, second)? {
4020                    continue;
4021                }
4022                pierces[side].push((hit.point, tangency));
4023            }
4024        }
4025    }
4026    let nearest = |point: Vec3, among: &[(Vec3, f64)]| -> Option<(Vec3, f64)> {
4027        among.iter().copied().min_by(|a, b| a.0.sub(point).length().total_cmp(&b.0.sub(point).length()))
4028    };
4029    let weld = assembler_weld(options.tolerance);
4030    for &(from, from_tangency) in &pierces[0] {
4031        let Some((to, to_tangency)) = nearest(from, &pierces[1]) else {
4032            continue;
4033        };
4034        let mutual = nearest(to, &pierces[0]).is_some_and(|(back, _)| back.sub(from).length() <= options.tolerance);
4035        let gap = from.sub(to).length();
4036        let reach = (4.0 * options.tolerance / from_tangency.min(to_tangency)).min(1e-3);
4037        if debug_pairs {
4038            eprintln!(
4039                "pair {}x{}: rim bridge candidate ({:.7},{:.7},{:.7}) -> ({:.7},{:.7},{:.7}) gap {gap:.3e} reach {reach:.3e} mutual {mutual}",
4040                first.face.id, second.face.id, from.x, from.y, from.z, to.x, to.y, to.z
4041            );
4042        }
4043        if !mutual || gap <= weld || gap > reach {
4044            continue;
4045        }
4046        let segment = crate::make_line(from, to).or_refuse(KernelStage::Intersect, "make_line")?;
4047        builder.process_curve(segment, first, second, &[first, second], &[first, second], true, None)?;
4048    }
4049    Ok(())
4050}
4051
4052/// `BREP_PIERCE_NEAR_END_STEP` (default on, `=0` off): [`edge_crosses_carrier`] reads
4053/// a hit within its step of an open edge's end with the step shortened to it.
4054fn pierce_near_end_step_enabled() -> bool {
4055    crate::switch!("BREP_PIERCE_NEAR_END_STEP", true)
4056}
4057
4058/// Does `edge` CROSS `carrier` at parameter `t` — leave one side of the
4059/// surface for the other — rather than touch it or lie on it? Read from the
4060/// signed distance of the edge to the carrier a step either side of `t`
4061/// (one hundredth of the edge's live window): a crossing changes sign with
4062/// both readings clear of the tolerance; a lies-on edge reads zero on both
4063/// sides and a kiss reads one sign on both. A hit at the edge's end has no
4064/// far side and is not a crossing, UNLESS the face's boundary continues the
4065/// same curve there: `siblings` are the face's edges, and one that carries
4066/// this edge's curve bit for bit over the adjoining parameter window is the
4067/// other half of an edge a vertex was put on (`apply_edge_splits` keeps the
4068/// parent curve and narrows the window). The live window is then the whole
4069/// chain's, so the step and both readings are the ones the unsplit edge
4070/// gave. Fixture 31's union on its own split operands: pad edge 2 pierces
4071/// the model's blend at 0.0525 rad inside both trims, the imprint had put a
4072/// vertex at that very pierce, both halves then read "at the end", the
4073/// sub-gate march never started and the section it imprints on the unsplit
4074/// operands was missing (4 open edges). The signed distance is read against the
4075/// carrier itself (projection), never against the tangent plane at the hit,
4076/// where a curve lying ON a curved carrier would read a same-signed sagitta
4077/// on both sides that outweighs a grazing crossing's first-order departure.
4078/// A CLOSED edge (a cap's rim circle) has no end: a hit within a step of its
4079/// seam reads its far side across the seam (the G1 elbow's arm cap pierces
4080/// the lower torus half at t = 0.0037 of its rim circle).
4081/// A grazing pierce of `edge` near one of its end vertices that is the vertex
4082/// touching `carrier`, not a crossing (`BREP_IMPRINT_NEAR_END_SNAP`): the end
4083/// lies on the carrier and the edge from the pierce to it stays within the
4084/// overlap floor of it, inside the tangency band where a touch reads as a dip
4085/// through the carrier and back (a sweep's top edge leaving a disk's rim at the
4086/// sweep's end corner pierced the tool's wall 1.5e-3 from the corner and set
4087/// off a march along the contact). The end must be a true vertex of an open
4088/// edge lying on the carrier, and the stretch is certified over its whole
4089/// length ([`super::support::span_hull_within_surface`]), not sampled.
4090fn pierce_is_end_contact(edge: &EdgeRecord, t: f64, point: Vec3, carrier: &NurbsSurface, tolerance: f64) -> Result<bool, KernelRefusal> {
4091    let floor = tolerance.max(1e-5);
4092    let reach = 256.0 * floor;
4093    let (start, end) = (
4094        edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Intersect, "evaluate")?,
4095        edge.curve.evaluate(edge.t1).or_refuse(KernelStage::Intersect, "evaluate")?,
4096    );
4097    // A closed edge's seam is no vertex the edge touches anything at.
4098    if edge.degenerate || start.sub(end).length() <= floor {
4099        return Ok(false);
4100    }
4101    for (parameter, end_point) in [(edge.t0, start), (edge.t1, end)] {
4102        if parameter == t || end_point.sub(point).length() > reach {
4103            continue;
4104        }
4105        // The end itself lies on the carrier, as the corner a touch is at does.
4106        let on = project_point_to_surface(carrier, end_point).or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
4107        if !(on.distance <= tolerance * 10.0) {
4108            continue;
4109        }
4110        let mut budget = super::support::hug_budget();
4111        if super::support::span_hull_within_surface(&edge.curve, t.min(parameter), t.max(parameter), carrier, floor, &mut budget)? {
4112            return Ok(true);
4113        }
4114    }
4115    Ok(false)
4116}
4117
4118fn edge_crosses_carrier(
4119    edge: &EdgeRecord,
4120    siblings: &[&EdgeRecord],
4121    t: f64,
4122    carrier: &NurbsSurface,
4123    tolerance: f64,
4124) -> Result<bool, KernelRefusal> {
4125    if !(edge.t1 - edge.t0 > 0.0) {
4126        return Ok(false);
4127    }
4128    let (t0, t1) = same_curve_chain_window(edge, siblings);
4129    let window = t1 - t0;
4130    let mut delta = window * 1e-2;
4131    // A hit inside the step of an open edge's end is read with the step
4132    // halved to the end (`BREP_PIERCE_NEAR_END_STEP`): the readings must still
4133    // clear the band either side, so a hit at the end vertex itself is no
4134    // crossing, while one a short real distance in from it is.
4135    if pierce_near_end_step_enabled() && t > t0 && t < t1 {
4136        let (start, end) = (
4137            edge.curve.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?,
4138            edge.curve.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?,
4139        );
4140        if start.sub(end).length() > tolerance {
4141            delta = delta.min(0.5 * (t - t0)).min(0.5 * (t1 - t));
4142        }
4143    }
4144    let (mut before, mut after) = (t - delta, t + delta);
4145    if before < t0 || after > t1 {
4146        let start = edge.curve.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?;
4147        let end = edge.curve.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?;
4148        if start.sub(end).length() > tolerance {
4149            return Ok(false);
4150        }
4151        if before < t0 {
4152            before += window;
4153        }
4154        if after > t1 {
4155            after -= window;
4156        }
4157    }
4158    let mut readings = [0.0f64; 2];
4159    for (slot, parameter) in [before, after].into_iter().enumerate() {
4160        let point = edge.curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
4161        let projection = project_point_to_surface(carrier, point).or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
4162        let normal = match carrier.normal(projection.u, projection.v) {
4163            Ok(normal) => normal,
4164            Err(_) => return Ok(false),
4165        };
4166        readings[slot] = point.sub(projection.point).dot(normal);
4167    }
4168    let clear = tolerance * 10.0;
4169    Ok(readings[0] * readings[1] < 0.0 && readings[0].abs() > clear && readings[1].abs() > clear)
4170}
4171
4172/// The parameter window of the chain of `siblings` that continue `edge`'s own
4173/// curve: edges with a bit-identical curve whose windows adjoin end to start.
4174/// `edge`'s own window when nothing continues it.
4175fn same_curve_chain_window(edge: &EdgeRecord, siblings: &[&EdgeRecord]) -> (f64, f64) {
4176    let same_curve = |other: &EdgeRecord| other.id != edge.id && !other.degenerate && same_curve_bits(&other.curve, &edge.curve);
4177    let halves: Vec<&&EdgeRecord> = siblings.iter().filter(|other| same_curve(other)).collect();
4178    let (mut t0, mut t1) = (edge.t0, edge.t1);
4179    for _ in 0..halves.len() {
4180        let mut grew = false;
4181        for other in &halves {
4182            if other.t1 == t0 && other.t0 < t0 {
4183                t0 = other.t0;
4184                grew = true;
4185            } else if other.t0 == t1 && other.t1 > t1 {
4186                t1 = other.t1;
4187                grew = true;
4188            }
4189        }
4190        if !grew {
4191            break;
4192        }
4193    }
4194    (t0, t1)
4195}
4196
4197/// `BREP_IMPRINT_LIES_ON_SEED_SKIP=0` runs the seed solve on an edge that lies
4198/// on the other carrier as before (see the seed loop); unset or anything else
4199/// skips it. Read once.
4200fn lies_on_seed_skip_enabled() -> bool {
4201    switch!("BREP_IMPRINT_LIES_ON_SEED_SKIP", true)
4202}
4203
4204/// TANGENT-RIM LANDING (hosted report 2026-10-17, "boolean fails": a box
4205/// with a bore, its top face revolved 25° about a top edge and subtracted).
4206///
4207/// The revolve turns the profile's hole into a torus whose start rim IS the
4208/// bore's top rim, so the bore cylinder and the torus are tangent along that
4209/// whole circle — a shared TRIM EDGE of both faces, not an interior contact —
4210/// and inside the trims they cross along two transverse branches that leave
4211/// the rim at the two points where the torus's revolution-direction curvature
4212/// vanishes against the cylinder's. The classifier admits those as isolated
4213/// nodes (`tangent_contact.rs`: a third-order cusp reads as a saddle at every
4214/// stopping rule) and the branch is marched — but the marcher's step direction
4215/// `n_a × n_b` collapses as it nears the node, so the trace STALLS a few 1e-5
4216/// short of the rim instead of running past the trim with its usual slack.
4217/// Measured: the run ends 6.95e-5 and 1.17e-4 below y = 20, which on the
4218/// cylinder's 30-tall chart is 2.3e-6 and 3.9e-6 — just over the arrangement's
4219/// 1.4e-6 band — so the cut never reaches the boundary, the cylinder face is
4220/// not split, and six edges stand one-use (the torus faces, whose pcurve is
4221/// clamped at the rim's domain wall, DID split there, which is the asymmetry
4222/// the one-use count reads). The exact `A − B` is a manifold solid (two
4223/// slivers of box material inside the torus tube pinching to a zero-dihedral
4224/// edge along the rim), so the refusal was wrong, not the model.
4225///
4226/// A transverse section cannot end strictly inside both trims; a run end that
4227/// stops within the on-boundary clearance (`polish_endpoint`'s band) of a trim
4228/// edge which lies on BOTH carriers at the foot of that stop has merely been
4229/// truncated, and the foot — on the edge, hence on both carriers exactly — is
4230/// where the exact section continues to. Land the end there and split the
4231/// edge at it, so the ordinary machinery (pcurve projection, the arrangement's
4232/// boundary split, the assembler's vertex weld) takes the junction from here.
4233/// Reach: pairs carrying an admitted tangent node (the only place the march
4234/// stalls short — elsewhere it overshoots the trim), a foot within
4235/// `1e-2·(1 + |foot|)` of that node, and an end not already on the edge. The
4236/// moved sample is the run's own last station, so the section polyline keeps
4237/// every marched point and the landing segment is at most the clearance long.
4238/// Returns the splits to register, one per edge sharing the landing point:
4239/// `(operand, edge id, parameter, from, to)`.
4240///
4241/// Without an admitted node (`node` is `None`: the pair was marched from
4242/// sub-gate pierces, or its branch simply ran into a tangency — the −10°
4243/// sibling of the revolve-into-bore report, a near-tangent pair with no node
4244/// admitted whose ordinary march stalled 4e-5 and 2.4e-4 short of its rim),
4245/// the certificate is the run end itself: it must sit where the carriers are
4246/// TANGENT (`|n_a × n_b|` under the seed gate), which is the only place a
4247/// march stalls short. With or without a node the reach is `1e-2 (1 +
4248/// |point|)`, and a gap beyond the plain clearance is earned sample by
4249/// sample: the straight landing segment must stay within the on-boundary
4250/// clearance of BOTH carriers at every sample — a section through a tangency
4251/// band is within tolerance of both carriers all the way to the rim, so a
4252/// segment that leaves either is not the missing stretch (the −20° sibling's
4253/// 7x6 end stops 3e-4 short, over the plain clearance of 2.1e-4). A gap
4254/// within the plain clearance lands exactly as before.
4255fn land_run_ends_on_tangent_rim(
4256    run: &mut [Vec3],
4257    node: Option<Vec3>,
4258    first: TaggedFace<'_>,
4259    second: TaggedFace<'_>,
4260    face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
4261    tolerance: f64,
4262) -> Result<Vec<(u8, u64, f64, Vec3, Vec3)>, KernelRefusal> {
4263    let mut landings = Vec::new();
4264    if run.len() < 2 || std::env::var("BREP_TANGENT_RIM_LANDING").as_deref() == Ok("0") {
4265        return Ok(landings);
4266    }
4267    for index in [0, run.len() - 1] {
4268        let point = run[index];
4269        let clearance = (tolerance * 100.0).max(1e-6) * (1.0 + point.length());
4270        // No node: the end must stand in the tangency band, and the reach
4271        // beyond the plain clearance is earned sample by sample below.
4272        let stalled = match node {
4273            Some(_) => true,
4274            None => pair_normals_parallel_at(first, second, point)?,
4275        };
4276        if !stalled {
4277            continue;
4278        }
4279        let reach = 1e-2 * (1.0 + point.length());
4280        // Every qualifying foot over both faces' trim edges; the nearest is
4281        // where the end lands, and every edge whose foot coincides with it
4282        // (the two operands' copies of the shared rim) is split there, so
4283        // neither side depends on its pcurve happening to clamp at a domain
4284        // wall for its vertex.
4285        let mut feet: Vec<(f64, u8, u64, f64, Vec3)> = Vec::new();
4286        for face in [first, second] {
4287            let Some(edges) = face_edge_lists.get(&face.key()) else {
4288                continue;
4289            };
4290            for edge in edges {
4291                if edge.degenerate {
4292                    continue;
4293                }
4294                let projection = project_point_to_curve(&edge.curve, point)
4295                    .or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
4296                let parameter = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
4297                let foot = edge.curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
4298                let gap = foot.sub(point).length();
4299                if gap <= tolerance || gap > reach {
4300                    continue;
4301                }
4302                if let Some(node) = node {
4303                    if foot.sub(node).length() > 1e-2 * (1.0 + foot.length()) {
4304                        continue;
4305                    }
4306                }
4307                if gap > clearance
4308                    && !landing_segment_within(&first.face.surface, &second.face.surface, point, foot, clearance)
4309                {
4310                    continue;
4311                }
4312                // The edge must ride BOTH carriers at the foot: that is what
4313                // makes the foot a point of the section.
4314                let on_both = [first, second].iter().all(|face| {
4315                    project_point_to_surface(&face.face.surface, foot)
4316                        .map(|projection| projection.distance <= clearance)
4317                        .unwrap_or(false)
4318                });
4319                if !on_both {
4320                    continue;
4321                }
4322                feet.push((gap, face.operand, edge.id, parameter, foot));
4323            }
4324        }
4325        let Some(&(_, _, _, _, landing)) = feet.iter().min_by(|a, b| a.0.total_cmp(&b.0)) else {
4326            continue;
4327        };
4328        for (_, operand, edge_id, parameter, foot) in feet {
4329            if foot.sub(landing).length() <= tolerance * 10.0 {
4330                landings.push((operand, edge_id, parameter, point, landing));
4331            }
4332        }
4333        run[index] = landing;
4334    }
4335    Ok(landings)
4336}
4337/// TANGENT-NODE LANDING (hosted report 2026-11-01, "Boolean fails": a NURBS
4338/// Solid BOX cage, 10³ with 8 segments and 3 rings, unioned with a radius-5
4339/// cylinder standing on `y = 0`).
4340///
4341/// Three collinear cage points per side make the body flat to second order at
4342/// each side midpoint, and the cylinder's bottom rim passes through all four:
4343/// the two carriers touch at four isolated higher-order NODES that lie ON a
4344/// trim edge. Two section branches leave each node, mutually tangent there
4345/// (`z = ±c·y^{3/2}` on the wall). The march cannot place a station near such
4346/// a node: across the contact the carriers separate only as `δ² κ / 2`, so at
4347/// the model tolerance a station is uncertain by `√(2·tol/κ)` along the rim
4348/// (`1e-3` here). Measured: the four arcs ended ON the rim but 1.4e-5..2e-4
4349/// along it from their nodes, so each node's two arrivals split the rim twice
4350/// and left `On` slivers between, and the arcs into the node on the cylinder's
4351/// seam wobbled ACROSS the seam at `y ≈ 1.3e-3` (the true branch touches the
4352/// seam only at the node), leaving seam-hugging slivers. Six open corners and
4353/// a torn shell; [`land_run_ends_on_tangent_rim`] does not reach it because
4354/// those ends are already on the edge — they stopped at the wrong place ALONG
4355/// it, not short of it.
4356///
4357/// So: a run end where the carriers are tangent is refined onto its contact
4358/// (`classify_tangent_contact`); when that contact is an isolated node within
4359/// the landing reach that lies on a trim edge of either face, the stations
4360/// inside the node's ambiguity radius `3·√(2·tol/κ)` are dropped — they carry
4361/// no position the march could resolve — and the end is the node itself,
4362/// provided the closing chord stays on both carriers
4363/// ([`landing_segment_within`]). Every edge through the node is split exactly
4364/// there, so both branches arriving at a node share one vertex. Returns the
4365/// splits as [`land_run_ends_on_tangent_rim`] does.
4366fn land_run_ends_on_tangent_node(
4367    run: &mut Vec<Vec3>,
4368    first: TaggedFace<'_>,
4369    second: TaggedFace<'_>,
4370    face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
4371    tolerance: f64,
4372) -> Result<Vec<(u8, u64, f64, Vec3, Vec3)>, KernelRefusal> {
4373    let mut landings = Vec::new();
4374    if run.len() < 2 || std::env::var("BREP_TANGENT_NODE_LANDING").as_deref() == Ok("0") {
4375        return Ok(landings);
4376    }
4377    for at_end in [false, true] {
4378        let end = if at_end { run[run.len() - 1] } else { run[0] };
4379        if !pair_normals_parallel_at(first, second, end)? {
4380            continue;
4381        }
4382        let reach = 1e-2 * (1.0 + end.length());
4383        let Some(contact) =
4384            classify_tangent_contact(&first.face.surface, &second.face.surface, end, tolerance)?
4385        else {
4386            continue;
4387        };
4388        let node = contact.point;
4389        if !contact.is_isolated_node() || node.sub(end).length() > reach || contact.curvature_scale <= 0.0 {
4390            continue;
4391        }
4392        let clearance = (tolerance * 100.0).max(1e-6) * (1.0 + node.length());
4393        // Every trim edge of either face the node lies on.
4394        let mut splits: Vec<(u8, u64, f64)> = Vec::new();
4395        for face in [first, second] {
4396            let Some(edges) = face_edge_lists.get(&face.key()) else {
4397                continue;
4398            };
4399            for edge in edges {
4400                if edge.degenerate {
4401                    continue;
4402                }
4403                let projection = project_point_to_curve(&edge.curve, node)
4404                    .or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
4405                let parameter = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
4406                let foot = edge.curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
4407                if foot.sub(node).length() <= tolerance * 10.0
4408                    && !splits.iter().any(|&(operand, id, _)| operand == face.operand && id == edge.id)
4409                {
4410                    splits.push((face.operand, edge.id, parameter));
4411                }
4412            }
4413        }
4414        if splits.is_empty() {
4415            continue;
4416        }
4417        // The ambiguity radius: the stations inside it are noise along the
4418        // contact and are dropped outright. Beyond it, keep dropping while
4419        // the closing chord to the node still rides both carriers to ten
4420        // times the tolerance: near the node the branch is TANGENT to the
4421        // contact direction (on the seam node, to the seam itself), so its
4422        // true offset from that direction grows only as `r^{3/2}` and a
4423        // station must be far enough out for that offset to dominate the
4424        // corrector's noise — or the fitted piece wobbles across the seam.
4425        let ambiguity = 3.0 * (2.0 * tolerance / contact.curvature_scale).sqrt();
4426        let tight = tolerance * 10.0;
4427        let mut kept: Vec<Vec3> = if at_end { run.clone() } else { run.iter().rev().copied().collect() };
4428        while kept.len() > 1 && kept[kept.len() - 1].sub(node).length() <= ambiguity {
4429            kept.pop();
4430        }
4431        let last = kept[kept.len() - 1];
4432        if last.sub(node).length() > reach
4433            || !landing_segment_within(&first.face.surface, &second.face.surface, last, node, clearance)
4434        {
4435            continue;
4436        }
4437        while kept.len() > 2 {
4438            let further = kept[kept.len() - 2];
4439            if further.sub(node).length() > reach
4440                || !landing_segment_within(&first.face.surface, &second.face.surface, further, node, tight)
4441            {
4442                break;
4443            }
4444            kept.pop();
4445        }
4446        kept.push(node);
4447        if !at_end {
4448            kept.reverse();
4449        }
4450        *run = kept;
4451        for (operand, edge_id, parameter) in splits {
4452            landings.push((operand, edge_id, parameter, end, node));
4453        }
4454    }
4455    Ok(landings)
4456}
4457
4458/// The widened landing's certificate: is the straight segment from the
4459/// stalled run end `from` to the foot `to` within `clearance` of BOTH
4460/// carriers at every interior sample?
4461///
4462/// Why this is a construction guarantee and not a reading: the foot is on a
4463/// trim edge that rides both carriers (checked by the caller), so it is a
4464/// point of the carriers' intersection set to within the clearance. The run
4465/// end is a marched station, on both carriers to the corrector's residual.
4466/// A segment whose every sample is within the clearance of both carriers is
4467/// a chord of the band where the two carriers are within tolerance of each
4468/// other — exactly the set a section through a tangency is confined to —
4469/// and the section polyline's last chord is held to the same deviation every
4470/// marched chord is. A segment that leaves either carrier mid-way (a chord
4471/// across a curved rim: its sagitta clears the clearance by orders) is NOT
4472/// the missing stretch, whatever its ends read, and is refused here.
4473fn landing_segment_within(
4474    first: &NurbsSurface,
4475    second: &NurbsSurface,
4476    from: Vec3,
4477    to: Vec3,
4478    clearance: f64,
4479) -> bool {
4480    const SAMPLES: usize = 8;
4481    (1..SAMPLES).all(|k| {
4482        let sample = from.add(to.sub(from).scale(k as f64 / SAMPLES as f64));
4483        [first, second].iter().all(|surface| {
4484            project_point_to_surface(surface, sample)
4485                .map(|projection| projection.distance <= clearance)
4486                .unwrap_or(false)
4487        })
4488    })
4489}
4490
4491/// Are the two carriers TANGENT (normals parallel) where they both pass through
4492/// `point`?
4493///
4494/// The test the tangential-only refusal above needs: a point on the marched
4495/// intersection is a TANGENT NODE when the two surface normals there are
4496/// parallel. The threshold is the transversality bound the supplemental
4497/// detector already accepts seeds by (`TRANSVERSE_SEED_CROSS`), not the far
4498/// tighter pair-classifier bound — a node the march merely passes CLOSE to
4499/// still poisons the assembly, so this errs toward calling a pair singular.
4500/// The tangent-curve lane's recognition of one pair: find the pair's
4501/// tangential contact without a witness, keep only an EXTENDED one (a node or
4502/// a point contact is the existing paths' business), and with one planar
4503/// carrier march it along the null direction of `II_a − II_b` and clip the
4504/// curve to both trims. `None` when there is no extended contact, or its trace
4505/// has no run inside both trims (a contact on the carriers' extensions
4506/// imprints nothing, exactly as today).
4507///
4508/// The section is RECORDED, not imprinted: a tangent edge whose two sides
4509/// both survive is a four-coedge incidence the assembler cannot represent
4510/// (the pinch gate in `csg/boolean/mod.rs` names the subtract case), and a
4511/// tangent edge only one side of which survives dissolves into its face.
4512/// What the record buys is the boolean's attribution: a refusal whose faces
4513/// the contact involves names the contact instead of the arrangement's own
4514/// symptom. The involved faces are the two carriers' and every face sharing
4515/// an edge a run end lies on (`TangentSectionRecord::faces`).
4516#[allow(clippy::too_many_arguments)]
4517fn tangent_curve_section(
4518    first: TaggedFace<'_>,
4519    second: TaggedFace<'_>,
4520    options: &ImprintOptions,
4521    first_faces: &[TaggedFace<'_>],
4522    second_faces: &[TaggedFace<'_>],
4523    face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
4524    debug_pairs: bool,
4525) -> Result<Option<(TangentSectionRecord, Vec<Vec3>)>, KernelRefusal> {
4526    let _clock = ImprintSubphaseClock::new("tangent_section");
4527    let Some(contact) =
4528        crate::find_tangent_contact(&first.face.surface, &second.face.surface, options.tolerance)
4529            .or_refuse(KernelStage::Intersect, "find_tangent_contact")?
4530    else {
4531        return Ok(None);
4532    };
4533    if debug_pairs {
4534        eprintln!(
4535            "pair {}x{}: tangent-curve lane contact {:?}",
4536            first.face.id, second.face.id, contact
4537        );
4538    }
4539    if !contact.is_extended() {
4540        return Ok(None);
4541    }
4542    let is_plane = |face: TaggedFace<'_>| {
4543        matches!(face.face.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. }))
4544    };
4545    let planar = is_plane(first) || is_plane(second);
4546    if !planar {
4547        // The curved/curved branch: recognised and named, not traced.
4548        return Ok(Some((
4549            TangentSectionRecord {
4550                first: first.key(),
4551                second: second.key(),
4552                start: contact.point,
4553                end: contact.point,
4554                length: 0.0,
4555                closed: false,
4556                stations: 0,
4557                planar: false,
4558                faces: vec![first.key(), second.key()],
4559                piece_ids: Vec::new(),
4560                grazing: Vec::new(),
4561            },
4562            Vec::new(),
4563        )));
4564    }
4565    let Some(curve) = crate::trace_tangent_curve(
4566        &first.face.surface,
4567        &second.face.surface,
4568        &contact,
4569        &SurfaceIntersectionOptions {
4570            tolerance: options.tolerance,
4571            maximum_step: options.maximum_ssi_step,
4572            ..Default::default()
4573        },
4574    )
4575    .or_refuse(KernelStage::Intersect, "trace_tangent_curve")?
4576    else {
4577        return Ok(None);
4578    };
4579    let mut longest: Option<Vec<Vec3>> = None;
4580    let mut longest_length = 0.0f64;
4581    for run in clip_branch_to_trims(&curve.points, first, second)? {
4582        if run.len() < 2 {
4583            continue;
4584        }
4585        let length: f64 = run.windows(2).map(|pair| pair[1].sub(pair[0]).length()).sum();
4586        if length > longest_length {
4587            longest_length = length;
4588            longest = Some(run);
4589        }
4590    }
4591    let Some(run) = longest else {
4592        return Ok(None);
4593    };
4594    if longest_length <= options.tolerance * 100.0 {
4595        return Ok(None);
4596    }
4597    if debug_pairs {
4598        eprintln!(
4599            "pair {}x{}: tangent-curve lane traced {} stations, run of {} inside both trims, length {:.6}, closed {}",
4600            first.face.id, second.face.id, curve.points.len(), run.len(), longest_length, curve.closed
4601        );
4602    }
4603    let closed = curve.closed && run.len() == curve.points.len();
4604    // The faces the contact involves: the carriers' own, and across every
4605    // edge of theirs that a run end lies on, the faces sharing that edge.
4606    let mut faces = vec![first.key(), second.key()];
4607    if !closed {
4608        let band = options.tolerance * 100.0;
4609        for end in [run[0], run[run.len() - 1]] {
4610            for face in [first, second] {
4611                let Some(edges) = face_edge_lists.get(&face.key()) else {
4612                    continue;
4613                };
4614                for edge in edges {
4615                    if edge.degenerate {
4616                        continue;
4617                    }
4618                    let Ok(projection) = project_point_to_curve(&edge.curve, end) else {
4619                        continue;
4620                    };
4621                    if projection.distance > band {
4622                        continue;
4623                    }
4624                    let siblings = if face.operand == first.operand { first_faces } else { second_faces };
4625                    for sibling in siblings {
4626                        let shares = sibling
4627                            .face
4628                            .loops
4629                            .iter()
4630                            .flat_map(|loop_record| &loop_record.coedges)
4631                            .any(|coedge| coedge.edge_id == edge.id);
4632                        if shares && !faces.contains(&sibling.key()) {
4633                            faces.push(sibling.key());
4634                        }
4635                    }
4636                }
4637            }
4638        }
4639    }
4640    if debug_pairs {
4641        eprintln!(
4642            "pair {}x{}: tangent-curve lane involves faces {:?}",
4643            first.face.id, second.face.id, faces
4644        );
4645    }
4646    Ok(Some((
4647        TangentSectionRecord {
4648            first: first.key(),
4649            second: second.key(),
4650            start: run[0],
4651            end: run[run.len() - 1],
4652            length: longest_length,
4653            closed,
4654            stations: run.len(),
4655            planar: true,
4656            faces,
4657            piece_ids: Vec::new(),
4658            grazing: Vec::new(),
4659        },
4660        run,
4661    )))
4662}
4663
4664/// Imprint a traced tangent run ([`ImprintOptions::tangent_curve_imprint`]):
4665/// the run's stations become a section curve — the exact line through its
4666/// ends when they are collinear (a plane's contact with a cylinder or cone is
4667/// a generatrix), the marched lane's polyline fit otherwise (a torus parallel)
4668/// — and `process_curve` mints it on both carriers exactly as it mints a
4669/// transverse section: pieces with pcurves on each face, the operand edges the
4670/// ends lie on split there. Returns the ids of the pieces minted, in order.
4671///
4672/// Only a run that SPLITS both faces is minted: a closed run, or one each of
4673/// whose ends lies, on each carrier, on that face's trim or on a section
4674/// piece already minted on it (the through-bore's contact ends on the wall's
4675/// top and bottom edges and, on the bore, on the circles the box's top and
4676/// bottom cut there). A run with an end inside a face — the blind pocket's
4677/// contact ends on the bore's cap rings but inside the wall, where both of
4678/// its sides are one face — would be a slit, and a slit is not a boundary:
4679/// measured with the slit minted, the wall's four edges came out one-use and
4680/// the pocket refused `NonIntegralGenus`. Such a contact stays recorded only,
4681/// as before.
4682#[allow(clippy::too_many_arguments)]
4683fn imprint_tangent_run(
4684    builder: &mut ImprintBuilder<'_>,
4685    run: &[Vec3],
4686    closed: bool,
4687    first: TaggedFace<'_>,
4688    second: TaggedFace<'_>,
4689    face_edge_lists: &HashMap<FaceKey, Vec<&EdgeRecord>>,
4690    options: &ImprintOptions,
4691    debug: bool,
4692) -> Result<Vec<u64>, KernelRefusal> {
4693    if run.len() < 2 {
4694        return Ok(Vec::new());
4695    }
4696    if !closed {
4697        let band = options.tolerance * 100.0;
4698        let within = |curve: &NurbsCurve, t0: f64, t1: f64, point: Vec3| -> bool {
4699            project_point_to_curve(curve, point)
4700                .map(|projection| {
4701                    projection.distance <= band
4702                        && projection.u >= t0.min(t1) - 1e-9
4703                        && projection.u <= t0.max(t1) + 1e-9
4704                })
4705                .unwrap_or(false)
4706        };
4707        let on_boundary = |face: TaggedFace<'_>, point: Vec3| -> bool {
4708            let on_trim = face_edge_lists
4709                .get(&face.key())
4710                .map(|edges| {
4711                    edges
4712                        .iter()
4713                        .any(|edge| !edge.degenerate && within(&edge.curve, edge.t0, edge.t1, point))
4714                })
4715                .unwrap_or(false);
4716            on_trim
4717                || builder
4718                    .pieces
4719                    .iter()
4720                    .any(|piece| piece.support_faces.contains(&face.key()) && within(&piece.curve, piece.t0, piece.t1, point))
4721        };
4722        let ends = [run[0], run[run.len() - 1]];
4723        for face in [first, second] {
4724            if !ends.iter().all(|end| on_boundary(face, *end)) {
4725                if debug {
4726                    eprintln!(
4727                        "pair {}x{}: tangent-curve lane run not imprinted: an end lies inside face {}:{}'s trim (a slit)",
4728                        first.face.id, second.face.id, face.operand, face.face.id
4729                    );
4730                }
4731                return Ok(Vec::new());
4732            }
4733        }
4734    }
4735    let start = run[0];
4736    let end = run[run.len() - 1];
4737    let chord = end.sub(start);
4738    let chord_length = chord.length();
4739    let fit_tolerance = options.tolerance.max(1e-7);
4740    let collinear = chord_length > fit_tolerance && {
4741        let direction = chord.scale(1.0 / chord_length);
4742        run.iter().all(|station| {
4743            let offset = station.sub(start);
4744            offset.sub(direction.scale(offset.dot(direction))).length() <= 10.0 * fit_tolerance
4745        })
4746    };
4747    let curve = if collinear {
4748        crate::make_line(start, end).or_refuse(KernelStage::Intersect, "make_line")?
4749    } else {
4750        fit_polyline_of_degree(
4751            run,
4752            fit_tolerance,
4753            run.len().min(MAX_FIT_STATIONS),
4754            options.local_fit,
4755            section_fit_degree(),
4756        )
4757        .or_refuse(KernelStage::Intersect, "fit_polyline_of_degree")?
4758        .curve
4759    };
4760    let before = builder.pieces.len();
4761    builder.process_curve(curve, first, second, &[first, second], &[first, second], true, None)?;
4762    let ids: Vec<u64> = builder.pieces[before..].iter().map(|piece| piece.id).collect();
4763    if debug {
4764        eprintln!(
4765            "pair {}x{}: tangent-curve lane imprinted the run as {} ({} piece(s) {:?})",
4766            first.face.id,
4767            second.face.id,
4768            if collinear { "a line" } else { "a fitted section" },
4769            ids.len(),
4770            ids
4771        );
4772    }
4773    Ok(ids)
4774}
4775
4776/// Split every piece an imprinted tangent section ENDS ON, at that end
4777/// (`ImprintOptions::tangent_curve_imprint`). A tangent run is clipped to both
4778/// trims, so its ends lie on operand edges — split by `process_curve` — or on
4779/// the trim of the OTHER carrier's neighbours, where they also lie on the
4780/// sections those neighbours minted on this carrier: the through-bore's
4781/// contact line ends on the circles the box's top and bottom cut on the bore,
4782/// at a point no edge pierce put a vertex on (the box edge grazes the bore
4783/// there, and a grazing pierce is deliberately not a junction). Without the
4784/// vertex, the bore's arrangement would split the circle where the line
4785/// meets it while the cap's arrangement keeps the circle whole — one closed
4786/// edge against two arcs, one-use at assembly. The piece is split here, at
4787/// the imprint, so every face it is minted on sees the vertex: the halves
4788/// take the tangent end's vertex id, the pcurves are split with the curve
4789/// where they were emitted on its knots and rebuilt on the face's chart
4790/// otherwise, and the piece's face lists and lane sets follow the halves. A
4791/// piece that resolves to an operand edge (`shared_edge`) is left as it is:
4792/// that edge's own split is the exchange pass's.
4793fn split_pieces_at_tangent_ends(
4794    builder: &mut ImprintBuilder<'_>,
4795    sections: &[TangentSectionRecord],
4796    first_faces: &[TaggedFace<'_>],
4797    second_faces: &[TaggedFace<'_>],
4798    options: &ImprintOptions,
4799    debug: bool,
4800) -> Result<(), KernelRefusal> {
4801    let tangent_ids: HashSet<u64> = sections.iter().flat_map(|section| section.piece_ids.iter().copied()).collect();
4802    if tangent_ids.is_empty() {
4803        return Ok(());
4804    }
4805    let overlap_limit = options.tolerance.max(1e-5);
4806    let vertex_points: HashMap<u64, Vec3> =
4807        builder.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
4808    // (end vertex, its point, the tangent piece's supports)
4809    let mut ends: Vec<(u64, Vec3, [FaceKey; 2])> = Vec::new();
4810    for piece in builder.pieces.iter().filter(|piece| tangent_ids.contains(&piece.id)) {
4811        for vertex_id in [piece.start_vertex_id, piece.end_vertex_id] {
4812            if let Some(point) = vertex_points.get(&vertex_id) {
4813                if !ends.iter().any(|(id, _, _)| *id == vertex_id) {
4814                    ends.push((vertex_id, *point, piece.support_faces));
4815                }
4816            }
4817        }
4818    }
4819    let face_of = |key: FaceKey| {
4820        first_faces
4821            .iter()
4822            .chain(second_faces)
4823            .copied()
4824            .find(|face| face.key() == key)
4825    };
4826    let mut index = 0;
4827    while index < builder.pieces.len() {
4828        let piece = &builder.pieces[index];
4829        if tangent_ids.contains(&piece.id) || piece.shared_edge.is_some() || !(piece.t1 > piece.t0) {
4830            index += 1;
4831            continue;
4832        }
4833        let mut split: Option<(u64, f64, Vec3)> = None;
4834        for (vertex_id, point, supports) in &ends {
4835            if *vertex_id == piece.start_vertex_id || *vertex_id == piece.end_vertex_id {
4836                continue;
4837            }
4838            if !supports.iter().any(|support| piece.support_faces.contains(support)) {
4839                continue;
4840            }
4841            let projection = project_point_to_curve(&piece.curve, *point)
4842                .or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
4843            if projection.distance > overlap_limit {
4844                continue;
4845            }
4846            let span = piece.t1 - piece.t0;
4847            let margin = (span * KNOT_IDENTITY_TOL).max(2e-9);
4848            if projection.u <= piece.t0 + margin || projection.u >= piece.t1 - margin {
4849                continue;
4850            }
4851            // Interior in PARAMETER but at an END in space: a closed piece's
4852            // origin seen from the far side of its domain.
4853            if projection.point.sub(vertex_points[&piece.start_vertex_id]).length() <= overlap_limit
4854                || projection.point.sub(vertex_points[&piece.end_vertex_id]).length() <= overlap_limit
4855            {
4856                continue;
4857            }
4858            split = Some((*vertex_id, projection.u, *point));
4859            break;
4860        }
4861        let Some((vertex_id, parameter, point)) = split else {
4862            index += 1;
4863            continue;
4864        };
4865        let piece = builder.pieces.remove(index);
4866        let (left, right) = piece.curve.split(parameter).or_refuse(KernelStage::Intersect, "split")?;
4867        let [left_t0, _] = left.domain().or_refuse(KernelStage::Intersect, "domain")?;
4868        let [_, right_t1] = right.domain().or_refuse(KernelStage::Intersect, "domain")?;
4869        let start_point = vertex_points[&piece.start_vertex_id];
4870        let end_point = vertex_points[&piece.end_vertex_id];
4871        let left = snap_curve_ends(&left, start_point, point)?;
4872        let right = snap_curve_ends(&right, point, end_point)?;
4873        let left_id = builder.next_id;
4874        let right_id = builder.next_id + 1;
4875        builder.next_id += 2;
4876        let mut left_pcurves = Vec::with_capacity(piece.pcurves.len());
4877        let mut right_pcurves = Vec::with_capacity(piece.pcurves.len());
4878        for face_pcurve in &piece.pcurves {
4879            let key = FaceKey { operand: face_pcurve.operand, face_id: face_pcurve.face_id };
4880            let emitted = builder.emitted_pcurves.remove(&(piece.id, key));
4881            let halves = if emitted {
4882                match face_pcurve.pcurve.split(parameter) {
4883                    Ok((a, b)) => {
4884                        builder.emitted_pcurves.insert((left_id, key));
4885                        builder.emitted_pcurves.insert((right_id, key));
4886                        Some((a, b))
4887                    }
4888                    Err(_) => None,
4889                }
4890            } else {
4891                None
4892            };
4893            let (a, b) = match halves {
4894                Some(halves) => halves,
4895                None => {
4896                    let Some(face) = face_of(key) else {
4897                        return Err(KernelRefusal::internal(
4898                            KernelStage::Intersect,
4899                            "imprint.tangent_split",
4900                            format!("tangent-section split: piece {} has a pcurve on an unknown face {key:?}", piece.id),
4901                        ));
4902                    };
4903                    (
4904                        build_pcurve_on_surface_marched(face.chart(), &left)
4905                            .or_refuse(KernelStage::Intersect, "build_pcurve_on_surface_marched")?,
4906                        build_pcurve_on_surface_marched(face.chart(), &right)
4907                            .or_refuse(KernelStage::Intersect, "build_pcurve_on_surface_marched")?,
4908                    )
4909                }
4910            };
4911            left_pcurves.push(FacePcurve { operand: key.operand, face_id: key.face_id, pcurve: a });
4912            right_pcurves.push(FacePcurve { operand: key.operand, face_id: key.face_id, pcurve: b });
4913        }
4914        if builder.marched_pieces.remove(&piece.id) {
4915            builder.marched_pieces.insert(left_id);
4916            builder.marched_pieces.insert(right_id);
4917        }
4918        for ids in builder.by_face.values_mut() {
4919            if let Some(slot) = ids.iter().position(|id| *id == piece.id) {
4920                ids[slot] = left_id;
4921                ids.insert(slot + 1, right_id);
4922            }
4923        }
4924        if debug {
4925            eprintln!(
4926                "tangent-curve lane: piece {} split at vertex {} (t={parameter:.6}) into pieces {left_id} and {right_id}",
4927                piece.id, vertex_id
4928            );
4929        }
4930        builder.pieces.insert(
4931            index,
4932            ImprintPieceRecord {
4933                id: left_id,
4934                curve: left,
4935                t0: left_t0,
4936                t1: parameter,
4937                start_vertex_id: piece.start_vertex_id,
4938                end_vertex_id: vertex_id,
4939                pcurves: left_pcurves,
4940                support_faces: piece.support_faces,
4941                shared_edge: None,
4942                certified_ruling_side: None,
4943            },
4944        );
4945        builder.pieces.insert(
4946            index + 1,
4947            ImprintPieceRecord {
4948                id: right_id,
4949                curve: right,
4950                t0: parameter,
4951                t1: right_t1,
4952                start_vertex_id: vertex_id,
4953                end_vertex_id: piece.end_vertex_id,
4954                pcurves: right_pcurves,
4955                support_faces: piece.support_faces,
4956                shared_edge: None,
4957                certified_ruling_side: None,
4958            },
4959        );
4960        // Re-examine the halves: a run may end on the same piece twice.
4961    }
4962    Ok(())
4963}
4964
4965/// Past the first tangency witness of `clipped` (judged by the caller), every
4966/// other stretch of the runs where the pair's normals are parallel is judged
4967/// once, at its first point: an isolated node or a tangency off its carrier
4968/// is admitted; anything else (an extended or an unproven contact) is not
4969/// (`BREP_IMPRINT_TANGENCY_OFF_CARRIER`).
4970fn every_other_tangency_admitted(
4971    first: TaggedFace<'_>,
4972    second: TaggedFace<'_>,
4973    clipped: &[Vec<Vec3>],
4974    tolerance: f64,
4975) -> Result<bool, KernelRefusal> {
4976    later_parallel_stretch_starts_all(
4977        clipped,
4978        |point| pair_normals_parallel_at(first, second, point),
4979        |point| {
4980            Ok(match classify_tangent_contact(&first.face.surface, &second.face.surface, point, tolerance)? {
4981                Some(contact) => contact.is_isolated_node(),
4982                None => super::tangent_contact::tangency_runs_off_carrier(&first.face.surface, &second.face.surface, point, tolerance)?,
4983            })
4984        },
4985    )
4986}
4987
4988/// Walk `runs` and hand `admit` the first point of every stretch of
4989/// consecutive `parallel` points past the first such stretch (the caller's
4990/// witness), in order, as each is found; `false` at the first one `admit`
4991/// rejects, before any later point is read (so a later point's failure never
4992/// takes precedence over an earlier verdict). A stretch ends where a point is
4993/// not parallel or its run ends.
4994pub(super) fn later_parallel_stretch_starts_all(
4995    runs: &[Vec<Vec3>],
4996    mut parallel: impl FnMut(Vec3) -> Result<bool, KernelRefusal>,
4997    mut admit: impl FnMut(Vec3) -> Result<bool, KernelRefusal>,
4998) -> Result<bool, KernelRefusal> {
4999    let mut first_stretch = true;
5000    for run in runs {
5001        let mut inside_stretch = false;
5002        for &point in run {
5003            let is_parallel = parallel(point)?;
5004            if is_parallel && !inside_stretch {
5005                if first_stretch {
5006                    first_stretch = false;
5007                } else if !admit(point)? {
5008                    return Ok(false);
5009                }
5010            }
5011            inside_stretch = is_parallel;
5012        }
5013    }
5014    Ok(true)
5015}
5016
5017fn pair_normals_parallel_at(
5018    first: TaggedFace<'_>,
5019    second: TaggedFace<'_>,
5020    point: Vec3,
5021) -> Result<bool, KernelRefusal> {
5022    let mut normals = [Vec3::default(); 2];
5023    for (slot, face) in normals.iter_mut().zip([first, second]) {
5024        let projection = project_point_to_surface(&face.face.surface, point)
5025            .or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
5026        let Ok(normal) = face.face.surface.normal(projection.u, projection.v) else {
5027            // A pole/singular parameter point cannot witness transversality;
5028            // treat it as tangential so the pair stays refused.
5029            return Ok(true);
5030        };
5031        *slot = normal;
5032    }
5033    Ok(normals[0].cross(normals[1]).length() <= crate::TRANSVERSE_SEED_CROSS)
5034}
5035
5036
5037
5038/// Whether some curved boundary edge of one face comes within `reach` of a
5039/// curved boundary edge of the other: each non-degenerate edge of `first`
5040/// sampled at 17 points across its span, each sample's distance to every edge
5041/// of `second`. Straight edges (a cylinder's seam, along its axis) are not
5042/// read: two coaxial walls 2.1e-6 apart have their seams that close whatever
5043/// their rims do. Read only to decline [`concentric_carriers_apart`]'s use as
5044/// two surfaces (`BREP_COSURFACE_EXACT_APART`), so a missed closest point
5045/// keeps that use.
5046fn boundaries_within(first: &[&EdgeRecord], second: &[&EdgeRecord], reach: f64) -> bool {
5047    let curved = |edge: &&&EdgeRecord| !edge.degenerate && !straight(&edge.curve);
5048    first.iter().filter(curved).any(|edge| {
5049        (0..=16).any(|step| {
5050            let t = edge.t0 + (edge.t1 - edge.t0) * step as f64 / 16.0;
5051            let Ok(point) = edge.curve.evaluate(t) else { return false };
5052            second.iter().filter(curved).any(|other| project_point_to_curve(&other.curve, point).is_ok_and(|foot| foot.distance <= reach))
5053        })
5054    })
5055}
5056
5057/// Whether every control point of `curve` lies on the line through its first
5058/// and last, to 1e-12 of that chord: a straight curve whatever its weights.
5059fn straight(curve: &NurbsCurve) -> bool {
5060    let points: Vec<Vec3> = curve.control_points.iter().filter_map(|p| p.point().ok()).collect();
5061    if points.len() != curve.control_points.len() || points.len() < 2 {
5062        return false;
5063    }
5064    let (start, end) = (points[0], points[points.len() - 1]);
5065    let chord = end.sub(start);
5066    let length = chord.length();
5067    if !(length > 0.0) {
5068        return false;
5069    }
5070    let along = chord.scale(1.0 / length);
5071    points.iter().all(|p| {
5072        let offset = p.sub(start);
5073        offset.sub(along.scale(offset.dot(along))).length() <= 1e-12 * length
5074    })
5075}
5076
5077/// Two exact analytic carriers on one axis (or one centre) whose surfaces are
5078/// apart everywhere by more than `band`: concentric spheres of different
5079/// radii; coaxial tori in one plane whose tubes are nested or clear of each
5080/// other (their centre circles `|R1 - R2|` apart against the tube radii);
5081/// coaxial cylinders of different radii. A PROOF, read only by the boolean's
5082/// scoped acceptance (`ImprintResultRecord::faces_in_unproved_pairs`).
5083fn concentric_carriers_apart(first: &NurbsSurface, second: &NurbsSurface, band: f64) -> bool {
5084    use crate::AnalyticSurface as A;
5085    let (Some(a), Some(b)) = (first.analytic(), second.analytic()) else {
5086        return false;
5087    };
5088    let same_point = |p: Vec3, q: Vec3| p.sub(q).length() <= band * 1e-3;
5089    // The axes are one line over the carriers' whole EXTENT: an angle moves
5090    // the far end of a long carrier by the angle times its size (cross
5091    // review: two 1e7-long cylinders 5e-13 rad apart cross).
5092    let extent = match (crate::Aabb::from_surface_controls(first), crate::Aabb::from_surface_controls(second)) {
5093        (Ok(a), Ok(b)) => a.diagonal().max(b.diagonal()),
5094        _ => return false,
5095    };
5096    if !(extent.is_finite() && extent > 0.0) {
5097        return false;
5098    }
5099    let same_axis = |fa: &crate::RevolutionFrame, fb: &crate::RevolutionFrame| {
5100        fa.axis.cross(fb.axis).length() * extent <= band * 1e-3
5101    };
5102    // The second frame's origin on the first frame's axis line.
5103    let on_axis = |fa: &crate::RevolutionFrame, fb: &crate::RevolutionFrame| {
5104        let offset = fb.origin.sub(fa.origin);
5105        offset.sub(fa.axis.scale(offset.dot(fa.axis))).length() <= band * 1e-3
5106    };
5107    match (a, b) {
5108        (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
5109            same_point(fa.origin, fb.origin) && (ra - rb).abs() > band
5110        }
5111        (A::Torus { frame: fa, major_radius: big_a, minor_radius: small_a }, A::Torus { frame: fb, major_radius: big_b, minor_radius: small_b }) => {
5112            if !(same_axis(fa, fb) && same_point(fa.origin, fb.origin)) {
5113                return false;
5114            }
5115            let apart = (big_a - big_b).abs();
5116            let (small, large) = (small_a.min(*small_b), small_a.max(*small_b));
5117            apart + small < large - band || apart > small_a + small_b + band
5118        }
5119        (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. }) => {
5120            (a0 - a1).abs() <= band * 1e-3
5121                && (b0 - b1).abs() <= band * 1e-3
5122                && same_axis(fa, fb)
5123                && on_axis(fa, fb)
5124                && (a0 - b0).abs() > band
5125        }
5126        _ => false,
5127    }
5128}
5129
5130/// Whether two pieces are two different exact curves (`BREP_COINCIDENT_MERGE_EXACT_CIRCLES`,
5131/// default on, `=0` off): each recognized as a circle to round-off (its
5132/// sampled residual within 1e-9 of its chord, at least 1, and 1e-13 of its
5133/// distance from the origin: an analytic lane's section, not a fit), and a point of one
5134/// standing off the other's whole circle by more than round-off (1e-8 of the
5135/// larger chord, at least 1, and 1e-12 of that distance). Exact pieces of one locus lie on
5136/// one circle to round-off, wherever each arc ends; arcs within the weld of
5137/// each other but off each other's circles are two curves however close they
5138/// run: a lens 1.8e-6 deep between two crossing circles is bounded by two of
5139/// them. The recognized centres are not compared with each other (a short
5140/// arc's fitted centre moves by far more than its residual); each circle is
5141/// read only where its own arc runs. Pieces that are not both exact circles
5142/// are left to the weld.
5143
5144fn distinct_exact_circles(a: &NurbsCurve, b: &NurbsCurve) -> Result<bool, KernelRefusal> {
5145    if !crate::switch!("BREP_COINCIDENT_MERGE_EXACT_CIRCLES", true) {
5146        return Ok(false);
5147    }
5148    // The acceptance residual follows the arc's chord as the band below
5149    // does: a conic that is no circle but sits within a radius-scaled
5150    // residual of one would then read off its own fitted circle.
5151    let circle = |curve: &NurbsCurve| -> Option<(crate::RecognizedCircle, f64)> {
5152        let [t0, t1] = curve.domain().ok()?;
5153        let (start, end) = (curve.evaluate(t0).ok()?, curve.evaluate(t1).ok()?);
5154        let reach = start.length().max(end.length());
5155        let found = crate::recognize_circle(curve, t0, t1, f64::INFINITY)?;
5156        let residual = 1e-9 * start.sub(end).length().max(1.0) + 1e-13 * reach;
5157        (found.worst <= residual).then_some((found, reach))
5158    };
5159    let (Some((first, reach_a)), Some((second, reach_b))) = (circle(a), circle(b)) else { return distinct_exact_conics(a, b) };
5160    // The band follows the arcs' own size, not their radius: the flat end of
5161    // a long ellipse (a plane nearly along a cylinder) reads as an arc of a
5162    // circle hundreds across, and a band of its radius would swallow a lens.
5163    let chord = |curve: &NurbsCurve| -> f64 {
5164        curve.domain().ok().and_then(|[t0, t1]| Some(curve.evaluate(t0).ok()?.sub(curve.evaluate(t1).ok()?).length())).unwrap_or(0.0)
5165    };
5166    let band = 1e-8 * chord(a).max(chord(b)).max(1.0) + 1e-12 * reach_a.max(reach_b);
5167    // How far `curve`'s points stand off `circle` (the whole circle).
5168    let off = |curve: &NurbsCurve, circle: &crate::RecognizedCircle| -> f64 {
5169        let Ok([t0, t1]) = curve.domain() else { return 0.0 };
5170        (0..=32)
5171            .filter_map(|i| curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).ok())
5172            .map(|point| {
5173                let offset = point.sub(circle.centre);
5174                let height = offset.dot(circle.axis);
5175                let radial = offset.sub(circle.axis.scale(height)).length();
5176                ((radial - circle.radius).powi(2) + height * height).sqrt()
5177            })
5178            .fold(0.0, f64::max)
5179    };
5180    Ok(off(b, &first) > band || off(a, &second) > band)
5181}
5182
5183/// [`distinct_exact_circles`] for pieces that are not both circles: each a
5184/// planar rational quadratic (or a line), as an analytic lane writes a plane's
5185/// section of a quadric (a fitted or marched section is cubic), and a point of
5186/// one standing off the other by more than round-off (1e-8 of the larger span
5187/// and 1e-12 of the distance from the origin) where its foot falls inside the
5188/// other's span (an overhang past the other's end is no second curve). A plane
5189/// nearly along a lens 2.3e-6 thick cuts its two walls in two ellipse arcs
5190/// within the weld of each other.
5191fn distinct_exact_conics(a: &NurbsCurve, b: &NurbsCurve) -> Result<bool, KernelRefusal> {
5192    let shape = |curve: &NurbsCurve| -> Option<(f64, f64)> {
5193        if curve.degree > 2 {
5194            return None;
5195        }
5196        let points: Vec<Vec3> = curve.control_points.iter().filter_map(|p| p.point().ok()).collect();
5197        if points.len() != curve.control_points.len() || points.len() < 2 {
5198            return None;
5199        }
5200        let reach = points.iter().fold(0.0f64, |m, p| m.max(p.length()));
5201        let span = points.iter().fold(0.0f64, |m, p| m.max(p.sub(points[0]).length()));
5202        // Planar: every control point on the plane of the first and the two
5203        // farthest from it (a line is planar).
5204        let mut normal = Vec3::new(0.0, 0.0, 0.0);
5205        for i in 1..points.len() {
5206            for j in (i + 1)..points.len() {
5207                let candidate = points[i].sub(points[0]).cross(points[j].sub(points[0]));
5208                if candidate.length() > normal.length() {
5209                    normal = candidate;
5210                }
5211            }
5212        }
5213        if let Ok(unit) = normal.normalized() {
5214            let flat = 1e-12 * reach + 1e-10 * span;
5215            if points.iter().any(|p| p.sub(points[0]).dot(unit).abs() > flat) {
5216                return None;
5217            }
5218        }
5219        Some((span, reach))
5220    };
5221    let (Some((span_a, reach_a)), Some((span_b, reach_b))) = (shape(a), shape(b)) else { return Ok(false) };
5222    let band = 1e-8 * span_a.max(span_b).max(1.0) + 1e-12 * reach_a.max(reach_b);
5223    let off = |curve: &NurbsCurve, other: &NurbsCurve| -> Result<f64, KernelRefusal> {
5224        let [t0, t1] = curve.domain().or_refuse(KernelStage::Intersect, "domain")?;
5225        let [o0, o1] = other.domain().or_refuse(KernelStage::Intersect, "domain")?;
5226        let margin = 1e-9 * (o1 - o0).abs();
5227        let mut worst = 0.0f64;
5228        for i in 1..32 {
5229            let point = curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).or_refuse(KernelStage::Intersect, "evaluate")?;
5230            let Ok(foot) = crate::project_point_to_curve(other, point) else { continue };
5231            // The projector stops near 1e-7; Newton on (C(u) - p)·C'(u) takes
5232            // the foot to round-off before its distance is read.
5233            let mut u = foot.u;
5234            for _ in 0..8 {
5235                let Ok(d) = other.derivatives(u, 2) else { break };
5236                let gap = d[0].sub(point);
5237                let slope = d[1].dot(d[1]) + gap.dot(d[2]);
5238                if !(slope.abs() > 0.0) {
5239                    break;
5240                }
5241                let step = gap.dot(d[1]) / slope;
5242                u = (u - step).clamp(o0.min(o1), o0.max(o1));
5243                if step.abs() <= 1e-15 * (o1 - o0).abs() {
5244                    break;
5245                }
5246            }
5247            let Ok(at) = other.evaluate(u) else { continue };
5248            if u > o0.min(o1) + margin && u < o0.max(o1) - margin {
5249                worst = worst.max(at.sub(point).length().min(foot.distance));
5250            }
5251        }
5252        Ok(worst)
5253    };
5254    Ok(off(b, a)? > band || off(a, b)? > band)
5255}
5256
5257/// `BREP_COSURFACE_TANGENT_CYLINDERS` (default off; `on`, `check`). Two
5258/// cylinders tangent from outside along a line their seams share read
5259/// cosurface to the sampled pair classification (every sample on the shared
5260/// seam line is close and parallel), and the cosurface branch exchanges each
5261/// face's whole boundary onto the other. Only the shared seam lies on both
5262/// carriers; a rim touches the other carrier at one point. Once a rim carries
5263/// a vertex off that point (a second contact, where a hole is cut between two
5264/// earlier holes), an arc of it is minted on a carrier it does not lie on and
5265/// its pcurve refuses ("endpoint projection failed"). Under it, an edge whose
5266/// interior lies wholly off the other carrier is not exchanged for such a
5267/// pair. `check` prints the edges it would skip and exchanges them as before.
5268/// The boolean's cylinder re-seat retry ([`with_tangent_cylinder_filter`])
5269/// turns it on for its own attempt.
5270fn tangent_cylinders_off_carrier_mode() -> crate::env_read::Mode {
5271    if TANGENT_CYLINDER_FILTER.with(|cell| cell.get()) {
5272        return crate::env_read::Mode::On;
5273    }
5274    crate::mode_switch!("BREP_COSURFACE_TANGENT_CYLINDERS", false)
5275}
5276
5277thread_local! {
5278    static TANGENT_CYLINDER_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5279}
5280
5281/// Run `action` with `BREP_COSURFACE_TANGENT_CYLINDERS` on for this thread's
5282/// imprints (the re-seated attempt of a boolean, whose seams were moved onto
5283/// tangent contacts that read cosurface).
5284pub fn with_tangent_cylinder_filter<T>(action: impl FnOnce() -> T) -> T {
5285    struct Restore(bool);
5286    impl Drop for Restore {
5287        fn drop(&mut self) {
5288            TANGENT_CYLINDER_FILTER.with(|cell| cell.set(self.0));
5289        }
5290    }
5291    let _restore = Restore(TANGENT_CYLINDER_FILTER.with(|cell| cell.replace(true)));
5292    action()
5293}
5294
5295/// Two cylinder carriers on different axes (never one surface, whatever the
5296/// sampled reading says).
5297fn distinct_cylinder_carriers(first: &NurbsSurface, second: &NurbsSurface, tolerance: f64) -> bool {
5298    let cylinder = |surface: &NurbsSurface| match surface.analytic() {
5299        Some(crate::AnalyticSurface::RuledRevolution { frame, rho0, rho1, .. }) if rho0 == rho1 => Some((frame.origin, frame.axis, *rho0)),
5300        _ => None,
5301    };
5302    let (Some((o1, a1, r1)), Some((o2, _, r2))) = (cylinder(first), cylinder(second)) else { return false };
5303    let delta = o2.sub(o1);
5304    let off_axis = delta.sub(a1.scale(delta.dot(a1))).length();
5305    off_axis > (tolerance * 100.0).max(1e-9) * (1.0 + r1.max(r2))
5306}
5307
5308/// Whether every interior sample of `edge` lies farther than the contact band
5309/// from `surface` (its ends may touch it).
5310fn edge_interior_off_carrier(edge: &EdgeRecord, surface: &NurbsSurface, tolerance: f64) -> Result<bool, KernelRefusal> {
5311    let band = (tolerance * 100.0).max(1e-6);
5312    for k in 1..8 {
5313        let t = edge.t0 + (edge.t1 - edge.t0) * k as f64 / 8.0;
5314        let point = edge.curve.evaluate(t).or_refuse(KernelStage::Intersect, "evaluate")?;
5315        let projection = project_point_to_surface(surface, point).or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
5316        if projection.distance <= band {
5317            return Ok(false);
5318        }
5319    }
5320    Ok(true)
5321}