Skip to main content

brep_blend/blending/fillet/
edges.rs

1use super::*;
2
3/// Constant-radius rolling-ball fillet of one edge (Golovanov §4.9 march,
4/// §6.9 surgery; the cutter only where the march refuses).
5pub fn fillet_edge(
6    solid: &BrepSolid,
7    edge_id: u64,
8    radius: f64,
9    name: Option<&str>,
10) -> Result<BrepSolid, KernelRefusal> {
11    // One blend operation: the reports of an earlier one, never consumed, are
12    // dropped as it starts (nested calls keep this operation's).
13    let _operation = crate::blend::BlendOperation::enter();
14    check_mixed_concavity(solid, edge_id, "fillet_edge")?;
15    check_support_extent_clipping(solid, edge_id, radius, "fillet_edge")?;
16    fillet_or_chamfer(solid, edge_id, radius, false, name, ToolEnds::default(), Lane::GeneralFirst)
17        .map_err(|refusal| size_refusal(solid, edge_id, radius, false, name, "fillet_edge", refusal))
18}
19
20/// A blend refused because the rolling ball's contact system has no solution
21/// (`Newton is singular`) says so by name, with the size that does build.
22///
23/// A ball that does not fit beside the edge has no contact points to solve
24/// for: on the rim of a bore through a fillet (a wall 1.5 thick between the
25/// bore and the fillet's torus) no ball wider than the wall rolls, and every
26/// lane's solver stops singular, which was reported as an internal error of
27/// three lanes. A chamfer's distance is its ball's radius, so the same holds
28/// for it. This runs only after such a refusal: the same blend is tried at
29/// half, a quarter and an eighth of the size, and where one builds the
30/// largest size that does is bracketed in five more tries and named. Where
31/// none builds, the refusal is returned as it came.
32fn size_refusal(
33    solid: &BrepSolid,
34    edge_id: u64,
35    size: f64,
36    chamfer: bool,
37    name: Option<&str>,
38    entry: &str,
39    refusal: KernelRefusal,
40) -> KernelRefusal {
41    if !refusal.message.contains("Newton is singular") {
42        return refusal;
43    }
44    let builds = |size: f64| fillet_or_chamfer(solid, edge_id, size, chamfer, name, ToolEnds::default(), Lane::GeneralFirst).is_ok();
45    let mut too_large = size;
46    let mut fits = None;
47    for fraction in [0.5, 0.25, 0.125] {
48        if builds(size * fraction) {
49            fits = Some(size * fraction);
50            break;
51        }
52        too_large = size * fraction;
53    }
54    let Some(mut fits) = fits else {
55        return refusal;
56    };
57    for _ in 0..5 {
58        let middle = 0.5 * (fits + too_large);
59        if builds(middle) {
60            fits = middle;
61        } else {
62            too_large = middle;
63        }
64    }
65    KernelRefusal::input(
66        KernelStage::Refine,
67        "blend_size",
68        format!(
69            "{entry}: no rolling ball of radius {size} was found along this edge (a {kind}'s size is its ball's radius); \
70             a size up to about {fits:.3} builds. The solver's own words: {message}",
71            kind = if chamfer { "chamfer" } else { "fillet" },
72            message = refusal.message
73        ),
74    )
75}
76
77
78/// Equal-leg chamfer of one edge (Golovanov §6.11: the same construction
79/// with the arc's chord).
80pub fn chamfer_edge(
81    solid: &BrepSolid,
82    edge_id: u64,
83    distance: f64,
84    name: Option<&str>,
85) -> Result<BrepSolid, KernelRefusal> {
86    // One blend operation: the reports of an earlier one, never consumed, are
87    // dropped as it starts (nested calls keep this operation's).
88    let _operation = crate::blend::BlendOperation::enter();
89    check_mixed_concavity(solid, edge_id, "chamfer_edge")?;
90    check_support_extent(solid, edge_id, distance, "chamfer_edge")?;
91    fillet_or_chamfer(solid, edge_id, distance, true, name, ToolEnds::default(), Lane::GeneralFirst)
92        .map_err(|refusal| size_refusal(solid, edge_id, distance, true, name, "chamfer_edge", refusal))
93}
94
95/// Build and apply the chamfer tool for one straight edge from an already-built
96/// cross-section profile (curve index 1 is the chamfer chord / blend wall).
97/// Shared by the two-distance and distance-angle asymmetric entries.
98fn apply_chamfer_offsets_profile(
99    solid: &BrepSolid,
100    cross: &EdgeCross,
101    profile: &[NurbsCurve],
102    name: Option<&str>,
103    edge_id: u64,
104) -> Result<BrepSolid, KernelRefusal> {
105    // Run through to the faces the edge's ends meet where the rails go on past
106    // them (`BREP_CHAMFER_THROUGH_END_FACES`, default on; `=0` restores); the flush cutter
107    // below answers everything else.
108    if let Some(result) = super::tool::chamfer_through_end_faces(solid, edge_id, cross, profile, name) {
109        return Ok(settle_cutter_scaffold(result));
110    }
111    let mut tool = match &cross.path {
112        EdgePath::Straight { direction, length } => {
113            extrude_profile_brep(profile, *direction, *length)?
114        }
115        // A circular edge between carriers rotationally symmetric about its
116        // axis with straight meridians (`analyze_edge` admits nothing else):
117        // the legs lie on the meridians, so the chordal setbacks are also the
118        // distances along the faces, and the same section revolved about the
119        // axis is the exact tool (`BREP_CHAMFER_ASYM_CURVED`, default on).
120        EdgePath::Circular { .. } if chamfer_asym_curved_on() => {
121            super::tool::build_exact_tool(cross, profile, 0.0, ToolEnds::default(), name)?
122        }
123        EdgePath::Circular { .. } => {
124            return Err(KernelRefusal::unsupported(
125                KernelStage::Classify,
126                "asymmetric_curved_edge",
127                "chamfer_edge_asymmetric: only straight edges on planar faces are supported \
128                 in this slice (asymmetric chamfer on general/curved edges is out of scope)",
129            ));
130        }
131    };
132    // Side faces are emitted in input-curve order; the chamfer wall is the
133    // second profile curve (index 1). Every other face is the cutter's
134    // scaffold, tagged and settled exactly as the symmetric cutter's is.
135    let mut side_index = 0usize;
136    for shell in &mut tool.shells {
137        for face in &mut shell.faces {
138            if side_index == 1 {
139                if face.name.is_none() {
140                    face.name = name.map(str::to_string);
141                }
142            } else {
143                face.name = Some(scaffold_tag(name));
144            }
145            side_index += 1;
146        }
147    }
148    apply_tool(solid, &tool, cross.convex).map(settle_cutter_scaffold)
149}
150
151/// Asymmetric chamfers on curved edges (two-distance and distance-angle):
152/// on by default; `BREP_CHAMFER_ASYM_CURVED=0` restores the refusal
153/// `asymmetric_curved_edge`.
154pub fn chamfer_asym_curved_on() -> bool {
155    switch!("BREP_CHAMFER_ASYM_CURVED", true)
156}
157
158/// Asymmetric (two-distance) chamfer of one STRAIGHT edge between two planar
159/// faces (Golovanov §6.11): setback `d1` along face 1 and `d2` along face 2 —
160/// the standard CAD "d1 × d2" bevel.  General/curved edges are out of scope for
161/// this slice and return a clear error.
162pub fn chamfer_edge_asymmetric(
163    solid: &BrepSolid,
164    edge_id: u64,
165    d1: f64,
166    d2: f64,
167    name: Option<&str>,
168) -> Result<BrepSolid, KernelRefusal> {
169    // One blend operation: the reports of an earlier one, never consumed, are
170    // dropped as it starts (nested calls keep this operation's).
171    let _operation = crate::blend::BlendOperation::enter();
172    if !(d1 > 0.0) || !(d2 > 0.0) || !d1.is_finite() || !d2.is_finite() {
173        return Err(KernelRefusal::input(
174            KernelStage::Collect,
175            "setback_distances",
176            "chamfer_edge_asymmetric: both setback distances must be positive",
177        ));
178    }
179    // `analyze_edge` only uses the radius to size the orientation probe step;
180    // the smaller setback keeps that probe inside both faces.
181    let cross = match analyze_edge(solid, edge_id, d1.min(d2)) {
182        Ok(cross) => cross,
183        Err(refusal) if chamfer_asym_curved_on() => {
184            let faces = setback_faces(solid, edge_id).map_err(|_| refusal)?;
185            let law = crate::blend::setback::SetbackLaw::Distances { faces, distances: [d1, d2] };
186            return chamfer_by_setback_law(solid, edge_id, law, name, "chamfer_edge_asymmetric", false);
187        }
188        Err(refusal) => return Err(refusal),
189    };
190    let profile = chamfer_cross_section_offsets(&cross, d1, d2)?;
191    apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)
192}
193
194/// Conic-section blend of one edge: the rolling ball's two contacts joined by
195/// a conic instead of the ball's arc.
196///
197/// `radius` places the contacts exactly where `fillet_edge` places them, the
198/// distance `radius / tan(θ/2)` from the edge on each face (θ the angle
199/// between the faces; `radius` itself at a right angle). The section is the
200/// rational quadratic through those contacts whose middle pole is the point
201/// where the two faces' section lines meet (a point of the edge), with weights
202/// `1, rho / (1 − rho), 1`. It is tangent to both faces at the contacts. `rho`
203/// in `(0, 1)` is the fraction of the way from the contacts' chord to the edge
204/// that the section's middle reaches: `0.5` is a parabola, below it an ellipse,
205/// above it a hyperbola, and `sin(θ/2) / (1 + sin(θ/2))` (`√2 − 1` at a right
206/// angle) is the ball's own arc.
207///
208/// Built here for a straight edge between two planes, and for a circular edge
209/// between surfaces of revolution about its axis whose meridians are straight
210/// (a plane, a cylinder, a cone); any other edge is refused `conic_edge` by
211/// name. An edge that runs on into its neighbours is cut through to them, as
212/// a chamfer's is.
213pub fn fillet_edge_conic(
214    solid: &BrepSolid,
215    edge_id: u64,
216    radius: f64,
217    rho: f64,
218    name: Option<&str>,
219) -> Result<BrepSolid, KernelRefusal> {
220    let _operation = crate::blend::BlendOperation::enter();
221    if !(radius > 0.0) || !radius.is_finite() {
222        return Err(KernelRefusal::input(
223            KernelStage::Collect,
224            "conic_radius",
225            "fillet_edge_conic: the radius must be positive",
226        ));
227    }
228    if !(rho > 0.0 && rho < 1.0) {
229        return Err(KernelRefusal::input(
230            KernelStage::Collect,
231            "conic_rho",
232            "fillet_edge_conic: rho must lie strictly between 0 and 1",
233        ));
234    }
235    let cross = analyze_edge(solid, edge_id, radius).map_err(|refusal| {
236        KernelRefusal::unsupported(
237            KernelStage::Classify,
238            "conic_edge",
239            format!(
240                "fillet_edge_conic: a conic blend is built only on a straight edge between planes or a \
241                 circular edge between straight-sided surfaces about its axis ({})",
242                refusal.message
243            ),
244        )
245    })?;
246    if matches!(cross.path, EdgePath::Circular { .. }) && !chamfer_asym_curved_on() {
247        return Err(KernelRefusal::unsupported(
248            KernelStage::Classify,
249            "conic_edge",
250            "fillet_edge_conic: circular edges are switched off (BREP_CHAMFER_ASYM_CURVED=0)",
251        ));
252    }
253    let profile = super::tool::conic_cross_section(&cross, radius, rho)?;
254    let result = apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)?;
255    refuse_invalid_result(&result, "fillet_edge_conic")?;
256    Ok(result)
257}
258
259/// `fillet_edge_conic` for edges picked by a point on each. The edges are
260/// blended one after another and independently: where two of them meet, the
261/// vertex stays sharp between the two blends (no corner is built).
262pub fn fillet_edges_conic(
263    solid: &BrepSolid,
264    edge_points: &[Vec3],
265    edge_names: Option<&[String]>,
266    radius: f64,
267    rho: f64,
268    name: Option<&str>,
269) -> Result<BrepSolid, KernelRefusal> {
270    let _operation = crate::blend::BlendOperation::enter();
271    if edge_points.is_empty() {
272        return Err(KernelRefusal::input(
273            KernelStage::Collect,
274            "conic_selection",
275            "fillet_edges_conic: no edges selected",
276        ));
277    }
278    let mut result = solid.clone();
279    for (index, point) in edge_points.iter().enumerate() {
280        let edge_id = resolve_edge_by_point(&result, *point)?;
281        result = fillet_edge_conic(&result, edge_id, radius, rho, per_edge_name(edge_names, name, index))?;
282    }
283    Ok(result)
284}
285
286/// The ids of the edge's two faces in `analyze_edge`'s order (face 1 first):
287/// the faces the setbacks `d1` and `d2` are measured on.
288fn setback_faces(solid: &BrepSolid, edge_id: u64) -> Result<[u64; 2], KernelRefusal> {
289    let (_, faces) = super::analyze::edge_and_faces(solid, edge_id)?;
290    match faces.as_slice() {
291        [first, second] if first.id != second.id => Ok([first.id, second.id]),
292        _ => Err(KernelRefusal::input(
293            KernelStage::Collect,
294            "edge_faces",
295            format!("asymmetric chamfer: edge {edge_id} does not join two faces"),
296        )),
297    }
298}
299
300/// The input positions of the selected points that resolve onto the smooth
301/// chain through `edge_id`, when the chain has two or more edges and the
302/// not-yet-chamfered selection covers every one of them; else `None`.
303fn selected_chain(
304    solid: &BrepSolid,
305    edge_id: u64,
306    edge_points: &[Vec3],
307    done: &[bool],
308) -> Result<Option<Vec<usize>>, KernelRefusal> {
309    let Ok((members, _closed)) = crate::blend::smooth_chain_members(solid, edge_id) else {
310        return Ok(None);
311    };
312    if members.len() < 2 {
313        return Ok(None);
314    }
315    let mut positions = Vec::new();
316    for member in &members {
317        let position = edge_points.iter().enumerate().position(|(index, point)| {
318            !done[index] && resolve_edge_by_point(solid, *point).is_ok_and(|id| id == *member)
319        });
320        match position {
321            Some(position) => positions.push(position),
322            None => return Ok(None),
323        }
324    }
325    Ok(Some(positions))
326}
327
328/// An asymmetric chamfer the exact cutters do not cover (a curved edge on
329/// carriers that are not coaxial straight-meridian revolutions): the closed
330/// rim's march with its stations solved from the setback law
331/// (`blend/setback.rs`): a closed edge as its own rim, an open edge as the
332/// closed smooth chain it lies on or else alone, and with `walk_chain` the
333/// whole smooth chain (open or closed) a selection covers.
334fn chamfer_by_setback_law(
335    solid: &BrepSolid,
336    edge_id: u64,
337    law: crate::blend::setback::SetbackLaw,
338    name: Option<&str>,
339    entry: &str,
340    walk_chain: bool,
341) -> Result<BrepSolid, KernelRefusal> {
342    let edge = solid
343        .edges
344        .iter()
345        .find(|edge| edge.id == edge_id)
346        .ok_or_else(|| KernelRefusal::input(KernelStage::Collect, "edge", format!("{entry}: edge {edge_id} not found")))?;
347    let closed = edge.start_vertex_id == edge.end_vertex_id;
348    // The operand heal the symmetric ladder runs first (ids preserved).
349    let mut healed = solid.clone();
350    let policy = crate::KernelTolerances::for_solid(&healed, 1e-7);
351    crate::heal::heal_operands(&mut healed, &policy)?;
352    let reach = law.reach();
353    let mut result = crate::blend::setback::with_setback_law(law, || {
354        if walk_chain {
355            crate::blend::blend_smooth_chain(&healed, edge_id, reach, true, name)
356        } else if closed {
357            crate::blend::blend_closed_edge(&healed, edge_id, reach, true, name)
358        } else {
359            // An arc of a closed smooth chain (a rim the carriers' seams
360            // split) is chamfered as the whole rim; a lone open edge on its
361            // own.  An open tangent chain is not walked from one of its edges
362            // (`chamfer_edges_asymmetric` takes a whole selected chain).
363            crate::blend::blend_smooth_chain_if_closed(&healed, edge_id, reach, true, name).or_else(|refusal| {
364                let lone = matches!(&refusal.class, RefusalClass::Internal { what } if what == "chain_single_segment");
365                if lone {
366                    crate::blend::blend_open_edge(&healed, edge_id, reach, true, name)
367                } else {
368                    Err(refusal)
369                }
370            })
371        }
372    })?;
373    heal_edge_vertex_gaps(&mut result, reach)?;
374    crate::blend::fit_planar_charts_to_trims(&healed, &mut result)?;
375    let result = settle_cutter_scaffold(result);
376    refuse_invalid_result(&result, entry)?;
377    super::analyze::check_blend_interference(&healed, &result, &[edge_id], "chamfer")?;
378    super::analyze::check_blend_wall_loops(&result, "chamfer")?;
379    Ok(result)
380}
381
382/// Distance-angle chamfer of one STRAIGHT edge between two planar faces
383/// (Golovanov §6.11): setback `d1` along face 1 and angle `angle_rad` between
384/// the chamfer face and face 1.  `d2` is constructed geometrically in the
385/// cross-section plane (see `chamfer_angle_second_distance`), then the
386/// two-distance builder is applied.
387pub fn chamfer_edge_angle(
388    solid: &BrepSolid,
389    edge_id: u64,
390    d1: f64,
391    angle_rad: f64,
392    name: Option<&str>,
393) -> Result<BrepSolid, KernelRefusal> {
394    // One blend operation: the reports of an earlier one, never consumed, are
395    // dropped as it starts (nested calls keep this operation's).
396    let _operation = crate::blend::BlendOperation::enter();
397    if !(d1 > 0.0) || !d1.is_finite() {
398        return Err(KernelRefusal::input(
399            KernelStage::Collect,
400            "setback_d1",
401            "chamfer_edge_angle: setback distance d1 must be positive",
402        ));
403    }
404    let cross = match analyze_edge(solid, edge_id, d1) {
405        Ok(cross) => cross,
406        Err(refusal) if chamfer_asym_curved_on() => {
407            let [first, _] = setback_faces(solid, edge_id).map_err(|_| refusal)?;
408            if !(angle_rad > 1e-9) || !(angle_rad < std::f64::consts::PI) {
409                return Err(KernelRefusal::input(
410                    KernelStage::Collect,
411                    "chamfer_angle",
412                    format!("chamfer_edge_angle: angle {angle_rad} must be positive"),
413                ));
414            }
415            let law = crate::blend::setback::SetbackLaw::Angle { first, distance: d1, angle: angle_rad };
416            return chamfer_by_setback_law(solid, edge_id, law, name, "chamfer_edge_angle", false);
417        }
418        Err(refusal) => return Err(refusal),
419    };
420    let d2 = chamfer_angle_second_distance(&cross, d1, angle_rad)?;
421    let profile = chamfer_cross_section_offsets(&cross, d1, d2)?;
422    apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)
423}
424
425/// Snap small trim/intersection gaps between blend edges and their vertices.
426/// The boolean endpoint welder preserves gaps already inside the validation
427/// band and limits repairs to `max(|radius| * 1e-3, 1e-4)`.
428pub(super) fn heal_edge_vertex_gaps(
429    solid: &mut BrepSolid,
430    radius: f64,
431) -> Result<(), KernelRefusal> {
432    let search = (radius.abs() * 1e-3).max(1e-7);
433    crate::boolean::commit_nearby_edge_endpoints(solid, search)
434}
435
436/// The fillet pipeline's exit acceptance: a solid with a validation ERROR is
437/// refused by name, never returned.
438///
439/// Warnings do not refuse; only the issues `validate()` itself calls errors.
440fn refuse_invalid_result(result: &BrepSolid, entry: &str) -> Result<(), KernelRefusal> {
441    let errors: Vec<_> = result.validate_memoised().into_iter().filter(|issue| issue.severity == "error").collect();
442    let Some(first) = errors.first() else {
443        return Ok(());
444    };
445    Err(KernelRefusal::new(
446        RefusalClass::InvalidResultTopology { issues: errors.len() as u32 },
447        KernelStage::Validate,
448        format!(
449            "{entry}: the blend built a solid that fails validation ({} errors, first: {}); \
450             refused rather than returned",
451            errors.len(),
452            first.message
453        ),
454    ))
455}
456
457/// `BREP_FILLET_PICK_SKIPS_SEAM` (default on; `=0` restores): a pick point that lies as near a
458/// SEAM (an edge one face uses on both sides) as a blendable edge picks the
459/// blendable one.
460///
461/// Cause (brep-bench probe, a ball r 5 bored through by a cylinder r 2, its rim
462/// filleted or chamfered from the point (0, 2, √21), refused "edge 4 borders 1
463/// faces"): the point is the vertex where the rim meets the bore's seam, both
464/// edges read distance 0, and the first found, the seam, was taken. A seam has
465/// one face on both sides and can never be blended, so it loses every tie.
466fn pick_skips_seam_on() -> bool {
467    switch!("BREP_FILLET_PICK_SKIPS_SEAM", true)
468}
469
470/// Whether `edge_id` is a seam: every coedge of it lies on one face.
471fn is_seam(solid: &BrepSolid, edge_id: u64) -> bool {
472    let users = solid
473        .shells
474        .iter()
475        .flat_map(|shell| &shell.faces)
476        .filter(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges).any(|coedge| coedge.edge_id == edge_id))
477        .count();
478    users == 1
479}
480
481/// Resolve a point within 1e-3 of a trimmed edge.
482pub fn resolve_edge_by_point(solid: &BrepSolid, point: Vec3) -> Result<u64, KernelRefusal> {
483    let nearest = crate::topology::nearest_edge(solid, point);
484    if pick_skips_seam_on() {
485        if let Some((edge_id, distance)) = nearest {
486            if distance <= 1e-3 && is_seam(solid, edge_id) {
487                let tie = distance + 1e-9 * (1.0 + point.length());
488                let blendable = solid.edges.iter().filter(|edge| edge.id != edge_id && !edge.degenerate).find(|edge| {
489                    crate::project_point_to_curve(&edge.curve, point).ok().is_some_and(|projection| {
490                        let at = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
491                        edge.curve.evaluate(at).is_ok_and(|sample| sample.sub(point).length() <= tie)
492                    }) && !is_seam(solid, edge.id)
493                });
494                if let Some(edge) = blendable {
495                    return Ok(edge.id);
496                }
497            }
498        }
499    }
500    match nearest {
501        Some((edge_id, distance)) if distance <= 1e-3 => Ok(edge_id),
502        Some((_, distance)) => Err(KernelRefusal::input(
503            KernelStage::Collect,
504            "edge_point",
505            format!(
506                "fillet_edges: no edge within tolerance of the point (nearest {distance:.6})"
507            ),
508        )),
509        None => Err(KernelRefusal::input(
510            KernelStage::Collect,
511            "no_edges",
512            "fillet_edges: solid has no edges",
513        )),
514    }
515}
516
517/// Fillet (or chamfer) a GROUP of edges as ONE operation, and — for fillets —
518/// round the convex "star" vertices where three or more of the selected edges
519/// meet (Golovanov §6.9.7).  This is the whole multi-edge fillet in a single
520/// kernel call: the caller passes the object plus one 3D point on each edge,
521/// and the kernel orchestrates the filleting and corner blending against the
522/// full topology (so acute corners resolve coherently instead of being
523/// stitched edge-by-edge by the app).  A corner the kernel cannot round (e.g.
524/// non-orthogonal beyond support, or a general no-common-ball star) is left as
525/// the edge fillets rather than failing the whole group.
526///
527/// When the WHOLE selection cannot be blended as one unit — a shared convex
528/// corner where a revolve axis/pole edge meets the adjacent cap edges can
529/// defeat the sequential corner surgery even though each edge and every proper
530/// SUBSET of the selection blends cleanly (the three fillets converge on the
531/// pole with no single end face across the corner) — a maximal-valid-SUBSET
532/// search blends the largest subset that works, dropping only the edges that
533/// cannot co-blend.  That is a real outcome and [`fillet_edges_reported`]
534/// returns it, WITH the list of edges it could not blend.
535///
536/// This entry point does not.  A solid holding eight of the ten walls that
537/// were asked for is not the answer to the question that was asked, and
538/// returning it as a plain `Ok` reports success for a different result; so an
539/// incomplete selection is an error here, naming every edge that was dropped
540/// and the group refusal behind them.  A caller that genuinely wants the
541/// partial answer asks for it by name.
542///
543/// `edge_names` (when `Some`) is the per-edge blend-FACE name parallel to
544/// `edge_points` — each grown wall is named after ITS originating edge; `None`
545/// names every wall with the single base `name` (the legacy/test behavior,
546/// byte-identical to before). The whole `*_edges` family takes the same
547/// `edge_names` slot in the same position.
548pub fn fillet_edges(
549    solid: &BrepSolid,
550    edge_points: &[Vec3],
551    edge_names: Option<&[String]>,
552    radius: f64,
553    chamfer: bool,
554    name: Option<&str>,
555) -> Result<BrepSolid, KernelRefusal> {
556    // A selected closed rim with a corner at its one vertex, on a mate creased
557    // along its own seam, is blended on the body canonicalised for it — the
558    // mate split along a smooth meridian so the network's miter closes the
559    // crease — and the walls are merged back afterwards
560    // (`blend/creased_rim.rs`). Every other selection takes the body as it
561    // came.
562    let prepared = crate::blend::creased_rim::split_creased_rims(solid, edge_points, edge_names, &resolve_edge_by_point)?;
563    match prepared {
564        Some(prepared) => {
565            let names = prepared.names.as_deref();
566            let built = fillet_edges_prepared(&prepared.solid, &prepared.points, names, radius, chamfer, name)?;
567            Ok(prepared.rejoin(built))
568        }
569        None => {
570            // A chamfer selection holding a MIXED STAR (one concave and two
571            // convex selected edges at a vertex, the convex two on one cap) is
572            // built in two phases (`fillet/chamfer_star.rs`); a phase that
573            // refuses hands the selection to the ordinary path below.
574            if chamfer {
575                let build = |body: &BrepSolid, points: &[Vec3], names: Option<&[String]>| {
576                    fillet_edges_prepared(body, points, names, radius, true, name)
577                };
578                if let Some(built) = super::chamfer_star::chamfer_mixed_stars(solid, edge_points, edge_names, &build) {
579                    return Ok(built);
580                }
581            }
582            let ordinary = fillet_edges_prepared(solid, edge_points, edge_names, radius, chamfer, name);
583            // A closed rim written as a chain of edges along the halves of a
584            // split carrier, refused because only the closed-rim rollover
585            // follows its ball and that lane takes one closed edge, is blended
586            // on the body with those halves merged and the chain joined into one
587            // closed edge (`blend/split_rim.rs`; default on,
588            // `BREP_SPLIT_RIM_MERGE=0` off). Only that refusal asks: a selection
589            // the ordinary path builds keeps its body and names.
590            let answered = match ordinary {
591                Err(refusal)
592                    if crate::blend::split_rim::split_rim_merge_on()
593                        && matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == super::analyze::TANGENT_ROLLOVER_ONLY_WHAT) =>
594                {
595                    match crate::blend::split_rim::merge_split_rims(solid, edge_points, edge_names, &resolve_edge_by_point) {
596                        // The merged attempt's own reason is appended: the
597                        // first refusal names the lane that is missing, the
598                        // second why the canonical body did not answer either
599                        // (lane F's open item).
600                        Some(merged) => fillet_edges_prepared(&merged.solid, &merged.points, merged.names.as_deref(), radius, chamfer, name)
601                            .map_err(|merged_refusal| {
602                                refusal.with_message(|message| {
603                                    format!("{message} The rim merged into one closed edge refused too: {}", merged_refusal.message)
604                                })
605                            }),
606                        None => Err(refusal),
607                    }
608                }
609                other => other,
610            };
611            // A closed ridge split into two arcs because its walls' seams sit
612            // a hair apart is blended on the body with one wall turned about
613            // the axis onto the other's seam and the arcs joined into one
614            // closed edge (`blend/turned_rim.rs`; default on,
615            // `BREP_FILLET_TURNED_RIM=0` off). Only a refusal asks.
616            let answered = match answered {
617                Err(refusal) if crate::blend::turned_rim::turned_rim_on() => {
618                    match crate::blend::turned_rim::turn_rim_seams_together(solid, edge_points, edge_names, &resolve_edge_by_point) {
619                        Some(turned) => fillet_edges_prepared(&turned.solid, &turned.points, turned.names.as_deref(), radius, chamfer, name)
620                            .map_err(|turned_refusal| {
621                                refusal.with_message(|message| {
622                                    format!("{message} The rim turned into one closed edge refused too: {}", turned_refusal.message)
623                                })
624                            }),
625                        None => Err(refusal),
626                    }
627                }
628                other => other,
629            };
630            // A sheet's edge that runs out at the free boundary has no face
631            // across its end: each such end is closed by a temporary planar
632            // face, the body blended, and the faces removed again
633            // (`blend/sheet_ends.rs`; default on, `BREP_SHEET_FREE_END=0` off).
634            // Only a refused sheet selection asks; the refusal stands unless
635            // the reopened sheet validates.
636            match answered {
637                Err(refusal) if solid.kind == crate::BodyKind::Sheet && crate::blend::sheet_ends::sheet_free_end_on() => {
638                    let edge_ids = edge_points.iter().map(|point| resolve_edge_by_point(solid, *point)).collect::<Result<Vec<_>, _>>();
639                    let Ok(edge_ids) = edge_ids else { return Err(refusal) };
640                    let Some(closed) = crate::blend::sheet_ends::close_free_ends(solid, &edge_ids) else { return Err(refusal) };
641                    let count = crate::blend::sheet_ends::temporary_faces(&closed);
642                    match fillet_edges_prepared(&closed, edge_points, edge_names, radius, chamfer, name) {
643                        Ok(built) => crate::blend::sheet_ends::open_free_ends(built, count).ok_or(refusal),
644                        Err(closed_refusal) => Err(refusal.with_message(|message| {
645                            format!("{message} The sheet with its free ends closed refused too: {}", closed_refusal.message)
646                        })),
647                    }
648                }
649                other => other,
650            }
651        }
652    }
653}
654
655fn fillet_edges_prepared(
656    solid: &BrepSolid,
657    edge_points: &[Vec3],
658    edge_names: Option<&[String]>,
659    radius: f64,
660    chamfer: bool,
661    name: Option<&str>,
662) -> Result<BrepSolid, KernelRefusal> {
663    // One blend operation: the reports of an earlier one, never consumed, are
664    // dropped as it starts (nested calls keep this operation's).
665    let _operation = crate::blend::BlendOperation::enter();
666    // Each operation pays for the first read of every body it validates
667    // (`BrepSolid::validate_memoised`, lane R1 row 3).
668    BrepSolid::clear_validate_memo();
669    // One coedge-check memo per operation, as a boolean opens one (lane R1
670    // row 3b): the surgery's, the group lane's
671    // and the exit's validations re-read the coedges the rims left unchanged.
672    let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
673    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
674    // The search is capped at one dropped edge here (lane F row 3);
675    // `BREP_SUBSET_SEARCH_FULL=1` restores the full search.
676    let cap = std::env::var_os("BREP_SUBSET_SEARCH_FULL").is_none().then_some(1);
677    let _cap = SubsetDropCap::set(cap);
678    let (result, selection) = match fillet_edges_reported(solid, edge_points, edge_names, radius, chamfer, name) {
679        // A wall that folds is relieved where it folds, not refused
680        // (`blend/relief.rs`).
681        Err(fold) if !chamfer && crate::blend::is_wall_fold(&fold) && crate::blend::relief::radius_relief_on() => {
682            let misfit = crate::blend::relief::is_misfit_fold(&fold);
683            let relieved = relieve_fold(solid, edge_points, edge_names, radius, name, fold);
684            // A misfit (a lane's refusal read as the ball not fitting) took
685            // the group off the ladder that follows the network; when no
686            // relief builds, that ladder answers, as it did before the relief.
687            if relieved.is_err() && misfit {
688                let _off = crate::blend::relief::MisfitOff::enter();
689                return fillet_edges(solid, edge_points, edge_names, radius, chamfer, name);
690            }
691            return relieved;
692        }
693        reported => reported?,
694    };
695    if selection.is_complete() {
696        return Ok(result);
697    }
698    // Every dropped edge BY NAME: the caller's own per-edge name when it gave
699    // one, and always its index and the point it was selected by.
700    let dropped: Vec<String> = selection
701        .rejected
702        .iter()
703        .map(|index| {
704            let point = edge_points[*index];
705            let named = edge_names
706                .and_then(|names| names.get(*index))
707                .map(|name| format!("`{name}` "))
708                .unwrap_or_default();
709            format!(
710                "{named}#{index} at ({:.6}, {:.6}, {:.6})",
711                point.x, point.y, point.z
712            )
713        })
714        .collect();
715    // The selection, as specified, has no single answer the kernel will
716    // stand behind: the group refusal behind the drop travels as TEXT in
717    // `BlendSelection::reason`, so this refusal carries its own class.
718    Err(KernelRefusal::ill_posed(
719        KernelStage::Select,
720        "incomplete_selection",
721        format!(
722            "{entry}: {} of the {} selected edges were blended — {} could not co-blend with the \
723             rest of the selection and carry no wall in the result ({}). The group refusal was: \
724             {}. Blend them separately, or call the reported entry point to accept the partial \
725             selection deliberately.",
726            selection.applied.len(),
727            selection.requested,
728            selection.rejected.len(),
729            dropped.join(", "),
730            selection
731                .reason
732                .as_deref()
733                .unwrap_or("the whole group built but not every edge grew a wall"),
734        ),
735    ))
736}
737
738/// The fillet a constant `radius` would fold: rebuilt with the radius reduced
739/// only where it does not fit (`blend/relief.rs`), and a note saying where
740/// and to what. Selected edges joined (through shared vertices) to no relief
741/// zone are built at the constant radius first; each relieved group is then
742/// built by the taper network on that body. A relief that still folds is
743/// planned again with a wider margin; when none builds, the fold stands with
744/// the last relief's reason appended.
745fn relieve_fold(
746    solid: &BrepSolid,
747    edge_points: &[Vec3],
748    edge_names: Option<&[String]>,
749    radius: f64,
750    name: Option<&str>,
751    fold: KernelRefusal,
752) -> Result<BrepSolid, KernelRefusal> {
753    let _relieving = crate::blend::relief::Relieving::enter();
754    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
755    let selected: Vec<u64> = edge_points.iter().map(|point| resolve_edge_by_point(solid, *point)).collect::<Result<_, _>>()?;
756    // One edge per carrier continued (`relief::join_continuations`): the
757    // selection is read again on the joined body, two points on one joined
758    // edge selecting it once.
759    let joined = crate::blend::relief::join_continuations(solid, &selected);
760    let solid = joined.as_ref().unwrap_or(solid);
761    let mut ids: Vec<u64> = Vec::with_capacity(edge_points.len());
762    let mut points: Vec<Vec3> = Vec::with_capacity(edge_points.len());
763    let mut names: Vec<String> = Vec::with_capacity(edge_points.len());
764    for (index, point) in edge_points.iter().enumerate() {
765        let id = resolve_edge_by_point(solid, *point)?;
766        if !ids.contains(&id) {
767            ids.push(id);
768            points.push(*point);
769            if let Some(name) = edge_names.and_then(|names| names.get(index)) {
770                names.push(name.clone());
771            }
772        }
773    }
774    let (edge_points, edge_names) = (&points[..], edge_names.map(|_| &names[..]));
775    if debug && joined.is_some() {
776        eprintln!("radius relief: joined continuation edges, {} selected edges become {}", selected.len(), ids.len());
777    }
778    let started = web_time::Instant::now();
779    let measured = match crate::blend::relief::measure_ceilings(solid, &ids, radius) {
780        Ok(measured) => measured,
781        Err(refusal) => return Err(fold.with_message(|message| format!("{message}; the relief could not measure the edges: {refusal}"))),
782    };
783    if debug {
784        eprintln!("radius relief: ceilings measured in {:.1} ms", started.elapsed().as_secs_f64() * 1e3);
785    }
786    // A relief is LOCAL: the requested radius stands where it fits. Where it
787    // fits nowhere on the selection (a ball wider than a rod's rim, the whole
788    // rim short alike) a radius lowered everywhere is a different request,
789    // and the fold stands, naming the largest ball that does fit.
790    let largest = measured.iter().flatten().map(|(_, ceiling)| *ceiling).fold(0.0_f64, f64::max);
791    if largest < radius {
792        return Err(fold.with_message(|message| {
793            format!("{message}; r {radius} fits nowhere along the selection, so it is not reduced locally: the largest ball that fits anywhere on it is {largest:.6}")
794        }));
795    }
796    let mut last: Option<KernelRefusal> = None;
797    for attempt in 0..crate::blend::relief::ATTEMPTS {
798        let plan = match crate::blend::relief::plan_relief(solid, &ids, radius, &measured, attempt) {
799            Ok(Some(plan)) => plan,
800            // The ball fits everywhere the probe reads: the fold is not one
801            // a smaller radius answers.
802            Ok(None) => break,
803            Err(refusal) => {
804                last = Some(refusal);
805                break;
806            }
807        };
808        let mark = crate::blend::blend_notes_mark();
809        match build_relief_plan(solid, edge_points, edge_names, &ids, radius, name, &plan) {
810            Ok(body) => {
811                for zone in &plan.zones {
812                    let near: Vec<String> = zone
813                        .edges
814                        .iter()
815                        .filter_map(|index| solid.edges.iter().find(|edge| edge.id == ids[*index]))
816                        .map(|edge| edge.name.clone().unwrap_or_else(|| format!("edge #{}", edge.id)))
817                        .map(|label| format!("`{label}`"))
818                        .collect();
819                    // The note states what was built: where the law never
820                    // climbs back to the requested radius on the zone's edges
821                    // (report 5e49bb42's rim, 1.08 to 1.78 against r 2.2), it
822                    // says so instead of "locally".
823                    let (low, high) = zone
824                        .edges
825                        .iter()
826                        .flat_map(|index| plan.stops[*index].iter().map(|(_, r)| *r))
827                        .fold((f64::INFINITY, 0.0_f64), |(low, high), r| (low.min(r), high.max(r)));
828                    let note = if high < radius * (1.0 - 1e-9) {
829                        format!(
830                            "radius reduced over the whole of {}: {low:.2} to {high:.2}, so r {radius} is reached nowhere \
831                             on them (where they turn tightest the largest ball that fits is {:.2})",
832                            near.join(", "),
833                            zone.ceiling,
834                        )
835                    } else {
836                        format!(
837                            "radius reduced to {:.2} locally near {}: r {radius} does not fit there (the largest ball that does is {:.2})",
838                            zone.radius,
839                            near.join(", "),
840                            zone.ceiling,
841                        )
842                    };
843                    crate::blend::record_blend_note(note);
844                }
845                return Ok(body);
846            }
847            Err(refusal) => {
848                crate::blend::blend_notes_truncate(mark);
849                if debug {
850                    eprintln!("radius relief attempt {attempt} refused at {:.1} ms: {refusal}", started.elapsed().as_secs_f64() * 1e3);
851                }
852                last = Some(refusal);
853            }
854        }
855    }
856    Err(match last {
857        Some(last) => fold.with_message(|message| format!("{message}; a locally reduced radius did not build either: {last}")),
858        None => fold,
859    })
860}
861
862/// Build one relief plan (see [`relieve_fold`]).
863fn build_relief_plan(
864    solid: &BrepSolid,
865    edge_points: &[Vec3],
866    edge_names: Option<&[String]>,
867    ids: &[u64],
868    radius: f64,
869    name: Option<&str>,
870    plan: &crate::blend::relief::ReliefPlan,
871) -> Result<BrepSolid, KernelRefusal> {
872    // Groups of selected edges joined through shared vertices.
873    let count = ids.len();
874    let mut group: Vec<usize> = (0..count).collect();
875    let find = |group: &mut Vec<usize>, mut index: usize| {
876        while group[index] != index {
877            group[index] = group[group[index]];
878            index = group[index];
879        }
880        index
881    };
882    let vertices: Vec<[u64; 2]> = ids
883        .iter()
884        .map(|id| {
885            solid.edges.iter().find(|edge| edge.id == *id).map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).unwrap_or([u64::MAX; 2])
886        })
887        .collect();
888    for a in 0..count {
889        for b in a + 1..count {
890            if vertices[a].iter().any(|vertex| *vertex != u64::MAX && vertices[b].contains(vertex)) {
891                let (root_a, root_b) = (find(&mut group, a), find(&mut group, b));
892                group[root_a] = root_b;
893            }
894        }
895    }
896    let reduced: Vec<bool> = plan.stops.iter().map(|stops| stops.iter().any(|(_, r)| *r < radius)).collect();
897    let relieved_group: Vec<bool> = (0..count)
898        .map(|index| {
899            let root = find(&mut group, index);
900            (0..count).any(|other| reduced[other] && find(&mut group, other) == root)
901        })
902        .collect();
903    let pick = |want: bool| -> (Vec<Vec3>, Option<Vec<String>>, Vec<Vec<(f64, f64)>>) {
904        let indices: Vec<usize> = (0..count).filter(|index| relieved_group[*index] == want).collect();
905        (
906            indices.iter().map(|index| edge_points[*index]).collect(),
907            edge_names.map(|names| indices.iter().filter_map(|index| names.get(*index).cloned()).collect()),
908            indices.iter().map(|index| plan.stops[*index].clone()).collect(),
909        )
910    };
911    let (constant_points, constant_names, _) = pick(false);
912    let (relieved_points, relieved_names, relieved_stops) = pick(true);
913    let mut body = solid.clone();
914    if !constant_points.is_empty() {
915        body = fillet_edges(&body, &constant_points, constant_names.as_deref(), radius, false, name)?;
916    }
917    let built = fillet_edges_variable_impl(
918        &body,
919        &relieved_points,
920        relieved_names.as_deref(),
921        &relieved_stops,
922        false,
923        name,
924        "fillet_edges",
925        false,
926    )?;
927    let issues = built.validate();
928    if !issues.is_empty() {
929        return Err(KernelRefusal::internal(
930            KernelStage::Validate,
931            "relief_validate",
932            format!("radius relief: the relieved fillet does not validate: {issues:?}"),
933        ));
934    }
935    Ok(built)
936}
937
938/// What a blend selection actually achieved.
939///
940/// The kernel can answer a group blend with fewer walls than were asked for —
941/// the maximal-valid-subset search drops the edges that cannot co-blend at a
942/// shared corner rather than failing outright. This says WHICH, so partial
943/// fulfilment is a statement instead of a silence.
944#[derive(Clone, Debug)]
945pub struct BlendSelection {
946    /// How many edges the caller selected.
947    pub requested: usize,
948    /// Indices into that selection that carry a blend wall in the result.
949    pub applied: Vec<usize>,
950    /// Indices that do not.
951    pub rejected: Vec<usize>,
952    /// Why the whole selection could not be built, when something was dropped.
953    pub reason: Option<String>,
954}
955
956impl BlendSelection {
957    /// Every requested edge carries a wall.
958    pub fn is_complete(&self) -> bool {
959        self.rejected.is_empty()
960    }
961}
962
963/// [`fillet_edges`] with the selection outcome reported rather than refused.
964///
965/// The result is the same solid `fillet_edges` would build; the difference is
966/// that an incomplete selection comes back as `Ok` with the misses named,
967/// which is the explicit partial-result contract. Every named refusal that
968/// applies to the WHOLE selection — mixed concavity, a radius the local wall
969/// cannot hold, a mixed-convexity corner — is still an `Err`: dropping edges
970/// cannot rescue those, so a partial answer would be a different defect.
971/// [`fillet_edges_reported`] with the solid and the edge points translated by
972/// `offset` for the operation and the result translated back. Refusal
973/// messages name the translated coordinates.
974pub fn fillet_edges_reported_at_offset(
975    solid: &BrepSolid,
976    edge_points: &[Vec3],
977    edge_names: Option<&[String]>,
978    radius: f64,
979    chamfer: bool,
980    name: Option<&str>,
981    offset: Vec3,
982) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
983    fillet_translated(solid, edge_points, edge_names, radius, chamfer, name, offset, crate::recentre::EntryKind::Control)
984}
985
986/// The translated run behind the control and the guard.
987#[allow(clippy::too_many_arguments)]
988fn fillet_translated(
989    solid: &BrepSolid,
990    edge_points: &[Vec3],
991    edge_names: Option<&[String]>,
992    radius: f64,
993    chamfer: bool,
994    name: Option<&str>,
995    offset: Vec3,
996    kind: crate::recentre::EntryKind,
997) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
998    let _entry = crate::recentre::TranslatedEntry::open(kind);
999    let translate = |solid: &BrepSolid, offset: Vec3| {
1000        crate::recentre::translate_solid(solid, offset).map_err(|message| {
1001            KernelRefusal::internal(
1002                KernelStage::Collect,
1003                "translation_control",
1004                format!("fillet_edges: the translation control could not move the solid: {message}"),
1005            )
1006        })
1007    };
1008    let moved = translate(solid, offset)?;
1009    let points: Vec<Vec3> = edge_points.iter().map(|point| point.add(offset)).collect();
1010    let (result, selection) = fillet_edges_reported(&moved, &points, edge_names, radius, chamfer, name)?;
1011    Ok((translate(&result, offset.scale(-1.0))?, selection))
1012}
1013
1014pub fn fillet_edges_reported(
1015    solid: &BrepSolid,
1016    edge_points: &[Vec3],
1017    edge_names: Option<&[String]>,
1018    radius: f64,
1019    chamfer: bool,
1020    name: Option<&str>,
1021) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
1022    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`):
1023    // the outermost entry runs the fillet on a translated solid.
1024    if let Some(offset) = crate::recentre::control_offset_at_entry() {
1025        return fillet_edges_reported_at_offset(solid, edge_points, edge_names, radius, chamfer, name, offset);
1026    }
1027    // The recentre guard: a solid far from the origin in its own units
1028    // is filleted at the origin.
1029    let bounds = crate::recentre::solid_bounds(solid);
1030    if let Some(offset) = crate::recentre::guard_offset(bounds) {
1031        crate::recentre::profile_fired("fillet", offset, bounds);
1032        return fillet_translated(solid, edge_points, edge_names, radius, chamfer, name, offset, crate::recentre::EntryKind::Guard);
1033    }
1034    // One blend operation: the reports of an earlier one, never consumed, are
1035    // dropped as it starts (nested calls keep this operation's).
1036    let _operation = crate::blend::BlendOperation::enter();
1037    // Dropped before `_operation`, so the total is on the ledger when the
1038    // outermost operation prints it.
1039    let _total = crate::blend::BlendTimer::start("timing.total_ms");
1040    if !(radius > 0.0) || !radius.is_finite() {
1041        return Err(KernelRefusal::input(
1042            KernelStage::Collect,
1043            "radius",
1044            "fillet_edges: radius must be positive",
1045        ));
1046    }
1047    if edge_points.is_empty() {
1048        return Err(KernelRefusal::input(
1049            KernelStage::Collect,
1050            "selection",
1051            "fillet_edges: no edges selected",
1052        ));
1053    }
1054    // The rolling ball must reach both supports of every SELECTED edge — see
1055    // `check_support_extent`.  Checked ONCE, here, against the solid the
1056    // selection was made on: inside the group build the faces have already
1057    // been eaten into by earlier blends of the same selection, and a fillet
1058    // legitimately runs off that remainder (two rounds pinching on a shared
1059    // face).  Dropping edges cannot rescue an oversized radius either, so
1060    // this runs before the subset search rather than inside it.
1061    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
1062    let mut selected_ids = Vec::with_capacity(edge_points.len());
1063    if crate::blend::blend_operation_outermost() {
1064        super::analyze::clear_rollover_only();
1065    }
1066    let selection_checks = crate::blend::BlendTimer::start("timing.selection_checks_ms");
1067    let _boundaries = super::analyze::SupportBoundaryScope::open();
1068    for point in edge_points {
1069        let resolve = crate::blend::BlendTimer::start("timing.selection_checks.resolve_ms");
1070        let edge_id = resolve_edge_by_point(solid, *point)?;
1071        resolve.stop();
1072        let concavity = crate::blend::BlendTimer::start("timing.selection_checks.concavity_ms");
1073        check_mixed_concavity(solid, edge_id, entry)?;
1074        concavity.stop();
1075        let _extent = crate::blend::BlendTimer::start("timing.selection_checks.extent_ms");
1076        // A lone fillet edge may take the clipped concave fill (lane F row 5).
1077        if edge_points.len() == 1 && !chamfer {
1078            check_support_extent_clipping(solid, edge_id, radius, entry)?;
1079        } else {
1080            check_support_extent(solid, edge_id, radius, entry)?;
1081        }
1082        selected_ids.push(edge_id);
1083    }
1084    drop(_boundaries);
1085    selection_checks.stop();
1086    // A corner where the selection mixes convexity — a convex edge dying into
1087    // the concave edges it meets — has no rolling-ball closure at all: the
1088    // blends run out against each other partway along, which is the vertex
1089    // blend the stripe network does not construct yet.  It is TERMINAL, and
1090    // for the same reason as the two checks above it runs once, here: neither
1091    // the cutter composition nor the subset search below can rescue it.  The
1092    // cutter "succeeds" on this shape by shredding the solid (a sliver end cap
1093    // per corner, the carrier face split and renamed), which is worse than
1094    // the named refusal — see the 2026-09-09 rib-spine report.
1095    //
1096    // Nor can PARTITIONING the selection at the corner rescue it, which is why
1097    // this is still a refusal and not a split (measured 2026-09-13, the
1098    // partition record): the two convexity-pure halves each build on the
1099    // network, and composing them walls every selected edge and leaves every
1100    // other face's area identical to twelve digits — but the convex wall comes
1101    // out as the full untrimmed quarter-round prism (2·(1 − π/4)·r²·L to
1102    // 2.2e-10, with NO rolled-corner term) because its contact rail runs off
1103    // its own face at the TRI-TANGENT STATION and the surgery splices the
1104    // overhang in rather than clipping it. The faces it runs along come back
1105    // with self-crossing loops that `validate()`, `solid_self_intersections`,
1106    // the connectivity report and the Euler check all pass — and that
1107    // `check_loop_self_crossings` REFUSES since 9e50f6d55, so the split is not
1108    // a route to ten walls either: blend the concave half first and the
1109    // acceptance refuses every convex edge whose wall runs out into it — on
1110    // the rib both spines, at that same station, so that feature fails
1111    // outright; blend the convex half first and the maximal-valid-subset
1112    // search drops one ring edge and returns NINE walls of ten. The
1113    // construction that is missing is the runout itself: past that station the
1114    // ball rolls on one input face and on the concave stripe's own surface, so
1115    // the march needs a STRIPE as its second carrier.
1116    //
1117    // And more than that, measured 2026-09-13 (`blend/runout.rs`, which this
1118    // refusal now reports): the KEPT mate runs out too, at the mirror-image
1119    // station, so the FIRST carrier becomes the other concave stripe and the
1120    // last stretch rolls on two stripes; that stretch ends in a POLE where the
1121    // two stripes' rails on the face they share meet and the section shrinks
1122    // to a point. Two carrier switches and a degenerate terminus, not a march
1123    // with a stop.
1124    if !chamfer {
1125        // The class is BUILT where the runout composition applies — the ring
1126        // first, then one wall per spine from pole to pole (`blend/runout.rs`,
1127        // the 2026-09-30 record §5) — and refused by name, with the
1128        // composition's own reason appended, where it does not.
1129        let corner_analysis = crate::blend::BlendTimer::start("timing.corner_analysis_ms");
1130        let mut corners = crate::blend::mixed_convexity_corners(solid, &selected_ids, radius);
1131        corners.extend(crate::blend::runout::one_ended_runout_corners(solid, &selected_ids, radius));
1132        corner_analysis.stop();
1133        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1134            for corner in &corners {
1135                eprintln!(
1136                    "mixed corner at vertex {} ({:.4}, {:.4}, {:.4}): convex {:?} concave {:?}",
1137                    corner.vertex, corner.point.x, corner.point.y, corner.point.z,
1138                    corner.convex.iter().map(|index| selected_ids[*index]).collect::<Vec<_>>(),
1139                    corner.concave.iter().map(|index| selected_ids[*index]).collect::<Vec<_>>()
1140                );
1141            }
1142        }
1143        if !corners.is_empty() {
1144            // BREP lane L: begin walls_missing_tie_all_stations_20261015
1145            // Cleared on entry: only THIS composition's runout may set it.
1146            RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(false));
1147            // BREP lane L: end walls_missing_tie_all_stations_20261015
1148            let composed = rounded_boss_composition(
1149                solid, &selected_ids, edge_points, edge_names, radius, name, &corners,
1150            ).or_else(|error| {
1151                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1152                    eprintln!("rounded boss composition refused: {error}");
1153                }
1154                runout_composition(
1155                    solid, &selected_ids, edge_points, edge_names, radius, name, &corners, entry,
1156                )
1157            }).or_else(|error| {
1158                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1159                    eprintln!("runout composition refused: {error}");
1160                }
1161                // The open-pad composition (2026-10-17 face-ring report): one
1162                // convex and one concave edge at each mixed corner over a
1163                // planar face, the concave pads continued onto the convex
1164                // walls. Declines by name on any other corner shape, so the
1165                // runout's refusal stands where it stood.
1166                open_pad_composition(
1167                    solid, &selected_ids, edge_points, edge_names, radius, name, &corners, entry,
1168                ).map_err(|pad_error| {
1169                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1170                        eprintln!("open-pad composition refused: {pad_error}");
1171                    }
1172                    // The decline is carried in the refusal's CLASS (`what`),
1173                    // never in its text: 2026-10-18 the text test let the
1174                    // decline replace the runout's named refusal on the
1175                    // nine-pick wedge (three lib tests).
1176                    let declined = matches!(&pad_error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "open_pad_shape");
1177                    if declined { error } else { pad_error }
1178                })
1179            }).or_else(|error| {
1180                // The cusp composition (reports 80c5d9d1 and 6dfd5a22): every
1181                // mixed corner a CUSP, the convex and concave edges leaving it
1182                // tangent. Declines by class on any other corner, and every
1183                // other refusal keeps the one before it: it is the last try.
1184                cusp_composition(solid, &selected_ids, edge_points, edge_names, radius, name, &corners).map_err(|cusp_error| {
1185                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1186                        eprintln!("cusp composition refused: {cusp_error}");
1187                    }
1188                    error
1189                })
1190            });
1191            match composed {
1192                Ok(result) => {
1193                    // BREP lane L: begin walls_missing_tie_all_stations_20261015
1194                    // The runout composition's walls are built and checked by
1195                    // construction; a station its OWN neighbouring wall consumes
1196                    // (a runout trimmed at an edge's end) is not a missing wall.
1197                    // Only on the NETWORK's ring: there every concave edge has its
1198                    // own wall by construction and a runout trims at most its
1199                    // ends; a ring the cutter fallback built keeps the strict
1200                    // first-station rule (the rounded boss path too).
1201                    let network_ring = RUNOUT_RING_IS_NETWORK.with(|flag| flag.replace(false));
1202                    // Integrator merge 2026-10-16 (lanes F + L): the flag above is consumed
1203                    // BEFORE lane F's exit acceptance can return early, so a refused result
1204                    // never leaves it set for the next call on this thread.
1205                    refuse_invalid_result(&result, entry)?;
1206                    let missing = walls_missing_ties(
1207                        solid, &result, edge_points, &(0..edge_points.len()).collect::<Vec<_>>(), radius, chamfer, entry, network_ring,
1208                    )?;
1209                    // BREP lane L: end walls_missing_tie_all_stations_20261015
1210                    if !missing.is_empty() {
1211                        return Err(KernelRefusal::internal(
1212                            KernelStage::Validate,
1213                            "runout_walls_missing",
1214                            format!(
1215                                "{entry}: the composition built a solid with no wall on {}",
1216                                missing.iter().map(|index| selection_label(*index, edge_points, edge_names, name)).collect::<Vec<_>>().join(", ")
1217                            ),
1218                        ));
1219                    }
1220                    let n = edge_points.len();
1221                    return Ok((
1222                        result,
1223                        BlendSelection { requested: n, applied: (0..n).collect(), rejected: Vec::new(), reason: None },
1224                    ));
1225                }
1226                Err(error) => {
1227                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1228                        eprintln!("runout composition refused: {error}");
1229                    }
1230                    check_mixed_corner_convexity(
1231                        solid, &selected_ids, edge_points, edge_names, radius, name, Some(&error),
1232                    )?;
1233                }
1234            }
1235        }
1236        // A selection whose corner setbacks consume a whole edge — the exact
1237        // degenerate radius, every face shrunk to a point — has no strip for
1238        // the network to build and nothing the cutter or the subset search
1239        // can rescue (the search answered the r = 10 cube with nine walls and
1240        // a 5174 volume against the sphere's 4189).  Terminal, by name, here.
1241        let corner_analysis = crate::blend::BlendTimer::start("timing.corner_analysis_ms");
1242        check_degenerate_corner_setbacks(
1243            solid,
1244            &selected_ids,
1245            edge_points,
1246            edge_names,
1247            radius,
1248            name,
1249        )?;
1250        corner_analysis.stop();
1251    }
1252
1253    let n = edge_points.len();
1254    let complete = |applied: Vec<usize>| BlendSelection {
1255        requested: n,
1256        applied,
1257        rejected: Vec::new(),
1258        reason: None,
1259    };
1260    // Every subset below is built against the SAME solid, and a selection of
1261    // several components is composed one component at a time in input order,
1262    // so two subsets that keep the same leading components rebuild the same
1263    // intermediate solids. The memo keeps each component's result under the
1264    // chain of components composed before it, which is everything that result
1265    // depends on here (the solid, radius, chamfer and name are fixed for the
1266    // call), so the search returns what it did without the memo, only without
1267    // the rebuilding. On the 2026-09-26 cross-drilled sphere report four bored
1268    // rims were re-blended ahead of the same failing component in each of the
1269    // (up to 372) subsets tried: 13 min 25 s for one refusal, 34 s with it.
1270    let mut memo = ComponentMemo::default();
1271    let profile = crate::profile::profile_enabled();
1272    let group_started = web_time::Instant::now();
1273    let group = fillet_edges_group_in(
1274        solid,
1275        edge_points,
1276        edge_names,
1277        radius,
1278        chamfer,
1279        name,
1280        Some(&mut memo),
1281    );
1282    if profile {
1283        profile_line!(
1284            "blend.selection group edges={n} ok={} ms={:.3}",
1285            group.is_ok(),
1286            group_started.elapsed().as_secs_f64() * 1e3
1287        );
1288    }
1289    let group_err = match group {
1290        // A group solid that fails `validate()` is never returned: it becomes
1291        // the group's refusal, so the subset search below (which validates
1292        // every subset it builds) still gets its turn, and a selection with
1293        // nothing to drop refuses by that name.
1294        Ok(result) if refuse_invalid_result(&result, entry).is_err() => {
1295            refuse_invalid_result(&result, entry).unwrap_err()
1296        }
1297        Ok(result) => {
1298            // The group returned a solid, which is NOT the same as the group
1299            // having blended every edge.  `validate()` cannot tell the
1300            // difference — it checks incidence, and a solid missing a wall is
1301            // perfectly incident — so the walls are COUNTED.
1302            let missing =
1303                walls_missing(solid, &result, edge_points, &(0..n).collect::<Vec<_>>(), radius, chamfer, entry)?;
1304            if missing.is_empty() {
1305                return Ok((result, complete((0..n).collect())));
1306            }
1307            let applied: Vec<usize> = (0..n).filter(|index| !missing.contains(index)).collect();
1308            return Ok((
1309                result,
1310                BlendSelection {
1311                    requested: n,
1312                    applied,
1313                    rejected: missing,
1314                    reason: None,
1315                },
1316            ));
1317        }
1318        Err(error) => error,
1319    };
1320    // A wall that FOLDS THROUGH ITSELF is terminal for the whole selection, and
1321    // for the reason the two checks above are: dropping edges cannot rescue it.
1322    // The subset search would happily answer this document's two collars with
1323    // the ONE that does not fold, and return a solid whose volume is a blend
1324    // short — the same silent partial `both_collars_add_independently` exists
1325    // to catch.  Reported by name instead (`blend/fold.rs`).
1326    // A miter past the sharp edge's far vertex needs support-face switching,
1327    // not a smaller selection. Do not let the subset search mask the limit.
1328    // Nor can dropping another edge close a tangential end whose taper failed.
1329    if crate::blend::is_wall_fold(&group_err) || crate::blend::is_miter_support_overrun(&group_err)
1330        || crate::blend::is_tangential_transverse_end(&group_err)
1331        || matches!(&group_err.class, RefusalClass::UnsupportedGeometry { what } if what == "canal_footprint_bound")
1332        || crate::blend::is_ball_does_not_fit(&group_err)
1333    {
1334        return Err(group_err);
1335    }
1336    // Fewer than two edges: nothing to drop, so the group error is final.
1337    // Cap the combinatorial search so a large malformed selection cannot
1338    // explode (the full group carries the common case; the search is a
1339    // rare fallback).
1340    if n < 2 || n > 12 {
1341        return Err(group_err);
1342    }
1343    // Drop the fewest edges first (largest surviving subset), trying the
1344    // drop-sets in lexicographic order so the result is deterministic.
1345    // Take the first subset that blends to a valid solid IN WHICH EVERY KEPT
1346    // EDGE GREW A WALL: a subset that itself silently drops one of its own
1347    // edges is not the maximal subset, it is a smaller one wearing a larger
1348    // one's label.
1349    let max_drop = SUBSET_DROP_CAP.with(|cap| cap.get()).map_or(n - 1, |cap| cap.min(n - 1));
1350    for drop in 1..=max_drop {
1351        for dropped in index_combinations(n, drop) {
1352            let keep: Vec<usize> = (0..n).filter(|i| !dropped.contains(i)).collect();
1353            let points: Vec<Vec3> = keep.iter().map(|i| edge_points[*i]).collect();
1354            // Subset the per-edge blend-face names with the IDENTICAL
1355            // drop-set so `kept_names[k]` still names `kept[k]`.
1356            let kept_names: Option<Vec<String>> =
1357                edge_names.map(|names| keep.iter().map(|i| names[*i].clone()).collect());
1358            crate::blend::record_count("count.subset.builds", 1);
1359            let subset_started = web_time::Instant::now();
1360            let subset = fillet_edges_group_in(
1361                solid,
1362                &points,
1363                kept_names.as_deref(),
1364                radius,
1365                chamfer,
1366                name,
1367                Some(&mut memo),
1368            );
1369            if profile {
1370                profile_line!(
1371                    "blend.selection subset dropped={dropped:?} ok={} ms={:.3}",
1372                    subset.is_ok(),
1373                    subset_started.elapsed().as_secs_f64() * 1e3
1374                );
1375            }
1376            let result = match subset {
1377                Ok(result) => result,
1378                Err(error) => {
1379                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1380                        eprintln!("subset dropped={dropped:?} refused: {error}");
1381                    }
1382                    continue;
1383                }
1384            };
1385            if !result.validate().is_empty() {
1386                continue;
1387            }
1388            if !walls_missing(solid, &result, edge_points, &keep, radius, chamfer, entry)?.is_empty() {
1389                continue;
1390            }
1391            return Ok((
1392                result,
1393                BlendSelection {
1394                    requested: n,
1395                    applied: keep,
1396                    rejected: dropped,
1397                    reason: Some(group_err.message),
1398                },
1399            ));
1400        }
1401    }
1402    Err(group_err)
1403}
1404
1405
1406/// Which of `selected` (indices into the caller's own selection) carry NO blend
1407/// wall in `result` — decided by the MATERIAL, not by a name.
1408///
1409/// A blended edge is an edge whose material changed: a convex blend removes
1410/// the sliver under the edge, so a point of the original edge ends up OUTSIDE
1411/// the answer; a concave one pads the crease, so it ends up INSIDE. An edge
1412/// the selection dropped is still the sharp edge it was, and its points still
1413/// lie ON the skin. That statement holds for every caller and every lane,
1414/// which the previous attribution did not: it looked for one face per edge
1415/// carrying the caller's per-edge name, so a caller passing `None` (the wasm
1416/// ABI, `fillet_edges_json`) got NO count at all, and a caller passing names
1417/// was told a wall was missing where the network had merged two coaxial walls
1418/// into one face (the U-channel at half its width keeps one name for two
1419/// edges) or collapsed the walls of a full-width star into its corner patch
1420/// (`{base}:CORNER:…`, and no wall name at all). Both were measured
1421/// 2026-09-26; the named path REFUSED those complete blends.
1422///
1423/// The classifier answers `On` inside a band, so the check states how far
1424/// the blend of THIS size moves the edge at each probed station — `r·(1/cos(α/2)
1425/// − 1)` for a fillet and `d·sin(α/2)` for a chamfer, `α` the angle between the
1426/// two faces' outward normals there — and probes the station the blend moves
1427/// MOST. An edge that is tangent at one end (the miter seam two rounds leave
1428/// runs to 180° at its pole) is still attributed where it is sharp. Only when
1429/// no station clears the band is the selection refused by name, rather than
1430/// an unseeable move read as a missing wall.
1431pub fn walls_missing(
1432    original: &BrepSolid,
1433    result: &BrepSolid,
1434    edge_points: &[Vec3],
1435    selected: &[usize],
1436    size: f64,
1437    chamfer: bool,
1438    entry: &str,
1439) -> Result<Vec<usize>, KernelRefusal> {
1440    walls_missing_ties(original, result, edge_points, selected, size, chamfer, entry, false)
1441}
1442
1443// BREP lane L: begin walls_missing_tie_all_stations_20261015
1444/// [`walls_missing`], with `tie_majority`: on a clearance TIE (a uniform
1445/// dihedral, every station moving the same) the first station stands for
1446/// all of them unless this is set, when a wall is missing only if MORE THAN
1447/// HALF of the tied stations still lie on the skin (an unwalled edge whose
1448/// two ends neighbouring walls consume — the wedge nine-pick's unselected
1449/// side A ∩ wall — still reads missing; "every tied station" did not).  Only the runout composition sets it: its
1450/// own neighbouring wall may consume an edge's end (the rib nine-edge
1451/// selection's trimmed runout over the wall ∩ roof pad's first tenth read
1452/// as that pad having no wall), while elsewhere the first station is what
1453/// catches a cutter composition's wrong corners (the one-ended channel with
1454/// its runout switched off: stations ON at both ends of an edge whose middle
1455/// is walled — a measured 1253.219 against its 1253.373 body) and a station
1456/// reading alone cannot tell the two apart.
1457#[allow(clippy::too_many_arguments)]
1458pub fn walls_missing_ties(
1459    original: &BrepSolid,
1460    result: &BrepSolid,
1461    edge_points: &[Vec3],
1462    selected: &[usize],
1463    size: f64,
1464    chamfer: bool,
1465    entry: &str,
1466    tie_majority: bool,
1467) -> Result<Vec<usize>, KernelRefusal> {
1468// BREP lane L: end walls_missing_tie_all_stations_20261015
1469    use crate::{PointClass, SolidClassifier};
1470    if selected.is_empty() {
1471        return Ok(Vec::new());
1472    }
1473    let _timing = crate::blend::BlendTimer::start("timing.walls_missing_ms");
1474    crate::classification::classify_profile_begin();
1475    crate::classification::containment_profile_begin();
1476    let band = crate::KernelTolerances::for_solid(result, 1e-7).model;
1477    // `classify` reads `On` within ten times its band; attribution needs the
1478    // move to clear that by the same margin again.
1479    let visible = band * 100.0;
1480    let build_timing = crate::blend::BlendTimer::start("timing.walls_missing.classifier_ms");
1481    let classifier = SolidClassifier::new(result, band)
1482        .or_refuse(KernelStage::Validate, "wall_classifier")?;
1483    // Lane R1: a station's On-or-not is read
1484    // off its nearest face first (`NearestFaceSide`, the classifier's own On
1485    // band of ten `band`s, answering only where the read is rigorous); the
1486    // ray answers whatever it declines.
1487    let nearest = Some(super::analyze::NearestFaceSide::new(result, band).or_refuse(KernelStage::Validate, "wall_nearest_face")?);
1488    let reads_on = |point: Vec3| -> Result<bool, KernelRefusal> {
1489        if let Some(class) = nearest.as_ref().and_then(|nearest| nearest.side(point)) {
1490            crate::blend::record_count("count.walls_missing.nearest", 1);
1491            return Ok(class == PointClass::On);
1492        }
1493        Ok(classifier.classify(point).or_refuse(KernelStage::Validate, "wall_classify")?.class == PointClass::On)
1494    };
1495    build_timing.stop();
1496    const STATIONS: usize = 9;
1497    let mut missing = Vec::new();
1498    for &index in selected {
1499        let point = edge_points[index];
1500        let edge_id = resolve_edge_by_point(original, point)?;
1501        let (edge, faces) = super::analyze::edge_and_faces(original, edge_id)?;
1502        // The station the blend moves most, and how far.
1503        let mut best: Option<(Vec3, f64)> = None;
1504        // BREP lane L: begin walls_missing_tie_all_stations_20261015
1505        let mut read: Vec<(Vec3, f64)> = Vec::with_capacity(STATIONS);
1506        // BREP lane L: end walls_missing_tie_all_stations_20261015
1507        for step in 1..=STATIONS {
1508            let t = edge.t0 + (edge.t1 - edge.t0) * step as f64 / (STATIONS + 1) as f64;
1509            let Ok(station) = edge.curve.evaluate(t) else {
1510                continue;
1511            };
1512            let clearance = match faces[..] {
1513                [first, second] => {
1514                    let (Ok((_, a)), Ok((_, b))) = (
1515                        super::analyze::face_plane_normal(first, station),
1516                        super::analyze::face_plane_normal(second, station),
1517                    ) else {
1518                        continue;
1519                    };
1520                    let half: f64 = 0.5 * a.dot(b).clamp(-1.0, 1.0).acos();
1521                    if chamfer {
1522                        size * half.sin()
1523                    } else {
1524                        size * (1.0 / half.cos().max(1e-12) - 1.0)
1525                    }
1526                }
1527                // No dihedral to read: probe anyway, unguarded.
1528                _ => f64::INFINITY,
1529            };
1530            if best.map_or(true, |(_, known)| clearance > known) {
1531                best = Some((station, clearance));
1532            }
1533            // BREP lane L: begin walls_missing_tie_all_stations_20261015
1534            read.push((station, clearance));
1535            // BREP lane L: end walls_missing_tie_all_stations_20261015
1536        }
1537        let Some((station, clearance)) = best else {
1538            return Err(KernelRefusal::internal(
1539                KernelStage::Validate,
1540                "wall_attribution_stations",
1541                format!(
1542                    "{entry}: cannot attribute a wall to edge #{index} at ({:.6}, {:.6}, {:.6}) — no \
1543                     station of it could be evaluated",
1544                    point.x, point.y, point.z
1545                ),
1546            ));
1547        };
1548        if !(clearance > visible) {
1549            // The faces themselves put the move under the band: the input
1550            // leaves the attribution undecidable, and it is refused rather
1551            // than guessed.
1552            return Err(KernelRefusal::ill_posed(
1553                KernelStage::Validate,
1554                "wall_attribution_band",
1555                format!(
1556                    "{entry}: cannot attribute a wall to edge #{index} at ({:.6}, {:.6}, {:.6}) — \
1557                     its faces are so nearly tangent that a size-{size} blend moves the edge by at \
1558                     most {clearance:.3e}, inside the {visible:.3e} the classifier can see; the \
1559                     selection is refused rather than reported on a guess",
1560                    point.x, point.y, point.z
1561                ),
1562            ));
1563        }
1564        let classify_timing = crate::blend::BlendTimer::start("timing.walls_missing.classify_ms");
1565        // The question is On or not On, never In against Out: a station the
1566        // certificate below puts farther than `visible` from every face of
1567        // the result cannot read On by the classifier's band pass (a foot on
1568        // a carrier within ten bands) nor by its ray pass (a hit within ten
1569        // bands), so it is not asked. Anything the certificate declines is
1570        // classified as before.
1571        let certified = station_clear_of_skin(result, station, band * 10.0, visible)
1572            || station_clear_of_trimmed_skin(result, station, band * 10.0, visible);
1573        let on = if certified {
1574            crate::blend::record_count("count.walls_missing.certified", 1);
1575            false
1576        } else {
1577            crate::blend::record_count("count.walls_missing.classified", 1);
1578            reads_on(station)?
1579        };
1580        classify_timing.stop();
1581        // BREP lane L: begin walls_missing_tie_all_stations_20261015
1582        let on = on && (!tie_majority || {
1583            // The most-moved station read On; on a tie, so must more than
1584            // half of the tied stations (itself included).
1585            let tolerance = 1e-12 * clearance.abs().max(1.0);
1586            let (mut tied, mut on_skin) = (1usize, 1usize);
1587            for (other, other_clearance) in read.iter().copied() {
1588                if other.sub(station).length() == 0.0 || clearance - other_clearance > tolerance {
1589                    continue;
1590                }
1591                tied += 1;
1592                if !station_clear_of_skin(result, other, band * 10.0, visible) && reads_on(other)? {
1593                    on_skin += 1;
1594                }
1595            }
1596            2 * on_skin > tied
1597        });
1598        // BREP lane L: end walls_missing_tie_all_stations_20261015
1599        if on {
1600            missing.push(index);
1601        }
1602    }
1603    crate::classification::classify_profile_report("blend.walls_missing");
1604    crate::classification::containment_profile_report("blend.walls_missing");
1605    Ok(missing)
1606}
1607
1608
1609
1610/// Is `station` certainly farther than `margin` from every face of `result`,
1611/// trims included, read without a classifier query? `true` only when every
1612/// face is certified by one of three readings, each a lower bound on the
1613/// distance from the station to that face's trimmed carrier:
1614///
1615/// - its control-point box, widened by `on_band`, does not hold the station
1616///   (the carrier lies in the hull of positively weighted control points);
1617/// - its carrier is a recognised revolution (`NurbsSurface::analytic`,
1618///   matched to 1e-9 relative): a sphere or torus farther than `margin` in
1619///   closed form; a cone, cylinder or straight-generatrix partial sweep
1620///   whose PATCH is farther than `margin` by the larger of three lower
1621///   bounds, the meridian distance to the generatrix line, the axial
1622///   clearance from the generatrix's slab and the clearance from the
1623///   sweep's wedge (a station on one box edge lies ON the infinite cylinder
1624///   of each neighbouring wall, a radius from its centre line, and is a
1625///   radius short of its slab);
1626/// - its carrier is a recognised plane, the station's foot on it is
1627///   `Outside` the trims (`parameter_point_in_face`, the kernel's own lane
1628///   at the band the classifier would use), every loop pcurve is a straight
1629///   two-point unit-weight chord (so its image under the affine chart is a
1630///   straight 3-D segment, and the trim polygon is exact), and the station
1631///   is farther than `margin` from every chord's segment: a foot outside the
1632///   region is nearer to the region's boundary than to any of its points.
1633///
1634/// Any face none of the three reads (an unrecognised carrier, a plane the
1635/// station lies on whose trims are curved, a foot inside or on the trims)
1636/// declines the whole station to the classifier. The recogniser's 1e-9
1637/// relative bar sits four orders below the `margin` the caller passes
1638/// (a hundred model bands), which is what absorbs it.
1639fn station_clear_of_skin(result: &BrepSolid, station: Vec3, on_band: f64, margin: f64) -> bool {
1640    use crate::AnalyticSurface;
1641    // The station in a revolution frame: (ρ, h) in the meridian plane and
1642    // its azimuth θ in [0, 2π) from the frame's x axis.
1643    let meridian = |frame: &crate::RevolutionFrame| -> (f64, f64, f64) {
1644        let offset = station.sub(frame.origin);
1645        let axial = offset.dot(frame.axis);
1646        let radial = offset.sub(frame.axis.scale(axial));
1647        let mut azimuth = radial.dot(frame.y_axis).atan2(radial.dot(frame.x_axis));
1648        if azimuth < 0.0 {
1649            azimuth += std::f64::consts::TAU;
1650        }
1651        (radial.length(), axial, azimuth)
1652    };
1653    // A patch of a revolution lies inside the axial slab of its generatrix
1654    // and inside the wedge of its sweep, so the station's clearance from
1655    // either is a lower bound on its distance to the patch.
1656    let axial_clearance = |axial: f64, h0: f64, h1: f64| (h0.min(h1) - axial).max(axial - h0.max(h1)).max(0.0);
1657    let wedge_clearance = |radial: f64, azimuth: f64, sweep: f64| -> f64 {
1658        if sweep >= std::f64::consts::TAU || azimuth <= sweep {
1659            return 0.0;
1660        }
1661        // Outside the sweep: the angle to the nearer bounding meridian.
1662        let turn = (azimuth - sweep).min(std::f64::consts::TAU - azimuth);
1663        if turn >= std::f64::consts::FRAC_PI_2 { radial } else { radial * turn.sin() }
1664    };
1665    // Distance in the meridian plane from (ρ, h) to the LINE through two
1666    // generatrix points: a lower bound for a cone or cylinder's carrier.
1667    let line_distance = |radial: f64, axial: f64, (rho0, h0): (f64, f64), (rho1, h1): (f64, f64)| -> Option<f64> {
1668        let (du, dv) = (rho1 - rho0, h1 - h0);
1669        let length = (du * du + dv * dv).sqrt();
1670        (length > 0.0).then(|| ((radial - rho0) * dv - (axial - h0) * du).abs() / length)
1671    };
1672    let clear = |distance: f64| distance.is_finite() && distance > margin;
1673    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
1674        let Ok(controls) = crate::Aabb::from_surface_controls(&face.surface) else { return false };
1675        if !controls.expanded(on_band).contains(station) {
1676            continue;
1677        }
1678        let certified = match face.surface.analytic() {
1679            Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, height }) => {
1680                let (radial, axial, _) = meridian(frame);
1681                let Some(line) = line_distance(radial, axial, (*rho0, 0.0), (*rho1, *height)) else { return false };
1682                clear(line.max(axial_clearance(axial, 0.0, *height)))
1683            }
1684            Some(AnalyticSurface::Sphere { frame, radius }) => clear((station.sub(frame.origin).length() - radius).abs()),
1685            Some(AnalyticSurface::Torus { frame, major_radius, minor_radius }) => {
1686                let (radial, axial, _) = meridian(frame);
1687                let tube = radial - major_radius;
1688                clear(((tube * tube + axial * axial).sqrt() - minor_radius).abs())
1689            }
1690            Some(AnalyticSurface::Revolution { frame, sweep, generatrix, .. }) => {
1691                // A STRAIGHT generatrix in the frame's zero meridian (the
1692                // extruded-arc walls: a line parallel to the axis at the
1693                // radius): its two control points read as (ρ, h), and the
1694                // patch's distance is bounded below by the meridian line
1695                // distance, the axial clearance and the wedge clearance
1696                // together. A curved or off-meridian generatrix declines.
1697                let [a, b] = generatrix.control_points.as_slice() else { return false };
1698                if generatrix.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1699                    return false;
1700                }
1701                let meridian_of = |point: Vec3| -> Option<(f64, f64)> {
1702                    let offset = point.sub(frame.origin);
1703                    let axial = offset.dot(frame.axis);
1704                    let radial = offset.sub(frame.axis.scale(axial));
1705                    let rho = radial.length();
1706                    let on_meridian = radial.dot(frame.y_axis).abs() <= 1e-9 * rho.max(1.0) && radial.dot(frame.x_axis) >= -1e-9 * rho.max(1.0);
1707                    on_meridian.then_some((rho, axial))
1708                };
1709                let (Some(p0), Some(p1)) = (meridian_of(Vec3::new(a.x, a.y, a.z)), meridian_of(Vec3::new(b.x, b.y, b.z))) else {
1710                    return false;
1711                };
1712                let (radial, axial, azimuth) = meridian(frame);
1713                let Some(line) = line_distance(radial, axial, p0, p1) else { return false };
1714                // The TRIMMED face's slab is narrower than the surface's:
1715                // a station on one box edge lies on the untrimmed surface
1716                // of each perpendicular wall (that wall's rail line runs
1717                // through the corner), a radius short of its trimmed face.
1718                let slab = trimmed_axial_slab(face, frame).unwrap_or((p0.1, p1.1));
1719                clear(line.max(axial_clearance(axial, slab.0, slab.1)).max(wedge_clearance(radial, azimuth, *sweep)))
1720            }
1721            Some(plane @ AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) => {
1722                let Ok(normal) = u_dir.cross(*v_dir).normalized() else { return false };
1723                if clear(station.sub(*origin).dot(normal).abs()) {
1724                    true
1725                } else {
1726                    planar_trims_clear_of(face, plane, station, on_band, margin)
1727                }
1728            }
1729            None => false,
1730        };
1731        if !certified {
1732            return false;
1733        }
1734    }
1735    true
1736}
1737
1738/// A tighter sufficient Not-On certificate. General carriers use subdivided
1739/// positive-weight hulls. Analytic carriers retain the projector and trim
1740/// band used by the nearest-face reader; an exterior foot also needs every
1741/// exact boundary edge farther than the existing attribution margin.
1742/// Any inconclusive read leaves the original nearest/ray query in charge.
1743fn station_clear_of_trimmed_skin(result: &BrepSolid, point: Vec3, on_band: f64, margin: f64) -> bool {
1744    let _timer = crate::blend::BlendTimer::start("timing.walls_missing.trimmed_bound_ms");
1745    if !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite()
1746        || !margin.is_finite() || !(margin > on_band && on_band > 0.0)
1747    { return false; }
1748    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
1749        let Ok(bounds) = crate::Aabb::from_surface_controls(&face.surface) else { return false; };
1750        if !bounds.expanded(margin).contains(point) { continue; }
1751        if face.surface.analytic().is_none() {
1752            if general_carrier_clear(&face.surface, point, margin) { continue; }
1753            return false;
1754        }
1755        // Within `margin`, these regular carriers have a unique nearest
1756        // foot; every other stationary foot is farther than the margin.
1757        // The sphere/torus medial sets and spindle/horn tori decline. Thus
1758        // an exterior nearest foot can meet a trimmed region within the
1759        // margin only by crossing a boundary edge inside that same ball.
1760        match face.surface.analytic() {
1761            Some(crate::AnalyticSurface::Plane { .. }) => {},
1762            Some(crate::AnalyticSurface::Sphere { radius, .. }) if *radius > 4.0 * margin => {},
1763            Some(crate::AnalyticSurface::Torus { major_radius, minor_radius, .. })
1764                if *minor_radius > 4.0 * margin && *major_radius > *minor_radius + 4.0 * margin => {},
1765            _ => return false,
1766        }
1767        let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false; };
1768        if !projection.distance.is_finite() { return false; }
1769        if projection.distance > margin { continue; }
1770        let band = crate::classification::surface_uv_band(&face.surface, projection.u, projection.v, on_band);
1771        let Ok(inside) = crate::parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, band) else { return false; };
1772        if inside != crate::PolygonClass::Outside { return false; }
1773        let mut edges = 0;
1774        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1775            let Some(edge) = result.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false; };
1776            let Some(piece) = super::analyze::edge_piece(&edge.curve, edge.t0.min(edge.t1), edge.t0.max(edge.t1)) else { return false; };
1777            let Ok(foot) = crate::project_point_to_curve(&piece, point) else { return false; };
1778            if !foot.distance.is_finite() || foot.distance <= margin { return false; }
1779            edges += 1;
1780        }
1781        if edges == 0 { return false; }
1782    }
1783    true
1784}
1785
1786/// A sufficient clearance test for a general carrier, without finding its
1787/// nearest point. Positive-weight Bezier patches lie inside their control
1788/// hulls. Decompose both clamped knot vectors, then bisect only boxes still
1789/// within `margin` of the query. Any unsupported net or exhausted work budget
1790/// declines to the existing classifier; no approximate distance is accepted.
1791fn general_carrier_clear(surface: &crate::NurbsSurface, point: Vec3, margin: f64) -> bool {
1792    use crate::Vec4;
1793    let rows = surface.control_points.len();
1794    let columns = surface.control_points.first().map_or(0, Vec::len);
1795    if rows == 0 || columns == 0 || rows.saturating_mul(columns) > 4096
1796        || surface.degree_u > 16 || surface.degree_v > 16 || surface.control_points.iter().any(|row| row.len() != columns)
1797        || !margin.is_finite() || margin <= 0.0
1798        || !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite()
1799    { return false; }
1800    let mut scale = 1.0_f64;
1801    for control in surface.control_points.iter().flatten() {
1802        if !(control.w > 0.0) || !control.w.is_finite() { return false; }
1803        let Ok(p) = control.point() else { return false; };
1804        if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { return false; }
1805        scale = scale.max(p.x.abs()).max(p.y.abs()).max(p.z.abs());
1806    }
1807    // Leave a rounding cushion far below the caller's existing model margin.
1808    // Unsupported scales decline rather than consume the classification band.
1809    let roundoff = 256.0 * f64::EPSILON * scale * (surface.degree_u + 1) as f64 * (surface.degree_v + 1) as f64;
1810    if roundoff >= margin * 0.01 { return false; }
1811    let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1812    let blend = |a: Vec4, b: Vec4, alpha: f64| a.scale(alpha).add(b.scale(1.0 - alpha));
1813    let mut fibres = Vec::with_capacity(columns);
1814    for column in 0..columns {
1815        let controls: Vec<_> = surface.control_points.iter().map(|row| row[column]).collect();
1816        let Some(spans) = crate::curve::bezier_decompose_raw(&surface.knots_u, &controls, surface.degree_u, zero, blend) else { return false; };
1817        fibres.push(spans);
1818    }
1819    let mut budget = 256usize;
1820    for u_span in 0..fibres[0].len() {
1821        let mut across = Vec::with_capacity(surface.degree_u + 1);
1822        for row in 0..=surface.degree_u {
1823            let controls: Vec<_> = fibres.iter().map(|fibre| fibre[u_span][row]).collect();
1824            let Some(spans) = crate::curve::bezier_decompose_raw(&surface.knots_v, &controls, surface.degree_v, zero, blend) else { return false; };
1825            across.push(spans);
1826        }
1827        for v_span in 0..across[0].len() {
1828            let net = across.iter().map(|row| row[v_span].clone()).collect();
1829            if !bezier_box_clear(net, point, margin + roundoff, 0, &mut budget) { return false; }
1830        }
1831    }
1832    true
1833}
1834
1835fn bezier_box_clear(net: Vec<Vec<crate::Vec4>>, point: Vec3, margin: f64, depth: usize, budget: &mut usize) -> bool {
1836    if *budget == 0 { return false; }
1837    *budget -= 1;
1838    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
1839    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
1840    for control in net.iter().flatten() {
1841        if !(control.w > 0.0) || !control.w.is_finite() { return false; }
1842        let Ok(p) = control.point() else { return false; };
1843        if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { return false; }
1844        low.x = low.x.min(p.x); low.y = low.y.min(p.y); low.z = low.z.min(p.z);
1845        high.x = high.x.max(p.x); high.y = high.y.max(p.y); high.z = high.z.max(p.z);
1846    }
1847    // One separating coordinate is enough, and avoids a rounded square root.
1848    if point.x < low.x - margin || point.x > high.x + margin
1849        || point.y < low.y - margin || point.y > high.y + margin
1850        || point.z < low.z - margin || point.z > high.z + margin
1851    { return true; }
1852    if depth == 10 { return false; }
1853    let rows = net.len();
1854    let columns = net[0].len();
1855    let mut left = net.clone();
1856    let mut right = net.clone();
1857    // Alternate directions: every child covers exactly half the parent's
1858    // parameter rectangle; both must prove clearance.
1859    if depth % 2 == 0 {
1860        for column in 0..columns {
1861            let mut work: Vec<_> = net.iter().map(|row| row[column]).collect();
1862            for level in 1..rows {
1863                for i in 0..rows - level { work[i] = work[i].scale(0.5).add(work[i + 1].scale(0.5)); }
1864                left[level][column] = work[0];
1865                right[rows - level - 1][column] = work[rows - level - 1];
1866            }
1867        }
1868    } else {
1869        for row in 0..rows {
1870            let mut work = net[row].clone();
1871            for level in 1..columns {
1872                for i in 0..columns - level { work[i] = work[i].scale(0.5).add(work[i + 1].scale(0.5)); }
1873                left[row][level] = work[0];
1874                right[row][columns - level - 1] = work[columns - level - 1];
1875            }
1876        }
1877    }
1878    bezier_box_clear(left, point, margin, depth + 1, budget)
1879        && bezier_box_clear(right, point, margin, depth + 1, budget)
1880}
1881
1882/// The axial range `(h_low, h_high)` of a face's TRIMMED region on a
1883/// revolution whose generatrix is straight: the region lies in the uv box
1884/// of its straight-chord loops (every pcurve a two-point unit-weight
1885/// chord), the surface is a tensor product in which the axial coordinate
1886/// `h = (S − origin)·axis` depends on one parameter only and affinely
1887/// (degree 1, two control points along it), so `h` over the box is the
1888/// range between its values at the box's corners. `None` when any of that
1889/// is not read: a curved chord, an `h` that moves along both parameters,
1890/// a degree or control count that is not affine, an evaluation that fails.
1891fn trimmed_axial_slab(face: &FaceRecord, frame: &crate::RevolutionFrame) -> Option<(f64, f64)> {
1892    let (mut u_low, mut u_high, mut v_low, mut v_high) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
1893    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1894        let pcurve = &coedge.pcurve;
1895        let [a, b] = pcurve.control_points.as_slice() else { return None };
1896        if pcurve.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1897            return None;
1898        }
1899        for control in [a, b] {
1900            u_low = u_low.min(control.x);
1901            u_high = u_high.max(control.x);
1902            v_low = v_low.min(control.y);
1903            v_high = v_high.max(control.y);
1904        }
1905    }
1906    if !(u_low <= u_high && v_low <= v_high) {
1907        return None;
1908    }
1909    let axial_at = |u: f64, v: f64| face.surface.evaluate(u, v).ok().map(|point| point.sub(frame.origin).dot(frame.axis));
1910    let corners = [axial_at(u_low, v_low)?, axial_at(u_high, v_low)?, axial_at(u_low, v_high)?, axial_at(u_high, v_high)?];
1911    let scale = corners.iter().fold(1.0_f64, |scale, h| scale.max(h.abs()));
1912    let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * scale;
1913    let surface = &face.surface;
1914    // h constant along u (the generatrix runs along v), or along v.
1915    let affine_in_v = same(corners[0], corners[1]) && same(corners[2], corners[3])
1916        && surface.degree_v == 1 && surface.control_points.first().is_some_and(|row| row.len() == 2);
1917    let affine_in_u = same(corners[0], corners[2]) && same(corners[1], corners[3])
1918        && surface.degree_u == 1 && surface.control_points.len() == 2;
1919    if !(affine_in_v || affine_in_u) {
1920        return None;
1921    }
1922    let low = corners.iter().copied().fold(f64::INFINITY, f64::min);
1923    let high = corners.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1924    (low.is_finite() && high.is_finite()).then_some((low, high))
1925}
1926
1927/// The planar reading of [`station_clear_of_skin`]: the station's foot on
1928/// the plane lies `Outside` the face's trims and every straight loop chord's
1929/// 3-D segment is farther than `margin` from the station.
1930fn planar_trims_clear_of(
1931    face: &FaceRecord,
1932    plane: &crate::AnalyticSurface,
1933    station: Vec3,
1934    on_band: f64,
1935    margin: f64,
1936) -> bool {
1937    use crate::PolygonClass;
1938    let Some(foot) = plane.project(&face.surface, station) else { return false };
1939    let uv_band = crate::classification::surface_uv_band(&face.surface, foot.u, foot.v, on_band);
1940    match crate::parameter_point_in_face(face, crate::Vec2 { x: foot.u, y: foot.v }, uv_band) {
1941        Ok(PolygonClass::Outside) => {}
1942        _ => return false,
1943    }
1944    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1945        let pcurve = &coedge.pcurve;
1946        let [a, b] = pcurve.control_points.as_slice() else { return false };
1947        if pcurve.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1948            return false;
1949        }
1950        let (Ok(start), Ok(end)) = (face.surface.evaluate(a.x, a.y), face.surface.evaluate(b.x, b.y)) else { return false };
1951        let chord = end.sub(start);
1952        let length_squared = chord.dot(chord);
1953        let offset = station.sub(start);
1954        let along = if length_squared > 0.0 { (offset.dot(chord) / length_squared).clamp(0.0, 1.0) } else { 0.0 };
1955        let distance = offset.sub(chord.scale(along)).length();
1956        if !(distance.is_finite() && distance > margin) {
1957            return false;
1958        }
1959    }
1960    true
1961}
1962
1963/// The blend-FACE name for the `i`-th selected edge: its per-edge name when the
1964/// caller supplied the parallel `edge_names` (feature path — each wall named
1965/// after its originating edge, `{fid}:BLEND:{edge}`), else the single base
1966/// `name` for every wall (the legacy/test path, byte-identical to before).
1967fn per_edge_name<'a>(
1968    edge_names: Option<&'a [String]>,
1969    base: Option<&'a str>,
1970    i: usize,
1971) -> Option<&'a str> {
1972    match edge_names {
1973        Some(names) => names.get(i).map(|value| value.as_str()),
1974        None => base,
1975    }
1976}
1977
1978/// The star-corner patch name: `{base}:CORNER:{sorted+join of adjacent edge
1979/// names}` when per-edge names were supplied (feature path), else the single
1980/// `base` (legacy/test path — the corner keeps the wall name, pre-change
1981/// behavior).  `base` is `{fid}:BLEND` and each `edge_names[i]` is the composed
1982/// `{fid}:BLEND:{edge}`, so stripping the `{base}:` prefix recovers the bare
1983/// originating-edge name for the join.  Unique per corner: two distinct corners
1984/// never share the same set of >=3 selected edges.
1985fn corner_face_name(
1986    edge_names: Option<&[String]>,
1987    base: Option<&str>,
1988    adjacent: &[usize],
1989) -> Option<String> {
1990    match (edge_names, base) {
1991        (Some(names), Some(base)) => {
1992            let prefix = format!("{base}:");
1993            let mut raws: Vec<&str> = adjacent
1994                .iter()
1995                .filter_map(|&i| names.get(i))
1996                .map(|composed| composed.strip_prefix(&prefix).unwrap_or(composed.as_str()))
1997                .collect();
1998            raws.sort_unstable();
1999            raws.dedup();
2000            Some(format!("{base}:CORNER:{}", raws.join("+")))
2001        }
2002        _ => base.map(|value| value.to_string()),
2003    }
2004}
2005
2006/// Round a connected group of convex edges first, including its ordinary
2007/// convex corner patches, then blend the concave rim across a curved bridge
2008/// at each transverse mixed corner. The spine's carriers and the cap may be
2009/// planes or curved analytic faces alike: transversality is read from the
2010/// three normals at the corner, and the rim network marches the bridge on the
2011/// actual carriers. Without these bridges the rim stripes would remain
2012/// disconnected. Redispatch the remaining selection: other mixed corners may
2013/// need another convex group or a pole-to-pole runout.
2014/// Each step removes the rounded group from the pending selection.
2015#[allow(clippy::too_many_arguments)]
2016fn rounded_boss_composition(
2017    solid: &BrepSolid,
2018    selected_ids: &[u64],
2019    edge_points: &[Vec3],
2020    edge_names: Option<&[String]>,
2021    radius: f64,
2022    name: Option<&str>,
2023    corners: &[crate::blend::MixedCorner],
2024) -> Result<BrepSolid, KernelRefusal> {
2025    // The legacy API gives every wall the same base name (or none). Use
2026    // distinct temporary identities through the recursive composition so a
2027    // bridge can be attributed to its own convex wall. Restore that API's
2028    // naming contract after the whole selection has been built.
2029    if edge_names.is_none() {
2030        let prefix = "FILLET:COMPOSITION";
2031        let names: Vec<_> = selected_ids
2032            .iter()
2033            .map(|id| format!("{prefix}:{id}"))
2034            .collect();
2035        let mut result = rounded_boss_composition(
2036            solid,
2037            selected_ids,
2038            edge_points,
2039            Some(&names),
2040            radius,
2041            Some(prefix),
2042            corners,
2043        )?;
2044        for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
2045            if face
2046                .name
2047                .as_deref()
2048                .is_some_and(|value| value.starts_with("FILLET:COMPOSITION:"))
2049            {
2050                face.name = name.map(str::to_owned);
2051            }
2052        }
2053        return Ok(result);
2054    }
2055    let decline = || {
2056        KernelRefusal::unsupported(KernelStage::Classify, "rounded_boss_selection",
2057        "the rounded boss composition requires a convex group meeting transverse mixed corners at one end of each spine")
2058    };
2059    if std::env::var("BREP_NO_NETWORK").is_ok() {
2060        return Err(decline());
2061    }
2062    // Select by topology id so reversing the requested edges preserves the
2063    // construction order. Two-ended spines are left for runout composition.
2064    let corner = corners
2065        .iter()
2066        .filter(|corner| {
2067            corner.convex.len() == 1
2068                && corner.concave.len() == 2
2069                && corners
2070                    .iter()
2071                    .filter(|other| other.convex.contains(&corner.convex[0]))
2072                    .count()
2073                    == 1
2074        })
2075        .min_by_key(|corner| selected_ids[corner.convex[0]])
2076        .ok_or_else(decline)?;
2077    let convexity =
2078        crate::blend::selection_convexity(solid, selected_ids, radius).ok_or_else(decline)?;
2079    if !convexity[corner.convex[0]] {
2080        return Err(decline());
2081    }
2082    let spine_index = corner.convex[0];
2083    // Resolve once so a missing selected edge refuses before connectivity
2084    // traversal rather than panicking inside the adjacency predicate.
2085    let selected_edges: Vec<&EdgeRecord> = selected_ids
2086        .iter()
2087        .map(|id| {
2088            solid
2089                .edges
2090                .iter()
2091                .find(|edge| edge.id == *id)
2092                .ok_or_else(|| {
2093                    KernelRefusal::internal(
2094                        KernelStage::Collect,
2095                        "rounded_boss_selected_edge",
2096                        format!("rounded boss composition: selected edge {id} is missing"),
2097                    )
2098                })
2099        })
2100        .collect::<Result<_, _>>()?;
2101    // Round the connected convex selection together. Its far corners need
2102    // their usual vertex patches before a concave rim can cross these walls.
2103    let mut rounded_indices = vec![spine_index];
2104    loop {
2105        let next = (0..selected_ids.len()).find(|index| {
2106            convexity[*index]
2107                && !rounded_indices.contains(index)
2108                && rounded_indices.iter().any(|other| {
2109                    let edge = selected_edges[*index];
2110                    let mate = selected_edges[*other];
2111                    [edge.start_vertex_id, edge.end_vertex_id]
2112                        .iter()
2113                        .any(|v| *v == mate.start_vertex_id || *v == mate.end_vertex_id)
2114                })
2115        });
2116        match next {
2117            Some(index) => rounded_indices.push(index),
2118            None => break,
2119        }
2120    }
2121    // Keep complete stars together. A selected concave edge between two
2122    // convex rims is part of their vertex blend, even though it is not part
2123    // of the convex flood above. Rounding the rims without it builds a horn
2124    // torus for an *unselected* third edge; adding that edge later leaves a
2125    // flat cap against the torus instead of the selected star's tangent sector.
2126    // Only absorb an edge whose selected neighbours are already in this
2127    // group at BOTH ends. In particular, never pull in a concave rim leading
2128    // to another mixed corner: that rim still needs the bridge below.
2129    loop {
2130        let next = (0..selected_ids.len()).find(|&index| {
2131            if convexity[index] || rounded_indices.contains(&index) {
2132                return false;
2133            }
2134            let edge = selected_edges[index];
2135            let mut has_star = false;
2136            for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
2137                let neighbours: Vec<_> = selected_edges.iter().enumerate()
2138                    .filter(|(other, mate)| *other != index
2139                        && (mate.start_vertex_id == vertex || mate.end_vertex_id == vertex))
2140                    .map(|(other, _)| other)
2141                    .collect();
2142                if neighbours.iter().any(|other| !rounded_indices.contains(other)) {
2143                    return false;
2144                }
2145                has_star |= neighbours.len() >= 2;
2146            }
2147            has_star
2148        });
2149        match next {
2150            Some(index) => rounded_indices.push(index),
2151            None => break,
2152        }
2153    }
2154    rounded_indices.sort_by_key(|index| selected_ids[*index]);
2155    let mixed: Vec<_> = corners
2156        .iter()
2157        .filter(|corner| {
2158            corner
2159                .convex
2160                .iter()
2161                .any(|index| rounded_indices.contains(index))
2162        })
2163        .collect();
2164    if mixed.iter().any(|corner| {
2165        corner.convex.len() != 1
2166            || corner.concave.len() != 2
2167            || corners
2168                .iter()
2169                .filter(|other| other.convex.contains(&corner.convex[0]))
2170                .count()
2171                != 1
2172    }) {
2173        return Err(decline());
2174    }
2175    let uses = |face: &FaceRecord, edge: u64| {
2176        face.loops
2177            .iter()
2178            .flat_map(|rim| &rim.coedges)
2179            .any(|coedge| coedge.edge_id == edge)
2180    };
2181    let mut caps = Vec::new();
2182    for corner in &mixed {
2183        let spine_id = selected_ids[corner.convex[0]];
2184        let cap = solid
2185            .shells
2186            .iter()
2187            .flat_map(|shell| &shell.faces)
2188            .find(|face| {
2189                corner
2190                    .concave
2191                    .iter()
2192                    .all(|index| uses(face, selected_ids[*index]))
2193            })
2194            .ok_or_else(decline)?;
2195        let faces: Vec<_> = solid
2196            .shells
2197            .iter()
2198            .flat_map(|shell| &shell.faces)
2199            .filter(|face| face.id == cap.id || uses(face, spine_id))
2200            .collect();
2201        // The normals at the corner: a plane's from its frame, any other
2202        // carrier's at the corner's own foot on it.  The 2026-10-12 sprocket
2203        // report (`inbox_20261012_sprocket_fillet`) was the first curved CAP;
2204        // the 2026-10-13 reports on the same part put the SPINE on a cylinder
2205        // (the rim top's arc, rim wall ∩ rim top, dying into the spoke wall)
2206        // and were declined here before anything was tried, which handed the
2207        // whole selection to the runout lane and its refusal
2208        // (`inbox_20261013_sprocket_spoke_fillet`).
2209        let normals: Option<Vec<Vec3>> = faces
2210            .iter()
2211            .map(|face| match face.surface.analytic() {
2212                Some(crate::AnalyticSurface::Plane { u_dir, v_dir, .. }) => {
2213                    u_dir.cross(*v_dir).normalized().ok()
2214                }
2215                _ => {
2216                    let uv = crate::project_point_to_surface(&face.surface, corner.point).ok()?;
2217                    face.surface.normal(uv.u, uv.v).ok()
2218                }
2219            })
2220            .collect();
2221        let normals = normals.ok_or_else(decline)?;
2222        // The cap need not be perpendicular to the spine's two carriers.
2223        // An oblique or cylindrical cap cuts the rounded wall in a curved
2224        // bridge. The rim network marches that bridge on the actual carriers.
2225        // Test transversality at the corner; a cylindrical cap need not be
2226        // replaced by its tangent plane to build this composition.
2227        if normals.len() != 3
2228            || normals[0].cross(normals[1]).dot(normals[2]).abs() < 1e-6
2229        {
2230            return Err(decline());
2231        }
2232        caps.push(cap.id);
2233    }
2234    // Give unnamed walls distinct identities too: bridges are located by
2235    // their two carriers, never proximity to the old corner.
2236    let rounded_names: Vec<String> = rounded_indices
2237        .iter()
2238        .map(|index| {
2239            per_edge_name(edge_names, name, *index)
2240                .map(str::to_owned)
2241                .unwrap_or_else(|| format!("FILLET:ROUNDED_BOSS_SPINE:{index}"))
2242        })
2243        .collect();
2244    let rounded_points: Vec<Vec3> = rounded_indices
2245        .iter()
2246        .map(|index| edge_points[*index])
2247        .collect();
2248    let rounded = fillet_edges_group_in(
2249        solid,
2250        &rounded_points,
2251        Some(&rounded_names),
2252        radius,
2253        false,
2254        name,
2255        None,
2256    )?;
2257    let mut bridges = Vec::new();
2258    for (corner, cap) in mixed.iter().zip(&caps) {
2259        let wall_index = rounded_indices
2260            .iter()
2261            .position(|index| *index == corner.convex[0])
2262            .ok_or_else(|| {
2263                KernelRefusal::internal(
2264                    KernelStage::Classify,
2265                    "rounded_boss_bridge_wall",
2266                    format!(
2267                        "rounded boss composition: no convex wall for corner {}",
2268                        corner.vertex
2269                    ),
2270                )
2271            })?;
2272        let candidates: Vec<_> = rounded
2273            .edges
2274            .iter()
2275            .filter(|edge| {
2276                let faces: Vec<_> = rounded
2277                    .shells
2278                    .iter()
2279                    .flat_map(|shell| &shell.faces)
2280                    .filter(|face| uses(face, edge.id))
2281                    .collect();
2282                faces.iter().any(|face| face.id == *cap)
2283                    && faces
2284                        .iter()
2285                        .any(|face| face.name.as_deref() == Some(&rounded_names[wall_index]))
2286            })
2287            .collect();
2288        if candidates.len() != 1 {
2289            return Err(decline());
2290        }
2291        bridges.push(candidates[0]);
2292    }
2293    let rim_ids: Vec<u64> = selected_ids
2294        .iter()
2295        .enumerate()
2296        .filter(|(index, _)| !rounded_indices.contains(index))
2297        .map(|(_, id)| *id)
2298        .collect();
2299    // Both ends must join requested rim edges: never extend a selection
2300    // into an unselected perimeter.
2301    if !bridges.iter().all(|bridge| {
2302        [bridge.start_vertex_id, bridge.end_vertex_id]
2303            .iter()
2304            .all(|vertex| {
2305                rounded.edges.iter().any(|edge| {
2306                    rim_ids.contains(&edge.id)
2307                        && (edge.start_vertex_id == *vertex || edge.end_vertex_id == *vertex)
2308                })
2309            })
2310    }) {
2311        return Err(decline());
2312    }
2313    let mut points = Vec::new();
2314    let mut names = Vec::new();
2315    for (index, id) in selected_ids.iter().enumerate() {
2316        if rounded_indices.contains(&index) {
2317            continue;
2318        }
2319        let edge = rounded
2320            .edges
2321            .iter()
2322            .find(|edge| edge.id == *id)
2323            .ok_or_else(decline)?;
2324        points.push(
2325            edge.curve
2326                .evaluate(0.5 * (edge.t0 + edge.t1))
2327                .or_refuse(KernelStage::Collect, "rim_midpoint")?,
2328        );
2329        names.push(
2330            per_edge_name(edge_names, name, index)
2331                .unwrap_or("FILLET:RIM")
2332                .to_owned(),
2333        );
2334    }
2335    for (corner, bridge) in mixed.iter().zip(&bridges) {
2336        points.push(
2337            bridge
2338                .curve
2339                .evaluate(0.5 * (bridge.t0 + bridge.t1))
2340                .or_refuse(KernelStage::Collect, "bridge_midpoint")?,
2341        );
2342        let mut adjacent = corner.concave.clone();
2343        adjacent.push(corner.convex[0]);
2344        names.push(
2345            corner_face_name(edge_names, name, &adjacent)
2346                .unwrap_or_else(|| format!("FILLET:BOSS_CORNER:{}", corner.vertex)),
2347        );
2348    }
2349    // A partial rim would leave an open mixed-corner construction. Require
2350    // every pending wall, including each bridge, before accepting composition.
2351    fillet_edges_reported(&rounded, &points, Some(&names), radius, false, name).and_then(
2352        |(result, selection)| {
2353            if selection.applied.len() != points.len() {
2354                Err(decline())
2355            } else {
2356                Ok(result)
2357            }
2358        },
2359    )
2360}
2361
2362// A corner with two concave edges and a convex one requires composition.
2363//
2364// Where selected edges meet, the rolling ball has to touch every face around
2365// the vertex from ONE side. A convex edge running into the concave edges it
2366// meets (a rib spine dying into the fillets at its own base) asks the ball to
2367// sit under the shared face for one blend and over it for the other, so no
2368// ball seats there and the corner has no closure: physically the convex blend
2369// runs out against the concave beads partway along the edge, which is a vertex
2370// blend the stripe network does not construct.
2371//
2372// The re-entrant vertex of a notch — ONE concave edge, the rest convex — is
2373// NOT this: the ball rolls round that single concave edge from one convex
2374// blend to the next, and `round_concave_chain_corner` / `round_convex_corner`
2375// close it with the horn-torus sector.  Only its mirror is refused.
2376//
2377// This is TERMINAL — deliberately not a fall-through to the cutter
2378// composition. The cutter answers this shape with a watertight but shredded
2379// solid: a sliver end cap at each unclosed corner and the carrier face split
2380// so the original name lands on a fragment, which breaks every downstream
2381// reference to it. A named refusal that says which edges to separate is
2382// worth more than that solid. The runout composition (the 2026-09-30 record
2383// §5): a selection whose convex edges die into concave ones at
2384// mixed-convexity corners is built in two stages — the CONCAVE edges first,
2385// through the ordinary group path (exactly the ring the user gets selecting
2386// them alone), then one runout wall per convex spine on that ring result,
2387// marched from pole to pole with its carriers switching onto the ring's own
2388// pads. Accepted under the network's own checks.
2389//
2390// The class built here: every convex edge of the selection ends on a mixed
2391// corner at BOTH ends and shares no vertex with another convex edge, and
2392// every other selected edge is concave.  Anything else keeps the named
2393// refusal.
2394#[allow(clippy::too_many_arguments)]
2395/// The OPEN-PAD composition (the 2026-10-17 "fillet takes way too long"
2396/// face-ring report): a selection whose every mixed corner is ONE convex edge
2397/// meeting ONE concave edge over the planar face they share, the third edge
2398/// at the corner either a tangent rail (the convex edge is a blend's own end
2399/// cut by the plane, the concave one the boss it was blended to: a zero-angle
2400/// sliver on the plane) or a sharp concave edge (the boss meeting the convex
2401/// edge's other mate). Neither the rounded-boss nor the runout composition
2402/// admits it (flush-joined convex chains, concave pads ending at the corners,
2403/// no concave ring).
2404///
2405/// Built in two stages on the stripe network, each an ordinary group build:
2406///
2407/// 1. Every CONVEX edge first. A convex chain's free end at a mixed corner
2408///    is the §6.9 transverse construction against the boss as the end face:
2409///    the wall is trimmed where its envelope enters the boss, the sliver tip
2410///    of the planar face goes, and the boss skin that lay under it is exposed
2411///    along the trim curve (no cliff: the trim runs from the wall's floor
2412///    rail to its rail on the other mate, which at a tangent-rail corner
2413///    lands on that rail where wall and boss are tangent).
2414/// 2. Every CONCAVE edge on the stage-1 body, EXTENDED by the trim curves it
2415///    now continues into G1 at each trimmed end (floor|boss into wall|boss
2416///    across the wall's floor rail, a tangent seam): a flush join with a seam
2417///    at the trim's start, and at the trim's far end a pole where the wall
2418///    is tangent to the boss, or a cap where the trim meets an unselected
2419///    sharp edge. The pad rides the wall past the floor rails' crossing.
2420///
2421/// The walls are named after their edges; a trim continuation is named
2422/// `{base}:RUNOUT:{pad}+{wall}` from the two bare edge names.
2423#[allow(clippy::too_many_arguments)]
2424fn open_pad_composition(
2425    solid: &BrepSolid,
2426    selected_ids: &[u64],
2427    edge_points: &[Vec3],
2428    edge_names: Option<&[String]>,
2429    radius: f64,
2430    name: Option<&str>,
2431    corners: &[crate::blend::MixedCorner],
2432    entry: &str,
2433) -> Result<BrepSolid, KernelRefusal> {
2434    let shape = |message: String| KernelRefusal::unsupported(KernelStage::Classify, "open_pad_shape", message);
2435    if std::env::var("BREP_NO_NETWORK").is_ok() {
2436        return Err(shape("the open-pad composition is a network construction and BREP_NO_NETWORK is set".into()));
2437    }
2438    if corners.is_empty() || corners.iter().any(|corner| corner.convex.len() != 1 || corner.concave.len() != 1) {
2439        return Err(shape("the open-pad composition is built for corners of one convex and one concave edge".into()));
2440    }
2441    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2442        .ok_or_else(|| shape("the selection's convexity could not be read edge by edge".into()))?;
2443    let concave: Vec<usize> = (0..selected_ids.len()).filter(|index| !convexity[*index]).collect();
2444    let convex: Vec<usize> = (0..selected_ids.len()).filter(|index| convexity[*index]).collect();
2445    if concave.is_empty() || convex.is_empty() {
2446        return Err(shape("the open-pad composition needs convex and concave edges".into()));
2447    }
2448    // Every concave edge ends at mixed corners (an open pad), and the face
2449    // the two edges share at each corner is planar.
2450    let mates = crate::blend::selection_mates(solid, selected_ids, radius)
2451        .map_err(|error| shape(format!("the selection's mates could not be read: {error}")))?;
2452    for corner in corners {
2453        let (_, convex_faces) = &mates[corner.convex[0]];
2454        let (_, concave_faces) = &mates[corner.concave[0]];
2455        let Some(shared) = convex_faces.iter().find(|face| concave_faces.iter().any(|other| other.id == face.id)) else {
2456            return Err(shape(format!("the two edges at vertex {} share no face", corner.vertex)));
2457        };
2458        if !matches!(shared.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) {
2459            return Err(shape(format!("the face {} the edges share at vertex {} is not planar", shared.id, corner.vertex)));
2460        }
2461    }
2462    for &index in &concave {
2463        let edge = mates[index].0;
2464        for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
2465            if !corners.iter().any(|corner| corner.vertex == vertex && corner.concave[0] == index) {
2466                return Err(shape(format!(
2467                    "concave {} does not end at a mixed corner at vertex {vertex}; the open-pad composition is built for pads that do",
2468                    selection_label(index, edge_points, edge_names, name)
2469                )));
2470            }
2471        }
2472    }
2473    let base = name.unwrap_or("FILLET:OPEN_PAD");
2474    let bare = |index: usize| -> String {
2475        per_edge_name(edge_names, name, index)
2476            .map(|composed| composed.strip_prefix(&format!("{base}:")).unwrap_or(composed).to_string())
2477            .unwrap_or_else(|| selected_ids[index].to_string())
2478    };
2479    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2480
2481    // ---- Stage 1: the convex edges, as the group they are. ----
2482    let convex_points: Vec<Vec3> = convex.iter().map(|index| edge_points[*index]).collect();
2483    let convex_names: Vec<String> = convex
2484        .iter()
2485        .map(|index| per_edge_name(edge_names, name, *index).map(str::to_owned).unwrap_or_else(|| format!("{base}:WALL:{}", selected_ids[*index])))
2486        .collect();
2487    // Stage 1's body is an intermediate: the bowtie and soundness scans run
2488    // once, on stage 2's body (and the caller's acceptance after it), not on
2489    // a body the pads are about to change (1.2 s of tessellation on the
2490    // reported ring).
2491    // Both stages run as the open-pad composition's network
2492    // (`with_open_pad_network`: carrier-boundary stations, the march
2493    // extended to a section end outside the overshoot); no other network
2494    // takes those, so every body the plain network built stays as it was.
2495    let stage1 = crate::blend::with_open_pad_network(|| {
2496        fillet_edges_group_with_corner_policy(solid, &convex_points, Some(&convex_names), radius, false, name, None, true, false)
2497    })
2498    .map_err(|error| error.with_message(|error| format!("open-pad composition, the convex walls: {error}")))?;
2499    if debug {
2500        eprintln!("open-pad composition: stage 1 built the {} convex walls", convex.len());
2501    }
2502
2503    // ---- Stage 2: each pad with its trim continuations, on the stage-1 body. ----
2504    let uses = |face: &FaceRecord, edge_id: u64| face.loops.iter().flat_map(|l| &l.coedges).any(|c| c.edge_id == edge_id);
2505    let mut points: Vec<Vec3> = Vec::new();
2506    let mut names: Vec<String> = Vec::new();
2507    for &index in &concave {
2508        let (edge, faces) = &mates[index];
2509        let boss_id = if matches!(faces[0].surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) { faces[1].id } else { faces[0].id };
2510        let pad = stage1
2511            .edges
2512            .iter()
2513            .find(|candidate| candidate.id == edge.id)
2514            .ok_or_else(|| KernelRefusal::internal(KernelStage::Classify, "open_pad_edge", format!(
2515                "open-pad composition: concave edge {} vanished from the stage-1 body", edge.id
2516            )))?;
2517        points.push(pad.curve.evaluate(0.5 * (pad.t0 + pad.t1)).or_refuse(KernelStage::Collect, "pad_midpoint")?);
2518        names.push(per_edge_name(edge_names, name, index).map(str::to_owned).unwrap_or_else(|| format!("{base}:PAD:{}", edge.id)));
2519        // The trim continuations: at each end of the (trimmed) pad, the edge
2520        // that borders the boss and a stage-1 wall.
2521        for vertex in [pad.start_vertex_id, pad.end_vertex_id] {
2522            let trims: Vec<&EdgeRecord> = stage1
2523                .edges
2524                .iter()
2525                .filter(|candidate| {
2526                    candidate.id != pad.id
2527                        && !candidate.degenerate
2528                        && (candidate.start_vertex_id == vertex || candidate.end_vertex_id == vertex)
2529                })
2530                .filter(|candidate| {
2531                    let faces: Vec<&FaceRecord> = stage1.shells.iter().flat_map(|shell| &shell.faces).filter(|face| uses(face, candidate.id)).collect();
2532                    faces.iter().any(|face| face.id == boss_id)
2533                        && faces.iter().any(|face| face.name.as_deref().is_some_and(|value| convex_names.iter().any(|wall| wall == value)))
2534                })
2535                .collect();
2536            match trims.as_slice() {
2537                [trim] => {
2538                    let wall_name = stage1
2539                        .shells
2540                        .iter()
2541                        .flat_map(|shell| &shell.faces)
2542                        .filter(|face| uses(face, trim.id))
2543                        .find_map(|face| face.name.clone().filter(|value| convex_names.contains(value)))
2544                        .unwrap_or_default();
2545                    let wall_bare = wall_name.strip_prefix(&format!("{base}:")).unwrap_or(&wall_name).to_string();
2546                    points.push(trim.curve.evaluate(0.5 * (trim.t0 + trim.t1)).or_refuse(KernelStage::Collect, "trim_midpoint")?);
2547                    names.push(format!("{base}:RUNOUT:{}+{wall_bare}", bare(index)));
2548                    if debug {
2549                        eprintln!("open-pad composition: pad {} continues into trim edge {} (wall {wall_name}) at vertex {vertex}", edge.id, trim.id);
2550                    }
2551                }
2552                [] => {
2553                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "open_pad_trim", format!(
2554                        "open-pad composition: at vertex {vertex} the concave {} meets no trim curve of a stage-1 wall on the boss",
2555                        selection_label(index, edge_points, edge_names, name)
2556                    )));
2557                }
2558                _ => {
2559                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "open_pad_trim", format!(
2560                        "open-pad composition: at vertex {vertex} the concave {} meets {} trim curves",
2561                        selection_label(index, edge_points, edge_names, name), trims.len()
2562                    )));
2563                }
2564            }
2565        }
2566    }
2567    let result = crate::blend::with_open_pad_network(|| fillet_edges_group_in(&stage1, &points, Some(&names), radius, false, name, None))
2568        .map_err(|error| error.with_message(|error| format!("open-pad composition, the pads on the walls: {error}")))?;
2569    let _ = entry;
2570    Ok(result)
2571}
2572
2573/// The CUSP composition (2026-10-24/25 reports 80c5d9d1 and 6dfd5a22): a
2574/// selection whose every mixed corner is a CUSP — a convex edge and a concave
2575/// edge leaving the vertex tangent to each other, the face they share
2576/// narrowing to zero width between them. Report 6dfd5a22 selects the whole
2577/// of E6's start-face sliver outside F2's r 5 round: its two straight convex
2578/// edges run on G1 into the concave arc at both tips.
2579///
2580/// No other composition admits it: the pads of the open-pad composition
2581/// trim into the boss, and here both blends must TAPER to the tip, each
2582/// against the face the other leaves. Built in two stages, each an ordinary
2583/// group build, the order report 80c5d9d1 took by hand (F9, then F10):
2584///
2585/// 1. Every CONCAVE edge first: its round tapers to zero at each cusp
2586///    (`blend/taper_runout.rs`), leaving a hairline of the shared face
2587///    beside it.
2588/// 2. Every CONVEX edge on the stage-1 body: its round tapers to zero at the
2589///    same tips, with the width read against the stage-1 round's rail (the
2590///    face's boundary past the cusp line, `taper_runout::boundary_chain`).
2591///    The two rounds are G1 to the hairline between them.
2592fn cusp_composition(
2593    solid: &BrepSolid,
2594    selected_ids: &[u64],
2595    edge_points: &[Vec3],
2596    edge_names: Option<&[String]>,
2597    radius: f64,
2598    name: Option<&str>,
2599    corners: &[crate::blend::MixedCorner],
2600) -> Result<BrepSolid, KernelRefusal> {
2601    let shape = |message: String| KernelRefusal::unsupported(KernelStage::Classify, "cusp_composition_shape", message);
2602    if std::env::var("BREP_NO_NETWORK").is_ok() {
2603        return Err(shape("the cusp composition is a network construction and BREP_NO_NETWORK is set".into()));
2604    }
2605    let edge_of = |index: usize| solid.edges.iter().find(|edge| edge.id == selected_ids[index]);
2606    // The unit tangent leaving `vertex` into the edge.
2607    let away = |index: usize, vertex: u64| -> Option<Vec3> {
2608        let edge = edge_of(index)?;
2609        let at_start = edge.start_vertex_id == vertex;
2610        let tangent = edge.curve.unit_tangent(if at_start { edge.t0 } else { edge.t1 }, edge.t0, edge.t1).ok()?;
2611        Some(if at_start { tangent } else { tangent.scale(-1.0) })
2612    };
2613    if corners.is_empty() {
2614        return Err(shape("no mixed corners".into()));
2615    }
2616    for corner in corners {
2617        let cusped = corner.convex.iter().all(|&convex| {
2618            corner.concave.iter().any(|&concave| {
2619                matches!((away(convex, corner.vertex), away(concave, corner.vertex)), (Some(a), Some(b)) if a.dot(b) >= 1.0 - 1e-6)
2620            })
2621        });
2622        if !cusped || corner.convex.is_empty() || corner.concave.is_empty() {
2623            return Err(shape(format!("the mixed corner at vertex {} is not a cusp", corner.vertex)));
2624        }
2625    }
2626    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2627        .ok_or_else(|| shape("the selection's convexity could not be read edge by edge".into()))?;
2628    let concave: Vec<usize> = (0..selected_ids.len()).filter(|index| !convexity[*index]).collect();
2629    let convex: Vec<usize> = (0..selected_ids.len()).filter(|index| convexity[*index]).collect();
2630    if concave.is_empty() || convex.is_empty() {
2631        return Err(shape("the cusp composition needs convex and concave edges".into()));
2632    }
2633    let names_of = |indices: &[usize]| -> Option<Vec<String>> { edge_names.map(|names| indices.iter().map(|index| names[*index].clone()).collect()) };
2634    let points_of = |indices: &[usize]| -> Vec<Vec3> { indices.iter().map(|index| edge_points[*index]).collect() };
2635    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2636    let stage1 = fillet_edges_group_in(solid, &points_of(&concave), names_of(&concave).as_deref(), radius, false, name, None)
2637        .map_err(|error| error.with_message(|error| format!("cusp composition, the concave rounds: {error}")))?;
2638    if debug {
2639        eprintln!("cusp composition: stage 1 built the {} concave rounds", concave.len());
2640    }
2641    // Each convex edge is read again on the stage-1 body by its point: the
2642    // taper split it only at its hairline's end, beside the tip.
2643    for &index in &convex {
2644        resolve_edge_by_point(&stage1, edge_points[index])
2645            .map_err(|error| error.with_message(|error| format!("cusp composition: a convex edge is not on the stage-1 body: {error}")))?;
2646    }
2647    let result = fillet_edges_group_in(&stage1, &points_of(&convex), names_of(&convex).as_deref(), radius, false, name, None)
2648        .map_err(|error| error.with_message(|error| format!("cusp composition, the convex rounds: {error}")))?;
2649    // Every round here tapers to zero at a tip, and the two rounds meet on
2650    // the hairline of the face between them: an edge's end stations stay ON
2651    // the skin (the concave arc's first tenth, where the convex round's
2652    // contact lands back on the arc), and the wall check reads the majority
2653    // of a tie, as it does for the runout composition's network ring.
2654    RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(true));
2655    Ok(result)
2656}
2657
2658fn runout_composition(
2659    solid: &BrepSolid,
2660    selected_ids: &[u64],
2661    edge_points: &[Vec3],
2662    edge_names: Option<&[String]>,
2663    radius: f64,
2664    name: Option<&str>,
2665    corners: &[crate::blend::MixedCorner],
2666    entry: &str,
2667) -> Result<BrepSolid, KernelRefusal> {
2668    if std::env::var("BREP_NO_NETWORK").is_ok() {
2669        return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_no_network", "the runout composition is a network construction and BREP_NO_NETWORK is set"));
2670    }
2671    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2672        .ok_or(KernelRefusal::unsupported(KernelStage::Classify, "runout_convexity", "the selection's convexity could not be read edge by edge"))?;
2673    let mut spine_ends = vec![0usize; selected_ids.len()];
2674    for corner in corners {
2675        if corner.convex.len() != 1 {
2676            return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_corner_shape", format!(
2677                "the corner at ({:.3}, {:.3}, {:.3}) has {} convex edges; the runout is built for one convex edge dying into concave ones",
2678                corner.point.x, corner.point.y, corner.point.z, corner.convex.len()
2679            )));
2680        }
2681        spine_ends[corner.convex[0]] += 1;
2682    }
2683    let mut spines: Vec<usize> = Vec::new();
2684    let mut concave: Vec<usize> = Vec::new();
2685    for (index, ends) in spine_ends.iter().enumerate() {
2686        match (*ends, convexity[index]) {
2687            (2, true) => spines.push(index),
2688            (1, true) => spines.push(index),
2689            (0, false) => concave.push(index),
2690            (ends, convex) => {
2691                return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_selection_shape", format!(
2692                    "{} is {} and meets a mixed corner at {ends} of its ends; the runout is built for a convex edge running out at both ends among concave edges",
2693                    selection_label(index, edge_points, edge_names, name),
2694                    if convex { "convex" } else { "concave" },
2695                )));
2696            }
2697        }
2698    }
2699    if concave.is_empty() {
2700        return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_selection_shape", "no concave edges to build the ring from"));
2701    }
2702    // Stage 1: the ring, exactly as the concave edges build on their own.
2703    let ring_points: Vec<Vec3> = concave.iter().map(|index| edge_points[*index]).collect();
2704    let ring_names: Option<Vec<String>> = edge_names.map(|names| concave.iter().map(|index| names[*index].clone()).collect());
2705    LAST_NETWORK_REFUSAL.with(|last| *last.borrow_mut() = None);
2706    let ring = fillet_edges_group_with_corner_policy(solid, &ring_points, ring_names.as_deref(), radius, false, name, None, false, true)
2707        .map_err(|error| {
2708            LAST_NETWORK_REFUSAL.with(|last| last.borrow_mut().take());
2709            error.with_message(|error| format!("the concave ring did not build: {error}"))
2710        })?;
2711    // Whether the ring is the NETWORK's ring (no network refusal recorded).
2712    let network_declined = LAST_NETWORK_REFUSAL.with(|last| last.borrow_mut().take());
2713    // BREP lane L: begin walls_missing_tie_all_stations_20261015
2714    let ring_is_network = network_declined.is_none();
2715    // BREP lane L: end walls_missing_tie_all_stations_20261015
2716    // Stage 2: the runout walls on it.
2717    let spine_walls: Vec<(u64, Option<String>)> = spines
2718        .iter()
2719        .map(|index| (selected_ids[*index], per_edge_name(edge_names, name, *index).map(str::to_string)))
2720        .collect();
2721    let spine_ids: Vec<u64> = spine_walls.iter().map(|(id, _)| *id).collect();
2722    let mut result = crate::blend::build_runout_walls(&ring, &spine_walls, radius)?;
2723    heal_edge_vertex_gaps(&mut result, radius)?;
2724    crate::blend::fit_planar_charts_to_trims(&ring, &mut result)?;
2725    let issues = result.validate();
2726    if !issues.is_empty() {
2727        return Err(KernelRefusal::new(
2728            RefusalClass::InvalidResultTopology { issues: issues.len() as u32 },
2729            KernelStage::Validate,
2730            format!("the runout walls do not validate: {issues:?}"),
2731        ));
2732    }
2733    check_blend_interference(&ring, &result, &spine_ids, entry)?;
2734    check_loop_self_crossings(&result, entry)?;
2735    check_blend_wall_loops(&result, entry)?;
2736    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
2737    let accepted = crate::accept_sound(result, entry)?;
2738    // BREP lane L: begin walls_missing_tie_all_stations_20261015
2739    RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(ring_is_network));
2740    // BREP lane L: end walls_missing_tie_all_stations_20261015
2741    Ok(accepted)
2742}
2743
2744// BREP lane L: begin walls_missing_tie_all_stations_20261015
2745thread_local! {
2746    /// Set by a runout composition that SUCCEEDED on the network's ring (no
2747    /// network refusal recorded while its ring was built), and by a cusp
2748    /// composition that built (`cusp_composition`), read and cleared by the
2749    /// acceptance: only there does a tie take the majority.
2750    static RUNOUT_RING_IS_NETWORK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2751}
2752// BREP lane L: end walls_missing_tie_all_stations_20261015
2753
2754fn check_mixed_corner_convexity(
2755    solid: &BrepSolid,
2756    edge_ids: &[u64],
2757    edge_points: &[Vec3],
2758    edge_names: Option<&[String]>,
2759    radius: f64,
2760    name: Option<&str>,
2761    composition_error: Option<&KernelRefusal>,
2762) -> Result<(), KernelRefusal> {
2763    match crate::blend::mixed_convexity_corner(solid, edge_ids, radius) {
2764        Some(corner) => {
2765            // The refusal carries the RUNOUT's own numbers when they can be
2766            // measured — the station, the carrier pair, the stop and the pole
2767            // — so it says which construction is missing and where, not only
2768            // that the corner has none.  A measurement that fails leaves the
2769            // refusal exactly as it was: the corner is refused either way.
2770            let measured = match crate::blend::plan_runout(solid, edge_ids, radius, &corner) {
2771                Ok(plan) => Some(plan),
2772                Err(error) => {
2773                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
2774                        eprintln!("runout not measured: {error}");
2775                    }
2776                    None
2777                }
2778            };
2779            // "this kernel does not build that runout here": a named deferral,
2780            // carrying why the composition declined this selection.
2781            let mut message = mixed_corner_message(
2782                &corner,
2783                edge_points,
2784                edge_names,
2785                name,
2786                measured.as_ref(),
2787            );
2788            if let Some(error) = composition_error {
2789                message.push_str(&format!(" The runout composition was tried on this selection and refused: {error}"));
2790            }
2791            Err(KernelRefusal::unsupported(
2792                KernelStage::Classify,
2793                "mixed_corner_convexity",
2794                message,
2795            ))
2796        }
2797        None => Ok(()),
2798    }
2799}
2800
2801/// Refuse a selection one of whose edges keeps NO blend strip between the
2802/// corner balls at its two ends (see `degenerate_corner_setbacks`).
2803fn check_degenerate_corner_setbacks(
2804    solid: &BrepSolid,
2805    edge_ids: &[u64],
2806    edge_points: &[Vec3],
2807    edge_names: Option<&[String]>,
2808    radius: f64,
2809    name: Option<&str>,
2810) -> Result<(), KernelRefusal> {
2811    let Some(setback) = crate::blend::degenerate_corner_setbacks(solid, edge_ids, radius) else {
2812        return Ok(());
2813    };
2814    let [from, to] = setback.stops;
2815    let how = if setback.crossed {
2816        format!(
2817            "run {:.3e} PAST each other along it (the radius is beyond the limit)",
2818            setback.strip
2819        )
2820    } else {
2821        format!(
2822            "meet there ({:.3e} apart against a bar of {:.3e})",
2823            setback.strip, setback.bar
2824        )
2825    };
2826    // "The radius is at or past the degenerate limit … reduce it": a
2827    // parameter the geometry refuses, read at `Classify`.
2828    Err(KernelRefusal::input(
2829        KernelStage::Classify,
2830        "degenerate_corner_setbacks",
2831        format!(
2832            "fillet_edges: at r = {radius} the corner setbacks consume the whole of {} — the rolling \
2833             balls seated at its two corners touch face {} at ({:.4}, {:.4}, {:.4}) and ({:.4}, \
2834             {:.4}, {:.4}) and {how}, so no blend strip is left between them and the faces it lies \
2835             on are consumed whole. The radius is at or past the degenerate limit for this \
2836             selection; reduce it.",
2837            selection_label(setback.edge, edge_points, edge_names, name),
2838            setback.face_id,
2839            from.x,
2840            from.y,
2841            from.z,
2842            to.x,
2843            to.y,
2844            to.z,
2845        ),
2846    ))
2847}
2848
2849/// How a refusal names the `index`-th selected edge: its originating edge
2850/// name when the feature layer supplied one (with the feature's base prefix
2851/// stripped), else the picked point.
2852fn selection_label(
2853    index: usize,
2854    edge_points: &[Vec3],
2855    edge_names: Option<&[String]>,
2856    name: Option<&str>,
2857) -> String {
2858    let named = edge_names.and_then(|names| names.get(index)).map(|composed| match name {
2859        Some(base) => composed
2860            .strip_prefix(&format!("{base}:"))
2861            .unwrap_or(composed)
2862            .to_string(),
2863        None => composed.clone(),
2864    });
2865    named.unwrap_or_else(|| match edge_points.get(index) {
2866        Some(point) => format!("the edge at ({:.3}, {:.3}, {:.3})", point.x, point.y, point.z),
2867        None => format!("selection #{}", index + 1),
2868    })
2869}
2870
2871/// The refusal text for [`check_mixed_corner_convexity`], naming the edges the
2872/// way the user selected them (their originating edge names when the feature
2873/// layer supplied them, else the picked point).
2874fn mixed_corner_message(
2875    corner: &crate::blend::MixedCorner,
2876    edge_points: &[Vec3],
2877    edge_names: Option<&[String]>,
2878    name: Option<&str>,
2879    measured: Option<&crate::blend::RunoutPlan>,
2880) -> String {
2881    let label = |index: usize| selection_label(index, edge_points, edge_names, name);
2882    let list = |indices: &[usize]| -> String {
2883        let parts: Vec<String> = indices.iter().map(|index| label(*index)).collect();
2884        match parts.split_last() {
2885            None => "none".to_string(),
2886            Some((last, [])) => last.clone(),
2887            Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
2888        }
2889    };
2890    let mut message = format!(
2891        "fillet_edges: the selection mixes convexity at the corner ({:.3}, {:.3}, {:.3}) — convex \
2892         {} meets concave {} there. One rolling ball cannot touch the face they share from both \
2893         sides at once, so that corner has no closure: the convex blend runs out against the \
2894         concave ones partway along the edge, and this kernel does not build that runout yet. \
2895         Blending the concave edges in one fillet and the convex ones in another does not reach \
2896         a wall on every one of them either: the convex wall comes out at FULL length in either \
2897         order, and its contact leaves the faces it runs along where their own loops would then \
2898         cross. Blend the concave edges first and the blend acceptance refuses each convex edge \
2899         whose wall runs out into them; blend the convex ones first and the subset search drops \
2900         the concave edges it cannot compose instead, leaving those unfilleted.",
2901        corner.point.x,
2902        corner.point.y,
2903        corner.point.z,
2904        list(&corner.convex),
2905        list(&corner.concave),
2906    );
2907    // The runout, measured: where the ball's carriers switch, what they switch
2908    // to, and where the last stretch degenerates.  These are the numbers the
2909    // construction owes, so the refusal states them rather than leaving the
2910    // reader to derive them (`blend/runout.rs`).
2911    if let Some(plan) = measured {
2912        message.push_str(&format!(
2913            " Measured on this selection: the convex edge {}'s ball becomes tangent to face {} — \
2914             the face its two concave neighbours share — at s = {:.6} from the corner, centred \
2915             ({:.6}, {:.6}, {:.6}), where its contact on face {} reaches edge {}'s own rail \
2916             (ball-to-stripe residual {:.3e}). Past that station the second carrier is edge {}'s \
2917             STRIPE SURFACE, not a face of the input, and the march holds on it for {} \
2918             stations that fit rows reproducing their own contacts to {:.3e}. On the way the \
2919             kept mate's contact walks {:.3e} of a span off that face's own patch — into the \
2920             strip the concave stripe's pad ADDS to it — which is the shape, not an escape: \
2921             the bar a march is refused at is a full span.",
2922            plan.convex_edge,
2923            plan.shared_face,
2924            plan.station.s,
2925            plan.station.center.x,
2926            plan.station.center.y,
2927            plan.station.center.z,
2928            plan.replaced_mate,
2929            plan.second_carrier,
2930            plan.station.stripe_residual,
2931            plan.second_carrier,
2932            plan.marched,
2933            plan.fit_residual,
2934            plan.carrier_excursion,
2935        ));
2936        match (&plan.stop, plan.first_carrier) {
2937            (Some(stop), Some(first)) => message.push_str(&format!(
2938                " It does not simply stop there: at s = {:.6} the KEPT mate (face {}) runs out too \
2939                 — the ball's contact on it reaches edge {}'s rail, residual {:.3e} — so the FIRST \
2940                 carrier becomes that stripe as well and the last stretch rolls on two stripes.",
2941                stop.s, plan.kept_mate, first, stop.stripe_residual,
2942            )),
2943            _ => message.push_str(&format!(
2944                " Where the kept mate (face {}) runs out was not measurable on this selection.",
2945                plan.kept_mate
2946            )),
2947        }
2948        if let Some(pole) = plan.pole {
2949            message.push_str(&format!(
2950                " That stretch ends at a POLE, ({:.6}, {:.6}, {:.6}), where the two concave \
2951                 stripes' rails on face {} meet and the ball's two contacts merge, so the blend \
2952                 section shrinks to a point. Two carrier switches and a degenerate terminus is \
2953                 more than a stop station on a stripe, and none of it is composed yet.",
2954                pole.x, pole.y, pole.z, plan.shared_face,
2955            ));
2956        }
2957    }
2958    message
2959}
2960
2961/// All ways to choose `k` distinct indices from `0..n`, in lexicographic order.
2962fn index_combinations(n: usize, k: usize) -> Vec<Vec<usize>> {
2963    let mut out = Vec::new();
2964    if k == 0 || k > n {
2965        return out;
2966    }
2967    let mut idx: Vec<usize> = (0..k).collect();
2968    loop {
2969        out.push(idx.clone());
2970        // Advance to the next combination (like counting with carry).
2971        let mut i = k;
2972        loop {
2973            if i == 0 {
2974                return out;
2975            }
2976            i -= 1;
2977            if idx[i] != i + n - k {
2978                break;
2979            }
2980        }
2981        idx[i] += 1;
2982        for j in (i + 1)..k {
2983            idx[j] = idx[j - 1] + 1;
2984        }
2985    }
2986}
2987
2988thread_local! {
2989    /// Running count (per thread) of group builds that reached the CUTTER
2990    /// COMPOSITION — every network lane above it refused or was rejected.  A
2991    /// zero delta across a call is the witness that the network answered it;
2992    /// a face count or a volume cannot say which lane built a solid, since the
2993    /// cutter can build the same one.  Test-observable; not part of any result.
2994    pub static CUTTER_COMPOSITIONS: std::cell::Cell<u64> =
2995        const { std::cell::Cell::new(0) };
2996}
2997
2998thread_local! {
2999    /// The most edges the maximal-valid-subset search may drop on this
3000    /// thread; `None` searches every subset. Set by [`fillet_edges`] for its
3001    /// own call (lane F row 3, 2026-10-15): that entry refuses any partial
3002    /// selection, so the search there only words the refusal, and a search
3003    /// past one dropped edge cost lCount_125 117 s of booleans (112 subsets)
3004    /// to refuse what the drop-one level refuses in 11 s.
3005    static SUBSET_DROP_CAP: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
3006}
3007
3008/// Restores the previous [`SUBSET_DROP_CAP`] when the strict entry returns.
3009struct SubsetDropCap(Option<usize>);
3010
3011impl SubsetDropCap {
3012    fn set(cap: Option<usize>) -> Self {
3013        Self(SUBSET_DROP_CAP.with(|current| current.replace(cap)))
3014    }
3015}
3016
3017impl Drop for SubsetDropCap {
3018    fn drop(&mut self) {
3019        SUBSET_DROP_CAP.with(|current| current.set(self.0));
3020    }
3021}
3022
3023thread_local! {
3024    /// Running count (per thread) of [`fillet_edges_group_in`] builds, nested
3025    /// component builds included. Test-observable; not part of any result.
3026    pub static GROUP_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
3027    /// The network's last refusal in a group build on this thread, read
3028    /// back by the runout composition when its ring stage fails.
3029    static LAST_NETWORK_REFUSAL: std::cell::RefCell<Option<KernelRefusal>> = const { std::cell::RefCell::new(None) };
3030    /// The wall fold the network refused THIS group build's selection by,
3031    /// scoped to one [`fillet_edges_group_unchecked`] call (nested component
3032    /// builds save and restore it).
3033    static GROUP_NETWORK_FOLD: std::cell::RefCell<Option<KernelRefusal>> = const { std::cell::RefCell::new(None) };
3034}
3035
3036/// One component of a selection: its edge points (as bits, so the key is
3037/// exact) and its per-edge wall names.
3038type ComponentKey = (Vec<[u64; 3]>, Option<Vec<String>>);
3039
3040/// One step of the cutter composition's sequential build: the edge's
3041/// selection point (as bits), its wall name, the cutter's end pads (as bits)
3042/// and the composition lane (0 = general first, 1 = cutter first). The pads
3043/// and the lane are part of the key because both are read off the WHOLE
3044/// selection (its corners), so the same edge can take a different cutter in
3045/// a subset that drops a corner's third edge.
3046type SequentialKey = ([u64; 3], Option<String>, [u64; 2], u8);
3047
3048/// Component results of one [`fillet_edges_reported`] call, keyed by the chain
3049/// of components composed up to and including the one built. Valid only for
3050/// the solid, radius, chamfer flag and name of that call.
3051///
3052/// `sequential` is the same memo one level down, for a single connected
3053/// component: the evolving body of the cutter composition after each edge
3054/// blended, keyed by the chain of steps composed up to and including it. The
3055/// subset search's one-drop subsets of a connected selection mostly open
3056/// with the same edges in the same order, so without it every such subset
3057/// rebuilt the same cutter booleans before reaching the edge that refuses.
3058/// On the 2026-10-17 "fillet takes way too long" report (a 7-edge face ring
3059/// whose second edge refuses after the first edge's 6-8 s cutter boolean)
3060/// that boolean ran six times for one refusal: for the group and for the
3061/// five subsets that keep the first edge.
3062///
3063/// A one-drop subset of a connected ring can split it into two components
3064/// (the ring minus an edge that is not an end of a path), and the component
3065/// chains then differ from subset to subset while the cutter composition's
3066/// first steps do not; so the sequential memo is keyed by the chain of
3067/// components composed BEFORE the body being built (`prefix`, empty for a
3068/// single-component selection) together with the steps, and the component
3069/// builds carry the memo down instead of `None`. A FIRST component's steps
3070/// key under the empty prefix like a single-component selection's, which
3071/// is sound because both start from the same body: the component build
3072/// re-heals the selection's already healed input, and `heal_operands`
3073/// leaves a clean input byte-identical (its contract, stated at the heal
3074/// above; the cross-partition hits on the reported ring are its evidence).
3075#[derive(Default)]
3076struct ComponentMemo {
3077    built: std::collections::HashMap<Vec<ComponentKey>, Result<BrepSolid, KernelRefusal>>,
3078    /// The components composed before the build in progress, from the
3079    /// outermost selection down (set around each component build).
3080    prefix: Vec<ComponentKey>,
3081    sequential: std::collections::HashMap<
3082        (Vec<ComponentKey>, Vec<SequentialKey>),
3083        Result<BrepSolid, KernelRefusal>,
3084    >,
3085}
3086
3087/// [`fillet_edges_group_in`], with the subset search's component memo when
3088/// `memo` is `Some`. The search passes it on its own solid, and the component
3089/// builds pass it on down with `ComponentMemo::prefix` naming the components
3090/// composed before them (see `ComponentMemo::sequential`).
3091fn fillet_edges_group_in(
3092    solid: &BrepSolid,
3093    edge_points: &[Vec3],
3094    edge_names: Option<&[String]>,
3095    radius: f64,
3096    chamfer: bool,
3097    name: Option<&str>,
3098    memo: Option<&mut ComponentMemo>,
3099) -> Result<BrepSolid, KernelRefusal> {
3100    fillet_edges_group_with_corner_policy(solid, edge_points, edge_names, radius, chamfer, name, memo, true, true)
3101}
3102
3103fn fillet_edges_group_with_corner_policy(
3104    solid: &BrepSolid,
3105    edge_points: &[Vec3],
3106    edge_names: Option<&[String]>,
3107    radius: f64,
3108    chamfer: bool,
3109    name: Option<&str>,
3110    memo: Option<&mut ComponentMemo>,
3111    wrap_concave: bool,
3112    accept: bool,
3113) -> Result<BrepSolid, KernelRefusal> {
3114    GROUP_BUILDS.with(|count| count.set(count.get() + 1));
3115    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3116    let GroupBody { body: result, bowtie_clean } =
3117        fillet_edges_group_unchecked(solid, edge_points, edge_names, radius, chamfer, name, memo, wrap_concave)?;
3118    if !accept {
3119        return Ok(result);
3120    }
3121    // A body the network or the closed-rim lane already scanned clean and
3122    // handed up untouched is not scanned again (the scan is a pure function
3123    // of the body, 2026-10-12). The composite road and the cutter road hand
3124    // up bodies no lane scanned, and are scanned here.
3125    if bowtie_clean {
3126        crate::blend::record_count("count.bowtie.lane_scan_reused", 1);
3127    } else {
3128        check_loop_self_crossings(&result, entry)?;
3129        check_blend_wall_loops(&result, entry)?;
3130    }
3131    let soundness = crate::blend::BlendTimer::start("timing.soundness_ms");
3132    // The BODY's own soundness, beside the loop's. A blend wall is a FITTED
3133    // surface and a fit can carry two parameters of one wall to one point in
3134    // space — measured on `inbox-20260902-fillet-two-torus-box-edges`, whose
3135    // wall `F8:BLEND:Box_NZ|P.T5_Side[0]` does exactly that while `validate()`,
3136    // connectivity, Euler parity, the loop scan and the face-versus-face scan
3137    // are all silent. Two walls crossing each other is the same class and is
3138    // repaired where it can be. Neither is visible to a volume oracle, so a
3139    // result carrying one reports success for a different shape.
3140    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
3141    let accepted = crate::accept_sound(result, entry);
3142    soundness.stop();
3143    accepted
3144}
3145
3146/// What the unchecked group lane hands up: the body, and whether a lane's
3147/// own acceptance already ran the bowtie scan on exactly this body and
3148/// found it clean (the network and closed-rim exits return the scanned
3149/// body unchanged; the composite and cutter exits do not scan).
3150struct GroupBody {
3151    body: BrepSolid,
3152    bowtie_clean: bool,
3153}
3154
3155/// [`fillet_edges_group_lanes`], answering a selection the network refused
3156/// by a WALL FOLD and the cutter composition then failed too by that fold,
3157/// not by the composition's own text: the fold is the reason, and the
3158/// composition's last cutter ("mates share their end boundary edge" on the
3159/// 2026-10-21 sculpted cap, report 5e49bb42) names nothing the user can act
3160/// on. The fold keeps its class, so the subset search above stops on it.
3161fn fillet_edges_group_unchecked(
3162    solid: &BrepSolid,
3163    edge_points: &[Vec3],
3164    edge_names: Option<&[String]>,
3165    radius: f64,
3166    chamfer: bool,
3167    name: Option<&str>,
3168    memo: Option<&mut ComponentMemo>,
3169    wrap_concave: bool,
3170) -> Result<GroupBody, KernelRefusal> {
3171    let outer = GROUP_NETWORK_FOLD.with(|fold| fold.borrow_mut().take());
3172    let built = fillet_edges_group_lanes(solid, edge_points, edge_names, radius, chamfer, name, memo, wrap_concave);
3173    let fold = GROUP_NETWORK_FOLD.with(|fold| std::mem::replace(&mut *fold.borrow_mut(), outer));
3174    match (built, fold) {
3175        (Err(error), Some(fold)) if !crate::blend::is_wall_fold(&error) => Err(fold),
3176        (built, _) => built,
3177    }
3178}
3179
3180/// `BREP_FILLET_CONCAVE_FIRST_STAGES` (default on; `=0` restores the cutter
3181/// composition): a selection the network refuses for MIXED CONVEXITY whose
3182/// concave edges also meet each other at a corner no selected convex edge
3183/// reaches is built in two network stages, concave edges first.
3184///
3185/// Cause: a boss standing across a block's top edge, filleted along its base
3186/// (two vertical concave edges on the block's side, the concave arc on its
3187/// top) together with the boss's bottom face. The bottom corners are
3188/// re-entrant stars (one concave, two convex edges), which the network
3189/// refuses by convexity, so the WHOLE selection went to the sequential
3190/// cutter build; that build runs each concave cutter past the block's sharp
3191/// top edge and closes it with folded flat caps (a crease of 180 degrees)
3192/// instead of the miter the network builds where the two concave pads meet
3193/// over that edge.
3194/// The stage name a concave pad carries between the two stages of
3195/// [`concave_first_stages`], followed by its selection index.
3196const CONCAVE_FIRST_PAD: &str = "FILLET:CONCAVE_FIRST:";
3197
3198fn concave_first_stages_on() -> bool {
3199    switch!("BREP_FILLET_CONCAVE_FIRST_STAGES", true)
3200}
3201
3202/// One network stage of [`concave_first_stages`], under the acceptance the
3203/// group's own network result gets (heal, planar charts, validation,
3204/// interference, loop scans). `None` when the network refuses or the result
3205/// fails any check.
3206fn concave_first_network_stage(
3207    input: &BrepSolid,
3208    edge_ids: &[u64],
3209    network_names: &[Option<String>],
3210    corner_name: &dyn Fn(&[usize]) -> Option<String>,
3211    radius: f64,
3212    wrap_concave: bool,
3213) -> Option<BrepSolid> {
3214    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
3215    let mut body = match crate::blend::blend_star_network_with_corner_policy(
3216        input, edge_ids, radius, false, network_names, corner_name, wrap_concave,
3217    ) {
3218        Ok(body) => body,
3219        Err(refusal) => {
3220            if debug {
3221                eprintln!("concave-first stage on {edge_ids:?} refused: {refusal}");
3222            }
3223            return None;
3224        }
3225    };
3226    let entry = "fillet_edges";
3227    let healed = heal_edge_vertex_gaps(&mut body, radius);
3228    let charts = crate::blend::fit_planar_charts_to_trims(input, &mut body);
3229    let issues = body.validate_memoised();
3230    let interference = check_blend_interference(input, &body, edge_ids, entry);
3231    let bowtie = check_loop_self_crossings(&body, entry).and_then(|()| check_blend_wall_loops(&body, entry));
3232    if healed.is_ok() && charts.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
3233        return Some(body);
3234    }
3235    crate::blend::reject_wrapped_network();
3236    if debug {
3237        eprintln!(
3238            "concave-first stage on {edge_ids:?} rejected: heal={healed:?} charts={charts:?} issues={issues:?} \
3239             interference={interference:?} bowtie={bowtie:?}"
3240        );
3241    }
3242    None
3243}
3244
3245/// The two-stage build [`concave_first_stages_on`] describes: the concave
3246/// edges through the network on the input, then the convex edges through the
3247/// network on that body. Where a concave pad now separates two selected
3248/// convex edges that met it at a re-entrant star, the pad's own edge on their
3249/// shared face joins the second stage, so the star closes as one rounded run
3250/// (named as the star's corner) rather than with flat caps. `None` when the
3251/// selection is not of this shape or either stage fails: the caller's ladder
3252/// then goes on unchanged.
3253#[allow(clippy::too_many_arguments)]
3254fn concave_first_stages(
3255    solid: &BrepSolid,
3256    edge_points: &[Vec3],
3257    edge_names: Option<&[String]>,
3258    selected_edge_ids: &[u64],
3259    radius: f64,
3260    name: Option<&str>,
3261    wrap_concave: bool,
3262) -> Option<BrepSolid> {
3263    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
3264    let convex = crate::blend::selection_convexity(solid, selected_edge_ids, radius)?;
3265    let concave_indices: Vec<usize> = (0..convex.len()).filter(|&index| !convex[index]).collect();
3266    let convex_indices: Vec<usize> = (0..convex.len()).filter(|&index| convex[index]).collect();
3267    if concave_indices.is_empty() || convex_indices.is_empty() {
3268        return None;
3269    }
3270    let edge = |id: u64| solid.edges.iter().find(|edge| edge.id == id);
3271    let ends = |id: u64| edge(id).map(|edge| [edge.start_vertex_id, edge.end_vertex_id]);
3272    // The shape this answers: two concave edges meeting where no selected
3273    // convex edge ends (the miter the cutter build caps).
3274    let concave_corner = concave_indices.iter().enumerate().any(|(slot, &a)| {
3275        concave_indices[slot + 1..].iter().any(|&b| {
3276            let (Some(ends_a), Some(ends_b)) = (ends(selected_edge_ids[a]), ends(selected_edge_ids[b])) else {
3277                return false;
3278            };
3279            ends_a.iter().any(|vertex| {
3280                ends_b.contains(vertex)
3281                    && !convex_indices.iter().any(|&c| ends(selected_edge_ids[c]).is_some_and(|ends_c| ends_c.contains(vertex)))
3282            })
3283        })
3284    });
3285    if !concave_corner {
3286        return None;
3287    }
3288    let names_of = |indices: &[usize]| -> Vec<Option<String>> {
3289        indices.iter().map(|&index| per_edge_name(edge_names, name, index).map(str::to_string)).collect()
3290    };
3291    // Stage 1: the concave edges on the input. Each pad carries a stage name
3292    // of its own until the end, so finding a pad below never depends on the
3293    // names the caller supplied (or did not).
3294    let concave_ids: Vec<u64> = concave_indices.iter().map(|&index| selected_edge_ids[index]).collect();
3295    let stage_name = |index: usize| format!("{CONCAVE_FIRST_PAD}{index}");
3296    let concave_names: Vec<Option<String>> = concave_indices.iter().map(|&index| Some(stage_name(index))).collect();
3297    let concave_corner_name = |adjacent: &[usize]| {
3298        let members: Vec<usize> = adjacent.iter().map(|&slot| concave_indices[slot]).collect();
3299        corner_face_name(edge_names, name, &members)
3300    };
3301    let staged = concave_first_network_stage(solid, &concave_ids, &concave_names, &concave_corner_name, radius, wrap_concave)?;
3302    let original_faces: rustc_hash::FxHashSet<u64> =
3303        solid.shells.iter().flat_map(|shell| &shell.faces).map(|face| face.id).collect();
3304    let faces_of = |id: u64| -> Vec<&FaceRecord> {
3305        staged
3306            .shells
3307            .iter()
3308            .flat_map(|shell| &shell.faces)
3309            .filter(|face| face.loops.iter().flat_map(|rim| &rim.coedges).any(|coedge| coedge.edge_id == id))
3310            .collect()
3311    };
3312    // Stage 2: the convex edges, resolved on the staged body by their pick
3313    // points (a concave pad trims a convex edge at its end, never at the
3314    // point it was picked by).
3315    let mut stage_ids: Vec<u64> = Vec::with_capacity(convex_indices.len() + 2);
3316    let mut members: Vec<Vec<usize>> = Vec::with_capacity(convex_indices.len() + 2);
3317    for &index in &convex_indices {
3318        let id = resolve_edge_by_point(&staged, edge_points[index]).ok()?;
3319        // A pick that now lands on a pad (one made inside the stretch the pad
3320        // trimmed away) is not the convex edge it named.
3321        if stage_ids.contains(&id) || faces_of(id).iter().any(|face| !original_faces.contains(&face.id)) {
3322            return None;
3323        }
3324        stage_ids.push(id);
3325        members.push(vec![index]);
3326    }
3327    let staged_edge = |id: u64| staged.edges.iter().find(|edge| edge.id == id);
3328    let convex_count = stage_ids.len();
3329    for pad in &staged.edges {
3330        if pad.degenerate || stage_ids.contains(&pad.id) || pad.start_vertex_id == pad.end_vertex_id {
3331            continue;
3332        }
3333        let faces = faces_of(pad.id);
3334        if faces.len() != 2 {
3335            continue;
3336        }
3337        // One side is a stage-1 pad, named after the concave edge it rounds.
3338        let Some(concave_index) = faces.iter().find(|face| !original_faces.contains(&face.id)).and_then(|face| {
3339            concave_indices.iter().copied().find(|&index| face.name.as_deref() == Some(stage_name(index).as_str()))
3340        }) else {
3341            continue;
3342        };
3343        // Its two ends are ends of two DIFFERENT selected convex edges.
3344        let ender = |vertex: u64| {
3345            (0..convex_count).find(|&slot| {
3346                staged_edge(stage_ids[slot]).is_some_and(|edge| edge.start_vertex_id == vertex || edge.end_vertex_id == vertex)
3347            })
3348        };
3349        let (Some(first), Some(second)) = (ender(pad.start_vertex_id), ender(pad.end_vertex_id)) else {
3350            continue;
3351        };
3352        if first == second {
3353            continue;
3354        }
3355        // And the other side is a face both of those convex edges run along.
3356        let Some(other) = faces.iter().find(|face| original_faces.contains(&face.id)) else {
3357            continue;
3358        };
3359        let borders = |slot: usize| faces_of(stage_ids[slot]).iter().any(|face| face.id == other.id);
3360        if !borders(first) || !borders(second) {
3361            continue;
3362        }
3363        match super::analyze::scan_dihedral(&staged, pad.id) {
3364            Ok(profile) if profile.samples > 0 && profile.any_convex && !profile.any_concave => {}
3365            _ => continue,
3366        }
3367        let mut star = vec![concave_index, convex_indices[first], convex_indices[second]];
3368        star.sort_unstable();
3369        stage_ids.push(pad.id);
3370        members.push(star);
3371    }
3372    let mut stage_names = names_of(&convex_indices);
3373    stage_names.extend(members[convex_count..].iter().map(|star| corner_face_name(edge_names, name, star)));
3374    let stage_corner_name = |adjacent: &[usize]| {
3375        let mut flat: Vec<usize> = adjacent.iter().flat_map(|&slot| members[slot].iter().copied()).collect();
3376        flat.sort_unstable();
3377        flat.dedup();
3378        corner_face_name(edge_names, name, &flat)
3379    };
3380    let mut built = concave_first_network_stage(&staged, &stage_ids, &stage_names, &stage_corner_name, radius, wrap_concave)?;
3381    for face in built.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
3382        // The stage name, and anything a stage appended to it, back to the
3383        // pad's own name.
3384        let Some(tail) = face.name.as_deref().and_then(|value| value.strip_prefix(CONCAVE_FIRST_PAD)) else {
3385            continue;
3386        };
3387        let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
3388        let Ok(index) = tail[..digits].parse::<usize>() else {
3389            return None;
3390        };
3391        let rest = tail[digits..].to_string();
3392        face.name = per_edge_name(edge_names, name, index).map(|own| format!("{own}{rest}"));
3393    }
3394    if debug {
3395        eprintln!(
3396            "concave-first stages: {} concave, {} convex and {} star pad edge(s) built",
3397            concave_ids.len(),
3398            convex_count,
3399            stage_ids.len() - convex_count
3400        );
3401    }
3402    Some(built)
3403}
3404
3405fn fillet_edges_group_lanes(
3406    solid: &BrepSolid,
3407    edge_points: &[Vec3],
3408    edge_names: Option<&[String]>,
3409    radius: f64,
3410    chamfer: bool,
3411    name: Option<&str>,
3412    mut memo: Option<&mut ComponentMemo>,
3413    wrap_concave: bool,
3414) -> Result<GroupBody, KernelRefusal> {
3415    use rustc_hash::FxHashSet as HashSet;
3416
3417    // Fuse-first operand heal (Lever A) before the multi-edge surgery: snap the
3418    // input's near-coincident / off-plane vertices (e.g. a revolve pole apex
3419    // sitting a few microns off the axis) to exact and re-anchor incident
3420    // edges.  The selected edges are resolved geometrically below, so a
3421    // sub-heal_tol vertex move never changes which edges are picked; a clean
3422    // input is left byte-identical.
3423    let heal = crate::blend::BlendTimer::start("timing.heal_operands_ms");
3424    let mut healed_input = solid.clone();
3425    let heal_policy = crate::KernelTolerances::for_solid(&healed_input, 1e-7);
3426    crate::heal::heal_operands(&mut healed_input, &heal_policy)?;
3427    let solid = &healed_input;
3428    heal.stop();
3429    let group_analysis = crate::blend::BlendTimer::start("timing.group_analysis_ms");
3430
3431    // 1. Detect convex corners from the ORIGINAL solid: a point that is an
3432    //    endpoint of >=3 of the selected edges (a cube/prism-style vertex).
3433    let mut endpoints: Vec<(Vec3, usize)> = Vec::with_capacity(edge_points.len() * 2);
3434    // The extent each selected edge has BEFORE any blend trims it, so the
3435    // sequential build can run every cutter through the shared corners.
3436    let mut original_extents: Vec<(Vec3, Vec3)> = Vec::with_capacity(edge_points.len());
3437    let mut selected_edge_ids: Vec<u64> = Vec::with_capacity(edge_points.len());
3438    for (i, point) in edge_points.iter().enumerate() {
3439        let edge_id = resolve_edge_by_point(solid, *point)?;
3440        let edge = solid
3441            .edges
3442            .iter()
3443            .find(|e| e.id == edge_id)
3444            .ok_or_else(|| {
3445                KernelRefusal::internal(
3446                    KernelStage::Collect,
3447                    "resolved_edge",
3448                    "fillet_edges: resolved edge vanished",
3449                )
3450            })?;
3451        let (start, end) = (
3452            edge.curve
3453                .evaluate(edge.t0)
3454                .or_refuse(KernelStage::Collect, "edge_start")?,
3455            edge.curve
3456                .evaluate(edge.t1)
3457                .or_refuse(KernelStage::Collect, "edge_end")?,
3458        );
3459        endpoints.push((start, i));
3460        endpoints.push((end, i));
3461        original_extents.push((start, end));
3462        selected_edge_ids.push(edge_id);
3463    }
3464    let mut corners: Vec<Vec3> = Vec::new();
3465    // The selected-edge INPUT INDICES meeting at each star corner (parallel to
3466    // `corners`), sorted — used to name the corner patch after its adjacent
3467    // edges (`{fid}:BLEND:CORNER:{e_a}+{e_b}+…`), UNIQUE per corner because no
3468    // two distinct corners share the same set of >=3 selected edges.
3469    let mut corner_edges: Vec<Vec<usize>> = Vec::new();
3470    let mut chain_corner_count = 0usize;
3471    let mut chain_corners: Vec<(Vec3, [usize; 2])> = Vec::new();
3472    let mut used = vec![false; endpoints.len()];
3473    for i in 0..endpoints.len() {
3474        if used[i] {
3475            continue;
3476        }
3477        used[i] = true;
3478        let mut edges_here: HashSet<usize> = HashSet::default();
3479        edges_here.insert(endpoints[i].1);
3480        for j in (i + 1)..endpoints.len() {
3481            if used[j] {
3482                continue;
3483            }
3484            if endpoints[i].0.sub(endpoints[j].0).length() < 1e-6 {
3485                used[j] = true;
3486                edges_here.insert(endpoints[j].1);
3487            }
3488        }
3489        if edges_here.len() >= 3 {
3490            corners.push(endpoints[i].0);
3491            let mut adjacent: Vec<usize> = edges_here.into_iter().collect();
3492            adjacent.sort_unstable();
3493            corner_edges.push(adjacent);
3494        } else if edges_here.len() == 2 {
3495            chain_corner_count += 1;
3496            let mut adjacent = edges_here.into_iter().collect::<Vec<_>>();
3497            adjacent.sort_unstable();
3498            chain_corners.push((endpoints[i].0, [adjacent[0], adjacent[1]]));
3499        }
3500    }
3501
3502    // A FACE selection may contain several disconnected boundary components
3503    // (the common example is an outer perimeter plus a circular hole rim).
3504    // Miter composition is only meaningful inside one connected edge graph.
3505    // Feeding every component into the same INTERSECT/UNION combines multiple
3506    // independently filleted copies of otherwise untouched support faces; the
3507    // boolean then imprints those coincident copies and can leave redundant
3508    // seams (the reported through-hole cylinder split into three faces).
3509    //
3510    // Partition by shared original endpoints and process components in input
3511    // order.  Each recursive call sees one connected component, so it follows
3512    // the existing miter/sequential path without recursion cycling.  Distinct
3513    // components are then composed sequentially on the evolving solid.
3514    let mut component_of = vec![usize::MAX; edge_points.len()];
3515    let mut components: Vec<Vec<usize>> = Vec::new();
3516    for seed in 0..edge_points.len() {
3517        if component_of[seed] != usize::MAX {
3518            continue;
3519        }
3520        let component_index = components.len();
3521        component_of[seed] = component_index;
3522        let mut component = vec![seed];
3523        let mut cursor = 0;
3524        while cursor < component.len() {
3525            let current = component[cursor];
3526            cursor += 1;
3527            for candidate in 0..edge_points.len() {
3528                if component_of[candidate] != usize::MAX {
3529                    continue;
3530                }
3531                let connected = [original_extents[current].0, original_extents[current].1]
3532                    .into_iter()
3533                    .any(|a| {
3534                        [original_extents[candidate].0, original_extents[candidate].1]
3535                            .into_iter()
3536                            .any(|b| a.sub(b).length() < 1e-6)
3537                    });
3538                if connected {
3539                    component_of[candidate] = component_index;
3540                    component.push(candidate);
3541                }
3542            }
3543        }
3544        component.sort_unstable();
3545        components.push(component);
3546    }
3547    group_analysis.stop();
3548    if components.len() > 1 {
3549        let mut separated = solid.clone();
3550        // The chain continues the memo's prefix, so a component composed
3551        // inside another's build keys under the whole path to it.
3552        let mut chain: Vec<ComponentKey> = memo.as_deref().map(|memo| memo.prefix.clone()).unwrap_or_default();
3553        chain.reserve(components.len());
3554        for component in components {
3555            let points = component
3556                .iter()
3557                .map(|index| edge_points[*index])
3558                .collect::<Vec<_>>();
3559            let names = edge_names.map(|all| {
3560                component
3561                    .iter()
3562                    .map(|index| all[*index].clone())
3563                    .collect::<Vec<_>>()
3564            });
3565            let Some(memo) = memo.as_deref_mut() else {
3566                separated = fillet_edges_group_with_corner_policy(
3567                    &separated,
3568                    &points,
3569                    names.as_deref(),
3570                    radius,
3571                    chamfer,
3572                    name,
3573                    None,
3574                    wrap_concave,
3575                    false,
3576                )?;
3577                continue;
3578            };
3579            let bits = points.iter().map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);
3580            chain.push((bits.collect(), names.clone()));
3581            let built = match memo.built.get(&chain) {
3582                Some(built) => built.clone(),
3583                None => {
3584                    // The component builds on the body the chain before it
3585                    // composed: its own cutter steps key under that chain.
3586                    let outer_prefix = std::mem::replace(&mut memo.prefix, chain[..chain.len() - 1].to_vec());
3587                    let built = fillet_edges_group_with_corner_policy(
3588                        &separated,
3589                        &points,
3590                        names.as_deref(),
3591                        radius,
3592                        chamfer,
3593                        name,
3594                        Some(&mut *memo),
3595                        wrap_concave,
3596                        false,
3597                    );
3598                    memo.prefix = outer_prefix;
3599                    memo.built.insert(chain.clone(), built.clone());
3600                    built
3601                }
3602            };
3603            separated = built?;
3604        }
3605        return Ok(GroupBody { body: separated, bowtie_clean: false });
3606    }
3607
3608    // 2a. The stripe network (blend/network.rs) is the lane for EVERY
3609    //     selection: each stripe is marched against THIS solid, each shared
3610    //     vertex is solved before anything is cut — a star closed by a patch
3611    //     of the corner ball, a two-edge corner by the seam between the two
3612    //     blends, a re-entrant corner by a horn torus, a tangent pair by a
3613    //     flush join, an unselected tangent continuation by a cap — and
3614    //     nothing is subtracted, so no cutter can overshoot into a neighbour
3615    //     and no leftover cap has to be identified afterwards.  It refuses
3616    //     BY NAME on what it does not yet construct (mixed-convexity corners,
3617    //     no-common-ball stars, pinched edges), and those fall through to the
3618    //     cutter composition below.
3619    //
3620    //     A CLOSED edge is one of those refusals and it has an answer the
3621    //     network is simply not the lane for: a closed rim has no corner to
3622    //     share, so `blend_star_network` says "edge N is closed and has no
3623    //     corner to share" and the composition took it.  `blend_closed_edge`
3624    //     builds exactly that case and the single-edge ladder in `tool.rs`
3625    //     has always tried it first — but this function reached only the
3626    //     network, so a closed rim inside a GROUP went to a cutter that the
3627    //     same rim selected on its own never saw.  A bored hole's rim splits
3628    //     out as its own one-edge component (see the component partition
3629    //     above), so that was every hole rim chamfered as part of a face
3630    //     selection.  Try it here too, under the same acceptance the network
3631    //     result gets, and under the same `BREP_NO_NETWORK` A/B.
3632    if std::env::var("BREP_NO_NETWORK").is_err() {
3633        if selected_edge_ids.len() == 1 {
3634            let edge_id = selected_edge_ids[0];
3635            let closed = solid
3636                .edges
3637                .iter()
3638                .find(|edge| edge.id == edge_id)
3639                .is_some_and(|edge| edge.start_vertex_id == edge.end_vertex_id);
3640            if closed {
3641                let rim_name = per_edge_name(edge_names, name, 0);
3642                match crate::blend::blend_closed_edge(solid, edge_id, radius, chamfer, rim_name) {
3643                    Ok(mut rim) => {
3644                        let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3645                        let heal = crate::blend::BlendTimer::start("timing.heal_vertex_gaps_ms");
3646                        let healed = heal_edge_vertex_gaps(&mut rim, radius);
3647                        heal.stop();
3648                        // A trim the surgery ran outside its planar carrier's
3649                        // chart is a wrong body the three checks below all pass
3650                        // (`crate::blend::fit_planar_charts_to_trims`), so the
3651                        // carrier is widened here, after the heal has settled
3652                        // the edges the trims are rebuilt from and before the
3653                        // bowtie scan reads them.  Its refusals are TERMINAL:
3654                        // the composition is not a second opinion on a body
3655                        // whose trims left their carrier.
3656                        let charts = crate::blend::BlendTimer::start("timing.planar_charts_ms");
3657                        crate::blend::fit_planar_charts_to_trims(solid, &mut rim)?;
3658                        charts.stop();
3659                        let validate = crate::blend::BlendTimer::start("timing.validate_ms");
3660                        let issues = rim.validate_memoised();
3661                        validate.stop();
3662                        let interference =
3663                            check_blend_interference(solid, &rim, &selected_edge_ids, entry);
3664                        let bowtie = check_loop_self_crossings(&rim, entry).and_then(|()| check_blend_wall_loops(&rim, entry));
3665                        if healed.is_ok()
3666                            && issues.is_empty()
3667                            && interference.is_ok()
3668                            && bowtie.is_ok()
3669                        {
3670                            return Ok(GroupBody { body: rim, bowtie_clean: true });
3671                        }
3672                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3673                            eprintln!(
3674                                "closed-rim result rejected: heal={healed:?} issues={issues:?} \
3675                                 interference={interference:?} bowtie={bowtie:?}"
3676                            );
3677                        }
3678                    }
3679                    Err(refusal) => {
3680                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3681                            eprintln!("closed-rim refused: {refusal}");
3682                        }
3683                    }
3684                }
3685            }
3686        }
3687        let network_names: Vec<Option<String>> = (0..edge_points.len())
3688            .map(|index| per_edge_name(edge_names, name, index).map(str::to_string))
3689            .collect();
3690        let network_corner_name =
3691            |adjacent: &[usize]| corner_face_name(edge_names, name, adjacent);
3692        // BREP lane L: begin lcount229_knot_aware_group_network_20261016 A
3693        // support pcurve off the floor ends the group's network here, and
3694        // the ladder would go on to the cutter composition: re-run the
3695        // network ONCE with the knot-aware support fit; a re-run that also
3696        // fails keeps the first refusal.
3697        let group_network = || {
3698            crate::blend::blend_star_network_with_corner_policy(
3699                solid,
3700                &selected_edge_ids,
3701                radius,
3702                chamfer,
3703                &network_names,
3704                &network_corner_name,
3705                wrap_concave,
3706            )
3707        };
3708        let network_result = group_network().or_else(|first| {
3709            if crate::blend::is_pcurve_floor_refusal(&first) {
3710                crate::blend::with_pcurve_knot_retry(group_network).map_err(|_| first)
3711            } else {
3712                Err(first)
3713            }
3714        });
3715        // BREP lane L: end lcount229_knot_aware_group_network_20261016
3716        // The network's result under its acceptance: `Ok(Some)` accepted,
3717        // `Ok(None)` rejected (the ladder goes on), `Err` terminal.
3718        let accept_network = |mut network: BrepSolid, built_radius: f64| -> Result<Option<GroupBody>, KernelRefusal> {
3719                // Fail-safe like the rest of the ladder: a heal or validation
3720                // problem in the network result falls through to the cutter,
3721                // it does not fail the group.  So does an UNTRIMMED result: the
3722                // network re-trims only each stripe's two mates, and
3723                // `check_blend_interference` is what notices a third face
3724                // crossing the swept volume -- `validate` cannot, because a
3725                // self-intersecting solid is still a watertight one.
3726                let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3727                let heal = crate::blend::BlendTimer::start("timing.heal_vertex_gaps_ms");
3728                let healed = heal_edge_vertex_gaps(&mut network, built_radius);
3729                heal.stop();
3730                // See the closed-rim lane above: widen a planar carrier the
3731                // surgery overran, or refuse — terminally — rather than fall
3732                // through to a composition that cannot answer that question.
3733                let charts = crate::blend::BlendTimer::start("timing.planar_charts_ms");
3734                crate::blend::fit_planar_charts_to_trims(solid, &mut network)?;
3735                charts.stop();
3736                let validate = crate::blend::BlendTimer::start("timing.validate_ms");
3737                let issues = network.validate_memoised();
3738                validate.stop();
3739                let interference =
3740                    check_blend_interference(solid, &network, &selected_edge_ids, entry);
3741                // And the fourth question, which the other three all pass: does
3742                // any face of the result have a loop that crosses ITSELF? A
3743                // wall whose rail ran off its own face comes back as a bowtie,
3744                // and a bowtie is watertight, incident and connected.
3745                let bowtie = check_loop_self_crossings(&network, entry).and_then(|()| check_blend_wall_loops(&network, entry));
3746                if healed.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
3747                    return Ok(Some(GroupBody { body: network, bowtie_clean: true }));
3748                }
3749                crate::blend::reject_wrapped_network();
3750                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3751                    eprintln!(
3752                        "network result rejected: heal={healed:?} issues={issues:?} \
3753                         interference={interference:?} bowtie={bowtie:?}"
3754                    );
3755                    dump_loops_debug("INPUT", solid);
3756                    dump_loops_debug("RESULT", &network);
3757                }
3758                Ok(None)
3759        };
3760        match network_result {
3761            Ok(network) => {
3762                if let Some(body) = accept_network(network, radius)? {
3763                    return Ok(body);
3764                }
3765            }
3766            Err(refusal) => {
3767                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3768                    eprintln!("network refused: {refusal}");
3769                }
3770                // A mixed-convexity refusal over a selection whose concave
3771                // edges also miter each other: build them first, then the
3772                // convex edges (`concave_first_stages_on`).
3773                let mixed = matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what } if what == "mixed_convexity");
3774                if !chamfer && mixed && concave_first_stages_on() {
3775                    if let Some(body) = concave_first_stages(
3776                        solid, edge_points, edge_names, &selected_edge_ids, radius, name, wrap_concave,
3777                    ) {
3778                        return Ok(GroupBody { body, bowtie_clean: true });
3779                    }
3780                }
3781                // A stripe whose TAPER to a cusp reaches its full radius only
3782                // inside the corner setback at its other end has no constant
3783                // run at all (report 80c5d9d1's F10, 2026-10-24: r 1 on the two
3784                // straight edges of a sliver at most 2 wide within 0.9 of its
3785                // square corner). The round is built at the largest smaller
3786                // radius whose taper clears the setback, and says so, as the
3787                // relief says it over a whole rim. Before 2026-10-26 the group
3788                // fell through to the cutter composition, which closed each
3789                // round on a web and a cap under the neighbouring blend (an
3790                // undercut) in 9 minutes.
3791                let pinched_taper = matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what }
3792                    if what == crate::blend::STRIPE_PINCH_TAPER_WHAT);
3793                if !chamfer && pinched_taper && crate::blend::relief::radius_relief_on() {
3794                    let labels: Vec<String> =
3795                        (0..edge_points.len()).map(|index| selection_label(index, edge_points, edge_names, name)).collect();
3796                    for step in 1..=10u32 {
3797                        let reduced = radius * (1.0 - 0.05 * f64::from(step));
3798                        let built = crate::blend::blend_star_network_with_corner_policy(
3799                            solid, &selected_edge_ids, reduced, chamfer, &network_names, &network_corner_name, wrap_concave,
3800                        );
3801                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3802                            eprintln!(
3803                                "taper pinch ladder: r {reduced:.4} -> {}",
3804                                match &built {
3805                                    Ok(_) => "built".to_string(),
3806                                    Err(error) => format!("refused: {error}"),
3807                                }
3808                            );
3809                        }
3810                        match built {
3811                            Ok(network) => {
3812                                let Some(body) = accept_network(network, reduced)? else { break };
3813                                crate::blend::record_blend_note(format!(
3814                                    "radius reduced over the whole of {} to {reduced:.4}: at r {radius} the round tapering to \
3815                                     its tip reaches the full radius only inside the corner setback at its other end, so \
3816                                     r {radius} is reached nowhere",
3817                                    labels.join(", ")
3818                                ));
3819                                return Ok(body);
3820                            }
3821                            Err(again) if matches!(&again.class, crate::RefusalClass::UnsupportedGeometry { what }
3822                                if what == crate::blend::STRIPE_PINCH_TAPER_WHAT) => continue,
3823                            Err(_) => break,
3824                        }
3825                    }
3826                }
3827                // Independent stripe cutters cannot close a corner whose ball
3828                // exceeds the canal footprint. Preserve the requested radius
3829                // and its named refusal instead of searching partial selections.
3830                if matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what }
3831                    if what == "canal_footprint_bound") || crate::blend::is_ball_does_not_fit(&refusal) {
3832                    return Err(refusal);
3833                }
3834                // The runout composition reads the ring's own classification
3835                // back when the ring stage falls through to the cutter and
3836                // that refuses too (`LAST_NETWORK_REFUSAL`).
3837                LAST_NETWORK_REFUSAL.with(|last| *last.borrow_mut() = Some(refusal.clone()));
3838                if crate::blend::is_wall_fold(&refusal) {
3839                    GROUP_NETWORK_FOLD.with(|fold| *fold.borrow_mut() = Some(refusal.clone()));
3840                }
3841                // A refusal that is not a fold where the ball does not fit
3842                // (report 37e16630 at r 1.0, a ball the size of the round it
3843                // rides: its centre curve collapses to a point and the station
3844                // Newton is singular) is the fold the relief answers, not a
3845                // question for the composition, which took 143 s over it.
3846                if !chamfer && !crate::blend::is_wall_fold(&refusal) && crate::blend::relief::radius_relief_on() {
3847                    let started = web_time::Instant::now();
3848                    let misfit = crate::blend::relief::first_misfit(solid, &selected_edge_ids, radius);
3849                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3850                        eprintln!("radius relief: misfit probe {misfit:?} in {:.1} ms", started.elapsed().as_secs_f64() * 1e3);
3851                    }
3852                    if let Some((edge_id, least)) = misfit {
3853                        return Err(crate::blend::relief::misfit_fold(edge_id, least, radius, &refusal));
3854                    }
3855                }
3856                // The fail-safe above is for a refusal that says "not this
3857                // lane".  A marched fit that left its carriers does not say
3858                // that, and the cutter's answer to the same selection is not a
3859                // second opinion on it: on the notched cap's stuck connector
3860                // the composition reads 1724.506048919, +1.81e-2 against the
3861                // closed form, and it VALIDATES.  A refusal that falls through
3862                // to a validating wrong solid is not a refusal.
3863                //
3864                // Not every WALL FOLD, though the single-edge tool reads them all
3865                // as terminal (`is_terminal_blend_refusal`): a fold of the lens
3866                // between the rails is one the composition's cutter carves
3867                // (`inbox_20260902_corner_torus_collar_fillet::each_collar_has_its_own_fold_threshold`,
3868                // the r 2.1 collar at fold factor 1.036). One that reaches a
3869                // RAIL is not: the ball pokes out through the face it rides,
3870                // there is no lens to carve, and every cutter sweeps the same
3871                // envelope. Until 2026-10-21 the group fell through on that too:
3872                // report 37e16630's end face at r 1.7 around an r 1 round on its
3873                // outline ran the composition and its subset search for over 20
3874                // minutes. A lens fold the composition cannot rescue either is
3875                // answered by the fold (`fillet_edges_group_unchecked`).
3876                //
3877                // A blend stopping within a sliver of its face's width that
3878                // cannot be snapped onto the far edge without opening the shell
3879                // is terminal for the same reason: the SIZE is the question
3880                // (`blend::CONSUMED_SNAP_UNSOUND`), and the composition's tool
3881                // cut a sliver short of an edge leaves the sliver no lane keeps.
3882                //
3883                // And a FULL-WIDTH corner the network cannot collapse soundly
3884                // (`blend::RAIL_COLLAPSE_UNSUPPORTED`,
3885                // `blend::FULL_WIDTH_COLLAPSE_UNSOUND`): the composition's answer
3886                // to a full-width corner was measured wrong — a 5F/8E/5V miter
3887                // 8.0e-4 off its closed form at 1e-5 short of the width, and the
3888                // picture-frame corner at a full-width chamfer star.
3889                //
3890                // And a trim that left its planar carrier's chart
3891                // (`blend::PLANAR_CHART_EDGE_OFF_PLANE`,
3892                // `blend::PLANAR_CHART_WIDEN_UNSOUND`): the clamped body the
3893                // composition would answer with is the defect being refused.
3894                // A tangential end whose taper could not be planned also has
3895                // no supported closure for cutter composition to recover.
3896                if crate::blend::is_rail_fold(&refusal)
3897                    || crate::blend::is_marched_fit_off_carriers(&refusal)
3898                    || crate::blend::is_consumed_snap(&refusal)
3899                    || crate::blend::is_rail_collapse(&refusal)
3900                    || crate::blend::is_full_width_collapse(&refusal)
3901                    || crate::blend::is_planar_chart_refusal(&refusal)
3902                    || crate::blend::is_miter_support_overrun(&refusal)
3903                    || crate::blend::is_tangential_transverse_end(&refusal)
3904                {
3905                    return Err(refusal);
3906                }
3907            }
3908        }
3909    }
3910
3911    // An edge whose ball reaches its support only by rolling over a tangent
3912    // neighbour (`analyze::rollover_only_refusal`): the composition's tool
3913    // rides the mates' own carriers past the tangent edge and fills over air
3914    // (lCount_409 at r 2: +1.096 against the quadrature's 1103.315046), so
3915    // the reach refusal the unsigned check gave stands.
3916    if let Some(refusal) = super::analyze::rollover_only_refusal(&selected_edge_ids) {
3917        return Err(refusal);
3918    }
3919    CUTTER_COMPOSITIONS.with(|count| count.set(count.get() + 1));
3920    crate::blend::record_count("count.cutter_fallback", 1);
3921    let _cutter = crate::blend::BlendTimer::start("timing.cutter_ms");
3922    // 2. Build the blends.
3923    //
3924    //    CHAIN corners (§6.9.6 — exactly TWO selected edges share a vertex):
3925    //    the sequential build truncates the later blend where it runs into the
3926    //    earlier one and closes it with a flat bulkhead across the fillet
3927    //    channel — a hard step, not a transition.  For selections containing
3928    //    chain corners, blend each edge FULL-LENGTH on the ORIGINAL solid and
3929    //    INTERSECT the per-edge results instead: the removal volumes union, so
3930    //    adjacent blends run through the shared corner and trim each other
3931    //    along their intersection curve — the standard MITER corner, tangent
3932    //    to the shared face at the seam's tangency end.  Non-adjacent edges
3933    //    are unaffected (their removals are disjoint, intersection ≡
3934    //    sequential).
3935    //
3936    //    Selections without chain corners keep the sequential build unchanged
3937    //    (star corners are rounded in step 3 against exactly the sequential
3938    //    geometry round_convex_corner was built for).
3939    //    CONVEXITY GUARD: a convex blend REMOVES material (fillet = orig −
3940    //    cut), a concave blend ADDS it (orig + pad).  Full-length blends
3941    //    combine as orig − ∪cuts + ∪pads, so the per-edge results compose by
3942    //    INTERSECTION when every edge is convex and by UNION when every edge
3943    //    is concave; a mixed selection has no single composition and falls
3944    //    back to the sequential build.
3945    // Fillet stars keep the sequential topology required by their sphere
3946    // patches. Chamfer stars have no subsequent corner patch: compose their
3947    // full-length removals too, so all bevel planes meet at the corner.
3948    let miter_operation = if (chain_corner_count > 0 || !corners.is_empty())
3949        && (chamfer || corners.is_empty())
3950    {
3951        let mut any_convex = false;
3952        let mut any_concave = false;
3953        for point in edge_points {
3954            // Convexity is a DIHEDRAL property, so it is read from the general
3955            // scan (`scan_dihedral`) — the same one `check_mixed_concavity`
3956            // has already run over every selected edge.  `analyze_edge` used
3957            // to answer here and it ALSO refuses an edge the EXACT CUTTER
3958            // cannot build: a straight edge whose mates are not both planes,
3959            // a circular one whose mates do not share its axis.  Reading that
3960            // refusal as "unknown convexity" dropped the §6.9.6 miter for
3961            // every selection touching a curved carrier — the groove rim of a
3962            // bored box, say — and the sequential build then left a bulkhead
3963            // face standing in the shared corner (the 2026-09-10 "chamfer
3964            // produced a spurious face" report).
3965            match resolve_edge_by_point(solid, *point)
3966                .and_then(|edge_id| super::analyze::scan_dihedral(solid, edge_id))
3967            {
3968                // A mixed edge has no single composition either; it takes the
3969                // `_ => None` arm below through both flags.
3970                Ok(profile) if profile.samples > 0 && !profile.is_mixed() => {
3971                    any_convex |= profile.any_convex;
3972                    any_concave |= profile.any_concave;
3973                }
3974                // Unknown edge class: let the sequential path produce its own
3975                // (more specific) error or result.
3976                _ => {
3977                    any_convex = true;
3978                    any_concave = true;
3979                    break;
3980                }
3981            }
3982        }
3983        match (any_convex, any_concave) {
3984            (true, false) => Some(crate::BooleanOperation::Intersect),
3985            (false, true) => Some(crate::BooleanOperation::Union),
3986            _ => None,
3987        }
3988    } else {
3989        None
3990    };
3991
3992    // Fillet/chamfer each edge in turn, resolving its point on the evolving
3993    // solid (ids shift as earlier fillets rewrite topology; the midpoint of an
3994    // edge is untouched by the corner surgery of the others).  This is the
3995    // baseline build used directly for non-miter selections AND as the
3996    // fallback when the miter composition below cannot reassemble.
3997    // The composition's per-edge lane: cutter-first ONLY when a corner
3998    // closure will run afterwards and read cutter-shaped topology (a star or
3999    // a chain corner).  A selection with no shared vertex — a lone closed
4000    // rim, a lone chamfer, disconnected edges — has no such closure, so each
4001    // edge gets the march first there too.
4002    let composition_lane = if corners.is_empty() && chain_corner_count == 0 {
4003        Lane::GeneralFirst
4004    } else {
4005        Lane::CutterFirst
4006    };
4007    // The order the sequential build blends the selection in: the input
4008    // order, except that a CONCAVE edge ending at a star corner goes before
4009    // every convex edge (`sequential_build_order`). The §6.9.7 torus-sector
4010    // closure of a re-entrant vertex whose concave edge is selected too
4011    // (`round_mixed_concave_corner`) reads the concave blend's tangency
4012    // vertices off the convex cap cutters, so it exists only when the concave
4013    // edge was cut FIRST; a user who picks the keyway's rim and then its
4014    // inner corners (the 2026-10-13 sprocket report) got flat caps at both
4015    // corners from the input order, and the closure's own closed form from
4016    // this one. Every other selection keeps its input order, byte for byte.
4017    let concave_at_star = concave_star_edges(solid, &selected_edge_ids, &corner_edges, radius, chamfer);
4018    // And at a star corner whose edges the ladder answers with DIFFERENT
4019    // cutters, the marched edges go before the exact ones and the revolved
4020    // cutters last (`mixed_star_class_ranks`): the 2026-10-13 sprocket
4021    // report whose slit walls were selected as faces.
4022    let class_ranks = mixed_star_class_ranks(solid, &selected_edge_ids, &corner_edges, radius, chamfer);
4023    let sequential_order = sequential_build_order(edge_points.len(), &concave_at_star, &class_ranks);
4024    // And the corners close in the same precedence: a star with a concave
4025    // edge (the torus sector) before the convex stars, which on the report's
4026    // keyway share a 3.8-long rim edge with it — the convex star's surgery
4027    // read an open edge when it ran first (measured 2026-10-13), and closes
4028    // cleanly after the sector has trimmed that rim.
4029    let (corners, corner_edges) = corners_concave_first(corners, corner_edges, &concave_at_star);
4030    let mut build_sequential = || -> Result<BrepSolid, KernelRefusal> {
4031        let mut sequential = solid.clone();
4032        // The prefix chain of this build, for the subset search's memo (see
4033        // `ComponentMemo::sequential`); unused without one.
4034        let mut chain: Vec<SequentialKey> = Vec::with_capacity(sequential_order.len());
4035        for &index in &sequential_order {
4036            let point = &edge_points[index];
4037            let edge_id = resolve_edge_by_point(&sequential, *point)?;
4038            // Earlier cutters in this loop TRIM the edges that share a corner
4039            // with them; extend this cutter back over what they took so the
4040            // two removal volumes union through the corner (§6.9.6 miter)
4041            // instead of leaving a wedge of material standing behind a flush
4042            // end cap.  Untouched edges get a zero pad and the historical
4043            // flush cutter.
4044            let ends = tool_ends_to_original_extent(
4045                &sequential,
4046                edge_id,
4047                radius,
4048                original_extents[index],
4049                if chamfer { &[] } else { &corners },
4050            );
4051            // This edge's blend wall carries the name of THIS input edge
4052            // (`edge_names[index]`); a smooth chain that engulfs several edges
4053            // is named after the FIRST such input edge processed here (input
4054            // order), the chain's representative.
4055            let edge_name = per_edge_name(edge_names, name, index);
4056            if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4057                eprintln!(
4058                    "sequential build: selection #{index} {} is edge {edge_id} on the evolving body (ends {ends:?}, {composition_lane:?})",
4059                    selection_label(index, edge_points, edge_names, name)
4060                );
4061            }
4062            // Every step is a deterministic function of the body it starts
4063            // from and these four inputs, and the body is itself the chain of
4064            // the steps before it: a chain the search already composed on
4065            // this solid is answered from the memo, refusals included.
4066            chain.push((
4067                [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()],
4068                edge_name.map(str::to_string),
4069                ends.key_bits(),
4070                u8::from(composition_lane == Lane::CutterFirst),
4071            ));
4072            if let Some(memo) = memo.as_deref_mut() {
4073                let key = (memo.prefix.clone(), chain.clone());
4074                let hit = memo.sequential.get(&key);
4075                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4076                    eprintln!(
4077                        "sequential memo: {} components before, step {} {} ({} chains stored)",
4078                        memo.prefix.len(),
4079                        chain.len(),
4080                        if hit.is_some() { "HIT" } else { "miss" },
4081                        memo.sequential.len(),
4082                    );
4083                }
4084                if let Some(built) = hit {
4085                    crate::blend::record_count("count.sequential.memo_hits", 1);
4086                    sequential = built.clone()?;
4087                    continue;
4088                }
4089            }
4090            crate::blend::record_count("count.sequential.steps_built", 1);
4091            let built = fillet_or_chamfer(
4092                &sequential,
4093                edge_id,
4094                radius,
4095                chamfer,
4096                edge_name,
4097                ends,
4098                composition_lane,
4099            );
4100            if let Some(memo) = memo.as_deref_mut() {
4101                memo.sequential.insert((memo.prefix.clone(), chain.clone()), built.clone());
4102            }
4103            sequential = built?;
4104        }
4105        Ok(sequential)
4106    };
4107
4108    let mut result = if let Some(operation) = miter_operation {
4109        // The per-edge results still carry their cutters' standing scaffold,
4110        // which the group settles once its corners are closed. A scaffold face
4111        // merged here would hand its tag to whatever it merged with.
4112        let options = crate::BooleanOptions {
4113            keep_unmerged_name_substrs: vec![CUTTER_SCAFFOLD_NAME.to_string()],
4114            ..crate::BooleanOptions::default()
4115        };
4116        let mut combined: Result<Option<BrepSolid>, KernelRefusal> = Ok(None);
4117        // The units the miter composes: one per selected edge, except that
4118        // edges joined at a TANGENT chain corner blend as one unit through
4119        // this same group build (see `miter_tangent_units`).
4120        let units = miter_tangent_units(solid, &selected_edge_ids, &chain_corners, edge_points.len());
4121        for unit in &units {
4122            let index = unit[0];
4123            let point = &edge_points[index];
4124            let blended = if unit.len() > 1 {
4125                let points = unit.iter().map(|&member| edge_points[member]).collect::<Vec<_>>();
4126                let names = edge_names.map(|all| unit.iter().map(|&member| all[member].clone()).collect::<Vec<_>>());
4127                fillet_edges_group_with_corner_policy(
4128                    solid,
4129                    &points,
4130                    names.as_deref(),
4131                    radius,
4132                    chamfer,
4133                    name,
4134                    None,
4135                    wrap_concave,
4136                    false,
4137                )?
4138            } else {
4139                let edge_id = resolve_edge_by_point(solid, *point)?;
4140                let edge_name = per_edge_name(edge_names, name, index);
4141                let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
4142                check_mixed_concavity(solid, edge_id, entry)?;
4143                check_support_extent(solid, edge_id, radius, entry)?;
4144                fillet_or_chamfer(
4145                    solid,
4146                    edge_id,
4147                    radius,
4148                    chamfer,
4149                    edge_name,
4150                    ToolEnds::default(),
4151                    Lane::CutterFirst,
4152                )?
4153            };
4154            combined = match combined {
4155                Err(e) => Err(e),
4156                Ok(None) => Ok(Some(blended)),
4157                Ok(Some(previous)) => {
4158                    crate::boolean_operation(&previous, &blended, operation, &options)
4159                        .map(Some)
4160                        .map_err(|error| {
4161                            // The boolean's own class survives the wrap.
4162                            error.with_message(|error| {
4163                                format!("fillet_edges: chain-corner miter composition failed: {error}")
4164                            })
4165                        })
4166                }
4167            };
4168            if combined.is_err() {
4169                break;
4170            }
4171        }
4172        // A §6.9.6 miter (per-edge blends intersected/unioned through the
4173        // shared chain corners) can fail to reassemble on faces whose
4174        // fragmented boundary does not close — e.g. a planar cap whose ENTIRE
4175        // perimeter is selected, where fragment_face reports an "incomplete
4176        // run".  Rather than let `fillet_edges` silently DROP a selected edge
4177        // to recover a valid subset (the reported defect: not every edge of
4178        // the face gets a fillet), fall back to the sequential build, which
4179        // blends EVERY selected edge (chain corners get a flat bulkhead
4180        // instead of a miter).  Only if that also fails to produce a valid
4181        // solid do we surface the miter error so the caller's
4182        // maximal-valid-subset search can still run.
4183        match combined {
4184            Ok(Some(mut mitered)) => {
4185                drop_slit_shells(&mut mitered);
4186                mitered
4187            }
4188            Ok(None) => {
4189                return Err(KernelRefusal::input(
4190                    KernelStage::Collect,
4191                    "miter_selection",
4192                    "fillet_edges: no edges selected",
4193                ))
4194            }
4195            Err(miter_err) => match build_sequential() {
4196                Ok(seq) if seq.validate().is_empty() => seq,
4197                _ => return Err(miter_err),
4198            },
4199        }
4200    } else {
4201        build_sequential()?
4202    };
4203
4204    // A re-entrant vertex of a selected face perimeter has two selected,
4205    // convex cap-wall edges and one UNSELECTED concave wall-wall edge.  The
4206    // two cutter volumes only touch there, so the boolean miter leaves a
4207    // triangular planar end-cap instead of carrying the rolling ball around
4208    // the corner.  Close that exact orthogonal class with its horn-torus
4209    // sector (major radius = minor radius = fillet radius).
4210    // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4211    let mut open_mixed_corners: Vec<(Vec3, [u64; 2], Option<String>)> = Vec::new();
4212    // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4213    if !chamfer {
4214        for (corner, adjacent) in &chain_corners {
4215            let has_concave_unselected_edge = solid.edges.iter().any(|edge| {
4216                if selected_edge_ids.contains(&edge.id) {
4217                    return false;
4218                }
4219                let Ok(a) = edge.curve.evaluate(edge.t0) else {
4220                    return false;
4221                };
4222                let Ok(b) = edge.curve.evaluate(edge.t1) else {
4223                    return false;
4224                };
4225                (a.sub(*corner).length() < 1e-6 || b.sub(*corner).length() < 1e-6)
4226                    && analyze_edge(solid, edge.id, radius)
4227                        .map(|cross| !cross.convex)
4228                        .unwrap_or(false)
4229            });
4230            // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4231            // The OPEN mixed corner (the 2026-10-13 sprocket's keyway floor):
4232            // one selected convex rim, one selected concave vertical and an
4233            // UNSELECTED convex third edge. The rim's cutter ran through the
4234            // concave pad and left a scaffold square and a misplaced
4235            // bulkhead there; the closure is the one-ended runout's body —
4236            // the §6.9.7 torus sector to C5's stop, ended by its cliff
4237            // (`blend/corner/mixed_open.rs`). It reads the SETTLED body (the
4238            // pad's flush end merged into the cap), so the corner is noted
4239            // here and closed after `settle_cutter_scaffold` below.
4240            if !has_concave_unselected_edge {
4241                let convexity = |edge_id: u64| analyze_edge(solid, edge_id, radius).map(|cross| cross.convex).ok();
4242                let selected_pair = [convexity(selected_edge_ids[adjacent[0]]), convexity(selected_edge_ids[adjacent[1]])];
4243                let one_concave = matches!(selected_pair, [Some(true), Some(false)] | [Some(false), Some(true)]);
4244                let has_convex_unselected_edge = solid.edges.iter().any(|edge| {
4245                    if selected_edge_ids.contains(&edge.id) {
4246                        return false;
4247                    }
4248                    let (Ok(a), Ok(b)) = (edge.curve.evaluate(edge.t0), edge.curve.evaluate(edge.t1)) else {
4249                        return false;
4250                    };
4251                    (a.sub(*corner).length() < 1e-6 || b.sub(*corner).length() < 1e-6)
4252                        && analyze_edge(solid, edge.id, radius).map(|cross| cross.convex).unwrap_or(false)
4253                });
4254                if one_concave && has_convex_unselected_edge {
4255                    open_mixed_corners.push((
4256                        *corner,
4257                        [selected_edge_ids[adjacent[0]], selected_edge_ids[adjacent[1]]],
4258                        corner_face_name(edge_names, name, adjacent),
4259                    ));
4260                }
4261                continue;
4262            }
4263            // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4264            let corner_name = corner_face_name(edge_names, name, adjacent);
4265            if let Ok(rounded) = crate::blend::round_concave_chain_corner(
4266                &result,
4267                solid,
4268                *corner,
4269                [
4270                    selected_edge_ids[adjacent[0]],
4271                    selected_edge_ids[adjacent[1]],
4272                ],
4273                radius,
4274                corner_name.as_deref(),
4275            ) {
4276                result = rounded;
4277            }
4278        }
4279    }
4280
4281    // 3. Round the convex corners (fillets only — chamfers keep sharp
4282    //    vertices).  A corner that cannot be rounded is left as the edge
4283    //    fillets so the group still succeeds.  Each corner patch is named after
4284    //    the selected edges meeting there (`{fid}:BLEND:CORNER:{e_a}+…`) so no
4285    //    two corners collide and the patch stays under the `{fid}:BLEND` prefix.
4286    if !chamfer {
4287        for (ci, corner) in corners.iter().enumerate() {
4288            let corner_name = corner_face_name(edge_names, name, &corner_edges[ci]);
4289            match crate::blend::round_convex_corner(&result, *corner, radius, corner_name.as_deref()) {
4290                Ok(rounded) => result = rounded,
4291                Err(error) => {
4292                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4293                        eprintln!("corner at {corner:?} left as the edge fillets: {error}");
4294                    }
4295                }
4296            }
4297        }
4298    }
4299
4300    // Heal any residual vertex/edge gaps introduced by the corner-rounding
4301    // surgery (the per-edge results are already healed inside fillet_or_chamfer).
4302    heal_edge_vertex_gaps(&mut result, radius)?;
4303    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
4304    // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4305    let mut body = settle_cutter_scaffold(result);
4306    for (corner, pair, corner_name) in &open_mixed_corners {
4307        match crate::blend::round_mixed_concave_open_corner(&body, solid, *corner, *pair, radius, corner_name.as_deref()) {
4308            Ok(rounded) => body = rounded,
4309            Err(error) => {
4310                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4311                    eprintln!("open mixed corner at {corner:?} left as the composition built it: {error}");
4312                }
4313            }
4314        }
4315    }
4316    Ok(GroupBody { body, bowtie_clean: false })
4317    // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4318}
4319
4320/// The selected edges (indices into the selection) that are CONCAVE and end
4321/// at a star corner (`corner_edges`: three or more selected edges at one
4322/// vertex), in input order. Empty for a chamfer, a selection with no star
4323/// corner, one whose star corners carry no concave edge, and one whose
4324/// convexity cannot be read — the cases the composition builds in input
4325/// order, exactly as before.
4326/// Whether the miter composition drops a stray SLIT shell: on unless
4327/// `BREP_FILLET_MITER_DROP_SLIT_SHELLS=0`/`off`.
4328fn drop_slit_shells_on() -> bool {
4329    switch!(live "BREP_FILLET_MITER_DROP_SLIT_SHELLS", true)
4330}
4331
4332/// Remove from a composed miter body every shell beyond the first whose faces
4333/// are all SLITS — each loop runs along each of its edges once forward and
4334/// once back — over edges no other shell uses, then the edges and vertices
4335/// nothing references any more. Returns how many shells went.
4336///
4337/// Such a shell bounds no area and no volume. The 2026-11-07 "fillet fails"
4338/// report's five-edge selection composed to the right body (the volume of
4339/// the same composition on the serialised input, which has one shell) plus
4340/// one face of the hole's floor plane, `Box_NZ_Offset_1_1`, whose single loop
4341/// ran 1.25 out along one edge and straight back; `validate()` accepts it.
4342fn drop_slit_shells(body: &mut BrepSolid) -> usize {
4343    if !drop_slit_shells_on() || body.shells.len() < 2 {
4344        return 0;
4345    }
4346    let mut users: std::collections::HashMap<u64, std::collections::HashSet<usize>> = std::collections::HashMap::new();
4347    for (index, shell) in body.shells.iter().enumerate() {
4348        for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
4349            users.entry(coedge.edge_id).or_default().insert(index);
4350        }
4351    }
4352    let slit_face = |face: &crate::topology::FaceRecord| {
4353        face.loops.iter().all(|lp| {
4354            let mut runs: std::collections::HashMap<u64, (usize, usize)> = std::collections::HashMap::new();
4355            for coedge in &lp.coedges {
4356                let entry = runs.entry(coedge.edge_id).or_default();
4357                if coedge.forward {
4358                    entry.0 += 1;
4359                } else {
4360                    entry.1 += 1;
4361                }
4362            }
4363            !runs.is_empty() && runs.values().all(|&(forward, back)| forward == 1 && back == 1)
4364        })
4365    };
4366    let mut index = 0usize;
4367    let mut dropped = 0usize;
4368    body.shells.retain(|shell| {
4369        let this = index;
4370        index += 1;
4371        let slit = this > 0
4372            && !shell.faces.is_empty()
4373            && shell.faces.iter().all(|face| slit_face(face))
4374            && shell
4375                .faces
4376                .iter()
4377                .flat_map(|face| &face.loops)
4378                .flat_map(|lp| &lp.coedges)
4379                .all(|coedge| users.get(&coedge.edge_id).is_some_and(|set| set.len() == 1));
4380        dropped += usize::from(slit);
4381        !slit
4382    });
4383    if dropped == 0 {
4384        return 0;
4385    }
4386    let used_edges: std::collections::HashSet<u64> = body
4387        .shells
4388        .iter()
4389        .flat_map(|shell| &shell.faces)
4390        .flat_map(|face| &face.loops)
4391        .flat_map(|lp| &lp.coedges)
4392        .map(|coedge| coedge.edge_id)
4393        .collect();
4394    body.edges.retain(|edge| used_edges.contains(&edge.id));
4395    let used_vertices: std::collections::HashSet<u64> =
4396        body.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
4397    body.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
4398    dropped
4399}
4400
4401/// Whether the miter composition blends a TANGENT run of the selection as
4402/// one unit: on unless `BREP_FILLET_MITER_TANGENT_UNITS=0`/`off`.
4403fn miter_tangent_units_on() -> bool {
4404    switch!(live "BREP_FILLET_MITER_TANGENT_UNITS", true)
4405}
4406
4407/// The units the §6.9.6 miter composition blends and then intersects (or
4408/// unions), in input order of each unit's first edge: every selected edge on
4409/// its own, except that edges meeting at a chain corner where their tangents
4410/// CONTINUE each other (a G1 joint, the 1e-6 bar of the tangent-chain walk)
4411/// form one unit.
4412///
4413/// The miter exists for SHARP chain corners: two full-length blends run
4414/// through the corner and trim each other. At a tangent joint there is
4415/// nothing to trim — the two walls meet flush — and two full-length
4416/// per-edge blends of the edges either side of it, each capped where its
4417/// tangent neighbour was left sharp, overlap along that joint in a sliver
4418/// the boolean cannot conform (2026-11-07 "fillet fails" report: a revolve
4419/// end cap's hole loop, one cylinder edge meeting a ceiling plane edge that
4420/// runs on tangentially through an offset blend into a wall; "one-use edge
4421/// conformance did not converge after 8 passes" on the plane-edge result
4422/// intersected with the blend-edge result). The network lane builds such a
4423/// tangent run whole with flush joins; it refused the selection only for
4424/// its sharp re-entrant corners, so a unit that is a STRICT part of the
4425/// selection goes back through the group build, which reaches it there.
4426/// A selection that is one tangent run keeps per-edge units, so the
4427/// recursion always shrinks the selection.
4428fn miter_tangent_units(
4429    solid: &BrepSolid,
4430    selected_edge_ids: &[u64],
4431    chain_corners: &[(Vec3, [usize; 2])],
4432    count: usize,
4433) -> Vec<Vec<usize>> {
4434    let singles = || (0..count).map(|index| vec![index]).collect::<Vec<_>>();
4435    if !miter_tangent_units_on() || selected_edge_ids.len() != count {
4436        return singles();
4437    }
4438    // The tangent along `edge` pointing AWAY from its end at `corner`.
4439    let leaving = |edge_id: u64, corner: Vec3| -> Option<Vec3> {
4440        let edge = solid.edges.iter().find(|edge| edge.id == edge_id)?;
4441        if edge.degenerate {
4442            return None;
4443        }
4444        let start = edge.curve.evaluate(edge.t0).ok()?;
4445        let end = edge.curve.evaluate(edge.t1).ok()?;
4446        let at_start = start.sub(corner).length() <= end.sub(corner).length();
4447        let t = if at_start { edge.t0 } else { edge.t1 };
4448        let tangent = edge.curve.unit_tangent(t, edge.t0, edge.t1).ok()?;
4449        Some(if at_start { tangent } else { tangent.scale(-1.0) })
4450    };
4451    let mut parent: Vec<usize> = (0..count).collect();
4452    fn root(parent: &mut [usize], mut index: usize) -> usize {
4453        while parent[index] != index {
4454            parent[index] = parent[parent[index]];
4455            index = parent[index];
4456        }
4457        index
4458    }
4459    for (corner, [a, b]) in chain_corners {
4460        let (Some(ta), Some(tb)) = (leaving(selected_edge_ids[*a], *corner), leaving(selected_edge_ids[*b], *corner)) else {
4461            continue;
4462        };
4463        // Leaving the corner, a tangent continuation points the opposite way.
4464        if ta.dot(tb) <= -(1.0 - 1e-6) {
4465            let (ra, rb) = (root(&mut parent, *a), root(&mut parent, *b));
4466            if ra != rb {
4467                parent[ra.max(rb)] = ra.min(rb);
4468            }
4469        }
4470    }
4471    let mut units: Vec<Vec<usize>> = Vec::new();
4472    let mut unit_of_root: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
4473    for index in 0..count {
4474        let r = root(&mut parent, index);
4475        let slot = *unit_of_root.entry(r).or_insert_with(|| {
4476            units.push(Vec::new());
4477            units.len() - 1
4478        });
4479        units[slot].push(index);
4480    }
4481    if units.len() <= 1 || units.iter().all(|unit| unit.len() == 1) {
4482        return singles();
4483    }
4484    units
4485}
4486
4487fn concave_star_edges(
4488    solid: &BrepSolid,
4489    selected_edge_ids: &[u64],
4490    corner_edges: &[Vec<usize>],
4491    radius: f64,
4492    chamfer: bool,
4493) -> Vec<usize> {
4494    if chamfer || corner_edges.is_empty() || !concave_first_on() {
4495        return Vec::new();
4496    }
4497    let Some(convexity) = crate::blend::selection_convexity(solid, selected_edge_ids, radius) else {
4498        return Vec::new();
4499    };
4500    (0..selected_edge_ids.len())
4501        .filter(|&index| !convexity[index] && corner_edges.iter().any(|adjacent| adjacent.contains(&index)))
4502        .collect()
4503}
4504
4505/// The cutter the sequential build's single-edge ladder answers a selected
4506/// edge with, read on the ORIGINAL solid: an exact extrusion (a straight
4507/// edge between planes), an exact revolution (a circular edge on
4508/// straight-meridian carriers about its own axis) or, for every other edge,
4509/// the general march (`fillet_or_chamfer_exact` refuses it, so the march
4510/// builds it with direct surgery on the evolving body).
4511#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4512enum CutterClass {
4513    Marched,
4514    Straight,
4515    Circular,
4516}
4517
4518fn cutter_class(solid: &BrepSolid, edge_id: u64, radius: f64) -> CutterClass {
4519    match super::analyze::analyze_edge(solid, edge_id, radius) {
4520        Ok(cross) => match cross.path {
4521            super::analyze::EdgePath::Straight { .. } => CutterClass::Straight,
4522            super::analyze::EdgePath::Circular { .. } => CutterClass::Circular,
4523        },
4524        Err(_) => CutterClass::Marched,
4525    }
4526}
4527
4528/// The sequential build's rank of every selected edge, from the cutter
4529/// classes meeting at the selection's star corners: `1` for a marched edge
4530/// and `3` for a revolved cutter at a star whose edges MIX classes, `2` for
4531/// everything else (a star of one class, a chain corner, a lone edge).
4532/// Within a rank the input order holds ([`sequential_build_order`]).
4533///
4534/// At such a corner the input order fails in two ways, both measured on the
4535/// 2026-10-13 sprocket report whose slit walls were selected as faces
4536/// (`inbox_20261013_sprocket_keyway_slit_fillet`): a revolved cutter leaves
4537/// a TORUS tangent to the hub's top plane along its rail, and the next
4538/// straight cutter's scaffold face lies in that very plane and ends on that
4539/// rail, so the boolean meets a tangent plane/torus contact along a 0.148
4540/// arc that the imprint traces but the assembly cannot close (`unsupported
4541/// tangent-curve surface intersection`, open edges, a 0.067 curve/vertex
4542/// gap); and the slit's vertical, a straight edge on the hub CYLINDER that
4543/// only the march builds, finds "no single end face across the corner" once
4544/// its star mates have been cut. The marched edge cut first sees the pristine
4545/// corner, and a straight cutter cut before the revolved one meets the
4546/// scaffold plane of a CYLINDER tangent along a line — the ordinary planar
4547/// star's own geometry, which the arrangement has always closed. Every
4548/// selection without a mixed-class star keeps its order, byte for byte.
4549fn mixed_star_class_ranks(
4550    solid: &BrepSolid,
4551    selected_edge_ids: &[u64],
4552    corner_edges: &[Vec<usize>],
4553    radius: f64,
4554    chamfer: bool,
4555) -> Vec<u8> {
4556    let mut ranks = vec![2u8; selected_edge_ids.len()];
4557    if chamfer || corner_edges.is_empty() || !class_order_on() {
4558        return ranks;
4559    }
4560    let classes: Vec<CutterClass> = selected_edge_ids
4561        .iter()
4562        .map(|&edge_id| cutter_class(solid, edge_id, radius))
4563        .collect();
4564    for adjacent in corner_edges {
4565        let Some(&head) = adjacent.first() else {
4566            continue;
4567        };
4568        if adjacent.iter().all(|&index| classes[index] == classes[head]) {
4569            continue;
4570        }
4571        for &index in adjacent {
4572            match classes[index] {
4573                CutterClass::Marched => ranks[index] = 1,
4574                CutterClass::Circular => ranks[index] = 3,
4575                CutterClass::Straight => {}
4576            }
4577        }
4578    }
4579    ranks
4580}
4581
4582/// The order the cutter composition's sequential build blends a selection
4583/// in: the input order, except that the edges in `first` (a star corner's
4584/// concave edges, [`concave_star_edges`]) are moved ahead of every other
4585/// edge and the rest follow by `ranks` ([`mixed_star_class_ranks`], lower
4586/// first), keeping the input order among the moved edges and within each
4587/// rank. With `first` empty and every rank equal this is the input order.
4588pub fn sequential_build_order(count: usize, first: &[usize], ranks: &[u8]) -> Vec<usize> {
4589    let mut order: Vec<usize> = (0..count).collect();
4590    // A stable sort: ties keep the input order.
4591    order.sort_by_key(|&index| if first.contains(&index) { 0 } else { ranks.get(index).copied().unwrap_or(2).max(1) });
4592    order
4593}
4594
4595/// Whether the sequential build ranks a mixed-class star's edges by cutter
4596/// class ([`mixed_star_class_ranks`]); always, outside a test that forces it
4597/// off.
4598fn class_order_on() -> bool {
4599    true
4600}
4601
4602
4603/// `corners` and their `corner_edges` (parallel), with every corner that one
4604/// of the `first` edges ends at moved ahead of the rest, both runs in their
4605/// detection order. With `first` empty both come back as they were.
4606fn corners_concave_first(
4607    corners: Vec<Vec3>,
4608    corner_edges: Vec<Vec<usize>>,
4609    first: &[usize],
4610) -> (Vec<Vec3>, Vec<Vec<usize>>) {
4611    if first.is_empty() {
4612        return (corners, corner_edges);
4613    }
4614    let mut ordered: Vec<(Vec3, Vec<usize>)> = Vec::with_capacity(corners.len());
4615    let pairs: Vec<(Vec3, Vec<usize>)> = corners.into_iter().zip(corner_edges).collect();
4616    let with_concave = |adjacent: &Vec<usize>| adjacent.iter().any(|index| first.contains(index));
4617    ordered.extend(pairs.iter().filter(|(_, adjacent)| with_concave(adjacent)).cloned());
4618    ordered.extend(pairs.iter().filter(|(_, adjacent)| !with_concave(adjacent)).cloned());
4619    ordered.into_iter().unzip()
4620}
4621
4622/// Whether the sequential build moves a star corner's concave edge first
4623/// ([`sequential_build_order`]); always, outside a test that forces it off.
4624fn concave_first_on() -> bool {
4625    true
4626}
4627
4628
4629/// Variable-radius fillet/chamfer of a GROUP of edges (§4.9.5), the app entry
4630/// for tapered blends: each selected edge (resolved by a point on it) is
4631/// blended with the SAME radius profile `radii` — a list of (edge-fraction,
4632/// radius) stops in `[0,1]` — applied along that edge's own parameterization.
4633/// Edges are blended independently (no shared-vertex corner rounding; a
4634/// variable-radius star has no single tangent ball), so this is the tapered
4635/// counterpart of `fillet_edges` for the constant case.
4636pub fn fillet_edges_variable(
4637    solid: &BrepSolid,
4638    edge_points: &[Vec3],
4639    edge_names: Option<&[String]>,
4640    radii: &[(f64, f64)],
4641    chamfer: bool,
4642    name: Option<&str>,
4643) -> Result<BrepSolid, KernelRefusal> {
4644    // One blend operation: the reports of an earlier one, never consumed, are
4645    // dropped as it starts (nested calls keep this operation's).
4646    let _operation = crate::blend::BlendOperation::enter();
4647    if edge_points.is_empty() {
4648        return Err(KernelRefusal::input(
4649            KernelStage::Collect,
4650            "variable_selection",
4651            "fillet_edges_variable: no edges selected",
4652        ));
4653    }
4654    let per_edge_stops: Vec<Vec<(f64, f64)>> = vec![radii.to_vec(); edge_points.len()];
4655    fillet_edges_variable_impl(
4656        solid,
4657        edge_points,
4658        edge_names,
4659        &per_edge_stops,
4660        chamfer,
4661        name,
4662        "fillet_edges_variable",
4663        true,
4664    )
4665}
4666
4667/// The shared variable-radius group core: each selected edge `i` is blended
4668/// with ITS OWN stop list `per_edge_stops[i]` (the legacy entry replicates one
4669/// list; the law entries sample a chain-abscissa [`crate::law::RadiusLaw`] per
4670/// edge).  `allow_tapered_sequential` keeps the legacy entry's sequential
4671/// fallback for tapered chains (whose end state is the honest
4672/// "mismatched radii" validation gate); the law entries pass `false` because
4673/// their stop fractions are computed against the ORIGINAL edges — the
4674/// sequential build re-resolves edges on the evolving solid whose shared
4675/// corners are already TRIMMED by earlier blends, which would silently distort
4676/// the law's abscissa mapping (constant stops are immune, so they may still
4677/// fall back).
4678#[allow(clippy::too_many_arguments)]
4679fn fillet_edges_variable_impl(
4680    solid: &BrepSolid,
4681    edge_points: &[Vec3],
4682    edge_names: Option<&[String]>,
4683    per_edge_stops: &[Vec<(f64, f64)>],
4684    chamfer: bool,
4685    name: Option<&str>,
4686    entry: &str,
4687    allow_tapered_sequential: bool,
4688) -> Result<BrepSolid, KernelRefusal> {
4689    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`)
4690    // and the recentre guard, as `fillet_edges_reported` applies them.
4691    let bounds = crate::recentre::solid_bounds(solid);
4692    let translated = match crate::recentre::control_offset_at_entry() {
4693        Some(offset) => Some((offset, crate::recentre::EntryKind::Control)),
4694        None => crate::recentre::guard_offset(bounds).map(|offset| {
4695            crate::recentre::profile_fired(entry, offset, bounds);
4696            (offset, crate::recentre::EntryKind::Guard)
4697        }),
4698    };
4699    if let Some((offset, kind)) = translated {
4700        let _entry = crate::recentre::TranslatedEntry::open(kind);
4701        let translate = |solid: &BrepSolid, offset: Vec3| {
4702            crate::recentre::translate_solid(solid, offset).map_err(|message| {
4703                KernelRefusal::internal(
4704                    KernelStage::Collect,
4705                    "translation_control",
4706                    format!("{entry}: the translation control could not move the solid: {message}"),
4707                )
4708            })
4709        };
4710        let moved = translate(solid, offset)?;
4711        let points: Vec<Vec3> = edge_points.iter().map(|point| point.add(offset)).collect();
4712        let result = fillet_edges_variable_impl(
4713            &moved,
4714            &points,
4715            edge_names,
4716            per_edge_stops,
4717            chamfer,
4718            name,
4719            entry,
4720            allow_tapered_sequential,
4721        )?;
4722        return translate(&result, offset.scale(-1.0));
4723    }
4724    debug_assert_eq!(per_edge_stops.len(), edge_points.len());
4725    // A law that is one constant everywhere IS the constant-radius fillet:
4726    // hand it to the constant group, whose corners are constructed (the
4727    // stripe network) rather than composed by boolean.
4728    if let Some(constant) = per_edge_stops
4729        .first()
4730        .and_then(|stops| stops.first())
4731        .map(|(_, radius)| *radius)
4732    {
4733        let uniform = per_edge_stops.iter().all(|stops| {
4734            stops
4735                .iter()
4736                .all(|(_, radius)| (radius - constant).abs() <= 1e-12 * (1.0 + constant.abs()))
4737        });
4738        if uniform && constant > 0.0 {
4739            return fillet_edges(solid, edge_points, edge_names, constant, chamfer, name);
4740        }
4741    }
4742    let max_radius = per_edge_stops
4743        .iter()
4744        .flat_map(|stops| stops.iter())
4745        .map(|(_, r)| r.abs())
4746        .fold(0.0_f64, f64::max);
4747
4748    // Tried first; whatever the network does not build (an unequal-radius
4749    // corner, a flush join or re-entrant vertex at a varying radius, a
4750    // result its acceptance rejects) falls through to the composition below
4751    // exactly as before.
4752    if edge_points.len() >= 2 {
4753        match fillet_variable_network(
4754            solid, edge_points, edge_names, per_edge_stops, chamfer, name, entry, max_radius,
4755        )? {
4756            Ok(built) => return Ok(built),
4757            // A radius relief's law is the network's to build: the
4758            // composition below took 75 s a plan on report 37e16630 at r 1.0
4759            // and built none, so the relief's next plan is asked instead.
4760            Err(refusal) if crate::blend::relief::relieving() => return Err(refusal),
4761            Err(_) => {}
4762        }
4763    }
4764
4765    // Chain corners miter exactly like the constant-radius group (§6.9.6):
4766    // per-edge blends on the ORIGINAL solid composed by boolean — Intersect
4767    // when every edge is convex, Union when every edge is concave.  Mixed or
4768    // unclassifiable selections keep the sequential build.  Variable blends
4769    // never round star vertices, so unlike the constant group there is no
4770    // sequential-only star path to protect.
4771    let mut chain_corner = false;
4772    {
4773        use rustc_hash::FxHashSet as HashSet;
4774        let mut endpoints: Vec<(Vec3, usize)> = Vec::with_capacity(edge_points.len() * 2);
4775        for (i, point) in edge_points.iter().enumerate() {
4776            if let Ok(edge_id) = resolve_edge_by_point(solid, *point) {
4777                if let Some(edge) = solid.edges.iter().find(|e| e.id == edge_id) {
4778                    if let (Ok(a), Ok(b)) =
4779                        (edge.curve.evaluate(edge.t0), edge.curve.evaluate(edge.t1))
4780                    {
4781                        endpoints.push((a, i));
4782                        endpoints.push((b, i));
4783                    }
4784                }
4785            }
4786        }
4787        let mut used = vec![false; endpoints.len()];
4788        for i in 0..endpoints.len() {
4789            if used[i] {
4790                continue;
4791            }
4792            used[i] = true;
4793            let mut edges_here: HashSet<usize> = HashSet::default();
4794            edges_here.insert(endpoints[i].1);
4795            for j in (i + 1)..endpoints.len() {
4796                if used[j] {
4797                    continue;
4798                }
4799                if endpoints[i].0.sub(endpoints[j].0).length() < 1e-6 {
4800                    used[j] = true;
4801                    edges_here.insert(endpoints[j].1);
4802                }
4803            }
4804            if edges_here.len() == 2 {
4805                chain_corner = true;
4806            }
4807        }
4808    }
4809    let miter_operation = if chain_corner {
4810        let probe_radius = if max_radius > 0.0 { max_radius } else { 1.0 };
4811        let mut any_convex = false;
4812        let mut any_concave = false;
4813        for point in edge_points {
4814            match resolve_edge_by_point(solid, *point)
4815                .and_then(|edge_id| analyze_edge(solid, edge_id, probe_radius))
4816            {
4817                Ok(cross) if cross.convex => any_convex = true,
4818                Ok(_) => any_concave = true,
4819                Err(_) => {
4820                    any_convex = true;
4821                    any_concave = true;
4822                    break;
4823                }
4824            }
4825        }
4826        match (any_convex, any_concave) {
4827            (true, false) => Some(crate::BooleanOperation::Intersect),
4828            (false, true) => Some(crate::BooleanOperation::Union),
4829            _ => None,
4830        }
4831    } else {
4832        None
4833    };
4834
4835    // Try the miter first; the variable blend's FITTED boundary curves are
4836    // only ~1e-3 accurate at blend-blend tangencies (unlike the exact
4837    // constant-radius cylinders), so the composition can fail — fall back to
4838    // the sequential build then, which is never worse than the pre-miter
4839    // behavior.  Tightening the taper surface's endpoint fitting is the
4840    // documented follow-up that would make the miter stick.
4841    let miter_attempt: Option<BrepSolid> = if let Some(operation) = miter_operation {
4842        let options = crate::BooleanOptions::default();
4843        let mut combined: Option<BrepSolid> = None;
4844        let mut failed = false;
4845        for (index, point) in edge_points.iter().enumerate() {
4846            let Ok(edge_id) = resolve_edge_by_point(solid, *point) else {
4847                failed = true;
4848                break;
4849            };
4850            let edge_name = per_edge_name(edge_names, name, index);
4851            let Ok(blended) = crate::blend::blend_edge_variable(
4852                solid,
4853                edge_id,
4854                &per_edge_stops[index],
4855                chamfer,
4856                edge_name,
4857            ) else {
4858                failed = true;
4859                break;
4860            };
4861            let next = match combined.take() {
4862                None => blended,
4863                Some(previous) => {
4864                    match crate::boolean_operation(&previous, &blended, operation, &options) {
4865                        Ok(next) => next,
4866                        Err(_) => {
4867                            failed = true;
4868                            break;
4869                        }
4870                    }
4871                }
4872            };
4873            combined = Some(next);
4874        }
4875        if failed {
4876            None
4877        } else {
4878            combined.filter(|s| s.validate().is_empty())
4879        }
4880    } else {
4881        None
4882    };
4883    let mut result = match miter_attempt {
4884        Some(mitered) => mitered,
4885        None => {
4886            // Any stop list that is NOT radius-uniform (the same 1e-12
4887            // relative criterion `blend_edge_variable` uses for its exact
4888            // constant-radius degeneration) makes the sequential build
4889            // abscissa-distorting on trimmed chain edges; law entries refuse
4890            // instead of silently shifting the law.
4891            let tapered = per_edge_stops.iter().any(|stops| {
4892                stops.first().is_some_and(|(_, first)| {
4893                    stops
4894                        .iter()
4895                        .any(|(_, r)| (r - first).abs() > 1e-12 * (1.0 + first.abs()))
4896                })
4897            });
4898            if chain_corner && tapered && !allow_tapered_sequential {
4899                // The transition patch that would carry a taper through the
4900                // corner is not built: a named deferral.
4901                return Err(KernelRefusal::unsupported(
4902                    KernelStage::Sew,
4903                    "tapered_chain_miter",
4904                    format!(
4905                        "{entry}: the tapered blends across the selected chain's shared corners \
4906                         did not compose to a valid solid (the fitted blend boundaries could not \
4907                         be mitered); fillet fewer edges per operation or reduce the taper"
4908                    ),
4909                ));
4910            }
4911            let mut sequential = solid.clone();
4912            for (index, point) in edge_points.iter().enumerate() {
4913                let edge_id = resolve_edge_by_point(&sequential, *point)?;
4914                let edge_name = per_edge_name(edge_names, name, index);
4915                sequential = crate::blend::blend_edge_variable(
4916                    &sequential,
4917                    edge_id,
4918                    &per_edge_stops[index],
4919                    chamfer,
4920                    edge_name,
4921                )?;
4922            }
4923            sequential
4924        }
4925    };
4926    // Heal §6.9 surgery so re-trimmed edges meet their vertices exactly; scale
4927    // the heal bound by the largest radius stop in the taper profile.
4928    heal_edge_vertex_gaps(&mut result, max_radius)?;
4929    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
4930    // Final honesty gate: a genuinely TAPERED chain (different radii at the
4931    // shared corner) has mismatched trim stations there — the blends cannot
4932    // meet without a transition patch (not implemented), and the sequential
4933    // surgery silently left broken topology before this gate existed.
4934    let issues = result.validate();
4935    if !issues.is_empty() {
4936        // Two verdicts share the text's shape: the legacy entry names the
4937        // transition patch it does not build (a deferral); the law entries,
4938        // whose taper is continuous through the corner, report the
4939        // composition failing its own validation (a check that tripped).
4940        let (detail, class) = if allow_tapered_sequential {
4941            (
4942                "tapered blends meet at a shared chain vertex with \
4943                 mismatched radii — the radius-transition corner patch is not implemented; \
4944                 fillet the edges in separate operations or use matching stop radii",
4945                RefusalClass::UnsupportedGeometry {
4946                    what: "taper_transition_patch".into(),
4947                },
4948            )
4949        } else {
4950            (
4951                "the composed radius-law blend produced invalid topology — the blends \
4952                 across a shared chain corner failed to reassemble",
4953                RefusalClass::Internal {
4954                    what: "law_chain_topology".into(),
4955                },
4956            )
4957        };
4958        return Err(KernelRefusal::new(
4959            class,
4960            KernelStage::Validate,
4961            format!(
4962                "{entry}: {detail} ({} validation issues, first: {})",
4963                issues.len(),
4964                issues
4965                    .first()
4966                    .map(|issue| issue.message.clone())
4967                    .unwrap_or_default()
4968            ),
4969        ));
4970    }
4971    // The variable-radius lane's own soundness acceptance, the same one the
4972    // constant-radius group exit takes. `validate()` above is an INCIDENCE
4973    // test: a tapered wall that passes through a neighbour, or through itself,
4974    // satisfies every check it makes and still measures a volume.
4975    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
4976    crate::accept_sound(result, entry)
4977}
4978
4979/// `Ok(None)` is "not this lane" — the network refused, or its result
4980/// failed the same acceptance the constant group holds the network to —
4981/// and the caller composes as before; `Err` is a refusal nothing below
4982/// can answer.
4983#[allow(clippy::too_many_arguments)]
4984fn fillet_variable_network(
4985    solid: &BrepSolid,
4986    edge_points: &[Vec3],
4987    edge_names: Option<&[String]>,
4988    per_edge_stops: &[Vec<(f64, f64)>],
4989    chamfer: bool,
4990    name: Option<&str>,
4991    entry: &str,
4992    max_radius: f64,
4993) -> Result<Result<BrepSolid, KernelRefusal>, KernelRefusal> {
4994    let mut edge_ids = Vec::with_capacity(edge_points.len());
4995    for point in edge_points {
4996        edge_ids.push(resolve_edge_by_point(solid, *point)?);
4997    }
4998    let laws: Vec<crate::blend::StripeRadius> =
4999        per_edge_stops.iter().map(|stops| crate::blend::StripeRadius::from_stops(stops)).collect();
5000    let network_names: Vec<Option<String>> = (0..edge_points.len())
5001        .map(|index| per_edge_name(edge_names, name, index).map(str::to_string))
5002        .collect();
5003    let network_corner_name = |adjacent: &[usize]| corner_face_name(edge_names, name, adjacent);
5004    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
5005    // A support pcurve off the floor is re-run ONCE with the knot-aware
5006    // support fit, as the constant group's network is; a re-run that also
5007    // fails keeps the first refusal. A radius relief's law crowds the
5008    // march's stations into its ramp, and the rail's knot spans there are
5009    // finer than the uniform track can follow (a reported model: r 1.4 on
5010    // the outline of a cut through a sub-D body, its relieved rail spans
5011    // 7.7e-5 against a track spacing of 2.4e-4, 1.5e-6 off at 4097
5012    // samples).
5013    let law_network = || {
5014        crate::blend::blend_star_network_laws(solid, &edge_ids, &laws, chamfer, &network_names, &network_corner_name, true)
5015    };
5016    let network_result = law_network().or_else(|first| {
5017        if crate::blend::is_pcurve_floor_refusal(&first) {
5018            crate::blend::with_pcurve_knot_retry(law_network).map_err(|_| first)
5019        } else {
5020            Err(first)
5021        }
5022    });
5023    let mut network = match network_result {
5024        Ok(network) => network,
5025        Err(refusal) => {
5026            if debug {
5027                eprintln!("law network refused: {refusal}");
5028            }
5029            return Ok(Err(refusal));
5030        }
5031    };
5032    // The constant group's acceptance of a network result, in its order:
5033    // the vertex-gap heal, the planar charts, validation, the interference
5034    // classifier and the bowtie scan; then the soundness acceptance the
5035    // variable lane's exit takes.
5036    let healed = heal_edge_vertex_gaps(&mut network, max_radius);
5037    crate::blend::fit_planar_charts_to_trims(solid, &mut network)?;
5038    let issues = network.validate();
5039    let interference = check_blend_interference(solid, &network, &edge_ids, entry);
5040    let bowtie = check_loop_self_crossings(&network, entry).and_then(|()| check_blend_wall_loops(&network, entry));
5041    if healed.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
5042        crate::soundness::census::profile_operation(&network, &[solid], None, entry);
5043        match crate::accept_sound(network, entry) {
5044            Ok(sound) => return Ok(Ok(sound)),
5045            Err(refusal) => {
5046                if debug {
5047                    eprintln!("law network result unsound: {refusal}");
5048                }
5049                return Ok(Err(refusal));
5050            }
5051        }
5052    }
5053    if debug {
5054        eprintln!(
5055            "law network result rejected: heal={healed:?} issues={issues:?} \
5056             interference={interference:?} bowtie={bowtie:?}"
5057        );
5058    }
5059    Ok(Err(KernelRefusal::unsupported(
5060        KernelStage::Validate,
5061        "law_network_rejected",
5062        format!(
5063            "{entry}: the tapered network's result was rejected (heal {}, {} validation issues, interference {}, loops {})",
5064            if healed.is_ok() { "ok" } else { "failed" },
5065            issues.len(),
5066            if interference.is_ok() { "ok" } else { "found" },
5067            if bowtie.is_ok() { "ok" } else { "found" },
5068        ),
5069    )))
5070}
5071
5072
5073/// One selected edge placed on the ordered chain, with its arc-length
5074/// parameterization (the caller-side mapping from chain abscissa to the
5075/// `blend_edge_variable` per-edge parameter-fraction stop seam).
5076struct ChainLink {
5077    /// Position of this edge in the caller's `edge_points` selection.
5078    input_index: usize,
5079    /// True when the edge's own t0→t1 parameter direction runs WITH the chain.
5080    forward: bool,
5081    /// Cumulative chord-length table from the edge's t0 end:
5082    /// `(parameter fraction, arc length)`, uniformly spaced in fraction.
5083    arc: Vec<(f64, f64)>,
5084    /// Total arc length of the edge.
5085    length: f64,
5086    /// Chain abscissa at the link's ENTRY vertex (the end reached first when
5087    /// walking the chain from its start).
5088    abscissa: f64,
5089}
5090
5091/// Cumulative chord-length table of one edge, `(parameter fraction, arc
5092/// length)` at uniform fractions.  The sample count doubles until two
5093/// successive total-length estimates agree within `tol` (chord length
5094/// converges O(N⁻²) for smooth curves, so the agreement of the N and 2N
5095/// estimates bounds the remaining error at the same order); straight edges
5096/// converge on the first doubling.  The 16-sample start resolves any
5097/// single-span arc of up to half a turn to sub-percent before refinement; the
5098/// 4096 cap (8 doublings) guards adversarial curves — beyond it the table is
5099/// two orders denser than the blend march's station grid, so finer chords
5100/// cannot move any station's sampled radius meaningfully.
5101fn edge_arc_table(
5102    curve: &NurbsCurve,
5103    t0: f64,
5104    t1: f64,
5105    tol: f64,
5106) -> Result<(Vec<(f64, f64)>, f64), KernelRefusal> {
5107    let evaluate = |t: f64| curve.evaluate(t).or_refuse(KernelStage::Collect, "arc_table");
5108    let build = |n: usize| -> Result<(Vec<(f64, f64)>, f64), KernelRefusal> {
5109        let mut table = Vec::with_capacity(n + 1);
5110        let mut cumulative = 0.0;
5111        let mut previous = evaluate(t0)?;
5112        table.push((0.0, 0.0));
5113        for j in 1..=n {
5114            let fraction = j as f64 / n as f64;
5115            let point = evaluate(t0 + (t1 - t0) * fraction)?;
5116            cumulative += point.sub(previous).length();
5117            previous = point;
5118            table.push((fraction, cumulative));
5119        }
5120        Ok((table, cumulative))
5121    };
5122    let mut n = 16usize;
5123    let (mut table, mut length) = build(n)?;
5124    while n < 4096 {
5125        n *= 2;
5126        let (next_table, next_length) = build(n)?;
5127        let converged = (next_length - length).abs() <= tol;
5128        table = next_table;
5129        length = next_length;
5130        if converged {
5131            break;
5132        }
5133    }
5134    Ok((table, length))
5135}
5136
5137/// Arc length from the edge's t0 end at `fraction` of its parameter span,
5138/// linearly interpolated in the uniform chord table.
5139fn arc_length_at_fraction(table: &[(f64, f64)], fraction: f64) -> f64 {
5140    let fraction = fraction.clamp(0.0, 1.0);
5141    let intervals = table.len() - 1;
5142    let scaled = fraction * intervals as f64;
5143    let index = (scaled.floor() as usize).min(intervals - 1);
5144    let local = scaled - index as f64;
5145    let (_, a) = table[index];
5146    let (_, b) = table[index + 1];
5147    a + (b - a) * local
5148}
5149
5150/// Resolve the selected edges and order them into ONE OPEN CHAIN with
5151/// cumulative arc-length abscissas.  The chain starts at the free endpoint
5152/// belonging to the EARLIEST-selected end edge (so users get the natural
5153/// "first pick carries the law start" orientation); a single selected edge is
5154/// its own chain oriented t0→t1 (which also admits a closed edge — the law's
5155/// end radii must then match, enforced downstream by `blend_edge_variable`).
5156/// Branching (a vertex shared by 3+ selected edges), closed rings of several
5157/// edges, and disconnected selections refuse with named errors.
5158fn resolve_selected_chain(
5159    solid: &BrepSolid,
5160    edge_points: &[Vec3],
5161    entry: &str,
5162    tol: f64,
5163) -> Result<Vec<ChainLink>, KernelRefusal> {
5164    // Endpoint identity uses the kernel-wide COINCIDENCE_DISTANCE_FLOOR — the
5165    // same band the constant-radius group's corner detector applies.
5166    let band = crate::tolerance::COINCIDENCE_DISTANCE_FLOOR;
5167
5168    struct Resolved {
5169        edge_id: u64,
5170        start: Vec3,
5171        end: Vec3,
5172        arc: Vec<(f64, f64)>,
5173        length: f64,
5174    }
5175    let mut resolved: Vec<Resolved> = Vec::with_capacity(edge_points.len());
5176    for point in edge_points {
5177        let edge_id = resolve_edge_by_point(solid, *point)?;
5178        if resolved.iter().any(|r| r.edge_id == edge_id) {
5179            return Err(KernelRefusal::input(
5180                KernelStage::Collect,
5181                "duplicate_edge",
5182                format!("{entry}: the same edge was selected more than once"),
5183            ));
5184        }
5185        let edge = solid
5186            .edges
5187            .iter()
5188            .find(|e| e.id == edge_id)
5189            .ok_or_else(|| {
5190                KernelRefusal::internal(
5191                    KernelStage::Collect,
5192                    "chain_resolved_edge",
5193                    format!("{entry}: resolved edge vanished"),
5194                )
5195            })?;
5196        let (arc, length) = edge_arc_table(&edge.curve, edge.t0, edge.t1, tol)?;
5197        if !(length > 0.0) {
5198            return Err(KernelRefusal::input(
5199                KernelStage::Collect,
5200                "zero_length_edge",
5201                format!("{entry}: selected edge has zero length"),
5202            ));
5203        }
5204        resolved.push(Resolved {
5205            edge_id,
5206            start: edge
5207                .curve
5208                .evaluate(edge.t0)
5209                .or_refuse(KernelStage::Collect, "chain_edge_start")?,
5210            end: edge
5211                .curve
5212                .evaluate(edge.t1)
5213                .or_refuse(KernelStage::Collect, "chain_edge_end")?,
5214            arc,
5215            length,
5216        });
5217    }
5218    let n = resolved.len();
5219    if n == 1 {
5220        let only = resolved.remove(0);
5221        return Ok(vec![ChainLink {
5222            input_index: 0,
5223            forward: true,
5224            arc: only.arc,
5225            length: only.length,
5226            abscissa: 0.0,
5227        }]);
5228    }
5229
5230    // Cluster the 2n endpoints; each entry is (edge index, is_start_end).
5231    let mut clusters: Vec<(Vec3, Vec<(usize, bool)>)> = Vec::new();
5232    for (i, r) in resolved.iter().enumerate() {
5233        for (point, is_start) in [(r.start, true), (r.end, false)] {
5234            match clusters
5235                .iter_mut()
5236                .find(|(anchor, _)| anchor.sub(point).length() < band)
5237            {
5238                Some((_, members)) => members.push((i, is_start)),
5239                None => clusters.push((point, vec![(i, is_start)])),
5240            }
5241        }
5242    }
5243    if clusters.iter().any(|(_, members)| members.len() > 2) {
5244        return Err(KernelRefusal::input(
5245            KernelStage::Collect,
5246            "chain_branching",
5247            format!(
5248                "{entry}: selected edges must form one open chain \
5249                 (a vertex is shared by three or more selected edges)"
5250            ),
5251        ));
5252    }
5253    let free: Vec<usize> = clusters
5254        .iter()
5255        .enumerate()
5256        .filter(|(_, (_, members))| members.len() == 1)
5257        .map(|(c, _)| c)
5258        .collect();
5259    if free.len() != 2 {
5260        return Err(KernelRefusal::input(
5261            KernelStage::Collect,
5262            "chain_open",
5263            format!(
5264                "{entry}: selected edges must form one OPEN chain \
5265                 (closed rings and disconnected selections are not supported)"
5266            ),
5267        ));
5268    }
5269    // Start at the free end whose edge appears EARLIEST in the selection.
5270    let start_cluster = *free
5271        .iter()
5272        .min_by_key(|&&c| clusters[c].1[0].0)
5273        .expect("two free ends");
5274
5275    // Walk the chain.
5276    let mut links: Vec<ChainLink> = Vec::with_capacity(n);
5277    let mut visited = vec![false; n];
5278    let mut abscissa = 0.0_f64;
5279    let mut cluster = start_cluster;
5280    for _ in 0..n {
5281        let Some(&(edge_index, entered_at_start)) = clusters[cluster]
5282            .1
5283            .iter()
5284            .find(|(edge_index, _)| !visited[*edge_index])
5285        else {
5286            return Err(KernelRefusal::input(
5287                KernelStage::Collect,
5288                "chain_walk",
5289                format!(
5290                    "{entry}: selected edges are not connected into one chain"
5291                ),
5292            ));
5293        };
5294        visited[edge_index] = true;
5295        let r = &resolved[edge_index];
5296        links.push(ChainLink {
5297            input_index: edge_index,
5298            forward: entered_at_start,
5299            arc: r.arc.clone(),
5300            length: r.length,
5301            abscissa,
5302        });
5303        abscissa += r.length;
5304        let exit_point = if entered_at_start { r.end } else { r.start };
5305        cluster = clusters
5306            .iter()
5307            .position(|(anchor, _)| anchor.sub(exit_point).length() < band)
5308            .ok_or_else(|| {
5309                KernelRefusal::internal(
5310                    KernelStage::Collect,
5311                    "chain_cluster",
5312                    format!("{entry}: chain walk lost an endpoint cluster"),
5313                )
5314            })?;
5315    }
5316    if visited.iter().any(|v| !v) {
5317        return Err(KernelRefusal::input(
5318            KernelStage::Collect,
5319            "chain_connected",
5320            format!(
5321                "{entry}: selected edges are not connected into one chain"
5322            ),
5323        ));
5324    }
5325    Ok(links)
5326}
5327
5328/// Sample the law into one edge's `(parameter fraction, radius)` stop list —
5329/// the caller-side bridge from chain abscissa into the `radius_at` closure
5330/// seam that `blend_edge_variable` builds over its stops.
5331///
5332/// `scale` maps chain abscissa into the law's own abscissa units
5333/// (`law.total_length() / chain_length` — proportional, so a law built from
5334/// the measured chain lengths maps 1:1).  The base stop count derives from
5335/// the law's curvature: piecewise-linear sampling of a C1, piecewise-C2
5336/// function over step `h` errs at most `h²·max|r''|/8`, so
5337/// `h = sqrt(8·tol/max|r''|)` holds the sampling error under the SSI fit
5338/// tolerance the variable lane is built to.  That bound is exact for
5339/// arc-length-linear (straight) edges; curved edges bend the
5340/// parameter→abscissa map, so each interval is additionally midpoint-checked
5341/// against the law and bisected on violation (up to 8 halvings — a 4⁸ ≈ 6·10⁴
5342/// error reduction, decisive for any C1 law).  The base count is capped at
5343/// 256 intervals: 4× the blend march's 64-station density
5344/// (blend/stations.rs), beyond which denser stops cannot move any station's
5345/// sampled radius by more than the fit tolerance.
5346fn law_stops_for_link(
5347    link: &ChainLink,
5348    law: &crate::law::RadiusLaw,
5349    scale: f64,
5350    tol: f64,
5351) -> Vec<(f64, f64)> {
5352    let radius_at_fraction = |fraction: f64| -> f64 {
5353        let arc = arc_length_at_fraction(&link.arc, fraction);
5354        let chain_s = if link.forward {
5355            link.abscissa + arc
5356        } else {
5357            link.abscissa + (link.length - arc)
5358        };
5359        law.radius_at(chain_s * scale)
5360    };
5361    // Curvature of the law in edge-fraction units: d²r/df² ≤
5362    // max|r''|·(scale·length)² for the arc-length-linear map.
5363    let curvature = law
5364        .max_second_derivative(link.abscissa * scale, (link.abscissa + link.length) * scale)
5365        * (scale * link.length).powi(2);
5366    let base = if curvature * 0.125 <= tol {
5367        1usize
5368    } else {
5369        ((curvature / (8.0 * tol)).sqrt().ceil() as usize).clamp(1, 256)
5370    };
5371    let mut stops: Vec<(f64, f64)> = (0..=base)
5372        .map(|j| {
5373            let fraction = j as f64 / base as f64;
5374            (fraction, radius_at_fraction(fraction))
5375        })
5376        .collect();
5377    // Midpoint refinement for curved parameter→abscissa maps.
5378    let mut depth = 0usize;
5379    while depth < 8 {
5380        let mut refined: Vec<(f64, f64)> = Vec::with_capacity(stops.len());
5381        let mut inserted = false;
5382        for pair in stops.windows(2) {
5383            refined.push(pair[0]);
5384            let mid_fraction = 0.5 * (pair[0].0 + pair[1].0);
5385            let law_mid = radius_at_fraction(mid_fraction);
5386            let linear_mid = 0.5 * (pair[0].1 + pair[1].1);
5387            if (law_mid - linear_mid).abs() > tol {
5388                refined.push((mid_fraction, law_mid));
5389                inserted = true;
5390            }
5391        }
5392        refined.push(*stops.last().expect("at least two stops"));
5393        stops = refined;
5394        if !inserted {
5395            break;
5396        }
5397        depth += 1;
5398    }
5399    stops
5400}
5401
5402/// Fillet (or chamfer) a chain of edges under a composable radius law
5403/// evaluated on the chain's cumulative arc-length abscissa (the OCCT
5404/// `Law_Composite` model; see [`crate::law::RadiusLaw`]).  The selected edges
5405/// must form ONE OPEN CHAIN (or be a single edge); the chain starts at the
5406/// free end of the earliest-selected end edge, and the law's abscissa maps
5407/// proportionally onto the chain's measured arc length (a law built with the
5408/// chain's own lengths — e.g. [`crate::law::RadiusLaw::from_vertex_radii`] —
5409/// maps 1:1).  Endpoint radii are met exactly; radii at shared chain vertices
5410/// match by the law's continuity, so the per-edge blends miter through the
5411/// corners; a chain whose blends cannot be mitered REFUSES rather than
5412/// distorting the law through the sequential rebuild.
5413pub fn fillet_edges_variable_law(
5414    solid: &BrepSolid,
5415    edge_points: &[Vec3],
5416    edge_names: Option<&[String]>,
5417    law: &crate::law::RadiusLaw,
5418    chamfer: bool,
5419    name: Option<&str>,
5420) -> Result<BrepSolid, KernelRefusal> {
5421    // One blend operation: the reports of an earlier one, never consumed, are
5422    // dropped as it starts (nested calls keep this operation's).
5423    let _operation = crate::blend::BlendOperation::enter();
5424    const ENTRY: &str = "fillet_edges_variable_law";
5425    if edge_points.is_empty() {
5426        return Err(KernelRefusal::input(
5427            KernelStage::Collect,
5428            "law_selection",
5429            format!("{ENTRY}: no edges selected"),
5430        ));
5431    }
5432    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
5433    let chain = resolve_selected_chain(solid, edge_points, ENTRY, tolerances.intersection_fit)?;
5434    fillet_variable_law_on_chain(
5435        solid,
5436        edge_points,
5437        edge_names,
5438        &chain,
5439        law,
5440        chamfer,
5441        name,
5442        ENTRY,
5443        tolerances.intersection_fit,
5444    )
5445}
5446
5447/// The natural per-vertex user model: radius `vertex_radii[i]` at chain
5448/// vertex `i` (in CHAIN order, starting at the free end of the
5449/// earliest-selected edge), smoothly interpolated along the chain
5450/// (monotone C1 — every vertex radius met exactly, no overshoot).  Requires
5451/// exactly one radius per chain vertex (`edges + 1`).
5452pub fn fillet_edges_variable_vertex_radii(
5453    solid: &BrepSolid,
5454    edge_points: &[Vec3],
5455    edge_names: Option<&[String]>,
5456    vertex_radii: &[f64],
5457    chamfer: bool,
5458    name: Option<&str>,
5459) -> Result<BrepSolid, KernelRefusal> {
5460    // One blend operation: the reports of an earlier one, never consumed, are
5461    // dropped as it starts (nested calls keep this operation's).
5462    let _operation = crate::blend::BlendOperation::enter();
5463    const ENTRY: &str = "fillet_edges_variable_vertex_radii";
5464    if edge_points.is_empty() {
5465        return Err(KernelRefusal::input(
5466            KernelStage::Collect,
5467            "vertex_radii_selection",
5468            format!("{ENTRY}: no edges selected"),
5469        ));
5470    }
5471    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
5472    let chain = resolve_selected_chain(solid, edge_points, ENTRY, tolerances.intersection_fit)?;
5473    let lengths: Vec<f64> = chain.iter().map(|link| link.length).collect();
5474    let law = crate::law::RadiusLaw::from_vertex_radii(&lengths, vertex_radii)
5475        .map_err(|error| error.with_message(|error| format!("{ENTRY}: {error}")))?;
5476    fillet_variable_law_on_chain(
5477        solid,
5478        edge_points,
5479        edge_names,
5480        &chain,
5481        &law,
5482        chamfer,
5483        name,
5484        ENTRY,
5485        tolerances.intersection_fit,
5486    )
5487}
5488
5489/// Shared law-entry tail: sample per-edge stop lists from the law over the
5490/// resolved chain and run the variable group core (miter-or-refuse: no
5491/// sequential fallback for tapered chains — see `fillet_edges_variable_impl`).
5492#[allow(clippy::too_many_arguments)]
5493fn fillet_variable_law_on_chain(
5494    solid: &BrepSolid,
5495    edge_points: &[Vec3],
5496    edge_names: Option<&[String]>,
5497    chain: &[ChainLink],
5498    law: &crate::law::RadiusLaw,
5499    chamfer: bool,
5500    name: Option<&str>,
5501    entry: &str,
5502    tol: f64,
5503) -> Result<BrepSolid, KernelRefusal> {
5504    let chain_length: f64 = chain.iter().map(|link| link.length).sum();
5505    let scale = law.total_length() / chain_length;
5506    let mut per_edge_stops: Vec<Vec<(f64, f64)>> = vec![Vec::new(); edge_points.len()];
5507    for link in chain {
5508        per_edge_stops[link.input_index] = law_stops_for_link(link, law, scale, tol);
5509    }
5510    fillet_edges_variable_impl(
5511        solid,
5512        edge_points,
5513        edge_names,
5514        &per_edge_stops,
5515        chamfer,
5516        name,
5517        entry,
5518        false,
5519    )
5520}
5521
5522/// Asymmetric (two-distance) chamfer of a GROUP of edges, the app entry: each
5523/// selected edge (resolved by a point on it) gets a `d1 × d2` bevel (§6.11).
5524/// Edges are chamfered independently — asymmetric chamfers keep sharp vertices,
5525/// so there is no shared-corner blending.
5526pub fn chamfer_edges_asymmetric(
5527    solid: &BrepSolid,
5528    edge_points: &[Vec3],
5529    edge_names: Option<&[String]>,
5530    d1: f64,
5531    d2: f64,
5532    name: Option<&str>,
5533) -> Result<BrepSolid, KernelRefusal> {
5534    // One blend operation: the reports of an earlier one, never consumed, are
5535    // dropped as it starts (nested calls keep this operation's).
5536    let _operation = crate::blend::BlendOperation::enter();
5537    if edge_points.is_empty() {
5538        return Err(KernelRefusal::input(
5539            KernelStage::Collect,
5540            "asymmetric_selection",
5541            "chamfer_edges_asymmetric: no edges selected",
5542        ));
5543    }
5544    let mut result = solid.clone();
5545    let mut done = vec![false; edge_points.len()];
5546    // `edge_names[index]` is keyed by INPUT position; the loop resolves each
5547    // point on the EVOLVING `result`, but enumerates the input points in order,
5548    // so the index alignment holds.
5549    for (index, point) in edge_points.iter().enumerate() {
5550        if done[index] {
5551            continue;
5552        }
5553        let edge_id = resolve_edge_by_point(&result, *point)?;
5554        let edge_name = per_edge_name(edge_names, name, index);
5555        // A smooth chain the selection covers whole is chamfered as one unit
5556        // (its setbacks run on through the tangent joins).
5557        if chamfer_asym_curved_on() {
5558            if let Some(members) = selected_chain(&result, edge_id, edge_points, &done)? {
5559                let faces = setback_faces(&result, edge_id)?;
5560                let law = crate::blend::setback::SetbackLaw::Distances { faces, distances: [d1, d2] };
5561                result = chamfer_by_setback_law(&result, edge_id, law, edge_name, "chamfer_edges_asymmetric", true)?;
5562                for member in members {
5563                    done[member] = true;
5564                }
5565                continue;
5566            }
5567        }
5568        result = chamfer_edge_asymmetric(&result, edge_id, d1, d2, edge_name)?;
5569        done[index] = true;
5570    }
5571    refuse_invalid_result(&result, "chamfer_edges_asymmetric")?;
5572    Ok(result)
5573}
5574
5575/// Distance-angle chamfer of a GROUP of edges, the app entry: each selected
5576/// edge (resolved by a point on it) gets a setback `d1` on face 1 and a chamfer
5577/// face at `angle_rad` from face 1 (§6.11); `d2` is constructed per edge.
5578pub fn chamfer_edges_angle(
5579    solid: &BrepSolid,
5580    edge_points: &[Vec3],
5581    edge_names: Option<&[String]>,
5582    d1: f64,
5583    angle_rad: f64,
5584    name: Option<&str>,
5585) -> Result<BrepSolid, KernelRefusal> {
5586    // One blend operation: the reports of an earlier one, never consumed, are
5587    // dropped as it starts (nested calls keep this operation's).
5588    let _operation = crate::blend::BlendOperation::enter();
5589    if edge_points.is_empty() {
5590        return Err(KernelRefusal::input(
5591            KernelStage::Collect,
5592            "angle_selection",
5593            "chamfer_edges_angle: no edges selected",
5594        ));
5595    }
5596    let mut result = solid.clone();
5597    let mut done = vec![false; edge_points.len()];
5598    for (index, point) in edge_points.iter().enumerate() {
5599        if done[index] {
5600            continue;
5601        }
5602        let edge_id = resolve_edge_by_point(&result, *point)?;
5603        let edge_name = per_edge_name(edge_names, name, index);
5604        // A smooth chain the selection covers whole is chamfered as one unit,
5605        // as `chamfer_edges_asymmetric` does.
5606        if chamfer_asym_curved_on() && d1 > 0.0 && d1.is_finite() && angle_rad > 1e-9 && angle_rad < std::f64::consts::PI {
5607            if let Some(members) = selected_chain(&result, edge_id, edge_points, &done)? {
5608                let [first, _] = setback_faces(&result, edge_id)?;
5609                let law = crate::blend::setback::SetbackLaw::Angle { first, distance: d1, angle: angle_rad };
5610                result = chamfer_by_setback_law(&result, edge_id, law, edge_name, "chamfer_edges_angle", true)?;
5611                for member in members {
5612                    done[member] = true;
5613                }
5614                continue;
5615            }
5616        }
5617        result = chamfer_edge_angle(&result, edge_id, d1, angle_rad, edge_name)?;
5618        done[index] = true;
5619    }
5620    refuse_invalid_result(&result, "chamfer_edges_angle")?;
5621    Ok(result)
5622}
5623
5624/// Debug aid (`BREP_DEBUG_NETWORK`): every face loop as its coedge walk, with
5625/// each edge's stored vertices, so a loop the surgery left open can be read
5626/// against the input it was built from.
5627fn dump_loops_debug(label: &str, solid: &BrepSolid) {
5628    for shell in &solid.shells {
5629        for face in &shell.faces {
5630            for (index, loop_record) in face.loops.iter().enumerate() {
5631                let walk: Vec<String> = loop_record
5632                    .coedges
5633                    .iter()
5634                    .map(|coedge| {
5635                        // The pcurve's walk endpoints in the face's (u, v), so a
5636                        // loop that closes in space but not in parameter space
5637                        // (a periodic carrier's seam) is visible in the dump.
5638                        let uv = coedge
5639                            .pcurve
5640                            .domain()
5641                            .ok()
5642                            .and_then(|[q0, q1]| {
5643                                let a = coedge.pcurve.evaluate(q0).ok()?;
5644                                let b = coedge.pcurve.evaluate(q1).ok()?;
5645                                Some(format!("uv[({:.4},{:.4})->({:.4},{:.4})]", a.x, a.y, b.x, b.y))
5646                            })
5647                            .unwrap_or_default();
5648                        match solid.edges.iter().find(|e| e.id == coedge.edge_id) {
5649                            Some(edge) => format!(
5650                                "c{}:e{}{}({}->{}){uv}",
5651                                coedge.id,
5652                                edge.id,
5653                                if coedge.forward { "+" } else { "-" },
5654                                edge.start_vertex_id,
5655                                edge.end_vertex_id
5656                            ),
5657                            None => format!("c{}:e{}?MISSING", coedge.id, coedge.edge_id),
5658                        }
5659                    })
5660                    .collect();
5661                eprintln!(
5662                    "{label} face {} ({:?}) loop {index}: {}",
5663                    face.id,
5664                    face.name,
5665                    walk.join(" ")
5666                );
5667            }
5668        }
5669    }
5670}
5671
5672