Skip to main content

fuel_dispatch/
region_pathfinder.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The multi-node placement pathfinder (ROADMAP row 157, GAP-385).
3//!
4//! [`PlacementRegionPathfinder`] records one `Op::Branch` per **region**: a single-entry, single-exit
5//! stretch of nodes between a diverge node `D` and a reconverge node `R`, where arm 0 is the stretch
6//! as placed by the DP winner and arm 1 is a clone of the whole stretch on one alternative placement.
7//! The stretch is any connected set of nodes (a chain, a residual block, a fan-out that rejoins), so
8//! the picker can choose "stay on this device for these N ops" rather than a one-node swap.
9//!
10//! Design: `docs/design-notes/2026-11-15-multi-node-placement-pathfinder.md`. In short:
11//!
12//! 1. Post-dominators over the realize-reachable DAG give, for each node `D`, the candidate reconverge
13//!    nodes `R` (its post-dominator chain).
14//! 2. The interior of `(D, R)` is every node on a `D -> R` path. A region is valid when `R` reads
15//!    exactly one interior node (the exit), no interior node is read from outside (only the exit is read,
16//!    and only by `R`), every interior node has a candidate on one common alternative placement that
17//!    differs from its winner, and the alternative stretch is competitive on summed time.
18//! 3. Valid regions are chosen largest first; regions must be disjoint and neither endpoint may lie in
19//!    another chosen interior (a laminar family is NOT built yet: nested regions are a follow-up).
20//!
21//! This replaces the one-node `PlacementForkPathfinder` in the default pass registries; a one-node
22//! region is the old behaviour, so graphs with isolated forks are unchanged.
23
24use std::collections::{HashMap, HashSet};
25
26use fuel_graph::{Graph, Node, NodeId, Op};
27use fuel_ir::Result;
28use fuel_ir::probe::BackendId;
29
30use crate::driver::{OptimizationContext, Pathfinder};
31use crate::ranker::CostVector;
32
33/// Largest interior (in nodes) a region may have. A first-slice cap; the design note requires it be
34/// measured on real models before it is fixed.
35pub const MAX_REGION_NODES: usize = 64;
36
37/// A region is recorded only when the alternative stretch's summed time is at most this multiple of
38/// the winner's. A first-slice bound, to be measured against the per-device frontier.
39pub const REGION_COMPETITIVE_FACTOR: u64 = 2;
40
41/// Records multi-node placement forks as `Op::Branch` regions. See the module docs.
42pub struct PlacementRegionPathfinder;
43
44#[derive(Clone)]
45struct Region {
46    diverge: NodeId,
47    reconverge: NodeId,
48    /// Interior nodes in dispatch (topological) order.
49    interior: Vec<NodeId>,
50    exit: NodeId,
51    alt_backend: BackendId,
52    /// The device the alternative placement runs on (the plan's own device for it).
53    alt_device: fuel_ir::DeviceLocation,
54    /// The device arm 0's exit lives on (its DP winner's), which the reconverge node reads.
55    exit_device: fuel_ir::DeviceLocation,
56    diverge_idx: usize,
57    reconverge_idx: usize,
58}
59
60impl Pathfinder for PlacementRegionPathfinder {
61    fn name(&self) -> &'static str {
62        "PlacementRegionSeed"
63    }
64
65    fn propose(&self, graph: &mut Graph, ctx: &OptimizationContext<'_>) -> Result<()> {
66        if std::env::var_os("FUEL_PRINT_BRANCH_COUNT").is_some() {
67            let mut hist = [0usize; 5];
68            for &id in ctx.order {
69                hist[placements(ctx, id).len().min(4)] += 1;
70            }
71            eprintln!(
72                "fuel: region pathfinder sees {} nodes; placements-per-node histogram [0,1,2,3,4+] = {:?}; pinned/cycle-guarded = {}",
73                ctx.order.len(),
74                hist,
75                ctx.cycle_guard.len()
76            );
77        }
78        let found = find_regions(graph, ctx);
79        if std::env::var_os("FUEL_PRINT_BRANCH_COUNT").is_some() {
80            eprintln!(
81                "fuel: region pathfinder found {} candidate region(s)",
82                found.len()
83            );
84        }
85        let candidates = found.len();
86        if std::env::var_os("FUEL_PRINT_BRANCH_COUNT").is_some() {
87            let c = policy_counts(&found);
88            eprintln!(
89                "fuel: region policy counts over {candidates} candidate(s) (diagnostic only; today's choice is the first): \
90                 today (largest first, disjoint) = {}, laminar family (nested allowed; NOT buildable yet) = {}, \
91                 smallest first, disjoint = {}, one-node regions only, disjoint = {}",
92                c.today, c.laminar, c.smallest_first, c.one_node
93            );
94        }
95        let regions = choose_regions(found);
96        let chosen = regions.len();
97        let (mut recorded, mut collapsed) = (0usize, 0usize);
98        let mut rejected: Vec<String> = Vec::new();
99        for region in regions {
100            // A rejected or collapsed branch is not an error (the single route is kept); the outcome is
101            // only counted, for the `FUEL_PRINT_BRANCH_COUNT` report below.
102            match try_record_branch(
103                graph,
104                region.diverge,
105                region.reconverge,
106                &region.interior,
107                region.exit,
108                region.alt_backend,
109                region.alt_device,
110                region.exit_device,
111            ) {
112                Ok(Some(_)) => recorded += 1,
113                Ok(None) => collapsed += 1,
114                Err(e) => rejected.push(format!("{e:?}")),
115            }
116        }
117        crate::optimizer_trace::global().record_regions(
118            candidates - chosen,
119            recorded,
120            collapsed,
121            &rejected,
122        );
123        if std::env::var_os("FUEL_PRINT_BRANCH_COUNT").is_some() {
124            eprintln!(
125                "fuel: region pathfinder: {candidates} candidate(s) -> {chosen} chosen by choose_regions \
126                 ({} dropped as overlapping an already-chosen larger region) -> {recorded} recorded, \
127                 {collapsed} collapsed, {} rejected by finalize_branches",
128                candidates - chosen,
129                rejected.len()
130            );
131            for reason in rejected.iter().take(5) {
132                eprintln!("fuel: region pathfinder: rejected: {reason}");
133            }
134        }
135        Ok(())
136    }
137}
138
139/// Distinct `(backend, device)` placements of a node's alternative set, in rank order.
140fn placements(
141    ctx: &OptimizationContext<'_>,
142    id: NodeId,
143) -> Vec<(BackendId, fuel_ir::DeviceLocation)> {
144    let mut out: Vec<(BackendId, fuel_ir::DeviceLocation)> = Vec::new();
145    // The DP prunes each node's set to its committed device, so a second placement lives in the plan's
146    // off-device side map (read here; the realize path never reads it).
147    for set in [
148        ctx.plan.alternatives(id),
149        ctx.plan.off_device_alternatives(id),
150    ]
151    .into_iter()
152    .flatten()
153    {
154        for c in set.alternatives() {
155            let p = (c.backend, c.device);
156            if !out.contains(&p) {
157                out.push(p);
158            }
159        }
160    }
161    out
162}
163
164/// `(compute_ns, inbound_transfer_ns)` of the best candidate of `id` on `place` (best by their sum),
165/// or `None` when it has none. A candidate's `time` includes the transfer of its inputs onto its
166/// device, which is only paid where a value actually crosses the region boundary, so the two terms are
167/// kept apart.
168fn time_on(
169    ctx: &OptimizationContext<'_>,
170    id: NodeId,
171    place: (BackendId, fuel_ir::DeviceLocation),
172) -> Option<(u64, u64)> {
173    [
174        ctx.plan.alternatives(id),
175        ctx.plan.off_device_alternatives(id),
176    ]
177    .into_iter()
178    .flatten()
179    .flat_map(|set| set.alternatives().iter())
180    .filter(|c| (c.backend, c.device) == place)
181    .map(|c| {
182        let total = CostVector::from_candidate(c).time;
183        (
184            total.saturating_sub(c.inbound_transfer_ns),
185            c.inbound_transfer_ns,
186        )
187    })
188    .min_by_key(|&(compute, inbound)| compute.saturating_add(inbound))
189}
190
191fn find_regions(graph: &Graph, ctx: &OptimizationContext<'_>) -> Vec<Region> {
192    let order = ctx.order;
193    let n = order.len();
194    let idx: HashMap<NodeId, usize> = order.iter().enumerate().map(|(i, &id)| (id, i)).collect();
195
196    // Consumers over the realize-reachable set.
197    let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); n];
198    for (i, &id) in order.iter().enumerate() {
199        for &input in &graph.node(id).inputs {
200            if let Some(&j) = idx.get(&input)
201                && !consumers[j].contains(&i)
202            {
203                consumers[j].push(i);
204            }
205        }
206    }
207
208    // Tensors a destructive op consumes: cloning a reader of one would escape the ordering edge that
209    // pins destructive writers after every reader, so regions that read them are skipped.
210    let mut destroyed: HashSet<NodeId> = HashSet::new();
211    for &id in order {
212        let node = graph.node(id);
213        if let Some(k) = node.op.destructive_input()
214            && let Some(&t) = node.inputs.get(k)
215        {
216            destroyed.insert(t);
217        }
218    }
219
220    // Per-node placements and eligibility.
221    let places: Vec<Vec<(BackendId, fuel_ir::DeviceLocation)>> =
222        order.iter().map(|&id| placements(ctx, id)).collect();
223    let eligible: Vec<bool> = order
224        .iter()
225        .enumerate()
226        .map(|(i, &id)| {
227            let node = graph.node(id);
228            places[i].len() >= 2
229                && !ctx.cycle_guard.contains(&id)
230                && !matches!(node.op, Op::Branch { .. })
231                && node.op.destructive_input().is_none()
232                && !node.inputs.iter().any(|t| destroyed.contains(t))
233        })
234        .collect();
235
236    // Immediate post-dominators; index `n` is the virtual exit that every realize root flows to.
237    let mut ipdom = vec![n; n + 1];
238    for i in (0..n).rev() {
239        let cs = &consumers[i];
240        if cs.is_empty() {
241            ipdom[i] = n;
242            continue;
243        }
244        let mut r = cs[0];
245        for &c in &cs[1..] {
246            r = intersect(r, c, &ipdom);
247        }
248        ipdom[i] = r;
249    }
250
251    let mut regions = Vec::new();
252    for d in 0..n {
253        // A region's first node must be a consumer of D and eligible.
254        if !consumers[d].iter().any(|&c| eligible[c]) {
255            continue;
256        }
257        let mut r = ipdom[d];
258        while r < n {
259            let Some(interior) = interior_of(graph, order, &idx, &consumers, d, r) else {
260                break; // grew past the cap; every farther R only grows the interior
261            };
262            if let Some(region) = check_region(
263                graph, ctx, order, &idx, &consumers, &places, &eligible, d, r, interior,
264            ) {
265                regions.push(region);
266            }
267            r = ipdom[r];
268        }
269    }
270    regions
271}
272
273fn intersect(mut a: usize, mut b: usize, ipdom: &[usize]) -> usize {
274    while a != b {
275        while a < b {
276            a = ipdom[a];
277        }
278        while b < a {
279            b = ipdom[b];
280        }
281    }
282    a
283}
284
285/// Nodes on a `d -> r` path, strictly between them, in topological order. `None` when the stretch is
286/// larger than the cap.
287fn interior_of(
288    graph: &Graph,
289    order: &[NodeId],
290    idx: &HashMap<NodeId, usize>,
291    consumers: &[Vec<usize>],
292    d: usize,
293    r: usize,
294) -> Option<Vec<usize>> {
295    let mut fwd: HashSet<usize> = HashSet::new();
296    let mut stack: Vec<usize> = consumers[d].iter().copied().filter(|&c| c < r).collect();
297    while let Some(x) = stack.pop() {
298        if !fwd.insert(x) {
299            continue;
300        }
301        if fwd.len() > 4 * MAX_REGION_NODES {
302            return None;
303        }
304        stack.extend(consumers[x].iter().copied().filter(|&c| c < r));
305    }
306    let mut interior: HashSet<usize> = HashSet::new();
307    let mut stack: Vec<usize> = graph
308        .node(order[r])
309        .inputs
310        .iter()
311        .filter_map(|i| idx.get(i).copied())
312        .filter(|x| fwd.contains(x))
313        .collect();
314    while let Some(x) = stack.pop() {
315        if !interior.insert(x) {
316            continue;
317        }
318        stack.extend(
319            graph
320                .node(order[x])
321                .inputs
322                .iter()
323                .filter_map(|i| idx.get(i).copied())
324                .filter(|y| fwd.contains(y)),
325        );
326    }
327    if interior.len() > MAX_REGION_NODES {
328        return None;
329    }
330    let mut v: Vec<usize> = interior.into_iter().collect();
331    v.sort_unstable();
332    Some(v)
333}
334
335#[allow(clippy::too_many_arguments)]
336fn check_region(
337    graph: &Graph,
338    ctx: &OptimizationContext<'_>,
339    order: &[NodeId],
340    idx: &HashMap<NodeId, usize>,
341    consumers: &[Vec<usize>],
342    places: &[Vec<(BackendId, fuel_ir::DeviceLocation)>],
343    eligible: &[bool],
344    d: usize,
345    r: usize,
346    interior: Vec<usize>,
347) -> Option<Region> {
348    if interior.is_empty() || !interior.iter().all(|&x| eligible[x]) {
349        return None;
350    }
351    let inside: HashSet<usize> = interior.iter().copied().collect();
352
353    // R reads exactly one interior node: the arm exit.
354    let reads: HashSet<usize> = graph
355        .node(order[r])
356        .inputs
357        .iter()
358        .filter_map(|i| idx.get(i).copied())
359        .filter(|x| inside.contains(x))
360        .collect();
361    if reads.len() != 1 {
362        return None;
363    }
364    let exit = *reads.iter().next()?;
365
366    // Nothing inside is read from outside: non-exit nodes only by interior nodes, the exit only by R.
367    for &x in &interior {
368        let cs = &consumers[x];
369        let ok = if x == exit {
370            cs.len() == 1 && cs[0] == r
371        } else {
372            cs.iter().all(|c| inside.contains(c))
373        };
374        if !ok {
375            return None;
376        }
377    }
378
379    // One alternative placement shared by every interior node and different from each node's winner.
380    let winners: Vec<(BackendId, fuel_ir::DeviceLocation)> = interior
381        .iter()
382        .map(|&x| {
383            ctx.plan
384                .alternatives(order[x])
385                .and_then(|s| s.winner())
386                .map(|w| (w.backend, w.device))
387        })
388        .collect::<Option<Vec<_>>>()?;
389    let alt = places[interior[0]].iter().copied().find(|p| {
390        interior
391            .iter()
392            .zip(&winners)
393            .all(|(&x, w)| p != w && places[x].contains(p))
394    })?;
395
396    // Competitive on summed time.
397    let mut win_total: u64 = 0;
398    let mut alt_total: u64 = 0;
399    for (&x, w) in interior.iter().zip(&winners) {
400        // Only an entry node (one reading a value from outside the stretch) pays an inbound transfer;
401        // interior edges stay on one device inside an arm. The exit transfer back is not priced here
402        // (unmeasured; the DP prices it when it commits a placement).
403        let is_entry = graph
404            .node(order[x])
405            .inputs
406            .iter()
407            .any(|i| !idx.get(i).is_some_and(|j| inside.contains(j)));
408        let (wc, wi) = time_on(ctx, order[x], *w)?;
409        let (ac, ai) = time_on(ctx, order[x], alt)?;
410        win_total = win_total.saturating_add(wc);
411        alt_total = alt_total.saturating_add(ac);
412        if is_entry {
413            win_total = win_total.saturating_add(wi);
414            alt_total = alt_total.saturating_add(ai);
415        }
416    }
417    if std::env::var_os("FUEL_PRINT_BRANCH_COUNT").is_some() {
418        eprintln!(
419            "fuel: region d={d} r={r} interior={} win_total={win_total} alt_total={alt_total}",
420            interior.len()
421        );
422    }
423    if alt_total > win_total.saturating_mul(REGION_COMPETITIVE_FACTOR) {
424        return None;
425    }
426
427    Some(Region {
428        diverge: order[d],
429        reconverge: order[r],
430        interior: interior.iter().map(|&x| order[x]).collect(),
431        exit: order[exit],
432        alt_backend: alt.0,
433        alt_device: alt.1,
434        exit_device: interior
435            .iter()
436            .position(|&x| x == exit)
437            .and_then(|p| winners.get(p))
438            .map(|w| w.1)?,
439        diverge_idx: d,
440        reconverge_idx: r,
441    })
442}
443
444/// Largest regions first; disjoint interiors; an endpoint may not lie inside another chosen interior.
445fn choose_regions(mut candidates: Vec<Region>) -> Vec<Region> {
446    candidates.sort_by_key(|r| {
447        (
448            std::cmp::Reverse(r.interior.len()),
449            r.diverge_idx,
450            r.reconverge_idx,
451        )
452    });
453    choose_in_order(candidates)
454}
455
456/// How many regions each selection policy would keep from the same candidates. Diagnostic only
457/// (`FUEL_PRINT_BRANCH_COUNT`): the pathfinder's behaviour is [`choose_regions`] alone.
458struct PolicyCounts {
459    today: usize,
460    laminar: usize,
461    smallest_first: usize,
462    one_node: usize,
463}
464
465fn policy_counts(found: &[Region]) -> PolicyCounts {
466    let today = choose_regions(found.to_vec()).len();
467
468    let mut asc = found.to_vec();
469    asc.sort_by_key(|r| (r.interior.len(), r.diverge_idx, r.reconverge_idx));
470    let smallest_first = choose_in_order(asc).len();
471
472    let mut one: Vec<Region> = found
473        .iter()
474        .filter(|r| r.interior.len() == 1)
475        .cloned()
476        .collect();
477    one.sort_by_key(|r| (r.diverge_idx, r.reconverge_idx));
478    let one_node = choose_in_order(one).len();
479
480    PolicyCounts {
481        today,
482        laminar: laminar_count(found),
483        smallest_first,
484        one_node,
485    }
486}
487
488/// Greedy largest-first selection that keeps a pair when its interiors are disjoint (with the same
489/// endpoint rule as today) or strictly nested with the inner region's endpoints on or inside the outer
490/// one, and drops a pair that overlaps without nesting (`docs/design-notes/2026-11-15-multi-node-
491/// placement-pathfinder.md`, section 5). Counting only: nested branches are not built.
492fn laminar_count(found: &[Region]) -> usize {
493    let mut sorted: Vec<&Region> = found.iter().collect();
494    sorted.sort_by_key(|r| {
495        (
496            std::cmp::Reverse(r.interior.len()),
497            r.diverge_idx,
498            r.reconverge_idx,
499        )
500    });
501    let mut kept: Vec<(&Region, HashSet<NodeId>)> = Vec::new();
502    for r in sorted {
503        let inner: HashSet<NodeId> = r.interior.iter().copied().collect();
504        let ok = kept.iter().all(|(q, outer)| {
505            if inner.is_disjoint(outer) {
506                !outer.contains(&r.diverge)
507                    && !outer.contains(&r.reconverge)
508                    && !inner.contains(&q.diverge)
509                    && !inner.contains(&q.reconverge)
510            } else if inner.is_subset(outer) {
511                (outer.contains(&r.diverge) || r.diverge == q.diverge)
512                    && (outer.contains(&r.reconverge) || r.reconverge == q.reconverge)
513            } else {
514                false
515            }
516        });
517        if ok {
518            kept.push((r, inner));
519        }
520    }
521    kept.len()
522}
523
524/// The disjointness rule of [`choose_regions`], applied in the order given.
525fn choose_in_order(candidates: Vec<Region>) -> Vec<Region> {
526    let mut taken: HashSet<NodeId> = HashSet::new();
527    let mut ends: HashSet<NodeId> = HashSet::new();
528    let mut chosen = Vec::new();
529    for r in candidates {
530        let clash = r
531            .interior
532            .iter()
533            .any(|x| taken.contains(x) || ends.contains(x))
534            || taken.contains(&r.diverge)
535            || taken.contains(&r.reconverge);
536        if clash {
537            continue;
538        }
539        taken.extend(r.interior.iter().copied());
540        ends.insert(r.diverge);
541        ends.insert(r.reconverge);
542        chosen.push(r);
543    }
544    chosen
545}
546
547/// Clone the interior on the alternative placement and record the 2-arm branch, returning the branch
548/// node when it was recorded. A rejected branch is not an error (as for the one-node fork): the clones
549/// are unreachable and the single route is kept. `pub(crate)` so tests can build the exact structure
550/// the pathfinder builds with an alternative backend that can run on the host.
551#[cfg(test)]
552pub(crate) fn record_branch(
553    graph: &mut Graph,
554    diverge: NodeId,
555    reconverge: NodeId,
556    interior: &[NodeId],
557    exit: NodeId,
558    alt_backend: BackendId,
559) -> Option<NodeId> {
560    // A host test double: the alternative runs on the backend's default device and arm 0's exit lives
561    // there too, so no exit bridge is added (a test that wants one calls `try_record_branch`).
562    let device = alt_backend.default_location();
563    try_record_branch(
564        graph,
565        diverge,
566        reconverge,
567        interior,
568        exit,
569        alt_backend,
570        device,
571        device,
572    )
573    .ok()
574    .flatten()
575}
576
577/// [`record_branch`] with the outcome kept: `Ok(Some(branch))` recorded, `Ok(None)` collapsed to one arm,
578/// `Err` rejected by `finalize_branches` (the reason names the rule).
579#[allow(clippy::too_many_arguments)]
580pub(crate) fn try_record_branch(
581    graph: &mut Graph,
582    diverge: NodeId,
583    reconverge: NodeId,
584    interior: &[NodeId],
585    exit: NodeId,
586    alt_backend: BackendId,
587    alt_device: fuel_ir::DeviceLocation,
588    exit_device: fuel_ir::DeviceLocation,
589) -> Result<Option<NodeId>> {
590    let mut clone_of: HashMap<NodeId, NodeId> = HashMap::new();
591    for &x in interior {
592        let (op, inputs, shape, dtype) = {
593            let n = graph.node(x);
594            (n.op.clone(), n.inputs.clone(), n.shape.clone(), n.dtype)
595        };
596        let inputs = inputs
597            .into_iter()
598            .map(|i| clone_of.get(&i).copied().unwrap_or(i))
599            .collect();
600        let c = graph.push(Node {
601            op,
602            inputs,
603            shape,
604            dtype,
605        });
606        graph.set_target_backend(c, alt_backend);
607        // The clone's PLACEMENT, not only its backend stamp: the residency pass places a node with no
608        // placement and no plan entry on the pinned realize device, so without this it never sees the
609        // arm's inputs cross a device and inserts no inbound copy (ROADMAP row 158: a CPU arm in a Vulkan
610        // realize read Vulkan storage directly, "cpu kernel wrapper called with non-CPU input").
611        graph.set_placement(c, alt_device);
612        clone_of.insert(x, c);
613    }
614    let mut arm1 = clone_of[&exit];
615    // The reconverge node reads ARM 0's exit, which lives on `exit_device`, and the executor aliases the
616    // chosen arm's exit onto it with a zero-copy view. When the alternative runs elsewhere, bring the
617    // arm's result back with an explicit copy so both exits live on the same device.
618    if alt_device != exit_device {
619        let (shape, dtype) = {
620            let n = graph.node(arm1);
621            (n.shape.clone(), n.dtype)
622        };
623        let back = graph.push(Node {
624            op: Op::Copy {
625                target: exit_device,
626            },
627            inputs: vec![arm1],
628            shape,
629            dtype,
630        });
631        // A copy runs where its bytes come from (the residency pass re-stamps it the same way).
632        graph.set_target_backend(back, alt_backend);
633        graph.set_placement(back, exit_device);
634        arm1 = back;
635    }
636    let mut builder = graph.open_branch(diverge);
637    builder.add_arm(exit); // arm 0 = the DP winner's stretch, in place
638    builder.add_arm(arm1);
639    builder.finalize_branches(graph, reconverge)
640}
641
642#[cfg(test)]
643mod choose_regions_tests {
644    //! Pins TODAY's `choose_regions` policy (ROADMAP row 157): largest interior first, interiors
645    //! disjoint, no chosen region's endpoint inside another chosen interior, one survivor per
646    //! overlapping family. One test per drop reason, plus controls. They pin behaviour; they do not
647    //! argue it is the right policy (a laminar family would keep nested regions, a separate row).
648    use super::*;
649
650    fn region(d: usize, r: usize, interior: &[usize]) -> Region {
651        let ids: Vec<NodeId> = interior.iter().map(|&x| NodeId(x)).collect();
652        Region {
653            diverge: NodeId(d),
654            reconverge: NodeId(r),
655            exit: *ids.last().expect("non-empty interior"),
656            interior: ids,
657            alt_backend: BackendId::Cuda,
658            alt_device: fuel_ir::DeviceLocation::Cuda { gpu_id: 0 },
659            exit_device: fuel_ir::DeviceLocation::Cpu,
660            diverge_idx: d,
661            reconverge_idx: r,
662        }
663    }
664
665    /// `(diverge, reconverge)` of every chosen region, in choice order.
666    fn chosen(candidates: Vec<Region>) -> Vec<(usize, usize)> {
667        choose_regions(candidates)
668            .iter()
669            .map(|r| (r.diverge.0, r.reconverge.0))
670            .collect()
671    }
672
673    /// Region A: 0 -> 10 over interior {1,2,3}. The larger region in every test below.
674    fn a() -> Region {
675        region(0, 10, &[1, 2, 3])
676    }
677
678    #[test]
679    fn control_disjoint_regions_are_all_kept() {
680        let b = region(20, 30, &[21, 22]);
681        assert_eq!(chosen(vec![b, a()]), vec![(0, 10), (20, 30)]);
682    }
683
684    #[test]
685    fn control_regions_chained_at_an_endpoint_are_both_kept() {
686        // B starts at A's reconverge node (10): sharing an endpoint is allowed, no interior node is shared.
687        let b = region(10, 20, &[11, 12]);
688        assert_eq!(chosen(vec![b, a()]), vec![(0, 10), (10, 20)]);
689    }
690
691    #[test]
692    fn drop_reason_1_interior_overlaps_a_chosen_interior() {
693        let b = region(20, 30, &[3, 4]); // shares node 3 with A's interior
694        assert_eq!(chosen(vec![b, a()]), vec![(0, 10)]);
695    }
696
697    #[test]
698    fn drop_reason_2_interior_contains_a_chosen_endpoint() {
699        let b = region(8, 12, &[10, 11]); // node 10 is A's reconverge
700        assert_eq!(chosen(vec![b, a()]), vec![(0, 10)]);
701    }
702
703    #[test]
704    fn drop_reason_3_diverge_lies_in_a_chosen_interior() {
705        let b = region(2, 20, &[40, 41]); // diverge 2 is inside A's interior
706        assert_eq!(chosen(vec![b, a()]), vec![(0, 10)]);
707    }
708
709    #[test]
710    fn drop_reason_4_reconverge_lies_in_a_chosen_interior() {
711        let b = region(30, 3, &[50, 51]); // reconverge 3 is inside A's interior
712        assert_eq!(chosen(vec![b, a()]), vec![(0, 10)]);
713    }
714
715    #[test]
716    fn the_larger_of_two_overlapping_regions_wins_regardless_of_input_order() {
717        // Nested family: same diverge, growing reconverge (what the toy Llama log shows: d=7, r=156..159).
718        let small = region(7, 20, &[8]);
719        let large = region(7, 22, &[8, 20, 21]);
720        assert_eq!(chosen(vec![small, large]), vec![(7, 22)]);
721        let small = region(7, 20, &[8]);
722        let large = region(7, 22, &[8, 20, 21]);
723        assert_eq!(chosen(vec![large, small]), vec![(7, 22)]);
724    }
725
726    #[test]
727    fn policy_counts_on_a_nested_family_and_on_a_partial_overlap() {
728        // The diagnostic that feeds the policy decision must itself be checked on known shapes.
729        let nested = vec![
730            region(7, 20, &[8]),
731            region(7, 21, &[8, 20]),
732            region(7, 22, &[8, 20, 21]),
733            region(7, 23, &[8, 20, 21, 22]),
734        ];
735        let c = policy_counts(&nested);
736        assert_eq!(
737            (c.today, c.laminar, c.smallest_first, c.one_node),
738            (1, 4, 1, 1),
739            "nested family: today keeps the largest only; a laminar family keeps all four",
740        );
741        // Overlap WITHOUT nesting (shares node 3, neither contains the other): no policy keeps both.
742        let partial = vec![region(0, 10, &[1, 2, 3]), region(5, 15, &[3, 4, 6])];
743        let c = policy_counts(&partial);
744        assert_eq!(
745            (c.today, c.laminar, c.smallest_first, c.one_node),
746            (1, 1, 1, 0),
747            "partial overlap is dropped by every policy; no interior has one node",
748        );
749        // Disjoint regions: every policy keeps both (one-node policy only sees size-1 interiors).
750        let disjoint = vec![region(0, 10, &[1]), region(20, 30, &[21])];
751        let c = policy_counts(&disjoint);
752        assert_eq!(
753            (c.today, c.laminar, c.smallest_first, c.one_node),
754            (2, 2, 2, 2)
755        );
756    }
757
758    #[test]
759    fn a_family_of_four_nested_candidates_leaves_one_survivor() {
760        // Interiors of size 1..=4, same diverge: the shape behind "100 candidates -> 18 chosen".
761        let family = vec![
762            region(7, 20, &[8]),
763            region(7, 21, &[8, 20]),
764            region(7, 22, &[8, 20, 21]),
765            region(7, 23, &[8, 20, 21, 22]),
766        ];
767        assert_eq!(chosen(family), vec![(7, 23)]);
768    }
769}