Skip to main content

fuel_dispatch/
plan.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Execution plan — per-realize compilation output, Phase 1.5
3//! reshape of the picker-work arc.
4//!
5//! The plan is a topological order plus a sparse `NodeId ->
6//! AlternativeSet` map. Each entry is the per-decision-point top-N
7//! candidates the optimizer ranker considered, filtered and ranked
8//! per the configured `PlanOptions`. The eventual executor reads
9//! `alternatives` per node, takes the winner (Picker 2 territory in
10//! the long-term shape; Phase 4 wires the executor to this surface),
11//! and dispatches the resolved kernel.
12//!
13//! ## What changed in Phase 1.5
14//!
15//! Pre-1.5 this module hosted `NodeKernelBinding`, `TolerancePolicy`,
16//! and `resolve_kernel` — the v1 picker that fell out of Phase 7.6
17//! step 9b. Those types had zero callers (verified by the
18//! 2026-05-30 picker-alternatives audit), so Phase 1.5 retires
19//! them and ships the AlternativeSet-based plan in their place. The
20//! shape composes with everything Phase 1.1–1.4 already shipped:
21//! the enumerator builds candidates, the filter chain narrows them,
22//! the cost composer scores them, and the plan stores the
23//! top-N-after-filter-and-rank.
24//!
25//! Phase 4 of the picker-work arc migrates the PipelinedExecutor to
26//! consume `ExecutionPlan::alternatives` instead of `compile_node`'s
27//! first-registered path. Until then this module ships the
28//! infrastructure with no production consumer.
29
30use std::collections::HashMap;
31
32use fuel_graph::{Graph, NodeId};
33use fuel_ir::dispatch::{OpKind, SizeClass};
34use fuel_ir::probe::BackendId;
35use fuel_ir::{DType, DeviceLocation, Error, Result, Shape};
36
37use smallvec::SmallVec;
38
39use crate::kernel::KernelBindingTable;
40use crate::pipelined::{build_lookup_dtypes, op_to_op_kind};
41use crate::ranker::{
42    AlternativeSet, CapabilitiesLookup, ChainInput, DecisionContext, FilterContext, JudgeOracle,
43    KEEP_PER_DEVICE, PlacementDp, PrecisionRequirement, TransferEstimator, apply_filter_chain,
44    apply_inbound_transfer_costs, composite_ns, compute_static_costs, default_backend_rates,
45    default_chain, enumerate_candidates,
46};
47
48/// Per-realize execution plan. Built by [`compile_plan`].
49///
50/// `alternatives` is sparse — view ops, `Op::Const`, and ops
51/// `op_to_op_kind` returns `None` for get no entry. The executor's
52/// per-node dispatch reads `alternatives.get(&id)` and either takes
53/// the winner (top entry after rank) or, in the long-term shape,
54/// hands the full set to the runtime selector (Picker 2) for
55/// layer-3-telemetry-driven choice.
56#[derive(Debug)]
57pub struct ExecutionPlan {
58    /// Topological order — same shape the executor walks.
59    pub order: Vec<NodeId>,
60    /// One `AlternativeSet` per kernel-bearing node. Sparse.
61    pub alternatives: HashMap<NodeId, AlternativeSet>,
62    /// Candidates the placement DP priced and then pruned off a node because they sit on a device
63    /// other than the one it committed (the single-device-set invariant above). Kept so a pathfinder
64    /// can still see a second placement; nothing on the realize path reads this map. Sparse: only
65    /// nodes that had off-device candidates.
66    pub off_device: HashMap<NodeId, AlternativeSet>,
67    /// `SystemTopology` generation counter snapshotted at
68    /// [`compile_plan`] time. The executor (Phase 4.3) checks this
69    /// against `crate::dispatch::topology_generation()` at every
70    /// dispatch-chunk boundary; mismatch surfaces
71    /// [`Error::TopologyChanged`] so the realize layer can rebuild
72    /// the plan against the fresh topology.
73    ///
74    /// `0` for [`ExecutionPlan::empty()`] — empty plans by definition
75    /// have no alternatives to invalidate, so the executor's chunk-
76    /// boundary check skips them.
77    pub generation: u64,
78}
79
80impl ExecutionPlan {
81    /// Empty plan. Tests + future direct-call sites.
82    pub fn empty() -> Self {
83        Self {
84            order: Vec::new(),
85            alternatives: HashMap::new(),
86            off_device: HashMap::new(),
87            generation: 0,
88        }
89    }
90
91    /// Read-only handle to a node's alternative set. `None` for
92    /// nodes outside the plan's map.
93    pub fn alternatives(&self, node: NodeId) -> Option<&AlternativeSet> {
94        self.alternatives.get(&node)
95    }
96
97    /// Mutable handle — used by post-plan refinement passes (Phase
98    /// 3's Judge integration may re-rank top-N after the plan is
99    /// built).
100    pub fn alternatives_mut(&mut self, node: NodeId) -> Option<&mut AlternativeSet> {
101        self.alternatives.get_mut(&node)
102    }
103
104    /// Candidates of `node` on devices other than the one the DP committed (pruned from
105    /// [`Self::alternatives`]). `None` when there were none.
106    pub fn off_device_alternatives(&self, node: NodeId) -> Option<&AlternativeSet> {
107        self.off_device.get(&node)
108    }
109}
110
111/// Default [`DeviceLocation`] for a `BackendId` when the graph has
112/// no per-node placement set. Mirrors the convention in
113/// `fuel-graph-router` (CPU is the singleton `Cpu`; GPU backends
114/// default to ordinal 0).
115pub fn default_device_for(backend: BackendId) -> DeviceLocation {
116    backend.default_location()
117}
118
119/// The node's **decision device** — the single resolution chain the planner
120/// uses, extracted so every pass that must agree with [`compile_plan`] asks
121/// exactly the same question instead of approximating it.
122///
123/// Priority (see [`PlanOptions::pinned_device`]): explicit `Graph::placement`
124/// (the scheduler's per-node assignment) → the realize call's `pinned_device`
125/// → `default_device_for(target_backend)` (legacy stamped graphs). `None`
126/// means the node has no device context — `compile_plan` turns that into a
127/// typed error at its call site.
128pub(crate) fn decision_device_for(
129    graph: &Graph,
130    options: &PlanOptions<'_>,
131    id: NodeId,
132) -> Option<DeviceLocation> {
133    graph
134        .placement(id)
135        .or(options.pinned_device)
136        .or_else(|| graph.target_backend(id).map(default_device_for))
137}
138
139/// Every `BackendId` [`compile_plan`] may enumerate a kernel from **for this
140/// node**.
141///
142/// This is the authority on "can this node be served?", and **a pass that asks
143/// a weaker question will disagree with the planner.** That divergence is not
144/// hypothetical — it shipped: `insert_dtype_fixups` used to ask whether *any*
145/// registered backend served a key, so a backend the node could never run on
146/// suppressed the dtype reconciliation the node actually needed, and planning
147/// then dead-ended at `NoBackendForOp`. Concretely, compiling the Vulkan
148/// backend in broke CPU-pinned mixed-precision matmul, because Vulkan is the
149/// only backend registering `MatMul[F32, BF16, F32]`. Nothing about that is
150/// Vulkan-specific: *any* backend registering a mixed-dtype kernel would have
151/// broken every other backend's pinned graphs the same way.
152///
153/// Mirrors the enumeration in `plan_node`: the decision device's backends
154/// (cross-backend when a topology enumerator is configured, else the single
155/// legacy backend), plus the off-device fallback set when admission allows it
156/// — those backends are genuinely reachable for the node, so a native kernel
157/// there is a real alternative and must count.
158pub(crate) fn candidate_backends_for(
159    graph: &Graph,
160    options: &PlanOptions<'_>,
161    id: NodeId,
162    node: &fuel_graph::Node,
163) -> Vec<BackendId> {
164    let Some(target_device) = decision_device_for(graph, options, id) else {
165        return Vec::new();
166    };
167    let mut backends: Vec<BackendId> = match options.placements_for_device {
168        Some(f) => f(target_device),
169        None => vec![
170            graph
171                .target_backend(id)
172                .unwrap_or_else(|| backend_for_device(target_device)),
173        ],
174    };
175    // Picker-arc step 4b: the planner admits off-device candidates for a
176    // non-destructive node whenever a fallback enumerator is configured, so
177    // those backends ARE candidates here too. Destructive ops never move off
178    // the device owning their mutation target, matching `fallback_allowed`.
179    if node.op.destructive_input().is_none()
180        && let Some(fallback) = options.fallback_placements_for
181    {
182        backends.extend(fallback(target_device).into_iter().map(|(b, _)| b));
183    }
184    // Dedup without requiring `Ord` on the non-exhaustive `BackendId`.
185    let mut unique: Vec<BackendId> = Vec::with_capacity(backends.len());
186    for b in backends {
187        if !unique.contains(&b) {
188            unique.push(b);
189        }
190    }
191    unique
192}
193
194/// The `BackendId` that owns a `DeviceLocation`'s storage substrate.
195/// Total — `BackendId` mirrors `DeviceLocation` 1:1 (AOCL/MKL are
196/// `kernel_source` siblings under `Cpu`, not distinct backends).
197/// Inverse of [`default_device_for`] modulo GPU ordinals.
198pub fn backend_for_device(loc: DeviceLocation) -> BackendId {
199    loc.backend()
200}
201
202/// Plan-time configuration the caller hands to [`compile_plan`].
203///
204/// Most fields have sensible defaults via [`PlanOptions::new`] +
205/// chained builders. The two callback fields are required for
206/// non-trivial usage — the `'env` lifetime ties them to the
207/// caller's environment.
208///
209/// # `placements_for_device`
210///
211/// When `Some`, called per kernel-bearing node with the node's
212/// target `DeviceLocation` and expected to return every
213/// `BackendId` the picker is allowed to consider at that device.
214/// This is the cross-co-located-backend integration point —
215/// callers wire it to `SystemTopology::backends_for(device)` to
216/// unlock the AOCL/MKL/CPU competition story.
217///
218/// When `None`, the planner uses single-backend placement: only
219/// `(target_backend, placement)` from the graph node's side-table.
220/// Matches the pre-1.5 picker's pinned-backend behavior; useful as
221/// a transitional default and for tests.
222///
223/// # `pinned_device`
224///
225/// Picker-arc step 4a. When `Some`, nodes WITHOUT an explicit graph
226/// placement resolve their decision device to this location — the
227/// realize call's pinned DEVICE. This replaces the bridge's
228/// pre-plan monolithic per-node `set_target_backend` loop: the
229/// graph no longer needs `target_backend` stamped before planning;
230/// the plan's per-node winner is stamped back onto the graph AFTER
231/// planning (`fuel-tensor::pipelined_bridge::stamp_plan_backends`).
232///
233/// Resolution priority per node: explicit `Graph::placement` (the
234/// scheduler's per-node assignment) → `pinned_device` →
235/// `default_device_for(target_backend)` (legacy stamped graphs) →
236/// error.
237///
238/// # `fallback_placements_for`
239///
240/// Picker-arc step 4b, relaxed by planner Stage 2. The closure
241/// supplies the OFF-DEVICE placements the picker may consider
242/// beyond the node's decision device. Two admission regimes:
243///
244/// - **Priced (Stage 2)** — when a [`Self::transfer_estimator`] is
245///   configured (with `populate_costs` + a capabilities lookup),
246///   off-device placements ALWAYS enumerate alongside the decision
247///   device's, and every candidate carries an inbound-transfer
248///   term; locality emerges from the pricing (ties break toward
249///   the decision device via the rank's stable sort). After the
250///   rank the set is pruned to the winner's device. Nodes with an
251///   explicit `Graph::placement` are HARD pins — they stay on the
252///   legacy regime below.
253/// - **Legacy (unpriced)** — without an estimator, the closure is
254///   consulted only when the decision device can't deliver: empty
255///   enumeration for the `(op, dtypes)`, or (Stage-2 fix) a hard
256///   filter chain that rejects every decision-device registration.
257///
258/// Constraints enforced by `compile_plan` in both regimes:
259///
260/// - **Destructive ops never fall back** (`Op::destructive_input()`
261///   is `Some`): in-place mutation semantics don't survive moving
262///   the op away from the device that owns its mutation target;
263///   those ops keep the plan-time `NoBackendForOp` error.
264/// - **Each NODE's surviving alternative set lives on one device**
265///   (legacy fallback sets freeze to their single ranked winner;
266///   relaxed sets prune to *that node's* winner's device): the
267///   residency stitch (`Op::Copy` insertion) is a graph rewrite
268///   computed from the static winner, so a dispatch-time selector
269///   (the `Op::Branch` arm picker) must not be able to swap in a
270///   sibling on a *different* device whose inputs were never copied
271///   there. This is a **per-node** invariant on the candidate set —
272///   NOT a graph-global "everything realizes on one device" claim.
273///   Step E A4a-1 confirmed (CireSnave 2026-06-29) device placement
274///   is per-node: the surviving graph is almost never single-device,
275///   and even a path between decision points may span devices. The
276///   planner already honors that — each node's decision device is
277///   `Graph::placement` → `pinned_device` → stamp-default
278///   (independently per node), `stamp_plan_backends` writes each
279///   node's own winner backend, and `insert_residency_copies`
280///   bridges every resulting cross-device boundary edge. A
281///   single-device plan is just the degenerate case where every
282///   node's per-node device happens to coincide; this prune is a
283///   no-op there, so single-device realize stays byte-identical.
284///
285/// # `capabilities_for`
286///
287/// Required when `populate_costs` is true (the default). The
288/// closure resolves a `BackendId` to its `BackendCapabilities` —
289/// callers typically wire it to `SystemTopology::capabilities(...)`
290/// or the CapabilityRegistry. Returns `None` for backends not in
291/// the topology (their candidates retain default zero cost).
292pub struct PlanOptions<'env> {
293    /// Hard precision floor the picker enforces. Default: empty
294    /// (unconstrained — every candidate passes the precision filter).
295    pub precision_requirement: PrecisionRequirement,
296    /// Whether to invoke [`compute_static_costs`] + rank after
297    /// filtering. Default: true. Disable for tests that just want
298    /// to verify enumeration + filtering without cost machinery.
299    pub populate_costs: bool,
300    /// Cross-co-located-backend placement enumerator. See struct
301    /// docs.
302    pub placements_for_device: Option<&'env (dyn Fn(DeviceLocation) -> Vec<BackendId> + 'env)>,
303    /// Realize-call device pin (picker-arc step 4a). See struct
304    /// docs.
305    pub pinned_device: Option<DeviceLocation>,
306    /// Off-device fallback enumerator for missing-impl ops
307    /// (picker-arc step 4b). See struct docs.
308    pub fallback_placements_for:
309        Option<&'env (dyn Fn(DeviceLocation) -> Vec<(BackendId, DeviceLocation)> + 'env)>,
310    /// Capabilities lookup. Required when `populate_costs` is
311    /// true.
312    pub capabilities_for: Option<&'env CapabilitiesLookup<'env>>,
313    /// Optional Phase 3 Layer-2 oracle. When `Some` AND
314    /// `populate_costs` is true, the cost composer refines each
315    /// candidate's Layer-1 estimate with the Judge's measured
316    /// latency at that cell. Candidates the oracle hasn't measured
317    /// keep the Layer-1 estimate (silent fallback — absence ≠ zero).
318    pub judge: Option<&'env dyn JudgeOracle>,
319    /// Planner Stage-2 transfer-cost oracle. When `Some` AND
320    /// `populate_costs` is true (with a capabilities lookup), the
321    /// cost composer adds a per-candidate inbound-transfer term:
322    /// the sum over the node's inputs of
323    /// `estimate_transfer_ns(input residency, candidate device,
324    /// input bytes)`, for every input whose residency is known at
325    /// plan time. Producer residencies are committed along the topo
326    /// walk (producers rank before consumers); graph-input
327    /// residencies come from [`Self::input_residency`].
328    ///
329    /// Also the gate for the Stage-2 admission relax: with pricing
330    /// active, off-device candidates ALWAYS enumerate (priced) for
331    /// nodes without an explicit `Graph::placement` — locality
332    /// emerges from the numbers, not from the legacy
333    /// missing-impl-only fallback gate.
334    ///
335    /// Production callers wire this to
336    /// `SystemTopology::estimate_transfer_ns` (Stage-1
337    /// `TransferCalibration` behind it); unit tests use synthetic
338    /// estimators — never live calibration.
339    pub transfer_estimator: Option<&'env dyn TransferEstimator>,
340    /// Guard against silently planning cost-based placement WITHOUT
341    /// transfer pricing. When `true`, [`compile_plan`] fails fast with an
342    /// error if [`Self::transfer_estimator`] is `None` — i.e. the caller
343    /// has declared "I intend to price transfer; if the estimator isn't
344    /// wired, that's a bug, not a silent revert to latency-greedy."
345    ///
346    /// Default `false` so the many unit tests that legitimately plan
347    /// *unpriced* (see `compile_plan_without_estimator_prices_nothing`) are
348    /// unaffected. The PRODUCTION realize entry (`fuel-core`'s
349    /// `build_optimized_graph`) sets this whenever cost-based cross-device
350    /// placement is active, so a future edit that drops the
351    /// `.with_transfer_estimator(...)` wiring — or a new production planner
352    /// that forgets it — fails loudly at plan-build time instead of quietly
353    /// pricing every transfer at zero. Opt-in rather than default-on
354    /// because "cost placement, unpriced" is a supported mode for callers
355    /// that ask for it; production simply never does.
356    pub require_transfer_pricing: bool,
357    /// Residency resolver for graph INPUTS whose bytes already
358    /// exist outside the plan — `Op::Const` storages uploaded by
359    /// the const cache and persistent `initial` slots
360    /// (InferenceContext). Consulted while threading residency
361    /// through the plan walk, with the same priority the bridge's
362    /// `effective_placements` gives cached storages: after
363    /// residency-declaring ops and explicit placements, before the
364    /// plan's own winner. `None` for a node means "not a resident
365    /// input" — its residency resolves through the remaining rules
366    /// (or stays unknown, in which case no transfer term fires on
367    /// its edges).
368    pub input_residency: Option<&'env (dyn Fn(NodeId) -> Option<DeviceLocation> + 'env)>,
369    /// Planner Stage 4: incremental extension over a previously
370    /// compiled plan. Nodes already covered by `reuse_plan` (an
371    /// `AlternativeSet` exists for them) skip enumeration / filter /
372    /// cost / DP entirely — their stored set is cloned into the new
373    /// plan and their residency commits as the stored winner's
374    /// device (mirroring the priority-4 "plan winner" rule), so the
375    /// delta's pricing sees the same residency picture the original
376    /// walk committed.
377    ///
378    /// The caller (the plan store) is responsible for only reusing
379    /// plans built under the SAME topology generation and pinned
380    /// device — `compile_plan` does not re-validate the reused sets.
381    /// Reused candidates keep their original `inbound_transfer_ns`
382    /// terms; a residency shift between builds is repriced only for
383    /// delta nodes (acceptable drift — placement correctness is
384    /// re-stitched per realize by the bridge's residency passes).
385    pub reuse_plan: Option<&'env ExecutionPlan>,
386    /// Gate for the Stage-2 relaxed **cross-device** placement (cost-based
387    /// off-device enumeration). Default: `true` — a node without an explicit
388    /// `Graph::placement` may be priced onto (and moved to) a cheaper sibling
389    /// device, the "plan IS the graph" auto-placement.
390    ///
391    /// Set `false` to keep every node on its pinned/decision device: the
392    /// relaxed branch is suppressed, so no off-device candidate is enumerated
393    /// on cost grounds.
394    ///
395    /// This is what a **reference / single-device realize** wants. A CPU-pinned
396    /// oracle must genuinely run on CPU — never cost-relocated to the very
397    /// backend it validates — and by the always-built coverage commitment
398    /// (fuel-cpu-backend ships a `bit_stable_on_same_hardware` kernel for every
399    /// primitive op) the CPU decision device can always supply a kernel, so
400    /// suppressing off-device placement never strands a node. A single-op
401    /// parity probe pinned to backend B likewise stays on B regardless of op
402    /// size. Explicit `Graph::placement` is a hard pin either way; this flag
403    /// governs only the *un-pinned* nodes.
404    pub allow_cost_placement: bool,
405    /// Byte budget for the pinned device's resident working set (ROADMAP row 67, increment I1).
406    /// When `Some(budget)` AND [`Self::pinned_device`] is set, `optimize_graph` runs the
407    /// residency-eviction pass after the residency-copy pass: while the graph's analysed peak
408    /// exceeds `budget`, it inserts an `Op::Move{Cpu}` + reload `Op::Copy{device}` chain around the
409    /// best candidate. `None` (the default) leaves the graph exactly as it was: the pass was
410    /// written for this but had no production caller. No default budget is derived from the
411    /// device here; a caller (or a later increment) supplies it.
412    pub device_budget_bytes: Option<usize>,
413    /// Which rule produced [`Self::device_budget_bytes`] (ROADMAP row 67 I2), when it came from
414    /// [`crate::device_budget::resolve_device_budget`]; `None` for a bare number set by hand. The
415    /// optimizer copies it onto the eviction outcome so a plan report names its budget's origin.
416    pub device_budget_source: Option<crate::device_budget::BudgetSource>,
417    /// Baracuda dispatch-telemetry hooks (behind the `telemetry` cargo
418    /// feature). When `Some` AND the config's mode is not `Off`,
419    /// `compile_plan` runs a post-plan pass that emits a structural
420    /// **miss** for every node whose winning kernel is the FKC generic
421    /// fallback (see [`crate::telemetry::TelemetryHooks`]). `None` (the
422    /// default) makes the pass a no-op — the branch-predictable off gate,
423    /// so a default realize never touches the sink or the provider.
424    #[cfg(feature = "telemetry")]
425    pub telemetry: Option<&'env crate::telemetry::TelemetryHooks<'env>>,
426}
427
428impl Default for PlanOptions<'_> {
429    fn default() -> Self {
430        Self {
431            precision_requirement: PrecisionRequirement::default(),
432            populate_costs: true,
433            placements_for_device: None,
434            pinned_device: None,
435            fallback_placements_for: None,
436            capabilities_for: None,
437            judge: None,
438            transfer_estimator: None,
439            require_transfer_pricing: false,
440            input_residency: None,
441            reuse_plan: None,
442            allow_cost_placement: true,
443            device_budget_bytes: None,
444            device_budget_source: None,
445            #[cfg(feature = "telemetry")]
446            telemetry: None,
447        }
448    }
449}
450
451impl<'env> PlanOptions<'env> {
452    /// Builder constructor; same fields as [`Default`].
453    pub fn new() -> Self {
454        Self::default()
455    }
456
457    /// Set the pinned device's resident-bytes budget; see [`Self::device_budget_bytes`].
458    pub fn with_device_budget_bytes(mut self, budget_bytes: usize) -> Self {
459        self.device_budget_bytes = Some(budget_bytes);
460        self
461    }
462
463    /// Set the budget from a [`crate::device_budget::ResolvedBudget`], keeping the rule that
464    /// produced it for the plan report.
465    pub fn with_resolved_device_budget(
466        mut self,
467        budget: crate::device_budget::ResolvedBudget,
468    ) -> Self {
469        self.device_budget_bytes = Some(budget.bytes);
470        self.device_budget_source = Some(budget.source);
471        self
472    }
473
474    /// Set the precision requirement hard filter.
475    pub fn with_precision_requirement(mut self, req: PrecisionRequirement) -> Self {
476        self.precision_requirement = req;
477        self
478    }
479
480    /// Disable cost computation + ranking. Sets `populate_costs =
481    /// false`; alternatives end up in enumerator order, useful for
482    /// tests that don't care about ranking.
483    pub fn without_cost_population(mut self) -> Self {
484        self.populate_costs = false;
485        self
486    }
487
488    /// Attach a co-located-backend enumerator. Wire to
489    /// `SystemTopology::backends_for(device)` for production.
490    pub fn with_placements_for_device(
491        mut self,
492        f: &'env (dyn Fn(DeviceLocation) -> Vec<BackendId> + 'env),
493    ) -> Self {
494        self.placements_for_device = Some(f);
495        self
496    }
497
498    /// Pin the realize call's device. Nodes without an explicit
499    /// graph placement enumerate their candidates at this location
500    /// — no per-node `target_backend` stamp needed before planning.
501    /// Picker-arc step 4a.
502    pub fn with_pinned_device(mut self, device: DeviceLocation) -> Self {
503        self.pinned_device = Some(device);
504        self
505    }
506
507    /// Suppress the Stage-2 relaxed cross-device placement (see
508    /// [`Self::allow_cost_placement`]): every un-pinned node stays on its
509    /// decision device; only the missing-impl fallback may still go
510    /// off-device. Use for a reference / single-device realize.
511    pub fn without_cost_placement(mut self) -> Self {
512        self.allow_cost_placement = false;
513        self
514    }
515
516    /// Declare that this plan MUST price transfer: [`compile_plan`] errors
517    /// if no [`Self::transfer_estimator`] is set. Production realize wires
518    /// this whenever cost-based cross-device placement is active, so a
519    /// dropped or forgotten `.with_transfer_estimator(...)` fails loudly at
520    /// plan-build time rather than silently reverting to latency-greedy
521    /// placement (transfers priced at zero). See
522    /// [`Self::require_transfer_pricing`].
523    pub fn require_transfer_pricing(mut self) -> Self {
524        self.require_transfer_pricing = true;
525        self
526    }
527
528    /// Attach an off-device fallback enumerator. With a Stage-2
529    /// transfer estimator configured, off-device placements always
530    /// enumerate, priced; without one, the closure is consulted
531    /// only when the decision device can't deliver (no impl, or
532    /// every impl hard-filtered). Wire to the `SystemTopology`
533    /// device list for production. Picker-arc step 4b + planner
534    /// Stage 2 — see struct docs for the destructive-op,
535    /// hard-pin, and single-device constraints.
536    pub fn with_fallback_placements_for(
537        mut self,
538        f: &'env (dyn Fn(DeviceLocation) -> Vec<(BackendId, DeviceLocation)> + 'env),
539    ) -> Self {
540        self.fallback_placements_for = Some(f);
541        self
542    }
543
544    /// Attach a capabilities lookup. Required when `populate_costs`
545    /// is true.
546    pub fn with_capabilities_for(mut self, f: &'env CapabilitiesLookup<'env>) -> Self {
547        self.capabilities_for = Some(f);
548        self
549    }
550
551    /// Attach a Layer-2 Judge oracle. When set, `compile_plan`'s
552    /// cost composer refines Layer-1 estimates with measured
553    /// latencies per [`JudgeOracle::measured_latency_ns`].
554    pub fn with_judge(mut self, judge: &'env dyn JudgeOracle) -> Self {
555        self.judge = Some(judge);
556        self
557    }
558
559    /// Attach a Stage-2 transfer-cost oracle. See the
560    /// [`Self::transfer_estimator`] field docs — enables inbound-
561    /// transfer pricing AND the priced off-device admission relax.
562    /// Production wires `SystemTopology::estimate_transfer_ns`;
563    /// tests use synthetic estimators.
564    pub fn with_transfer_estimator(mut self, est: &'env dyn TransferEstimator) -> Self {
565        self.transfer_estimator = Some(est);
566        self
567    }
568
569    /// Attach a residency resolver for already-resident graph
570    /// inputs (consts + persistent cache slots). See the
571    /// [`Self::input_residency`] field docs.
572    pub fn with_input_residency(
573        mut self,
574        f: &'env (dyn Fn(NodeId) -> Option<DeviceLocation> + 'env),
575    ) -> Self {
576        self.input_residency = Some(f);
577        self
578    }
579
580    /// Attach a base plan for incremental extension (planner Stage
581    /// 4). See the [`Self::reuse_plan`] field docs.
582    pub fn with_reuse_plan(mut self, base: &'env ExecutionPlan) -> Self {
583        self.reuse_plan = Some(base);
584        self
585    }
586
587    /// Attach Baracuda dispatch-telemetry hooks (behind the `telemetry`
588    /// cargo feature). With them set and the config not `Off`,
589    /// `compile_plan`'s post-plan pass emits a structural miss per node
590    /// whose winning kernel is the FKC generic fallback. See the
591    /// [`Self::telemetry`] field docs.
592    #[cfg(feature = "telemetry")]
593    pub fn with_telemetry(mut self, hooks: &'env crate::telemetry::TelemetryHooks<'env>) -> Self {
594        self.telemetry = Some(hooks);
595        self
596    }
597}
598
599/// Build an [`ExecutionPlan`] from a topologically-ordered node
600/// sequence + binding table + options.
601///
602/// For each node in `order`:
603///
604/// - If `op_to_op_kind(&node.op)` returns `None` (view ops,
605///   `Op::Const`, ops not yet wired into dispatch), the node gets
606///   no entry — view-only adoption + const adoption flow through
607///   the legacy paths unchanged.
608/// - `Op::Copy` / `Op::Move` nodes get no entry either (picker-arc
609///   step 4a): their kernel backend is residency-determined (the
610///   SOURCE backend), so transfer-kernel resolution stays with the
611///   executor's `compile_node` path keyed by the bridge-maintained
612///   source-backend stamp.
613/// - Otherwise:
614///   1. Resolve `(op_kind, dtypes, device)` from the graph + the
615///      options (`device` via `Graph::placement`, then
616///      `PlanOptions::pinned_device`, then
617///      `default_device_for(target_backend)` for legacy stamped
618///      graphs).
619///   2. Build the placement list — either via
620///      `options.placements_for_device` (cross-backend mode) or
621///      `[(target_backend, device)]` (legacy single-backend mode).
622///   3. Enumerate candidates via [`enumerate_candidates`].
623///   4. Apply the default filter chain (precision floor +
624///      strided-input pref + bit-stable pref).
625///   5. If `populate_costs`, compute static costs via the
626///      capabilities lookup — plus, when a
627///      [`PlanOptions::transfer_estimator`] is configured, the
628///      Stage-2 inbound-transfer term per candidate — and rank
629///      ascending by composite cost.
630///   6. Retain the per-ending-device Pareto frontier + crowding cap
631///      ([`AlternativeSet::retain_per_device_frontier`], `keep =
632///      KEEP_PER_DEVICE`).
633///   7. If the set is empty after filtering, return
634///      [`Error::NoBackendForOp`] (fail-fast at plan time, not
635///      deep in executor dispatch).
636///   8. Insert into `plan.alternatives`.
637///
638/// ## Stage-2 residency threading
639///
640/// `order` is topological, so each node's producers are planned —
641/// and their placements committed — before the node itself ranks.
642/// The walk maintains a per-node residency view mirroring the
643/// bridge's `effective_placements` priority: residency-declaring
644/// ops (`Op::Copy`/`Move`/`Alloc` targets) → explicit
645/// `Graph::placement` → caller-supplied input residency
646/// ([`PlanOptions::input_residency`], consts + persistent cache
647/// slots) → the plan's own committed winner → backend stamp →
648/// view-op pass-through inheritance. Inputs whose residency
649/// resolves feed the inbound-transfer pricing; unknown residency
650/// prices no term (conservative — an unpriceable edge neither
651/// justifies nor penalizes a move).
652///
653/// ## Stage-3 carry-forward placement DP
654///
655/// Relaxed nodes whose admissible candidates span ≥ 2 devices defer
656/// their winner choice to the carry-forward DP
657/// ([`crate::ranker::placement_dp`]): the walk opens a state row
658/// per such node (`best[d]` = accumulated cost arriving with output
659/// on `d`), extends rows along the dominant chain (view-shaped
660/// pass-throughs alias through), merges joins per-device by the
661/// cheaper producer state, prices the exit crossing back to the
662/// realize target on terminal rows, and backtracks the cheapest
663/// terminal state into per-node device commitments. Each committed
664/// row's `AlternativeSet` is then priced, ranked, and pruned to the
665/// committed device — preserving the Stage-2 single-device-set
666/// invariant the residency stitch depends on.
667///
668/// Gating: a row only opens when the node is relaxed (estimator +
669/// fallback enumerator configured, no explicit placement, not
670/// destructive, not already-resident) AND its candidates span more
671/// than one device. Single-device plans never open a row and take
672/// the Stage-2 greedy path bit-identically — zero overhead beyond
673/// an empty-map check per node.
674///
675/// Documented debt (see the `placement_dp` module docs): fan-out
676/// rows chain into their FIRST consumer only (later consumers price
677/// that edge as unknown); diamonds re-anchor the second branch as a
678/// fresh chain; hard-pinned consumers of an open row close it
679/// toward their device at walk time, which prices the crossing but
680/// cannot revisit it later.
681pub fn compile_plan(
682    graph: &Graph,
683    order: &[NodeId],
684    bindings_table: &KernelBindingTable,
685    options: &PlanOptions<'_>,
686) -> Result<ExecutionPlan> {
687    // Transfer-pricing guard (opt-in via `PlanOptions::require_transfer_pricing`).
688    // A caller that declared it must price transfer, yet wired no estimator,
689    // would silently price every cross-device transfer at zero — reverting
690    // placement to latency-greedy. That is precisely the drift the production
691    // realize path guards against, so fail fast at plan-build time. Result, not
692    // panic (never panic on production paths); build-time validation, not a
693    // runtime surprise mid-dispatch.
694    if options.require_transfer_pricing && options.transfer_estimator.is_none() {
695        return Err(Error::Msg(
696            "compile_plan: require_transfer_pricing is set but no transfer \
697             estimator is wired — placement would silently price transfers at \
698             zero (latency-greedy). Wire PlanOptions::with_transfer_estimator(..) \
699             or drop the pricing requirement."
700                .into(),
701        )
702        .bt());
703    }
704
705    // Snapshot the topology generation at plan-build time. The
706    // executor (Phase 4.3) checks this against the live counter at
707    // every dispatch-chunk boundary; mismatch surfaces
708    // `Error::TopologyChanged` so the realize layer can rebuild
709    // against the fresh topology.
710    let generation = crate::dispatch::topology_generation();
711    let mut alternatives_map = HashMap::with_capacity(order.len());
712    let mut off_device_map: HashMap<NodeId, AlternativeSet> = HashMap::new();
713
714    // Stage-2 residency view, threaded along the walk (see the
715    // doc comment). Nodes matching no resolution rule stay absent —
716    // residency unknown, no transfer term fires on their edges.
717    let mut residency: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
718
719    // Stage-3 DP state. Empty (and cost-free) unless multi-device
720    // placement freedom actually materializes at some node.
721    let mut dp = PlacementDp::new();
722    let mut dp_drafts: HashMap<NodeId, NodeDraft> = HashMap::new();
723
724    for &id in order {
725        let node = graph.node(id);
726
727        // Planner Stage 4: incremental-extension fast path. A node
728        // already covered by the base plan reuses its stored set
729        // verbatim; its residency commits with the same priority
730        // order the full walk uses (early rules, then the stored
731        // winner's device — the priority-4 "plan winner" rule).
732        if let Some(base) = options.reuse_plan
733            && let Some(set) = base.alternatives(id)
734        {
735            let resident = early_residency(graph, options, id, node)
736                .or_else(|| set.winner().map(|w| w.device));
737            if let Some(loc) = resident {
738                residency.insert(id, loc);
739            }
740            alternatives_map.insert(id, set.clone());
741            continue;
742        }
743
744        // Residency priorities 1–3: definitional transfer/alloc
745        // targets, explicit placements, already-resident inputs.
746        let early = early_residency(graph, options, id, node);
747
748        let mut dp_row_opened = false;
749        let winner_device = match build_node_draft(graph, id, node, bindings_table, options)? {
750            Some(draft) => {
751                let devices = distinct_devices(&draft.set);
752                let dp_estimator = options
753                    .transfer_estimator
754                    .filter(|_| draft.relaxed && early.is_none() && devices.len() >= 2);
755                if let Some(est) = dp_estimator {
756                    // Stage 3: open a DP row instead of committing a
757                    // winner. Residency stays unresolved until the
758                    // backtrack commits a device.
759                    open_dp_row(
760                        &mut dp,
761                        graph,
762                        id,
763                        node,
764                        &draft.set,
765                        &devices,
766                        &residency,
767                        est,
768                        options.capabilities_for,
769                    );
770                    dp_drafts.insert(id, draft);
771                    dp_row_opened = true;
772                    None
773                } else {
774                    // Stage-2 greedy finalize. When the node's device
775                    // is already determined (single-device candidate
776                    // set — hard pins, destructive ops, frozen
777                    // fallbacks), close any open producer rows toward
778                    // it FIRST so the close prices the crossing and
779                    // the finalize prices the edge.
780                    if let Some(est) = options.transfer_estimator
781                        && let [single] = devices.as_slice()
782                    {
783                        close_open_inputs(&mut dp, graph, node, *single, est, &mut residency);
784                    }
785                    let mut off = None;
786                    let set = finalize_node_greedy(
787                        graph,
788                        node,
789                        draft,
790                        bindings_table,
791                        options,
792                        &residency,
793                        &mut off,
794                    )?;
795                    if let Some(off) = off {
796                        off_device_map.insert(id, off);
797                    }
798                    let dev = set.winner().map(|w| w.device);
799                    // Multi-device greedy sets (legacy missing-impl
800                    // fallback shapes) learn their device only after
801                    // ranking — close producers toward the winner.
802                    if devices.len() > 1
803                        && let (Some(est), Some(wd)) = (options.transfer_estimator, dev)
804                    {
805                        close_open_inputs(&mut dp, graph, node, wd, est, &mut residency);
806                    }
807                    alternatives_map.insert(id, set);
808                    dev
809                }
810            }
811            None => {
812                // Structural / residency-determined nodes. An
813                // `Op::Copy`/`Op::Move` consuming an open row anchors
814                // the chain at its transfer target (the production
815                // realize-root splice is exactly this shape — closing
816                // here IS the exit pricing through an explicit node).
817                if let fuel_graph::Op::Copy { target } | fuel_graph::Op::Move { target } = node.op
818                    && let Some(est) = options.transfer_estimator
819                {
820                    close_open_inputs(&mut dp, graph, node, target, est, &mut residency);
821                }
822                None
823            }
824        };
825
826        if dp_row_opened {
827            // Residency intentionally NOT committed — the DP owns
828            // this node's placement; priorities 5–6 must not leak a
829            // stamp-derived device downstream.
830            continue;
831        }
832
833        // Commit this node's residency for downstream consumers.
834        let resident = early
835            .or(winner_device)
836            .or_else(|| {
837                // Priority 5: a backend stamp without a plan entry
838                // (structural ops + legacy stamps) follows the
839                // realize device, or the stamp's default device
840                // when no pin is set.
841                graph.target_backend(id).map(|b| {
842                    options
843                        .pinned_device
844                        .unwrap_or_else(|| default_device_for(b))
845                })
846            })
847            .or_else(|| {
848                // Priority 6: residency-inheriting pass-throughs —
849                // view ops, Reshape, Contiguize produce no new
850                // residency; they follow their data input (already
851                // resolved — the walk is topological).
852                if is_passthrough(node) {
853                    node.inputs.first().and_then(|i| residency.get(i)).copied()
854                } else {
855                    None
856                }
857            });
858        if let Some(loc) = resident {
859            residency.insert(id, loc);
860        } else if is_passthrough(node) {
861            // Stage 3: a pass-through of a DP-tracked node keeps the
862            // chain connected — alias it to the producer's row so
863            // consumers extend through the view. (If the row already
864            // committed, surface its device as this view's residency,
865            // mirroring priority 6.)
866            if let Some(&input) = node.inputs.first() {
867                let root = dp.resolve(input);
868                if let Some(dev) = dp.committed_device(root) {
869                    residency.insert(id, dev);
870                } else {
871                    dp.add_alias(id, root);
872                }
873            }
874        }
875    }
876
877    // Stage 3: commit the DP (exit pricing + backtrack), then
878    // finalize each deferred row against the committed placements.
879    if !dp_drafts.is_empty() {
880        let Some(est) = options.transfer_estimator else {
881            // Rows only open with an estimator; this is unreachable
882            // in practice but degrades typed rather than panicking.
883            return Err(Error::Msg(
884                "compile_plan: placement DP rows exist without a transfer \
885                 estimator — internal invariant violated"
886                    .into(),
887            )
888            .bt());
889        };
890        let commits = dp.finish(options.pinned_device, |nid| node_bytes(graph, nid), est);
891        for (n, d) in commits {
892            residency.insert(n, d);
893        }
894        // Pass-through residency for view chains the walk left
895        // unresolved (views of DP nodes) — topo order, so producers
896        // resolve before their views.
897        for &id in order {
898            if residency.contains_key(&id) {
899                continue;
900            }
901            let node = graph.node(id);
902            if is_passthrough(node)
903                && let Some(&loc) = node.inputs.first().and_then(|i| residency.get(i))
904            {
905                residency.insert(id, loc);
906            }
907        }
908        // Finalize deferred rows in topo order: price inbound
909        // transfers from the final residencies, rank, prune to the
910        // DP-committed device (Stage-2 single-device-set invariant),
911        // truncate.
912        for &id in order {
913            let Some(draft) = dp_drafts.remove(&id) else {
914                continue;
915            };
916            let chosen = dp.committed_device(id).ok_or_else(|| {
917                Error::Msg(format!(
918                    "compile_plan: placement DP left node {:?} uncommitted — \
919                     internal invariant violated",
920                    id,
921                ))
922                .bt()
923            })?;
924            let node = graph.node(id);
925            let mut set = draft.set;
926            let inputs = priced_inputs_for(graph, node, &residency);
927            apply_inbound_transfer_costs(&mut set, &inputs, est);
928            set.rank_by_composite_cost();
929            let keep: Vec<usize> = set
930                .alternatives()
931                .iter()
932                .enumerate()
933                .filter_map(|(i, c)| (c.device == chosen).then_some(i))
934                .collect();
935            if keep.len() < set.len() {
936                let off_keep: Vec<usize> = (0..set.len()).filter(|i| !keep.contains(i)).collect();
937                let mut off = set.clone();
938                off.retain_indices(&off_keep);
939                off.retain_per_device_frontier(KEEP_PER_DEVICE);
940                off_device_map.insert(id, off);
941                set.retain_indices(&keep);
942            }
943            // PR-B2: retire the fixed top-N. The set is now pruned to
944            // the DP-committed single device, so the per-ending-device
945            // Pareto frontier keeps that device's non-dominated paths
946            // (crowding-capped at KEEP_PER_DEVICE); the arm-0 winner —
947            // the realize pick — is preserved at index 0.
948            set.retain_per_device_frontier(KEEP_PER_DEVICE);
949            if set.is_empty() {
950                // Defensive — the committed device came from the
951                // row's own candidates, so this shouldn't fire.
952                return Err(missing_binding_error(
953                    bindings_table,
954                    draft.op_kind,
955                    &draft.dtypes,
956                    draft.diag_backend,
957                ));
958            }
959            alternatives_map.insert(id, set);
960        }
961    }
962
963    // Baracuda dispatch + structural-miss telemetry (opt-in, behind the
964    // `telemetry` feature). Post-plan pass over the finalized winners; a no-op
965    // unless hooks are threaded AND enabled — the emission never perturbs the
966    // plan.
967    #[cfg(feature = "telemetry")]
968    emit_plan_telemetry(graph, &alternatives_map, bindings_table, options);
969
970    Ok(ExecutionPlan {
971        order: order.to_vec(),
972        alternatives: alternatives_map,
973        off_device: off_device_map,
974        generation,
975    })
976}
977
978/// Post-plan Baracuda **dispatch + structural-miss** emission (behind the
979/// `telemetry` feature). For every kernel-bearing node it emits a
980/// [`crate::telemetry::DispatchRecord`] for the winning kernel (the `chosen`
981/// signal, every planned cell) and — when the winner is the FKC generic
982/// fallback (`is_generic`) — additionally a
983/// [`crate::telemetry::MissRecord`] via the shared
984/// [`crate::telemetry::detect_miss_precomputed`] core.
985///
986/// ## What each mode emits
987/// - **Off** (default): nothing (the branch-predictable gate below).
988/// - **Coarse**: a `DispatchRecord` per cell with an EMPTY `candidates[]`
989///   (chosen + count + structure_key + hw) plus the miss histogram — no Judge
990///   reads.
991/// - **Detailed**: Coarse plus `candidates[]` filled from the plan-time Judge
992///   oracle (the SAME `measured_latency_ns` read the ranker uses), one measured
993///   latency per admitted alternative (`None` for unmeasured cells).
994///
995/// The `chosen`/`candidates`/`fallback` [`crate::telemetry::ImplId`]s carry the
996/// FKC revision threaded onto [`crate::kernel::BindingEntry`] (0 = untracked for
997/// hand-written kernels). Emission is best-effort and can never break dispatch —
998/// a poisoned sink lock is swallowed to a no-op, and a missing provider token
999/// forms no miss signal (never a fabricated one). The plan itself is never
1000/// mutated, so a run with telemetry on is byte-identical to one with it off save
1001/// for the sink's contents.
1002#[cfg(feature = "telemetry")]
1003fn emit_plan_telemetry(
1004    graph: &Graph,
1005    alternatives: &HashMap<NodeId, AlternativeSet>,
1006    bindings_table: &KernelBindingTable,
1007    options: &PlanOptions<'_>,
1008) {
1009    use crate::telemetry::{
1010        DispatchRecord, FdxOperandDesc, ImplId, TELEMETRY_SCHEMA_VERSION, detect_miss_precomputed,
1011    };
1012
1013    // Off gate (branch-predictable, first): no hooks or disabled ⇒ nothing.
1014    let Some(hooks) = options.telemetry else {
1015        return;
1016    };
1017    if !hooks.config.is_enabled() {
1018        return;
1019    }
1020    let arch = hooks.arch_tag();
1021    let want_candidates = hooks.config.mode.wants_candidates();
1022
1023    for (&id, set) in alternatives {
1024        let Some(winner) = set.winner() else {
1025            continue;
1026        };
1027        let node = graph.node(id);
1028        let Some(op_kind) = op_to_op_kind(&node.op) else {
1029            continue;
1030        };
1031        let dtypes = build_lookup_dtypes(graph, node);
1032
1033        // Resolve the winning kernel back to its binding entry to read its
1034        // registration-time `is_generic` bit + FKC revision (the winning ENTRY
1035        // is in hand here — the finalize gate guarantees distinct fn-pointers
1036        // per key, so the pointer match is unambiguous).
1037        let winner_ptr = winner.kernel as *const () as usize;
1038        let winner_entry = bindings_table
1039            .lookup_alternatives(op_kind, &dtypes, winner.backend)
1040            .iter()
1041            .find(|e| e.kernel as *const () as usize == winner_ptr)
1042            .copied();
1043        let is_generic = winner_entry.is_some_and(|e| e.is_generic);
1044        let winner_revision = winner_entry.map_or(0, |e| e.kernel_revision_hash);
1045
1046        // The demand descriptor for the LIVE operands (shared by the structure
1047        // key + the miss detector). Baracuda's `structure_key` keys on operands
1048        // in inputs-THEN-OUTPUT order (its `OperandDesc` convention / reply), so
1049        // the node's own output operand is folded in after the inputs — derived
1050        // from the node's output layout + dtype exactly as the inputs are.
1051        let mut operands: Vec<FdxOperandDesc> = node
1052            .inputs
1053            .iter()
1054            .map(|&input_id| {
1055                FdxOperandDesc::from_layout(&graph.layout(input_id), graph.node(input_id).dtype)
1056            })
1057            .collect();
1058        operands.push(FdxOperandDesc::from_layout(&graph.layout(id), node.dtype));
1059        let op_class = format!("{op_kind:?}");
1060
1061        // Union row 172: `Op::MatMul` declares its M/N/K/batch roles, so Fuel's
1062        // own `sk8` derivation runs here, the first production caller of
1063        // `derive_structure_key_token`. Recorded in a separate ledger; the
1064        // wire `structure_key` below stays Baracuda's token. A node that is not
1065        // a plain matmul, a non-CUDA arch, or a decline records nothing.
1066        if matches!(node.op, fuel_graph::Op::MatMul)
1067            && let [a, b, out] = operands.as_slice()
1068            && let Some(target) = arch.strip_prefix("sm_").map(|cc| format!("cuda:sm{cc}"))
1069            && let Ok(Some(token)) =
1070                crate::telemetry::contraction_facts::matmul_structure_key(a, b, out, &target)
1071            && let Ok(mut sink) = hooks.sink.lock()
1072        {
1073            sink.record_derived_contraction_key(token);
1074        }
1075
1076        // The structure key for the LIVE operands (Fuel CALLS the provider,
1077        // never derives). `None` when the callable is unlinked (the v1
1078        // NullProvider) — the record then omits the key, and no miss forms.
1079        let structure_key = hooks.provider.structure_key(&op_class, &operands, &arch);
1080
1081        // The chosen (winner) `ImplId`.
1082        let chosen = ImplId {
1083            backend: winner.backend,
1084            op: op_kind,
1085            dtypes: dtypes.to_vec(),
1086            kernel_source: winner.kernel_source.to_string(),
1087            kernel_revision_hash: winner_revision,
1088        };
1089
1090        // `candidates[]` — Detailed mode only; each admitted alternative's own
1091        // Judge latency (Coarse leaves it empty per the documented semantics).
1092        let candidates = if want_candidates {
1093            build_candidates(set, op_kind, &dtypes, bindings_table, options.judge)
1094        } else {
1095            Vec::new()
1096        };
1097
1098        // Emit the dispatch record for this cell (every planned cell).
1099        let dispatch = DispatchRecord {
1100            schema: TELEMETRY_SCHEMA_VERSION,
1101            structure_key,
1102            chosen: chosen.clone(),
1103            candidates,
1104            count: 1,
1105            hw: hooks.hw.clone(),
1106        };
1107        if let Ok(mut sink) = hooks.sink.lock() {
1108            sink.record_dispatch(dispatch);
1109        }
1110
1111        // Structural miss — only when the winner is the FKC generic fallback.
1112        // Reuse the shared emission core (single source of truth for the
1113        // never-fabricate rule); `fallback` is the generic winner's `ImplId`.
1114        if let Some(miss) = detect_miss_precomputed(
1115            is_generic,
1116            chosen,
1117            &op_class,
1118            &operands,
1119            &arch,
1120            hooks.provider,
1121            hooks.hw.clone(),
1122        ) {
1123            // Never break dispatch: a poisoned sink lock is swallowed to a
1124            // no-op (best-effort telemetry). `record_miss` itself cannot fail.
1125            if let Ok(mut sink) = hooks.sink.lock() {
1126                sink.record_miss(miss);
1127            }
1128        }
1129    }
1130}
1131
1132/// Build the `candidates[]` for a dispatch record: one
1133/// [`crate::telemetry::Candidate`] per admitted alternative in `set`, each
1134/// carrying its OWN measured latency read from the plan-time Judge oracle (the
1135/// SAME `measured_latency_ns` lookup the ranker/cost composer uses, keyed by the
1136/// decision-point context the planner stamped). `None` = unmeasured cell — never
1137/// a fabricated `0`; the static estimate stood. Each candidate's `ImplId`
1138/// resolves its FKC revision back through the binding table by fn-pointer
1139/// identity (0 = untracked).
1140#[cfg(feature = "telemetry")]
1141fn build_candidates(
1142    set: &AlternativeSet,
1143    op_kind: OpKind,
1144    dtypes: &[DType],
1145    bindings_table: &KernelBindingTable,
1146    judge: Option<&dyn JudgeOracle>,
1147) -> Vec<crate::telemetry::Candidate> {
1148    use crate::telemetry::{Candidate as TeleCandidate, ImplId};
1149
1150    // The decision-point identity the planner stamped (op, principal dtype,
1151    // size class) — the exact Judge key axes. Absent ⇒ no measured latencies.
1152    let ctx = set.context();
1153    set.alternatives()
1154        .iter()
1155        .map(|cand| {
1156            let ptr = cand.kernel as *const () as usize;
1157            let revision = bindings_table
1158                .lookup_alternatives(op_kind, dtypes, cand.backend)
1159                .iter()
1160                .find(|e| e.kernel as *const () as usize == ptr)
1161                .map_or(0, |e| e.kernel_revision_hash);
1162            let impl_id = ImplId {
1163                backend: cand.backend,
1164                op: op_kind,
1165                dtypes: dtypes.to_vec(),
1166                kernel_source: cand.kernel_source.to_string(),
1167                kernel_revision_hash: revision,
1168            };
1169            let latency_ns = match (judge, ctx) {
1170                (Some(j), Some(ctx)) => j.measured_latency_ns(
1171                    ctx.op,
1172                    ctx.principal_dtype,
1173                    ctx.size_class,
1174                    cand.backend,
1175                    cand.kernel_source,
1176                    // Same `revision` the `ImplId` above is keyed by (one
1177                    // binding, two uses) — NOT a literal 0, which would query
1178                    // the untracked cell and collapse variant siblings, the
1179                    // exact regression per-variant `kernel_revision_hash` keys
1180                    // the oracle to prevent.
1181                    revision,
1182                ),
1183                _ => None,
1184            };
1185            TeleCandidate {
1186                impl_id,
1187                latency_ns,
1188            }
1189        })
1190        .collect()
1191}
1192
1193/// Does this op receive an `AlternativeSet` entry from
1194/// [`compile_plan`]? The single source of truth for the plan-entry
1195/// gate (used by `build_node_draft` and `PlanOptions::reuse_plan`
1196/// incremental extension): `true` exactly when `op_to_op_kind` maps
1197/// the op AND it is not a residency-determined transfer (`Op::Copy` /
1198/// `Op::Move`, whose kernel backend the executor resolves from the
1199/// bridge-maintained source-backend stamp).
1200pub fn node_needs_plan_entry(op: &fuel_graph::Op) -> bool {
1201    op_to_op_kind(op).is_some()
1202        && !matches!(
1203            op,
1204            fuel_graph::Op::Copy { .. } | fuel_graph::Op::Move { .. }
1205        )
1206}
1207
1208/// Residency-inheriting pass-throughs: view ops, `Reshape`,
1209/// `Contiguize` produce no new residency — their bytes follow their
1210/// data input.
1211fn is_passthrough(node: &fuel_graph::Node) -> bool {
1212    node.op.is_view_op()
1213        || matches!(
1214            node.op,
1215            fuel_graph::Op::Reshape(_) | fuel_graph::Op::Contiguize
1216        )
1217}
1218
1219/// Distinct candidate devices in first-seen order (the enumerator
1220/// lists the decision device first, so index 0 is the locality
1221/// anchor and DP argmin ties break toward it).
1222fn distinct_devices(set: &AlternativeSet) -> SmallVec<[DeviceLocation; 4]> {
1223    let mut out: SmallVec<[DeviceLocation; 4]> = SmallVec::new();
1224    for c in set.alternatives() {
1225        if !out.contains(&c.device) {
1226            out.push(c.device);
1227        }
1228    }
1229    out
1230}
1231
1232/// Output bytes of a node — element count × dtype size, saturating.
1233/// Sub-byte dtypes price latency-only (same bounded undercount as
1234/// [`priced_inputs_for`]).
1235fn node_bytes(graph: &Graph, id: NodeId) -> u64 {
1236    let n = graph.node(id);
1237    (n.shape.elem_count() as u64).saturating_mul(n.dtype.size_in_bytes() as u64)
1238}
1239
1240/// Stage 3: open a DP row for a relaxed multi-device node. Inputs
1241/// partition into known-fixed residencies (priced per device into
1242/// the row's base cost), open-row chain edges (extended via the DP
1243/// recurrence), and unknown edges (no term — conservative).
1244fn open_dp_row(
1245    dp: &mut PlacementDp,
1246    graph: &Graph,
1247    id: NodeId,
1248    node: &fuel_graph::Node,
1249    set: &AlternativeSet,
1250    devices: &[DeviceLocation],
1251    residency: &HashMap<NodeId, DeviceLocation>,
1252    est: &dyn TransferEstimator,
1253    caps_for: Option<&CapabilitiesLookup<'_>>,
1254) {
1255    // Per-device node cost: the cheapest same-device candidate's
1256    // composite (static + Judge-refined) figure. Each candidate's FLOP
1257    // / byte pressure is converted to nanoseconds by ITS backend's
1258    // throughput — the authoritative registered `BackendCapabilities`
1259    // figure when caps are in hand, else the per-backend prior. This is
1260    // what makes the cross-device placement DP honest: a GPU candidate
1261    // is priced on GPU throughput, so it can out-price a CPU candidate
1262    // for large parallel work despite paying an inbound transfer.
1263    let rates_for = |backend: BackendId| -> (f64, f64) {
1264        caps_for
1265            .and_then(|f| f(backend))
1266            .map(|caps| {
1267                (
1268                    caps.compute_throughput_flops_per_ns,
1269                    caps.mem_bandwidth_bytes_per_ns,
1270                )
1271            })
1272            .unwrap_or_else(|| default_backend_rates(backend))
1273    };
1274    let device_costs: Vec<(DeviceLocation, u64)> = devices
1275        .iter()
1276        .map(|&d| {
1277            let min = set
1278                .alternatives()
1279                .iter()
1280                .filter(|c| c.device == d)
1281                .map(|c| {
1282                    let (cr, bw) = rates_for(c.backend);
1283                    composite_ns(&c.static_cost, cr, bw)
1284                })
1285                .min()
1286                .unwrap_or(u64::MAX);
1287            (d, min)
1288        })
1289        .collect();
1290
1291    let mut fixed: Vec<(DeviceLocation, u64)> = Vec::new();
1292    let mut chains: Vec<ChainInput> = Vec::new();
1293    for &input in &node.inputs {
1294        let bytes = node_bytes(graph, input);
1295        if let Some(&src) = residency.get(&input) {
1296            fixed.push((src, bytes));
1297            continue;
1298        }
1299        let root = dp.resolve(input);
1300        if dp.is_open(root) {
1301            match chains.iter_mut().find(|ci| ci.producer == root) {
1302                Some(ci) => ci.edge_bytes.push(bytes),
1303                None => chains.push(ChainInput {
1304                    producer: root,
1305                    edge_bytes: smallvec::smallvec![bytes],
1306                }),
1307            }
1308        } else if let Some(dev) = dp.committed_device(root) {
1309            // Producer row already closed toward an earlier consumer
1310            // — its device is fixed now.
1311            fixed.push((dev, bytes));
1312        }
1313        // else: chained-but-uncommitted or genuinely unknown — no
1314        // term (documented fan-out debt).
1315    }
1316    dp.push_row(id, &device_costs, &fixed, &chains, est);
1317}
1318
1319/// Close any open producer rows feeding `node` toward `toward` —
1320/// the consumer's (already-known) device. Commitments merge into
1321/// the walk's residency view so the consumer's own pricing and all
1322/// later consumers see them; direct inputs that alias to a
1323/// committed row inherit its device (pass-through residency).
1324fn close_open_inputs(
1325    dp: &mut PlacementDp,
1326    graph: &Graph,
1327    node: &fuel_graph::Node,
1328    toward: DeviceLocation,
1329    est: &dyn TransferEstimator,
1330    residency: &mut HashMap<NodeId, DeviceLocation>,
1331) {
1332    for &input in &node.inputs {
1333        if residency.contains_key(&input) {
1334            continue;
1335        }
1336        let root = dp.resolve(input);
1337        if dp.is_open(root) {
1338            let commits = dp.close_toward(root, toward, &[node_bytes(graph, input)], est);
1339            for (n, d) in commits {
1340                residency.insert(n, d);
1341            }
1342        }
1343        if !residency.contains_key(&input)
1344            && let Some(d) = dp.committed_device(root)
1345        {
1346            residency.insert(input, d);
1347        }
1348    }
1349}
1350
1351/// Stage-2 residency, priorities 1–3: rules that resolve a node's
1352/// placement WITHOUT the plan — residency-declaring ops
1353/// (`Op::Copy`/`Move`/`Alloc` carry their output's location in the
1354/// op variant), explicit `Graph::placement` (scheduler
1355/// assignments), and the caller's already-resident input lookup
1356/// (consts + persistent cache slots via
1357/// [`PlanOptions::input_residency`]). Mirrors the top of the
1358/// bridge's `effective_placements` priority list.
1359fn early_residency(
1360    graph: &Graph,
1361    options: &PlanOptions<'_>,
1362    id: NodeId,
1363    node: &fuel_graph::Node,
1364) -> Option<DeviceLocation> {
1365    match node.op {
1366        fuel_graph::Op::Copy { target }
1367        | fuel_graph::Op::Move { target }
1368        | fuel_graph::Op::Alloc { target } => return Some(target),
1369        _ => {}
1370    }
1371    if let Some(loc) = graph.placement(id) {
1372        return Some(loc);
1373    }
1374    options.input_residency.and_then(|f| f(id))
1375}
1376
1377/// Collect `(resident device, byte size)` for every input of `node`
1378/// whose residency is known. Bytes = element count × dtype size.
1379/// Sub-byte dtypes (`size_in_bytes() == 0`) price latency-only — a
1380/// bounded undercount, acceptable until a packed-bit byte-size
1381/// helper exists (no such dtype crosses devices today).
1382fn priced_inputs_for(
1383    graph: &Graph,
1384    node: &fuel_graph::Node,
1385    residency: &HashMap<NodeId, DeviceLocation>,
1386) -> Vec<(DeviceLocation, u64)> {
1387    node.inputs
1388        .iter()
1389        .filter_map(|&input_id| {
1390            let src = residency.get(&input_id).copied()?;
1391            let in_node = graph.node(input_id);
1392            let bytes = (in_node.shape.elem_count() as u64)
1393                .saturating_mul(in_node.dtype.size_in_bytes() as u64);
1394            Some((src, bytes))
1395        })
1396        .collect()
1397}
1398
1399/// The residency-independent half of one node's plan: the
1400/// enumerated + filtered + statically-costed candidate set, plus
1401/// the flags the finalize step (greedy or DP) needs. Produced by
1402/// [`build_node_draft`]; consumed by [`finalize_node_greedy`] or
1403/// deferred into the Stage-3 DP.
1404struct NodeDraft {
1405    set: AlternativeSet,
1406    /// Stage-2 priced-admission regime (estimator + fallback +
1407    /// non-destructive + no explicit placement).
1408    relaxed: bool,
1409    /// Set was produced by the legacy missing-impl fallback —
1410    /// freezes to its single ranked winner.
1411    from_fallback: bool,
1412    /// Static costs (Layer 1 + Judge Layer 2) were computed —
1413    /// gates transfer pricing + ranking in the finalize step,
1414    /// mirroring the `populate_costs && capabilities_for` gate.
1415    costed: bool,
1416    op_kind: OpKind,
1417    dtypes: Vec<DType>,
1418    diag_backend: BackendId,
1419}
1420
1421/// `compile_plan`'s per-node enumeration phase: enumeration +
1422/// filter chain + static cost composition for one kernel-bearing
1423/// node — everything that does NOT depend on producer residency.
1424/// Returns `Ok(None)` for nodes that get no plan entry (view ops,
1425/// `Op::Const`, residency-determined `Op::Copy`/`Op::Move`, ops
1426/// without a dispatch OpKind).
1427fn build_node_draft(
1428    graph: &Graph,
1429    id: NodeId,
1430    node: &fuel_graph::Node,
1431    bindings_table: &KernelBindingTable,
1432    options: &PlanOptions<'_>,
1433) -> Result<Option<NodeDraft>> {
1434    // Gate shared with the plan store's coverage check
1435    // ([`node_needs_plan_entry`]): no OpKind mapping → no entry;
1436    // Op::Copy / Op::Move are residency-determined, not picker
1437    // decisions — their kernel runs on the backend that owns the
1438    // SOURCE bytes (`copy_from_cpu_wrapper` for H2D, the source
1439    // backend's download wrapper for D2H). Enumerating them
1440    // against a single decision device would key the lookup at
1441    // the wrong end of the transfer for placement-carrying
1442    // copies (the consumer device, where the H2D copy's kernel
1443    // does NOT run). The executor's legacy `compile_node` path
1444    // resolves these via the source-backend `target_backend`
1445    // stamp maintained by the bridge's copy-insertion passes.
1446    // Picker-arc step 4a; Op::Move added with the executor's
1447    // Move arm (Op::Move maps to OpKind::Copy — same kernel,
1448    // destructive release is realize-loop bookkeeping).
1449    if !node_needs_plan_entry(&node.op) {
1450        return Ok(None);
1451    }
1452    let Some(op_kind) = op_to_op_kind(&node.op) else {
1453        // Unreachable given the gate above; keep the typed shape.
1454        return Ok(None);
1455    };
1456
1457    // Decision-device resolution (step 4a): explicit per-node
1458    // placement (scheduler assignments) → the realize call's
1459    // pinned device → the legacy stamped-backend default.
1460    let explicit_backend = graph.target_backend(id);
1461    let target_device = decision_device_for(graph, options, id).ok_or_else(|| {
1462        Error::Msg(format!(
1463            "compile_plan: node {:?} ({:?}) has no device context — \
1464                 set PlanOptions::pinned_device, a graph placement, or \
1465                 the node's target_backend",
1466            id, node.op,
1467        ))
1468        .bt()
1469    })?;
1470    // Diagnostic backend for error reporting; also the legacy
1471    // single-backend placement when no topology enumerator is
1472    // configured.
1473    let diag_backend = explicit_backend.unwrap_or_else(|| backend_for_device(target_device));
1474    let dtypes = build_lookup_dtypes(graph, node);
1475
1476    // Build the placement list: cross-backend if a topology
1477    // enumerator is configured, otherwise single-backend
1478    // legacy mode.
1479    let placements: Vec<(BackendId, DeviceLocation)> = match options.placements_for_device {
1480        Some(f) => f(target_device)
1481            .into_iter()
1482            .map(|backend| (backend, target_device))
1483            .collect(),
1484        None => vec![(diag_backend, target_device)],
1485    };
1486
1487    let op_params = candidate_default_op_params(graph, node);
1488
1489    // Stage-2 admission relax: when inbound-transfer pricing is
1490    // active, off-device candidates ALWAYS enumerate — priced;
1491    // locality emerges from the numbers, not from the legacy
1492    // missing-impl-only gate. Three hard exclusions keep the
1493    // relax sound:
1494    //
1495    // - **Explicit `Graph::placement` is a hard pin.** A per-node
1496    //   placement is a scheduler / profiling decision (the Judge
1497    //   measuring a specific backend pins its profile graphs this
1498    //   way) — the planner must not silently move it to a
1499    //   "cheaper" sibling device. The realize-call `pinned_device`
1500    //   is a soft default the planner may improve on.
1501    // - **Destructive ops never move** off the device that owns
1502    //   their mutation target.
1503    // - **Pricing must actually be active** (estimator +
1504    //   populate_costs + capabilities): an unpriced rank would
1505    //   move ops on kernel cost alone, regressing locality.
1506    let pricing_active = options.transfer_estimator.is_some()
1507        && options.populate_costs
1508        && options.capabilities_for.is_some();
1509    let fallback_allowed =
1510        node.op.destructive_input().is_none() && options.fallback_placements_for.is_some();
1511    let relaxed = options.allow_cost_placement
1512        && pricing_active
1513        && fallback_allowed
1514        && graph.placement(id).is_none();
1515
1516    let mut set;
1517    let mut from_fallback = false;
1518    if relaxed {
1519        // Merged enumeration: decision-device placements FIRST so
1520        // the rank's stable sort breaks zero-signal ties toward
1521        // locality, then every off-device placement — all priced
1522        // by the same cost + transfer composition.
1523        let mut merged = placements.clone();
1524        if let Some(fallback) = options.fallback_placements_for {
1525            merged.extend(fallback(target_device));
1526        }
1527        set = enumerate_candidates(op_kind, &dtypes, &merged, &op_params, bindings_table);
1528    } else {
1529        set = enumerate_candidates(op_kind, &dtypes, &placements, &op_params, bindings_table);
1530
1531        // Picker-arc step 4b (legacy, unpriced path): when the
1532        // decision device has NO implementation for this
1533        // (op, dtypes), admit off-device candidates from the
1534        // fallback enumerator. The missing-impl op becomes a
1535        // plan-time picker decision (the bridge stitches residency
1536        // via Op::Copy insertion around the off-device winner)
1537        // instead of a realize-time error.
1538        if set.is_empty()
1539            && fallback_allowed
1540            && let Some(fallback) = options.fallback_placements_for
1541        {
1542            let fb_placements = fallback(target_device);
1543            if !fb_placements.is_empty() {
1544                set = enumerate_candidates(
1545                    op_kind,
1546                    &dtypes,
1547                    &fb_placements,
1548                    &op_params,
1549                    bindings_table,
1550                );
1551                from_fallback = !set.is_empty();
1552            }
1553        }
1554    }
1555
1556    // Fail-fast: if enumeration found nothing (on the decision
1557    // device AND via fallback), surface the missing-binding
1558    // error before filters can also empty the set (which would
1559    // produce a less-specific FilterRejected).
1560    if set.is_empty() {
1561        return Err(missing_binding_error(
1562            bindings_table,
1563            op_kind,
1564            &dtypes,
1565            diag_backend,
1566        ));
1567    }
1568
1569    // Apply the default filter chain.
1570    let input_layouts: Vec<fuel_ir::Layout> = node
1571        .inputs
1572        .iter()
1573        .map(|&input_id| graph.layout(input_id))
1574        .collect();
1575    let ctx = FilterContext::new(op_kind, &dtypes, &input_layouts);
1576    let chain = default_chain(options.precision_requirement);
1577    if let Err(err) = apply_filter_chain(&mut set, &chain, &ctx) {
1578        // Stage-2 fix of the picker-4b verifier minor: a decision
1579        // device whose registrations all FAIL the hard filter
1580        // chain falls back exactly like an empty enumeration —
1581        // the pin can't deliver an admissible kernel either way.
1582        // Only meaningful when the rejected set couldn't already
1583        // contain off-device candidates: relaxed merged sets and
1584        // fallback sets rejected here are genuine global
1585        // rejections and propagate.
1586        if relaxed || from_fallback || !fallback_allowed {
1587            return Err(err);
1588        }
1589        let Some(fallback) = options.fallback_placements_for else {
1590            return Err(err);
1591        };
1592        let fb_placements = fallback(target_device);
1593        if fb_placements.is_empty() {
1594            return Err(err);
1595        }
1596        let mut fb_set =
1597            enumerate_candidates(op_kind, &dtypes, &fb_placements, &op_params, bindings_table);
1598        if fb_set.is_empty() {
1599            return Err(err);
1600        }
1601        // The fallback set faces the same chain — a hard reject
1602        // here is the surfaceable error (nowhere admissible).
1603        apply_filter_chain(&mut fb_set, &chain, &ctx)?;
1604        set = fb_set;
1605        from_fallback = true;
1606    }
1607
1608    // Stamp the decision-point identity so dispatch-time
1609    // selectors (Picker 2) can re-query the Judge per candidate.
1610    // The derivation mirrors `compute_static_costs`'s Layer-2
1611    // lookup key exactly: principal dtype = first lookup dtype,
1612    // size class = `SizeClass::for_op` over the input operand shapes
1613    // (the shared producer/consumer derivation — matmul keys on its
1614    // `(m,n,k)` aspect, every other op on the first operand's element
1615    // count; nullary ops → `SizeClass(0)`). Runs after the
1616    // filter/fallback resolution so a filter-rejection fallback set is
1617    // stamped too.
1618    if let Some(&principal_dtype) = dtypes.first() {
1619        let input_shapes: Vec<Shape> = node
1620            .inputs
1621            .iter()
1622            .map(|&input_id| graph.node(input_id).shape.clone())
1623            .collect();
1624        let size_class = SizeClass::for_op(op_kind, &input_shapes);
1625        set.set_context(DecisionContext {
1626            op: op_kind,
1627            principal_dtype,
1628            size_class,
1629        });
1630    }
1631
1632    // Static cost composition (optional — tests may skip). Layer-1
1633    // via the binding-table CostFns + Layer-2 Judge refinement;
1634    // both residency-independent, so they belong to the draft.
1635    let costed = if options.populate_costs {
1636        if let Some(caps_for) = options.capabilities_for {
1637            let input_shapes: Vec<Shape> = node
1638                .inputs
1639                .iter()
1640                .map(|&input_id| graph.node(input_id).shape.clone())
1641                .collect();
1642            compute_static_costs(
1643                &mut set,
1644                op_kind,
1645                &dtypes,
1646                &input_shapes,
1647                bindings_table,
1648                caps_for,
1649                options.judge,
1650            );
1651            true
1652        } else {
1653            false
1654        }
1655    } else {
1656        false
1657    };
1658
1659    Ok(Some(NodeDraft {
1660        set,
1661        relaxed,
1662        from_fallback,
1663        costed,
1664        op_kind,
1665        dtypes,
1666        diag_backend,
1667    }))
1668}
1669
1670/// `compile_plan`'s per-node commit phase, Stage-2 greedy regime:
1671/// inbound-transfer pricing against the committed producer
1672/// residencies, rank, relaxed winner-device prune, truncation, and
1673/// the fallback freeze. The Stage-3 DP path replaces this for
1674/// deferred rows (pricing + prune happen after the backtrack
1675/// instead).
1676fn finalize_node_greedy(
1677    graph: &Graph,
1678    node: &fuel_graph::Node,
1679    draft: NodeDraft,
1680    bindings_table: &KernelBindingTable,
1681    options: &PlanOptions<'_>,
1682    residency: &HashMap<NodeId, DeviceLocation>,
1683    off_device_out: &mut Option<AlternativeSet>,
1684) -> Result<AlternativeSet> {
1685    let NodeDraft {
1686        mut set,
1687        relaxed,
1688        from_fallback,
1689        costed,
1690        op_kind,
1691        dtypes,
1692        diag_backend,
1693    } = draft;
1694
1695    if costed {
1696        // Stage 2: price the transfers each candidate's placement
1697        // would induce from its inputs' committed residencies. Runs
1698        // AFTER the Layer-2 Judge refinement (which REPLACES the
1699        // kernel-time estimate) so the transfer term survives; the
1700        // rank adds the two.
1701        if let Some(estimator) = options.transfer_estimator {
1702            let inputs = priced_inputs_for(graph, node, residency);
1703            apply_inbound_transfer_costs(&mut set, &inputs, estimator);
1704        }
1705        set.rank_by_composite_cost();
1706    }
1707
1708    // Stage 2: after the priced rank, prune the relaxed set to the
1709    // winner's device. The bridge's residency stitch (Op::Copy
1710    // insertion) is a graph rewrite computed from the static
1711    // winner; cross-device siblings left in the set would let a
1712    // dispatch-time selector pick a candidate whose inputs were
1713    // never copied to its device. Same-device siblings stay — the
1714    // stitch covers all of them, and the transfer term is uniform
1715    // across one device so the selector's relative ranking is
1716    // unaffected. Pruned BEFORE truncation so same-device
1717    // alternatives fill the top-N.
1718    if relaxed && let Some(winner_device) = set.winner().map(|c| c.device) {
1719        let keep: Vec<usize> = set
1720            .alternatives()
1721            .iter()
1722            .enumerate()
1723            .filter_map(|(i, c)| (c.device == winner_device).then_some(i))
1724            .collect();
1725        if keep.len() < set.len() {
1726            // Keep the pruned-off candidates (see `ExecutionPlan::off_device`).
1727            let off_keep: Vec<usize> = (0..set.len()).filter(|i| !keep.contains(i)).collect();
1728            let mut off = set.clone();
1729            off.retain_indices(&off_keep);
1730            off.retain_per_device_frontier(KEEP_PER_DEVICE);
1731            *off_device_out = Some(off);
1732            set.retain_indices(&keep);
1733        }
1734    }
1735
1736    // PR-B2: retire the fixed top-N. Retain the per-ending-device
1737    // Pareto frontier (crowding-capped at KEEP_PER_DEVICE) instead of
1738    // a global top-N. The arm-0 winner — the realize pick — stays at
1739    // index 0. In the `relaxed` path the set was just pruned to the
1740    // winner's single device, so this reduces to that device's Pareto
1741    // front; in the legacy multi-backend-at-one-device path it keeps
1742    // the non-dominated kernels at the decision device.
1743    set.retain_per_device_frontier(KEEP_PER_DEVICE);
1744
1745    // Step 4b: off-device fallback sets freeze to their single
1746    // ranked winner. The bridge's residency stitch (Op::Copy
1747    // insertion) is a graph rewrite computed from the static
1748    // winner; leaving siblings on OTHER devices in the set
1749    // would let a dispatch-time selector pick a candidate whose
1750    // inputs were never copied to its device.
1751    if from_fallback && set.len() > 1 {
1752        set.retain_indices(&[0]);
1753    }
1754
1755    // After retention an empty set is the surfaceable error
1756    // (the filter chain or rank dropped everything). The chain
1757    // would have raised FilterRejected on hard-empty, so this
1758    // path is only reachable when populate_costs + ranking
1759    // pruned a structurally-empty set, which shouldn't happen
1760    // in practice — defensive only.
1761    if set.is_empty() {
1762        return Err(missing_binding_error(
1763            bindings_table,
1764            op_kind,
1765            &dtypes,
1766            diag_backend,
1767        ));
1768    }
1769
1770    Ok(set)
1771}
1772
1773/// Build an `Error::NoBackendForOp` diagnostic for a decision
1774/// point with no registered alternative. Same shape as
1775/// [`crate::kernel::KernelBindingTable::lookup_with_caps`]'s error
1776/// branch so callers see consistent output regardless of which
1777/// path surfaced the miss.
1778fn missing_binding_error(
1779    table: &KernelBindingTable,
1780    op: OpKind,
1781    dtypes: &[DType],
1782    backend: BackendId,
1783) -> Error {
1784    // The queried `backend` isn't a NoBackendForOp field; the diagnostic lists
1785    // the full coverage across all backends (the "what exists" context) so a
1786    // reader can see which `(op, dtypes)` ARE registered. Formerly this returned
1787    // empty lists, falsely reading as "no backend registered".
1788    let _ = backend;
1789    let (available_backends, supported_combinations) = table.coverage_diagnostic();
1790    Error::NoBackendForOp {
1791        op,
1792        dtypes: dtypes.to_vec(),
1793        available_backends,
1794        supported_combinations,
1795    }
1796    .bt()
1797}
1798
1799/// Helper that produces the `OpParams` to attach to enumerated
1800/// candidates for one graph node. Phase 1.5 ships with the
1801/// placeholder `OpParams::None` for every node — the live
1802/// op-params shape derivation lives in `pipelined::op_to_op_params`
1803/// but is currently mid-refactor for other reasons. Phase 4's
1804/// executor integration replaces this with the live derivation so
1805/// the planner's candidate set matches what dispatch sees.
1806fn candidate_default_op_params(
1807    _graph: &Graph,
1808    _node: &fuel_graph::Node,
1809) -> crate::kernel::OpParams {
1810    crate::kernel::OpParams::None
1811}
1812
1813#[cfg(test)]
1814mod tests {
1815    use super::*;
1816    use crate::fused::PrecisionGuarantee;
1817    use crate::kernel::{KernelCaps, OpParams, unknown_cost};
1818    use fuel_graph::{Node, Op, topo_order};
1819    use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
1820    use fuel_ir::{DType, Layout, Result as FuelResult, Shape, StrideVec};
1821    use fuel_memory::Storage;
1822    use smallvec::smallvec;
1823    use std::collections::HashSet;
1824    use std::sync::{Arc, RwLock};
1825
1826    fn noop_kernel(
1827        _i: &[Arc<RwLock<Storage>>],
1828        _o: &mut [Arc<RwLock<Storage>>],
1829        _l: &[Layout],
1830        _p: &OpParams,
1831    ) -> FuelResult<()> {
1832        Ok(())
1833    }
1834
1835    fn noop_kernel_b(
1836        _i: &[Arc<RwLock<Storage>>],
1837        _o: &mut [Arc<RwLock<Storage>>],
1838        _l: &[Layout],
1839        _p: &OpParams,
1840    ) -> FuelResult<()> {
1841        Ok(())
1842    }
1843
1844    fn noop_kernel_c(
1845        _i: &[Arc<RwLock<Storage>>],
1846        _o: &mut [Arc<RwLock<Storage>>],
1847        _l: &[Layout],
1848        _p: &OpParams,
1849    ) -> FuelResult<()> {
1850        Ok(())
1851    }
1852
1853    fn register_add_f32(
1854        table: &mut KernelBindingTable,
1855        backend: BackendId,
1856        kernel: crate::kernel::KernelRef,
1857        precision: PrecisionGuarantee,
1858    ) {
1859        table.register_full(
1860            OpKind::AddElementwise,
1861            &[DType::F32, DType::F32, DType::F32],
1862            backend,
1863            kernel,
1864            KernelCaps::empty(),
1865            precision,
1866            unknown_cost,
1867        );
1868    }
1869
1870    fn build_add_graph() -> (Graph, NodeId) {
1871        let mut g = Graph::new();
1872        let lhs = g.push(Node {
1873            op: Op::Const,
1874            inputs: vec![],
1875            shape: Shape::from_dims(&[3]),
1876            dtype: DType::F32,
1877        });
1878        let rhs = g.push(Node {
1879            op: Op::Const,
1880            inputs: vec![],
1881            shape: Shape::from_dims(&[3]),
1882            dtype: DType::F32,
1883        });
1884        let add = g.push(Node {
1885            op: Op::Add,
1886            inputs: vec![lhs, rhs],
1887            shape: Shape::from_dims(&[3]),
1888            dtype: DType::F32,
1889        });
1890        g.set_target_backend(add, BackendId::Cpu);
1891        (g, add)
1892    }
1893
1894    fn cpu_caps() -> BackendCapabilities {
1895        BackendCapabilities {
1896            backend_id: BackendId::Cpu,
1897            device_location: DeviceLocation::Cpu,
1898            op_dtype_support: HashSet::new(),
1899            required_alignment: 64,
1900            access_granularity_bits: 8,
1901            transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
1902            storage_substrate: SubstrateClass::HostBytes,
1903            compute_throughput_flops_per_ns: 1.0,
1904            mem_bandwidth_bytes_per_ns: 4.0,
1905        }
1906    }
1907
1908    #[test]
1909    fn empty_plan_has_no_alternatives() {
1910        let p = ExecutionPlan::empty();
1911        assert!(p.order.is_empty());
1912        assert!(p.alternatives.is_empty());
1913        assert!(p.alternatives(NodeId(0)).is_none());
1914    }
1915
1916    #[test]
1917    fn default_device_per_backend_matches_router_convention() {
1918        assert_eq!(default_device_for(BackendId::Cpu), DeviceLocation::Cpu);
1919        assert_eq!(
1920            default_device_for(BackendId::Cuda),
1921            DeviceLocation::Cuda { gpu_id: 0 },
1922        );
1923        assert_eq!(
1924            default_device_for(BackendId::Vulkan),
1925            DeviceLocation::Vulkan { gpu_id: 0 },
1926        );
1927    }
1928
1929    #[test]
1930    fn compile_plan_skips_view_and_const_nodes() {
1931        let mut table = KernelBindingTable::new();
1932        register_add_f32(
1933            &mut table,
1934            BackendId::Cpu,
1935            noop_kernel,
1936            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1937        );
1938
1939        let mut g = Graph::new();
1940        let lhs = g.push(Node {
1941            op: Op::Const,
1942            inputs: vec![],
1943            shape: Shape::from_dims(&[6]),
1944            dtype: DType::F32,
1945        });
1946        let rhs = g.push(Node {
1947            op: Op::Const,
1948            inputs: vec![],
1949            shape: Shape::from_dims(&[6]),
1950            dtype: DType::F32,
1951        });
1952        let add = g.push(Node {
1953            op: Op::Add,
1954            inputs: vec![lhs, rhs],
1955            shape: Shape::from_dims(&[6]),
1956            dtype: DType::F32,
1957        });
1958        let reshape = g.push(Node {
1959            op: Op::Reshape(Shape::from_dims(&[2, 3])),
1960            inputs: vec![add],
1961            shape: Shape::from_dims(&[2, 3]),
1962            dtype: DType::F32,
1963        });
1964        g.set_target_backend(add, BackendId::Cpu);
1965        g.set_target_backend(reshape, BackendId::Cpu);
1966
1967        let order = topo_order(&g, reshape);
1968        let opts = PlanOptions::new().without_cost_population();
1969        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
1970
1971        assert_eq!(plan.order.len(), 4);
1972        assert_eq!(
1973            plan.alternatives.len(),
1974            1,
1975            "only Add carries an alternative set",
1976        );
1977        let alts = plan.alternatives(add).expect("Add alternatives present");
1978        assert_eq!(alts.len(), 1);
1979        assert!(plan.alternatives(lhs).is_none());
1980        assert!(plan.alternatives(rhs).is_none());
1981        assert!(plan.alternatives(reshape).is_none());
1982    }
1983
1984    #[test]
1985    fn compile_plan_fails_fast_on_missing_binding() {
1986        let table = KernelBindingTable::new();
1987        let mut g = Graph::new();
1988        let lhs = g.push(Node {
1989            op: Op::Const,
1990            inputs: vec![],
1991            shape: Shape::from_dims(&[2, 3]),
1992            dtype: DType::F32,
1993        });
1994        let rhs = g.push(Node {
1995            op: Op::Const,
1996            inputs: vec![],
1997            shape: Shape::from_dims(&[3, 2]),
1998            dtype: DType::F32,
1999        });
2000        let mm = g.push(Node {
2001            op: Op::MatMul,
2002            inputs: vec![lhs, rhs],
2003            shape: Shape::from_dims(&[2, 2]),
2004            dtype: DType::F32,
2005        });
2006        g.set_target_backend(mm, BackendId::Cpu);
2007
2008        let order = topo_order(&g, mm);
2009        let opts = PlanOptions::new().without_cost_population();
2010        let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2011        match err {
2012            Error::NoBackendForOp { op, dtypes, .. } => {
2013                assert_eq!(op, OpKind::MatMul);
2014                assert_eq!(dtypes, vec![DType::F32, DType::F32, DType::F32]);
2015            }
2016            other => panic!("expected NoBackendForOp, got {other:?}"),
2017        }
2018    }
2019
2020    /// Regression: a plan-time binding miss reports the REAL registered coverage,
2021    /// not a hardcoded `[]`. Reproduces the observed `llama-lazy` failure — an
2022    /// F32-activation × BF16-weight (mixed-precision) matmul, which the CPU
2023    /// backend had no kernel for then (it served uniform `[T,T,T]` only; since
2024    /// ROADMAP row 34 it serves that key natively, so the test now uses an
2025    /// F64 weight, a key no CPU kernel serves) — against
2026    /// the fully-populated production binding table. Before the fix,
2027    /// `missing_binding_error` returned empty lists, so a mixed-precision gap
2028    /// surfaced as the maximally-misleading "available backends: []" (it cost two
2029    /// people an investigation + a wrong hypothesis). Now it lists Cpu + the
2030    /// uniform matmul combos, so a reader sees `[F32,F32,F32]` present and
2031    /// the mixed key absent and diagnoses it immediately.
2032    #[test]
2033    fn plan_time_miss_reports_real_coverage_not_empty() {
2034        let bindings = crate::dispatch::global_bindings(); // self-seeded, populated
2035        let mut g = Graph::new();
2036        let lhs = g.push(Node {
2037            op: Op::Const,
2038            inputs: vec![],
2039            shape: Shape::from_dims(&[2, 3]),
2040            dtype: DType::F32,
2041        });
2042        // F64 weight → the matmul dtype key becomes the mixed [F32, F64, F32], which no CPU kernel
2043        // serves (the [F32, BF16, F32] / [F32, F16, F32] keys have native kernels since row 34).
2044        let rhs = g.push(Node {
2045            op: Op::Const,
2046            inputs: vec![],
2047            shape: Shape::from_dims(&[3, 2]),
2048            dtype: DType::F64,
2049        });
2050        let mm = g.push(Node {
2051            op: Op::MatMul,
2052            inputs: vec![lhs, rhs],
2053            shape: Shape::from_dims(&[2, 2]),
2054            dtype: DType::F32,
2055        });
2056        g.set_target_backend(mm, BackendId::Cpu);
2057
2058        let order = topo_order(&g, mm);
2059        let opts = PlanOptions::new().without_cost_population();
2060        let err = compile_plan(&g, &order, &bindings, &opts).unwrap_err();
2061        match err {
2062            Error::NoBackendForOp {
2063                op,
2064                dtypes,
2065                available_backends,
2066                supported_combinations,
2067            } => {
2068                assert_eq!(op, OpKind::MatMul);
2069                assert_eq!(
2070                    dtypes,
2071                    vec![DType::F32, DType::F64, DType::F32],
2072                    "the mixed-precision key (F32 activation, F64 weight)",
2073                );
2074                // The fix: the diagnostic is TRUTHFUL, not a hardcoded empty stub.
2075                assert!(
2076                    available_backends.contains(&BackendId::Cpu),
2077                    "a populated table must report Cpu, never []: {available_backends:?}",
2078                );
2079                assert!(
2080                    supported_combinations
2081                        .iter()
2082                        .any(|(b, o, d)| *b == BackendId::Cpu
2083                            && *o == OpKind::MatMul
2084                            && *d == vec![DType::F32, DType::F32, DType::F32]),
2085                    "must show uniform F32 matmul IS registered (so the mixed gap is visible): \
2086                     {supported_combinations:?}",
2087                );
2088            }
2089            other => panic!("expected NoBackendForOp, got {other:?}"),
2090        }
2091    }
2092
2093    #[test]
2094    fn compile_plan_legacy_single_backend_uses_target_backend() {
2095        let mut table = KernelBindingTable::new();
2096        register_add_f32(
2097            &mut table,
2098            BackendId::Cpu,
2099            noop_kernel,
2100            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2101        );
2102        // Even with an AOCL alternative registered, the legacy mode
2103        // (placements_for_device = None) only uses the node's
2104        // target_backend (Cpu).
2105        register_add_f32(
2106            &mut table,
2107            BackendId::Cuda,
2108            noop_kernel_b,
2109            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2110        );
2111        let (g, add_id) = build_add_graph();
2112        let order = topo_order(&g, add_id);
2113        let opts = PlanOptions::new().without_cost_population();
2114        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2115        let alts = plan.alternatives(add_id).unwrap();
2116        assert_eq!(alts.len(), 1, "legacy mode → single backend → single alt");
2117        assert_eq!(alts.winner().unwrap().backend, BackendId::Cpu);
2118    }
2119
2120    #[test]
2121    fn compile_plan_cross_co_located_via_placements_callback() {
2122        let mut table = KernelBindingTable::new();
2123        register_add_f32(
2124            &mut table,
2125            BackendId::Cpu,
2126            noop_kernel,
2127            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2128        );
2129        register_add_f32(
2130            &mut table,
2131            BackendId::Cuda,
2132            noop_kernel_b,
2133            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2134        );
2135
2136        let (g, add_id) = build_add_graph();
2137        let order = topo_order(&g, add_id);
2138        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2139            if dev == DeviceLocation::Cpu {
2140                vec![BackendId::Cpu, BackendId::Cuda]
2141            } else {
2142                vec![]
2143            }
2144        };
2145        let opts = PlanOptions::new()
2146            .without_cost_population()
2147            .with_placements_for_device(&placements_fn);
2148        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2149        let alts = plan.alternatives(add_id).unwrap();
2150        assert_eq!(
2151            alts.len(),
2152            2,
2153            "cross-co-located mode aggregates Cpu + Aocl alternatives",
2154        );
2155    }
2156
2157    #[test]
2158    fn compile_plan_precision_requirement_filters_via_default_chain() {
2159        let mut table = KernelBindingTable::new();
2160        // Non-bit-stable.
2161        register_add_f32(
2162            &mut table,
2163            BackendId::Cpu,
2164            noop_kernel,
2165            PrecisionGuarantee {
2166                bit_stable_on_same_hardware: false,
2167                ..PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU
2168            },
2169        );
2170
2171        let (g, add_id) = build_add_graph();
2172        let order = topo_order(&g, add_id);
2173        let opts = PlanOptions::new()
2174            .without_cost_population()
2175            .with_precision_requirement(PrecisionRequirement::BIT_STABLE);
2176        let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2177        match err {
2178            Error::FilterRejected { filter, .. } => {
2179                assert_eq!(filter, "precision-floor");
2180            }
2181            other => panic!("expected FilterRejected, got {other:?}"),
2182        }
2183        // Sanity: drop the requirement → plan succeeds.
2184        let unconstrained = PlanOptions::new().without_cost_population();
2185        let plan = compile_plan(&g, &order, &table, &unconstrained).expect("compile");
2186        assert!(plan.alternatives(add_id).is_some());
2187        let _ = add_id;
2188    }
2189
2190    #[test]
2191    fn compile_plan_with_cost_ranks_cheaper_winner() {
2192        fn cheap_cost(
2193            _: &[Shape],
2194            _: &[DType],
2195            _: &OpParams,
2196            _: &BackendCapabilities,
2197        ) -> crate::fused::CostEstimate {
2198            crate::fused::CostEstimate {
2199                flops: 10,
2200                bytes_moved: 0,
2201                kernel_overhead_ns: 0,
2202            }
2203        }
2204        fn expensive_cost(
2205            _: &[Shape],
2206            _: &[DType],
2207            _: &OpParams,
2208            _: &BackendCapabilities,
2209        ) -> crate::fused::CostEstimate {
2210            crate::fused::CostEstimate {
2211                flops: 1_000_000,
2212                bytes_moved: 0,
2213                kernel_overhead_ns: 0,
2214            }
2215        }
2216        let mut table = KernelBindingTable::new();
2217        table.register_full(
2218            OpKind::AddElementwise,
2219            &[DType::F32, DType::F32, DType::F32],
2220            BackendId::Cpu,
2221            noop_kernel,
2222            KernelCaps::empty(),
2223            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2224            expensive_cost,
2225        );
2226        table.register_full(
2227            OpKind::AddElementwise,
2228            &[DType::F32, DType::F32, DType::F32],
2229            BackendId::Cuda,
2230            noop_kernel_b,
2231            KernelCaps::empty(),
2232            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2233            cheap_cost,
2234        );
2235
2236        let (g, add_id) = build_add_graph();
2237        let order = topo_order(&g, add_id);
2238        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2239            if dev == DeviceLocation::Cpu {
2240                vec![BackendId::Cpu, BackendId::Cuda]
2241            } else {
2242                vec![]
2243            }
2244        };
2245        let cpu_caps_val = cpu_caps();
2246        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2247        let opts = PlanOptions::new()
2248            .with_placements_for_device(&placements_fn)
2249            .with_capabilities_for(&caps_fn);
2250        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2251        let alts = plan.alternatives(add_id).unwrap();
2252        assert_eq!(alts.len(), 2);
2253        assert_eq!(
2254            alts.winner().unwrap().backend,
2255            BackendId::Cuda,
2256            "cheaper static cost wins after ranking",
2257        );
2258    }
2259
2260    #[test]
2261    fn compile_plan_judge_layer2_can_flip_layer1_winner() {
2262        // Layer-1 says CPU is cheap, Aocl is expensive.
2263        // Layer-2 (Judge) measured the opposite: Aocl 20 ns, CPU 5000 ns.
2264        // After compile_plan's cost composition + rank, Aocl wins.
2265        use crate::ranker::HashMapJudge;
2266        use fuel_ir::dispatch::SizeClass;
2267
2268        fn cpu_layer1(
2269            _: &[Shape],
2270            _: &[DType],
2271            _: &OpParams,
2272            _: &BackendCapabilities,
2273        ) -> crate::fused::CostEstimate {
2274            crate::fused::CostEstimate {
2275                flops: 10,
2276                bytes_moved: 0,
2277                kernel_overhead_ns: 0,
2278            }
2279        }
2280        fn aocl_layer1(
2281            _: &[Shape],
2282            _: &[DType],
2283            _: &OpParams,
2284            _: &BackendCapabilities,
2285        ) -> crate::fused::CostEstimate {
2286            crate::fused::CostEstimate {
2287                flops: 100_000,
2288                bytes_moved: 0,
2289                kernel_overhead_ns: 0,
2290            }
2291        }
2292        let mut table = KernelBindingTable::new();
2293        table.register_full(
2294            OpKind::AddElementwise,
2295            &[DType::F32, DType::F32, DType::F32],
2296            BackendId::Cpu,
2297            noop_kernel,
2298            KernelCaps::empty(),
2299            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2300            cpu_layer1,
2301        );
2302        table.register_full(
2303            OpKind::AddElementwise,
2304            &[DType::F32, DType::F32, DType::F32],
2305            BackendId::Cuda,
2306            noop_kernel_b,
2307            KernelCaps::empty(),
2308            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2309            aocl_layer1,
2310        );
2311
2312        let (g, add_id) = build_add_graph();
2313        let order = topo_order(&g, add_id);
2314        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2315            if dev == DeviceLocation::Cpu {
2316                vec![BackendId::Cpu, BackendId::Cuda]
2317            } else {
2318                vec![]
2319            }
2320        };
2321        let cpu_caps_val = cpu_caps();
2322        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2323
2324        // Each input is shape [3] (per build_add_graph); the
2325        // first-input-shape rule gives elem_count 3.
2326        let sc = SizeClass::from_elem_count(3);
2327        let mut judge = HashMapJudge::new();
2328        judge.insert(
2329            OpKind::AddElementwise,
2330            DType::F32,
2331            sc,
2332            BackendId::Cpu,
2333            "",
2334            5_000,
2335            0,
2336        );
2337        judge.insert(
2338            OpKind::AddElementwise,
2339            DType::F32,
2340            sc,
2341            BackendId::Cuda,
2342            "",
2343            20,
2344            0,
2345        );
2346
2347        let opts = PlanOptions::new()
2348            .with_placements_for_device(&placements_fn)
2349            .with_capabilities_for(&caps_fn)
2350            .with_judge(&judge);
2351
2352        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2353        let alts = plan.alternatives(add_id).unwrap();
2354        assert_eq!(alts.len(), 2);
2355        assert_eq!(
2356            alts.winner().unwrap().backend,
2357            BackendId::Cuda,
2358            "Layer-2 measurement reverses Layer-1 verdict via compile_plan",
2359        );
2360    }
2361
2362    /// `compile_plan` stamps each set with the decision-point
2363    /// context using the same key derivation as the cost composer's
2364    /// Layer-2 lookup: principal dtype = first lookup dtype, size
2365    /// class = first input's element count.
2366    #[test]
2367    fn compile_plan_stamps_decision_context() {
2368        use fuel_ir::dispatch::SizeClass;
2369
2370        let mut table = KernelBindingTable::new();
2371        register_add_f32(
2372            &mut table,
2373            BackendId::Cpu,
2374            noop_kernel,
2375            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2376        );
2377        let (g, add_id) = build_add_graph();
2378        let order = topo_order(&g, add_id);
2379        let opts = PlanOptions::new().without_cost_population();
2380        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2381        let alts = plan.alternatives(add_id).expect("Add alternatives present");
2382        let ctx = alts.context().expect("context stamped");
2383        assert_eq!(ctx.op, OpKind::AddElementwise);
2384        assert_eq!(ctx.principal_dtype, DType::F32);
2385        // build_add_graph inputs are shape [3].
2386        assert_eq!(ctx.size_class, SizeClass::from_elem_count(3));
2387    }
2388
2389    /// PR-B2: the fixed top-N is retired. Three distinct backends
2390    /// co-located at one ending device, all equally-costed (no cost
2391    /// population → equal cost vectors → mutually non-dominated), all
2392    /// survive the per-ending-device Pareto frontier — the
2393    /// never-strand-last-`(device, backend)` rule keeps each distinct
2394    /// backend, and the crowding cap (KEEP_PER_DEVICE = 32) is far
2395    /// above 3. The old `truncate_to_top_n` would have stranded one;
2396    /// this is the behavior change B2 introduces.
2397    #[test]
2398    fn compile_plan_retains_per_device_frontier_no_top_n() {
2399        let mut table = KernelBindingTable::new();
2400        // Three CPU-substrate backends competing at one decision point.
2401        // Distinct kernel fn items so the binding table accepts them.
2402        register_add_f32(
2403            &mut table,
2404            BackendId::Cpu,
2405            noop_kernel,
2406            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2407        );
2408        register_add_f32(
2409            &mut table,
2410            BackendId::Cuda,
2411            noop_kernel_b,
2412            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2413        );
2414        register_add_f32(
2415            &mut table,
2416            BackendId::Vulkan,
2417            noop_kernel_c,
2418            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2419        );
2420
2421        let (g, add_id) = build_add_graph();
2422        let order = topo_order(&g, add_id);
2423        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2424            if dev == DeviceLocation::Cpu {
2425                vec![BackendId::Cpu, BackendId::Cuda, BackendId::Vulkan]
2426            } else {
2427                vec![]
2428            }
2429        };
2430        let opts = PlanOptions::new()
2431            .without_cost_population()
2432            .with_placements_for_device(&placements_fn);
2433        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2434        let alts = plan.alternatives(add_id).unwrap();
2435        assert_eq!(
2436            alts.len(),
2437            3,
2438            "all three co-located (device, backend) paths survive — no top-N truncation",
2439        );
2440    }
2441
2442    /// Step 4a parity: an UNSTAMPED graph planned with
2443    /// `with_pinned_device(Cpu)` produces the same alternative sets
2444    /// as the legacy stamped graph — candidate-for-candidate
2445    /// (backend, device, kernel, kernel_source).
2446    #[test]
2447    fn compile_plan_pinned_device_matches_stamped_plan() {
2448        let mut table = KernelBindingTable::new();
2449        register_add_f32(
2450            &mut table,
2451            BackendId::Cpu,
2452            noop_kernel,
2453            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2454        );
2455
2456        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2457            if dev == DeviceLocation::Cpu {
2458                vec![BackendId::Cpu]
2459            } else {
2460                vec![]
2461            }
2462        };
2463
2464        // Legacy: stamped target_backend, no pinned device.
2465        let (g_stamped, add_stamped) = build_add_graph();
2466        let order_stamped = topo_order(&g_stamped, add_stamped);
2467        let opts_stamped = PlanOptions::new()
2468            .without_cost_population()
2469            .with_placements_for_device(&placements_fn);
2470        let plan_stamped = compile_plan(&g_stamped, &order_stamped, &table, &opts_stamped)
2471            .expect("stamped compile");
2472
2473        // New: same graph shape, NO target_backend anywhere, pinned
2474        // device instead.
2475        let mut g = Graph::new();
2476        let lhs = g.push(Node {
2477            op: Op::Const,
2478            inputs: vec![],
2479            shape: Shape::from_dims(&[3]),
2480            dtype: DType::F32,
2481        });
2482        let rhs = g.push(Node {
2483            op: Op::Const,
2484            inputs: vec![],
2485            shape: Shape::from_dims(&[3]),
2486            dtype: DType::F32,
2487        });
2488        let add = g.push(Node {
2489            op: Op::Add,
2490            inputs: vec![lhs, rhs],
2491            shape: Shape::from_dims(&[3]),
2492            dtype: DType::F32,
2493        });
2494        let order = topo_order(&g, add);
2495        let opts = PlanOptions::new()
2496            .without_cost_population()
2497            .with_placements_for_device(&placements_fn)
2498            .with_pinned_device(DeviceLocation::Cpu);
2499        let plan = compile_plan(&g, &order, &table, &opts).expect("pinned compile");
2500
2501        let a = plan_stamped.alternatives(add_stamped).expect("stamped set");
2502        let b = plan.alternatives(add).expect("pinned set");
2503        assert_eq!(a.len(), b.len(), "same candidate count");
2504        for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
2505            assert_eq!(ca.backend, cb.backend);
2506            assert_eq!(ca.device, cb.device);
2507            assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
2508            assert_eq!(ca.kernel_source, cb.kernel_source);
2509        }
2510        assert_eq!(a.context(), b.context(), "same decision context");
2511    }
2512
2513    /// Step 4a: a node with neither a placement, nor a pinned
2514    /// device, nor a target_backend stamp is a plan-time error —
2515    /// fail-fast with an actionable message.
2516    #[test]
2517    fn compile_plan_errors_without_any_device_context() {
2518        let mut table = KernelBindingTable::new();
2519        register_add_f32(
2520            &mut table,
2521            BackendId::Cpu,
2522            noop_kernel,
2523            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2524        );
2525        let mut g = Graph::new();
2526        let lhs = g.push(Node {
2527            op: Op::Const,
2528            inputs: vec![],
2529            shape: Shape::from_dims(&[3]),
2530            dtype: DType::F32,
2531        });
2532        let add = g.push(Node {
2533            op: Op::Add,
2534            inputs: vec![lhs, lhs],
2535            shape: Shape::from_dims(&[3]),
2536            dtype: DType::F32,
2537        });
2538        let order = topo_order(&g, add);
2539        let opts = PlanOptions::new().without_cost_population();
2540        let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2541        let msg = format!("{err:?}");
2542        assert!(
2543            msg.contains("no device context"),
2544            "expected the device-context diagnostic, got: {msg}",
2545        );
2546    }
2547
2548    /// Step 4a: `Op::Copy` nodes are excluded from the plan map —
2549    /// their kernel is residency-determined (source backend), so
2550    /// dispatch flows through the executor's legacy `compile_node`
2551    /// path keyed by the bridge's source-backend stamp.
2552    #[test]
2553    fn compile_plan_skips_op_copy_nodes() {
2554        let mut table = KernelBindingTable::new();
2555        register_add_f32(
2556            &mut table,
2557            BackendId::Cpu,
2558            noop_kernel,
2559            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2560        );
2561        // A Copy registration exists — the skip must not depend on
2562        // the table lacking one.
2563        table.register_full(
2564            OpKind::Copy,
2565            &[DType::F32, DType::F32],
2566            BackendId::Cpu,
2567            noop_kernel_b,
2568            KernelCaps::empty(),
2569            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2570            unknown_cost,
2571        );
2572
2573        let (mut g, add_id) = build_add_graph();
2574        let copy_id = g.push(Node {
2575            op: Op::Copy {
2576                target: DeviceLocation::Cpu,
2577            },
2578            inputs: vec![add_id],
2579            shape: Shape::from_dims(&[3]),
2580            dtype: DType::F32,
2581        });
2582        g.set_target_backend(copy_id, BackendId::Cpu);
2583        let order = topo_order(&g, copy_id);
2584        let opts = PlanOptions::new()
2585            .without_cost_population()
2586            .with_pinned_device(DeviceLocation::Cpu);
2587        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2588        assert!(plan.alternatives(add_id).is_some(), "Add is planned");
2589        assert!(
2590            plan.alternatives(copy_id).is_none(),
2591            "Op::Copy is residency-determined — no plan entry",
2592        );
2593    }
2594
2595    /// `Op::Move` follows `Op::Copy`'s exclusion: it dispatches the
2596    /// same residency-determined transfer kernel (`OpKind::Copy` on
2597    /// the SOURCE backend), so it gets no plan entry either.
2598    #[test]
2599    fn compile_plan_skips_op_move_nodes() {
2600        let mut table = KernelBindingTable::new();
2601        register_add_f32(
2602            &mut table,
2603            BackendId::Cpu,
2604            noop_kernel,
2605            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2606        );
2607        // A Copy registration exists (Op::Move keys the same row) —
2608        // the skip must not depend on the table lacking one.
2609        table.register_full(
2610            OpKind::Copy,
2611            &[DType::F32, DType::F32],
2612            BackendId::Cpu,
2613            noop_kernel_b,
2614            KernelCaps::empty(),
2615            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2616            unknown_cost,
2617        );
2618
2619        let (mut g, add_id) = build_add_graph();
2620        let move_id = g.push(Node {
2621            op: Op::Move {
2622                target: DeviceLocation::Cpu,
2623            },
2624            inputs: vec![add_id],
2625            shape: Shape::from_dims(&[3]),
2626            dtype: DType::F32,
2627        });
2628        g.set_target_backend(move_id, BackendId::Cpu);
2629        let order = topo_order(&g, move_id);
2630        let opts = PlanOptions::new()
2631            .without_cost_population()
2632            .with_pinned_device(DeviceLocation::Cpu);
2633        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2634        assert!(plan.alternatives(add_id).is_some(), "Add is planned");
2635        assert!(
2636            plan.alternatives(move_id).is_none(),
2637            "Op::Move is residency-determined — no plan entry",
2638        );
2639    }
2640
2641    /// Step 4b: an op with no implementation on the pinned device
2642    /// falls back to an off-device candidate — the missing-impl op
2643    /// becomes a plan-time picker decision.
2644    #[test]
2645    fn compile_plan_fallback_admits_off_device_candidate() {
2646        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2647        let mut table = KernelBindingTable::new();
2648        // Add f32 registered ONLY on Cpu — the pinned CUDA device
2649        // has no impl.
2650        register_add_f32(
2651            &mut table,
2652            BackendId::Cpu,
2653            noop_kernel,
2654            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2655        );
2656
2657        let mut g = Graph::new();
2658        let lhs = g.push(Node {
2659            op: Op::Const,
2660            inputs: vec![],
2661            shape: Shape::from_dims(&[3]),
2662            dtype: DType::F32,
2663        });
2664        let add = g.push(Node {
2665            op: Op::Add,
2666            inputs: vec![lhs, lhs],
2667            shape: Shape::from_dims(&[3]),
2668            dtype: DType::F32,
2669        });
2670        let order = topo_order(&g, add);
2671
2672        let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2673            if dev == cuda0 {
2674                vec![BackendId::Cuda]
2675            } else {
2676                vec![BackendId::Cpu]
2677            }
2678        };
2679        let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2680            vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2681        };
2682        let opts = PlanOptions::new()
2683            .without_cost_population()
2684            .with_pinned_device(cuda0)
2685            .with_placements_for_device(&placements_fn)
2686            .with_fallback_placements_for(&fallback_fn);
2687        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2688        let alts = plan.alternatives(add).expect("Add planned via fallback");
2689        assert_eq!(alts.len(), 1, "fallback set frozen to one winner");
2690        let w = alts.winner().unwrap();
2691        assert_eq!(w.backend, BackendId::Cpu);
2692        assert_eq!(w.device, DeviceLocation::Cpu, "off-device placement");
2693    }
2694
2695    /// Step 4b locality, UNPRICED regime: without a Stage-2
2696    /// transfer estimator the fallback enumerator is NOT consulted
2697    /// while the pinned device has a registered candidate — an
2698    /// unpriced rank must never move an op cross-device on kernel
2699    /// cost alone.
2700    #[test]
2701    fn compile_plan_fallback_not_consulted_when_pinned_has_impl() {
2702        let mut table = KernelBindingTable::new();
2703        register_add_f32(
2704            &mut table,
2705            BackendId::Cpu,
2706            noop_kernel,
2707            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2708        );
2709        register_add_f32(
2710            &mut table,
2711            BackendId::Cuda,
2712            noop_kernel_b,
2713            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2714        );
2715        let (g, add_id) = build_add_graph();
2716        let order = topo_order(&g, add_id);
2717        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
2718            if dev == DeviceLocation::Cpu {
2719                vec![BackendId::Cpu]
2720            } else {
2721                vec![]
2722            }
2723        };
2724        let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2725            panic!(
2726                "fallback consulted although the pinned device has an \
2727                 implementation — locality policy violated",
2728            );
2729        };
2730        let opts = PlanOptions::new()
2731            .without_cost_population()
2732            .with_pinned_device(DeviceLocation::Cpu)
2733            .with_placements_for_device(&placements_fn)
2734            .with_fallback_placements_for(&fallback_fn);
2735        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2736        let alts = plan.alternatives(add_id).unwrap();
2737        assert_eq!(alts.len(), 1);
2738        assert_eq!(alts.winner().unwrap().device, DeviceLocation::Cpu);
2739    }
2740
2741    /// Step 4b: destructive ops never fall back — the plan-time
2742    /// NoBackendForOp error is preserved.
2743    #[test]
2744    fn compile_plan_fallback_denied_for_destructive_ops() {
2745        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2746        let mut table = KernelBindingTable::new();
2747        // ReluInplace registered ONLY on Cpu; pinned device is CUDA.
2748        table.register_full(
2749            OpKind::ReluInplace,
2750            &[DType::F32, DType::F32],
2751            BackendId::Cpu,
2752            noop_kernel,
2753            KernelCaps::empty(),
2754            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2755            unknown_cost,
2756        );
2757        let mut g = Graph::new();
2758        let lhs = g.push(Node {
2759            op: Op::Const,
2760            inputs: vec![],
2761            shape: Shape::from_dims(&[3]),
2762            dtype: DType::F32,
2763        });
2764        let relu = g.push(Node {
2765            op: Op::ReluInplace,
2766            inputs: vec![lhs],
2767            shape: Shape::from_dims(&[3]),
2768            dtype: DType::F32,
2769        });
2770        let order = topo_order(&g, relu);
2771        let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2772            if dev == cuda0 {
2773                vec![BackendId::Cuda]
2774            } else {
2775                vec![BackendId::Cpu]
2776            }
2777        };
2778        let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2779            vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2780        };
2781        let opts = PlanOptions::new()
2782            .without_cost_population()
2783            .with_pinned_device(cuda0)
2784            .with_placements_for_device(&placements_fn)
2785            .with_fallback_placements_for(&fallback_fn);
2786        let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
2787        assert!(
2788            matches!(
2789                err,
2790                Error::NoBackendForOp {
2791                    op: OpKind::ReluInplace,
2792                    ..
2793                }
2794            ),
2795            "destructive op must NOT fall back off-device; got {err:?}",
2796        );
2797    }
2798
2799    /// Step 4b: even when MULTIPLE off-device backends could serve
2800    /// the op, the fallback set freezes to a single winner so the
2801    /// dispatch-time selector can't diverge from the residency
2802    /// stitch.
2803    #[test]
2804    fn compile_plan_fallback_freezes_to_single_winner() {
2805        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2806        let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
2807        let mut table = KernelBindingTable::new();
2808        register_add_f32(
2809            &mut table,
2810            BackendId::Cpu,
2811            noop_kernel,
2812            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2813        );
2814        register_add_f32(
2815            &mut table,
2816            BackendId::Vulkan,
2817            noop_kernel_b,
2818            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2819        );
2820
2821        let mut g = Graph::new();
2822        let lhs = g.push(Node {
2823            op: Op::Const,
2824            inputs: vec![],
2825            shape: Shape::from_dims(&[3]),
2826            dtype: DType::F32,
2827        });
2828        let add = g.push(Node {
2829            op: Op::Add,
2830            inputs: vec![lhs, lhs],
2831            shape: Shape::from_dims(&[3]),
2832            dtype: DType::F32,
2833        });
2834        let order = topo_order(&g, add);
2835        let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2836            if dev == cuda0 {
2837                vec![BackendId::Cuda]
2838            } else {
2839                vec![]
2840            }
2841        };
2842        let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2843            vec![
2844                (BackendId::Cpu, DeviceLocation::Cpu),
2845                (BackendId::Vulkan, vk0),
2846            ]
2847        };
2848        let opts = PlanOptions::new()
2849            .without_cost_population()
2850            .with_pinned_device(cuda0)
2851            .with_placements_for_device(&placements_fn)
2852            .with_fallback_placements_for(&fallback_fn);
2853        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2854        let alts = plan.alternatives(add).unwrap();
2855        assert_eq!(
2856            alts.len(),
2857            1,
2858            "fallback set must freeze to its single ranked winner",
2859        );
2860    }
2861
2862    /// Synthetic Stage-2 estimator: zero same-device, flat latency
2863    /// otherwise. Unit tests must never depend on live calibration.
2864    struct FlatEstimator {
2865        latency_ns: u64,
2866    }
2867
2868    impl crate::ranker::TransferEstimator for FlatEstimator {
2869        fn estimate_transfer_ns(
2870            &self,
2871            src: DeviceLocation,
2872            dst: DeviceLocation,
2873            _bytes: u64,
2874        ) -> u64 {
2875            if src == dst { 0 } else { self.latency_ns }
2876        }
2877    }
2878
2879    /// Stage 2 residency threading: a missing-impl fallback set is
2880    /// priced against the inputs' residency — with both inputs
2881    /// resident on vk0, the Vulkan fallback candidate beats the
2882    /// first-enumerated CPU one (both have zero kernel cost, so the
2883    /// transfer term decides).
2884    #[test]
2885    fn compile_plan_prices_fallback_by_input_residency() {
2886        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2887        let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
2888        let mut table = KernelBindingTable::new();
2889        // No CUDA impl — the pinned cuda0 device must fall back.
2890        register_add_f32(
2891            &mut table,
2892            BackendId::Cpu,
2893            noop_kernel,
2894            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2895        );
2896        register_add_f32(
2897            &mut table,
2898            BackendId::Vulkan,
2899            noop_kernel_b,
2900            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2901        );
2902
2903        let mut g = Graph::new();
2904        let lhs = g.push(Node {
2905            op: Op::Const,
2906            inputs: vec![],
2907            shape: Shape::from_dims(&[4]),
2908            dtype: DType::F32,
2909        });
2910        let add = g.push(Node {
2911            op: Op::Add,
2912            inputs: vec![lhs, lhs],
2913            shape: Shape::from_dims(&[4]),
2914            dtype: DType::F32,
2915        });
2916        let order = topo_order(&g, add);
2917
2918        let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
2919            if dev == cuda0 {
2920                vec![BackendId::Cuda]
2921            } else {
2922                vec![]
2923            }
2924        };
2925        let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
2926            vec![
2927                (BackendId::Cpu, DeviceLocation::Cpu),
2928                (BackendId::Vulkan, vk0),
2929            ]
2930        };
2931        // The const's bytes live on vk0 (e.g. a persistent cache
2932        // slot) — exactly what the bridge's input-residency callback
2933        // reports.
2934        let residency_fn =
2935            move |id: NodeId| -> Option<DeviceLocation> { (id == lhs).then_some(vk0) };
2936        let est = FlatEstimator { latency_ns: 1_000 };
2937        let cpu_caps_val = cpu_caps();
2938        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
2939        let opts = PlanOptions::new()
2940            .with_pinned_device(cuda0)
2941            .with_placements_for_device(&placements_fn)
2942            .with_fallback_placements_for(&fallback_fn)
2943            .with_capabilities_for(&caps_fn)
2944            .with_transfer_estimator(&est)
2945            .with_input_residency(&residency_fn);
2946        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
2947        let alts = plan.alternatives(add).expect("Add planned via fallback");
2948        assert_eq!(alts.len(), 1, "fallback narrows to a single winner");
2949        let w = alts.winner().unwrap();
2950        assert_eq!(
2951            w.device, vk0,
2952            "transfer pricing moves the fallback to the inputs' residency",
2953        );
2954        assert_eq!(w.inbound_transfer_ns, 0, "co-resident inputs price zero");
2955    }
2956
2957    /// Plan-time cost fns for the Stage-2 relax tests. Composite is
2958    /// the flops figure directly (no bytes, no overhead).
2959    fn cost_600(
2960        _: &[Shape],
2961        _: &[DType],
2962        _: &OpParams,
2963        _: &BackendCapabilities,
2964    ) -> crate::fused::CostEstimate {
2965        crate::fused::CostEstimate {
2966            flops: 600,
2967            bytes_moved: 0,
2968            kernel_overhead_ns: 0,
2969        }
2970    }
2971    fn cost_10(
2972        _: &[Shape],
2973        _: &[DType],
2974        _: &OpParams,
2975        _: &BackendCapabilities,
2976    ) -> crate::fused::CostEstimate {
2977        crate::fused::CostEstimate {
2978            flops: 10,
2979            bytes_moved: 0,
2980            kernel_overhead_ns: 0,
2981        }
2982    }
2983    // 15 000 FLOPs → 500 ns at the GPU throughput prior (30 FLOPs/ns):
2984    // a kernel whose GPU compute is faster than a 600-ns CPU kernel, but
2985    // whose 200 ns inbound transfer tips the honest total past it.
2986    fn cost_15_000(
2987        _: &[Shape],
2988        _: &[DType],
2989        _: &OpParams,
2990        _: &BackendCapabilities,
2991    ) -> crate::fused::CostEstimate {
2992        crate::fused::CostEstimate {
2993            flops: 15_000,
2994            bytes_moved: 0,
2995            kernel_overhead_ns: 0,
2996        }
2997    }
2998    fn cost_10_000_000(
2999        _: &[Shape],
3000        _: &[DType],
3001        _: &OpParams,
3002        _: &BackendCapabilities,
3003    ) -> crate::fused::CostEstimate {
3004        crate::fused::CostEstimate {
3005            flops: 10_000_000,
3006            bytes_moved: 0,
3007            kernel_overhead_ns: 0,
3008        }
3009    }
3010
3011    /// Test fixture for the relax: Add f32 on CPU (cost via
3012    /// `cpu_cost`) + CUDA at cuda:0 (cost via `cuda_cost`), graph
3013    /// pinned to CPU, both consts resident on CPU, fallback
3014    /// enumerator offering cuda:0. Returns the planned set for the
3015    /// Add node.
3016    fn relaxed_plan_with_costs(
3017        cpu_cost: crate::kernel::CostFn,
3018        cuda_cost: crate::kernel::CostFn,
3019        estimator: &FlatEstimator,
3020    ) -> AlternativeSet {
3021        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3022        let mut table = KernelBindingTable::new();
3023        table.register_full(
3024            OpKind::AddElementwise,
3025            &[DType::F32, DType::F32, DType::F32],
3026            BackendId::Cpu,
3027            noop_kernel,
3028            KernelCaps::empty(),
3029            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3030            cpu_cost,
3031        );
3032        table.register_full(
3033            OpKind::AddElementwise,
3034            &[DType::F32, DType::F32, DType::F32],
3035            BackendId::Cuda,
3036            noop_kernel_b,
3037            KernelCaps::empty(),
3038            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3039            cuda_cost,
3040        );
3041
3042        let (g, add_id) = build_add_graph();
3043        let order = topo_order(&g, add_id);
3044        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3045            if dev == DeviceLocation::Cpu {
3046                vec![BackendId::Cpu]
3047            } else {
3048                vec![]
3049            }
3050        };
3051        let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3052            vec![(BackendId::Cuda, cuda0)]
3053        };
3054        // build_add_graph's consts have no cache entry; report them
3055        // CPU-resident as build_const_cache would for a CPU realize.
3056        let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3057        let cpu_caps_val = cpu_caps();
3058        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3059        let opts = PlanOptions::new()
3060            .with_pinned_device(DeviceLocation::Cpu)
3061            .with_placements_for_device(&placements_fn)
3062            .with_fallback_placements_for(&fallback_fn)
3063            .with_capabilities_for(&caps_fn)
3064            .with_transfer_estimator(estimator)
3065            .with_input_residency(&residency_fn);
3066        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3067        plan.alternatives(add_id).expect("Add planned").clone()
3068    }
3069
3070    /// Stage-2 parity gate: a tiny op stays local although the
3071    /// remote kernel is "faster" — the transfer term dominates.
3072    /// Off-device siblings are pruned from the surviving set.
3073    #[test]
3074    fn compile_plan_relaxed_tiny_op_stays_local_when_transfer_dominates() {
3075        // CPU 600 ns vs CUDA 10 ns kernel; 1 ms per input crossing.
3076        // CUDA total = 10 + 2 × 1_000_000 ≫ CPU 600.
3077        let est = FlatEstimator {
3078            latency_ns: 1_000_000,
3079        };
3080        let set = relaxed_plan_with_costs(cost_600, cost_10, &est);
3081        let w = set.winner().unwrap();
3082        assert_eq!(
3083            w.device,
3084            DeviceLocation::Cpu,
3085            "transfer dominates → stay local"
3086        );
3087        assert_eq!(w.inbound_transfer_ns, 0, "local winner pays no transfer");
3088        assert!(
3089            set.alternatives()
3090                .iter()
3091                .all(|c| c.device == DeviceLocation::Cpu),
3092            "off-device siblings pruned after rank",
3093        );
3094    }
3095
3096    /// FKC cost unification Part A — born-red for the "uncapped GPU
3097    /// prices at ZERO" bug.
3098    ///
3099    /// The production `capabilities_for` closure is
3100    /// `topology.capabilities(backend)`, which is backed by the
3101    /// `CapabilityRegistry`. Before Part A only the CPU auto-registered
3102    /// `BackendCapabilities`; a GPU backend registered its kernels into
3103    /// the binding table but NO caps. `compute_static_costs`
3104    /// (`ranker/cost.rs`) then hits `let Some(caps) =
3105    /// capabilities_for(backend) else { continue }` and SKIPS the GPU
3106    /// candidate's cost fn, leaving `static_cost` at the default ZERO.
3107    /// A CPU-pinned realize with a GPU fallback candidate then sees the
3108    /// GPU price at `0 + inbound_transfer` and win the priced relax —
3109    /// spilling onto an unseeded GPU (the observed `Op::Alloc/Copy`
3110    /// "no CUDA storage in input cache" crash).
3111    ///
3112    /// This test models both halves against the real placement DP:
3113    ///
3114    /// - **Bug half** (`caps_fn` returns `None` for CUDA, matching the
3115    ///   pre-Part-A registry): the CUDA fallback candidate is skipped,
3116    ///   prices at `0 + transfer(200) = 200 < CPU 600`, and wins.
3117    /// - **Fix half** (`caps_fn` returns the caps DERIVED FROM THE
3118    ///   BINDING TABLE by `dispatch::derive_backend_caps`, exactly what
3119    ///   Part A registers into the global registry): the CUDA candidate
3120    ///   is now costed via its flops fn — `500 + transfer(200) = 700 >
3121    ///   CPU 600` — so CPU wins and no spurious spill happens.
3122    ///
3123    /// The kernel gap (CUDA 500 < CPU 600) is deliberately real: the
3124    /// GPU is a *cheaper kernel*, so the only thing that makes CPU win
3125    /// is that the GPU is now HONESTLY priced (flops + transfer) rather
3126    /// than free. Same fixture as `relaxed_plan_with_costs` but with an
3127    /// explicit per-backend `caps_fn` so we can toggle the GPU's caps.
3128    #[test]
3129    fn compile_plan_uncapped_gpu_no_longer_wins_by_being_free() {
3130        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3131
3132        // A binding table exactly like production: CPU + CUDA kernels
3133        // for Add f32. On GPU throughput the CUDA kernel's compute is
3134        // nominally faster (15 000 FLOPs ≈ 500 ns at 30 FLOPs/ns < the
3135        // CPU's 600 ns), but its 200 ns inbound transfer tips the honest
3136        // total to 700 > 600 — so the CPU-pinned realize must stay put
3137        // once the GPU is priced honestly (the point of Part A).
3138        fn build_table() -> KernelBindingTable {
3139            let mut table = KernelBindingTable::new();
3140            table.register_full(
3141                OpKind::AddElementwise,
3142                &[DType::F32, DType::F32, DType::F32],
3143                BackendId::Cpu,
3144                noop_kernel,
3145                KernelCaps::empty(),
3146                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3147                cost_600,
3148            );
3149            table.register_full(
3150                OpKind::AddElementwise,
3151                &[DType::F32, DType::F32, DType::F32],
3152                BackendId::Cuda,
3153                noop_kernel_b,
3154                KernelCaps::empty(),
3155                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3156                cost_15_000,
3157            );
3158            table
3159        }
3160
3161        // Run the CPU-pinned Add + CUDA-fallback relax; `gpu_caps`
3162        // controls whether `capabilities_for(Cuda)` returns Some (the
3163        // fix) or None (the pre-Part-A registry bug). All the borrowed
3164        // `PlanOptions` fields — including the caps closure — are LOCAL
3165        // to this function so `PlanOptions`'s single lifetime unifies to
3166        // this body. The caps values are `'static` (leaked) so the
3167        // closure can be built here from the caller's choice.
3168        fn winner_device_under(
3169            table: &KernelBindingTable,
3170            cpu_caps_val: &'static BackendCapabilities,
3171            gpu_caps: Option<&'static BackendCapabilities>,
3172            cuda0: DeviceLocation,
3173        ) -> DeviceLocation {
3174            let (g, add_id) = build_add_graph();
3175            let order = topo_order(&g, add_id);
3176            let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3177                if dev == DeviceLocation::Cpu {
3178                    vec![BackendId::Cpu]
3179                } else {
3180                    vec![]
3181                }
3182            };
3183            let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3184                vec![(BackendId::Cuda, cuda0)]
3185            };
3186            // Both consts CPU-resident (a CPU realize) — the crash
3187            // scenario: the GPU is UNSEEDED, so any spill onto it is a
3188            // correctness bug downstream.
3189            let residency_fn =
3190                |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3191            // 100 ns per input crossing → 200 ns inbound transfer for
3192            // the two-input Add on the CUDA candidate.
3193            let est = FlatEstimator { latency_ns: 100 };
3194            let caps_fn = move |b: BackendId| -> Option<&BackendCapabilities> {
3195                match b {
3196                    BackendId::Cpu => Some(cpu_caps_val),
3197                    BackendId::Cuda => gpu_caps,
3198                    _ => None,
3199                }
3200            };
3201            let opts = PlanOptions::new()
3202                .with_pinned_device(DeviceLocation::Cpu)
3203                .with_placements_for_device(&placements_fn)
3204                .with_fallback_placements_for(&fallback_fn)
3205                .with_capabilities_for(&caps_fn)
3206                .with_transfer_estimator(&est)
3207                .with_input_residency(&residency_fn);
3208            let plan = compile_plan(&g, &order, table, &opts).expect("compile");
3209            plan.alternatives(add_id).unwrap().winner().unwrap().device
3210        }
3211
3212        let table = build_table();
3213        // `'static` caps values so the caps closure built inside the
3214        // helper can capture them without threading a lifetime through
3215        // `PlanOptions`.
3216        let cpu_caps_val: &'static BackendCapabilities = Box::leak(Box::new(cpu_caps()));
3217
3218        // --- Bug half: the pre-Part-A registry returns None for CUDA. ---
3219        // (Kept as an inner assertion, sharing one fixture with the fix
3220        // half, so the red→green contrast is a single self-checking test.)
3221        let winner_bug = winner_device_under(&table, cpu_caps_val, None, cuda0);
3222        assert_eq!(
3223            winner_bug, cuda0,
3224            "PRE-FIX: an uncapped CUDA candidate is skipped by \
3225             compute_static_costs, prices at 0 + 200 transfer, and \
3226             spuriously beats the CPU's honest 600 — this IS the bug",
3227        );
3228
3229        // --- Fix half: Part A derives CUDA caps from the binding table
3230        // and registers them, so capabilities_for(Cuda) returns Some. ---
3231        let cuda_caps_val: &'static BackendCapabilities = Box::leak(Box::new(
3232            crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table),
3233        ));
3234        // The derivation must advertise the CUDA-registered (op, dtype)
3235        // pair so the cost fn actually runs.
3236        assert!(
3237            cuda_caps_val
3238                .op_dtype_support
3239                .contains(&(OpKind::AddElementwise, DType::F32)),
3240            "derive_backend_caps must mirror the binding table's \
3241             registered (op, output-dtype) pairs for the backend",
3242        );
3243        assert_eq!(cuda_caps_val.backend_id, BackendId::Cuda);
3244        assert_eq!(cuda_caps_val.device_location, cuda0);
3245
3246        let winner_fixed = winner_device_under(&table, cpu_caps_val, Some(cuda_caps_val), cuda0);
3247        assert_eq!(
3248            winner_fixed,
3249            DeviceLocation::Cpu,
3250            "POST-FIX: with GPU caps registered the CUDA candidate is \
3251             costed honestly (15000 FLOPs ÷ 30/ns = 500 ns compute + 200 \
3252             transfer = 700 > CPU 600), so the CPU-pinned realize stays \
3253             on CPU — no spill onto the unseeded GPU",
3254        );
3255    }
3256
3257    /// FKC cost unification Part C — born-red for **per-backend
3258    /// throughput**. The SAME kernel-cost fn is registered on both CPU
3259    /// and CUDA (equal FLOP counts — the discriminator is the backend's
3260    /// throughput, NOT a hand-tuned kernel-cost gap like the huge-op
3261    /// test below). Inputs are CPU-resident, so the CUDA candidate pays
3262    /// a fixed 200 ns inbound transfer (100 ns × 2 Add inputs). Expected
3263    /// crossover:
3264    ///   - SMALL op (100 FLOPs) → stays on CPU: the GPU's throughput
3265    ///     win (100 → ~3 ns) can't overcome the 200 ns transfer.
3266    ///   - LARGE op (10 M FLOPs) → moves to CUDA: the throughput win
3267    ///     (10 M → ~333 k ns) dwarfs the 200 ns transfer.
3268    ///
3269    /// Under the pre-Part-C FIXED 1-FLOP/ns prior the GPU's compute-ns
3270    /// EQUALS the CPU's for equal FLOPs, so it can never overcome the
3271    /// transfer and the large-op case wrongly stays on CPU — that is
3272    /// the red this test is born in.
3273    #[test]
3274    fn compile_plan_places_large_compute_on_gpu_small_on_cpu_by_throughput() {
3275        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3276
3277        fn winner(cost: crate::kernel::CostFn, cuda0: DeviceLocation) -> DeviceLocation {
3278            let mut table = KernelBindingTable::new();
3279            table.register_full(
3280                OpKind::AddElementwise,
3281                &[DType::F32, DType::F32, DType::F32],
3282                BackendId::Cpu,
3283                noop_kernel,
3284                KernelCaps::empty(),
3285                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3286                cost,
3287            );
3288            table.register_full(
3289                OpKind::AddElementwise,
3290                &[DType::F32, DType::F32, DType::F32],
3291                BackendId::Cuda,
3292                noop_kernel_b,
3293                KernelCaps::empty(),
3294                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3295                cost,
3296            );
3297
3298            let (g, add_id) = build_add_graph();
3299            let order = topo_order(&g, add_id);
3300            let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3301                if dev == DeviceLocation::Cpu {
3302                    vec![BackendId::Cpu]
3303                } else {
3304                    vec![]
3305                }
3306            };
3307            let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3308                vec![(BackendId::Cuda, cuda0)]
3309            };
3310            let residency_fn =
3311                |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3312            // 100 ns per input crossing → 200 ns inbound transfer for
3313            // the two-input Add on the CUDA candidate.
3314            let est = FlatEstimator { latency_ns: 100 };
3315            let cpu_caps_val = cpu_caps();
3316            let cuda_caps_val =
3317                crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table);
3318            let caps_fn = |b: BackendId| -> Option<&BackendCapabilities> {
3319                match b {
3320                    BackendId::Cpu => Some(&cpu_caps_val),
3321                    BackendId::Cuda => Some(&cuda_caps_val),
3322                    _ => None,
3323                }
3324            };
3325            let opts = PlanOptions::new()
3326                .with_pinned_device(DeviceLocation::Cpu)
3327                .with_placements_for_device(&placements_fn)
3328                .with_fallback_placements_for(&fallback_fn)
3329                .with_capabilities_for(&caps_fn)
3330                .with_transfer_estimator(&est)
3331                .with_input_residency(&residency_fn);
3332            let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3333            plan.alternatives(add_id).unwrap().winner().unwrap().device
3334        }
3335
3336        assert_eq!(
3337            winner(cost_100, cuda0),
3338            DeviceLocation::Cpu,
3339            "SMALL op: the GPU's throughput win on 100 FLOPs (~3 ns) \
3340             can't overcome the 200 ns inbound transfer → stay on CPU",
3341        );
3342        assert_eq!(
3343            winner(cost_10_000_000, cuda0),
3344            cuda0,
3345            "LARGE op: the GPU's throughput win on 10 M FLOPs (~333 k ns) \
3346             dwarfs the 200 ns transfer → move to CUDA. RED under the \
3347             fixed 1-FLOP/ns prior (equal compute-ns → the transfer \
3348             always loses the GPU the placement)",
3349        );
3350    }
3351
3352    /// `without_cost_placement()` (the reference / single-device realize
3353    /// gate) keeps a large, GPU-favorable op on the pinned CPU device. Same
3354    /// setup as `..._large_compute_on_gpu_small_on_cpu_by_throughput`, whose
3355    /// LARGE case moves the op to CUDA — here that exact op stays on CPU
3356    /// because the relaxed cross-device enumeration is suppressed.
3357    ///
3358    /// This is the unit-level guard for the phase6b oracle crash: a CPU-pinned
3359    /// reference realize must not spill onto the present (unseeded) GPU. Born
3360    /// red before `PlanOptions::allow_cost_placement` existed — the large op
3361    /// would have moved to CUDA.
3362    #[test]
3363    fn compile_plan_without_cost_placement_keeps_large_op_on_cpu() {
3364        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3365        let mut table = KernelBindingTable::new();
3366        table.register_full(
3367            OpKind::AddElementwise,
3368            &[DType::F32, DType::F32, DType::F32],
3369            BackendId::Cpu,
3370            noop_kernel,
3371            KernelCaps::empty(),
3372            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3373            cost_10_000_000,
3374        );
3375        table.register_full(
3376            OpKind::AddElementwise,
3377            &[DType::F32, DType::F32, DType::F32],
3378            BackendId::Cuda,
3379            noop_kernel_b,
3380            KernelCaps::empty(),
3381            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3382            cost_10_000_000,
3383        );
3384
3385        let (g, add_id) = build_add_graph();
3386        let order = topo_order(&g, add_id);
3387        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3388            if dev == DeviceLocation::Cpu {
3389                vec![BackendId::Cpu]
3390            } else {
3391                vec![]
3392            }
3393        };
3394        let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3395            vec![(BackendId::Cuda, cuda0)]
3396        };
3397        let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3398        let est = FlatEstimator { latency_ns: 100 };
3399        let cpu_caps_val = cpu_caps();
3400        let cuda_caps_val = crate::dispatch::derive_backend_caps(BackendId::Cuda, cuda0, &table);
3401        let caps_fn = |b: BackendId| -> Option<&BackendCapabilities> {
3402            match b {
3403                BackendId::Cpu => Some(&cpu_caps_val),
3404                BackendId::Cuda => Some(&cuda_caps_val),
3405                _ => None,
3406            }
3407        };
3408        let opts = PlanOptions::new()
3409            .with_pinned_device(DeviceLocation::Cpu)
3410            .with_placements_for_device(&placements_fn)
3411            .with_fallback_placements_for(&fallback_fn)
3412            .with_capabilities_for(&caps_fn)
3413            .with_transfer_estimator(&est)
3414            .with_input_residency(&residency_fn)
3415            .without_cost_placement();
3416        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3417        let set = plan.alternatives(add_id).unwrap();
3418        assert_eq!(
3419            set.winner().unwrap().device,
3420            DeviceLocation::Cpu,
3421            "without_cost_placement: the large GPU-favorable op stays on the \
3422             pinned CPU device (no relaxed cross-device enumeration)",
3423        );
3424        assert!(
3425            set.alternatives()
3426                .iter()
3427                .all(|c| c.device == DeviceLocation::Cpu),
3428            "no off-device candidate enumerated at all",
3429        );
3430    }
3431
3432    /// Stage-2 parity gate: a huge op legitimately moves — the
3433    /// kernel gap dwarfs the transfer. The surviving set lives
3434    /// entirely on the winner's device so dispatch-time selectors
3435    /// can't diverge from the residency stitch.
3436    #[test]
3437    fn compile_plan_relaxed_huge_op_moves_when_kernel_gap_dominates() {
3438        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3439        // CPU 10 ms vs CUDA 10 ns kernel; 1 µs per input crossing.
3440        let est = FlatEstimator { latency_ns: 1_000 };
3441        let set = relaxed_plan_with_costs(cost_10_000_000, cost_10, &est);
3442        let w = set.winner().unwrap();
3443        assert_eq!(w.device, cuda0, "kernel gap dominates → move");
3444        assert_eq!(
3445            w.inbound_transfer_ns, 2_000,
3446            "the move's two input crossings are priced on the winner",
3447        );
3448        assert!(
3449            set.alternatives().iter().all(|c| c.device == cuda0),
3450            "set pruned to the winner's device",
3451        );
3452    }
3453
3454    /// Stage-2 parity gate: zero signal everywhere (zero kernel
3455    /// costs, zero-cost transfers) must still keep the op local —
3456    /// the decision device enumerates first and the rank's stable
3457    /// sort preserves that order on ties.
3458    #[test]
3459    fn compile_plan_relaxed_zero_signal_ties_stay_local() {
3460        let est = FlatEstimator { latency_ns: 0 };
3461        let set = relaxed_plan_with_costs(unknown_cost, unknown_cost, &est);
3462        assert_eq!(
3463            set.winner().unwrap().device,
3464            DeviceLocation::Cpu,
3465            "ties break toward the decision device",
3466        );
3467    }
3468
3469    /// Stage-2 parity gate: single-device systems produce
3470    /// byte-identical plans with the estimator wired — the fallback
3471    /// enumerator has nothing to offer and no transfer term fires.
3472    #[test]
3473    fn compile_plan_relaxed_single_device_plan_unchanged() {
3474        let mut table = KernelBindingTable::new();
3475        register_add_f32(
3476            &mut table,
3477            BackendId::Cpu,
3478            noop_kernel,
3479            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3480        );
3481        let (g, add_id) = build_add_graph();
3482        let order = topo_order(&g, add_id);
3483        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3484            if dev == DeviceLocation::Cpu {
3485                vec![BackendId::Cpu]
3486            } else {
3487                vec![]
3488            }
3489        };
3490        // Single-device system: no other device exists.
3491        let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> { Vec::new() };
3492        let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3493        let cpu_caps_val = cpu_caps();
3494        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3495
3496        let base_opts = PlanOptions::new()
3497            .with_pinned_device(DeviceLocation::Cpu)
3498            .with_placements_for_device(&placements_fn)
3499            .with_fallback_placements_for(&fallback_fn)
3500            .with_capabilities_for(&caps_fn);
3501        let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
3502
3503        let est = FlatEstimator {
3504            latency_ns: 1_000_000,
3505        };
3506        let wired_opts = PlanOptions::new()
3507            .with_pinned_device(DeviceLocation::Cpu)
3508            .with_placements_for_device(&placements_fn)
3509            .with_fallback_placements_for(&fallback_fn)
3510            .with_capabilities_for(&caps_fn)
3511            .with_transfer_estimator(&est)
3512            .with_input_residency(&residency_fn);
3513        let wired = compile_plan(&g, &order, &table, &wired_opts).expect("wired");
3514
3515        let a = base.alternatives(add_id).unwrap();
3516        let b = wired.alternatives(add_id).unwrap();
3517        assert_eq!(a.len(), b.len(), "same candidate count");
3518        for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
3519            assert_eq!(ca.backend, cb.backend);
3520            assert_eq!(ca.device, cb.device);
3521            assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
3522            assert_eq!(ca.static_cost, cb.static_cost, "same Layer-1 cost");
3523            assert_eq!(cb.inbound_transfer_ns, 0, "no transfer term fires");
3524        }
3525        assert_eq!(a.context(), b.context(), "same decision context");
3526    }
3527
3528    /// Stage-2 hard pin: an explicit `Graph::placement` keeps the
3529    /// node on its device even with pricing active and a free
3530    /// "faster" remote sibling — the fallback enumerator is never
3531    /// consulted for the pinned node.
3532    #[test]
3533    fn compile_plan_relaxed_respects_explicit_placement_pin() {
3534        let mut table = KernelBindingTable::new();
3535        register_add_f32(
3536            &mut table,
3537            BackendId::Cpu,
3538            noop_kernel,
3539            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3540        );
3541        register_add_f32(
3542            &mut table,
3543            BackendId::Cuda,
3544            noop_kernel_b,
3545            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3546        );
3547        let (mut g, add_id) = build_add_graph();
3548        // Hard pin: scheduler / Judge-profiling decision.
3549        g.set_placement(add_id, DeviceLocation::Cpu);
3550        let order = topo_order(&g, add_id);
3551        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3552            if dev == DeviceLocation::Cpu {
3553                vec![BackendId::Cpu]
3554            } else {
3555                vec![]
3556            }
3557        };
3558        let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3559            panic!(
3560                "fallback consulted for a hard-pinned node — explicit \
3561                 placements must not enter the priced relax",
3562            );
3563        };
3564        let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3565        let est = FlatEstimator { latency_ns: 0 };
3566        let cpu_caps_val = cpu_caps();
3567        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3568        let opts = PlanOptions::new()
3569            .with_pinned_device(DeviceLocation::Cpu)
3570            .with_placements_for_device(&placements_fn)
3571            .with_fallback_placements_for(&fallback_fn)
3572            .with_capabilities_for(&caps_fn)
3573            .with_transfer_estimator(&est)
3574            .with_input_residency(&residency_fn);
3575        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3576        assert_eq!(
3577            plan.alternatives(add_id).unwrap().winner().unwrap().device,
3578            DeviceLocation::Cpu,
3579        );
3580    }
3581
3582    /// Stage-2 hard pin: destructive ops never enter the priced
3583    /// relax — a free, faster off-device sibling must not win.
3584    #[test]
3585    fn compile_plan_relaxed_destructive_never_moves() {
3586        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3587        let mut table = KernelBindingTable::new();
3588        table.register_full(
3589            OpKind::ReluInplace,
3590            &[DType::F32, DType::F32],
3591            BackendId::Cpu,
3592            noop_kernel,
3593            KernelCaps::empty(),
3594            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3595            cost_600,
3596        );
3597        table.register_full(
3598            OpKind::ReluInplace,
3599            &[DType::F32, DType::F32],
3600            BackendId::Cuda,
3601            noop_kernel_b,
3602            KernelCaps::empty(),
3603            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3604            cost_10,
3605        );
3606        let mut g = Graph::new();
3607        let lhs = g.push(Node {
3608            op: Op::Const,
3609            inputs: vec![],
3610            shape: Shape::from_dims(&[3]),
3611            dtype: DType::F32,
3612        });
3613        let relu = g.push(Node {
3614            op: Op::ReluInplace,
3615            inputs: vec![lhs],
3616            shape: Shape::from_dims(&[3]),
3617            dtype: DType::F32,
3618        });
3619        let order = topo_order(&g, relu);
3620        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
3621            if dev == DeviceLocation::Cpu {
3622                vec![BackendId::Cpu]
3623            } else {
3624                vec![]
3625            }
3626        };
3627        let fallback_fn = move |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3628            vec![(BackendId::Cuda, cuda0)]
3629        };
3630        let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3631        let est = FlatEstimator { latency_ns: 0 };
3632        let cpu_caps_val = cpu_caps();
3633        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3634        let opts = PlanOptions::new()
3635            .with_pinned_device(DeviceLocation::Cpu)
3636            .with_placements_for_device(&placements_fn)
3637            .with_fallback_placements_for(&fallback_fn)
3638            .with_capabilities_for(&caps_fn)
3639            .with_transfer_estimator(&est)
3640            .with_input_residency(&residency_fn);
3641        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3642        assert_eq!(
3643            plan.alternatives(relu).unwrap().winner().unwrap().device,
3644            DeviceLocation::Cpu,
3645            "destructive op stays on the device owning its mutation target",
3646        );
3647    }
3648
3649    /// Stage-2 fix of the picker-4b verifier minor: a pinned device
3650    /// whose registrations all fail the HARD filter chain falls
3651    /// back off-device like an empty enumeration (legacy/unpriced
3652    /// regime — no estimator configured).
3653    #[test]
3654    fn compile_plan_filter_rejected_pinned_device_falls_back() {
3655        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
3656        let mut table = KernelBindingTable::new();
3657        // The pinned CUDA device's only registration is NOT
3658        // bit-stable; the CPU sibling is.
3659        register_add_f32(
3660            &mut table,
3661            BackendId::Cuda,
3662            noop_kernel_b,
3663            PrecisionGuarantee {
3664                bit_stable_on_same_hardware: false,
3665                ..PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU
3666            },
3667        );
3668        register_add_f32(
3669            &mut table,
3670            BackendId::Cpu,
3671            noop_kernel,
3672            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3673        );
3674        let mut g = Graph::new();
3675        let lhs = g.push(Node {
3676            op: Op::Const,
3677            inputs: vec![],
3678            shape: Shape::from_dims(&[3]),
3679            dtype: DType::F32,
3680        });
3681        let add = g.push(Node {
3682            op: Op::Add,
3683            inputs: vec![lhs, lhs],
3684            shape: Shape::from_dims(&[3]),
3685            dtype: DType::F32,
3686        });
3687        let order = topo_order(&g, add);
3688        let placements_fn = move |dev: DeviceLocation| -> Vec<BackendId> {
3689            if dev == cuda0 {
3690                vec![BackendId::Cuda]
3691            } else {
3692                vec![]
3693            }
3694        };
3695        let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
3696            vec![(BackendId::Cpu, DeviceLocation::Cpu)]
3697        };
3698        let opts = PlanOptions::new()
3699            .without_cost_population()
3700            .with_pinned_device(cuda0)
3701            .with_placements_for_device(&placements_fn)
3702            .with_fallback_placements_for(&fallback_fn)
3703            .with_precision_requirement(PrecisionRequirement::BIT_STABLE);
3704        let plan = compile_plan(&g, &order, &table, &opts)
3705            .expect("filter-rejected pin falls back instead of erroring");
3706        let alts = plan.alternatives(add).expect("Add planned via fallback");
3707        assert_eq!(alts.len(), 1, "fallback set frozen to one winner");
3708        let w = alts.winner().unwrap();
3709        assert_eq!(w.backend, BackendId::Cpu);
3710        assert_eq!(w.device, DeviceLocation::Cpu);
3711        assert!(
3712            w.precision.bit_stable_on_same_hardware,
3713            "the admissible off-device sibling won",
3714        );
3715    }
3716
3717    /// Stage 2: without an estimator nothing prices — candidates
3718    /// keep `inbound_transfer_ns == 0` and the plan matches the
3719    /// estimator-less plan candidate-for-candidate even when an
3720    /// input-residency callback is supplied.
3721    #[test]
3722    fn compile_plan_without_estimator_prices_nothing() {
3723        let mut table = KernelBindingTable::new();
3724        register_add_f32(
3725            &mut table,
3726            BackendId::Cpu,
3727            noop_kernel,
3728            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3729        );
3730        let (g, add_id) = build_add_graph();
3731        let order = topo_order(&g, add_id);
3732        let cpu_caps_val = cpu_caps();
3733        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3734        let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
3735
3736        let base_opts = PlanOptions::new().with_capabilities_for(&caps_fn);
3737        let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
3738
3739        let with_residency = PlanOptions::new()
3740            .with_capabilities_for(&caps_fn)
3741            .with_input_residency(&residency_fn);
3742        let plan = compile_plan(&g, &order, &table, &with_residency).expect("plan");
3743
3744        let a = base.alternatives(add_id).unwrap();
3745        let b = plan.alternatives(add_id).unwrap();
3746        assert_eq!(a.len(), b.len());
3747        for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
3748            assert_eq!(ca.backend, cb.backend);
3749            assert_eq!(ca.device, cb.device);
3750            assert_eq!(ca.kernel as usize, cb.kernel as usize);
3751            assert_eq!(ca.inbound_transfer_ns, 0);
3752            assert_eq!(cb.inbound_transfer_ns, 0);
3753        }
3754    }
3755
3756    /// The `require_transfer_pricing` guard: a plan that DECLARES it needs
3757    /// transfer pricing but has no estimator wired must fail fast at plan-build
3758    /// time — never silently price transfers at zero (latency-greedy). This is
3759    /// the production regression guard: dropping `.with_transfer_estimator(...)`
3760    /// from the realize path (while it still requires pricing) turns this red.
3761    #[test]
3762    fn compile_plan_require_transfer_pricing_errors_without_estimator() {
3763        let mut table = KernelBindingTable::new();
3764        register_add_f32(
3765            &mut table,
3766            BackendId::Cpu,
3767            noop_kernel,
3768            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3769        );
3770        let (g, add_id) = build_add_graph();
3771        let order = topo_order(&g, add_id);
3772        let cpu_caps_val = cpu_caps();
3773        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3774
3775        // Declares it requires pricing, but wires NO estimator — the exact
3776        // shape of a realize path that forgot `.with_transfer_estimator(...)`.
3777        let opts = PlanOptions::new()
3778            .with_capabilities_for(&caps_fn)
3779            .require_transfer_pricing();
3780        let err = compile_plan(&g, &order, &table, &opts).unwrap_err();
3781        let msg = format!("{err:?}");
3782        assert!(
3783            msg.contains("transfer") && (msg.contains("estimator") || msg.contains("pricing")),
3784            "error should name the missing transfer estimator / pricing; got: {msg}",
3785        );
3786    }
3787
3788    /// The guard is satisfied when both `require_transfer_pricing` AND an
3789    /// estimator are set — planning proceeds normally.
3790    #[test]
3791    fn compile_plan_require_transfer_pricing_ok_with_estimator() {
3792        let mut table = KernelBindingTable::new();
3793        register_add_f32(
3794            &mut table,
3795            BackendId::Cpu,
3796            noop_kernel,
3797            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3798        );
3799        let (g, add_id) = build_add_graph();
3800        let order = topo_order(&g, add_id);
3801        let cpu_caps_val = cpu_caps();
3802        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
3803        let est = FlatEstimator { latency_ns: 1000 };
3804
3805        let opts = PlanOptions::new()
3806            .with_capabilities_for(&caps_fn)
3807            .with_transfer_estimator(&est)
3808            .require_transfer_pricing();
3809        let plan = compile_plan(&g, &order, &table, &opts)
3810            .expect("require_transfer_pricing WITH an estimator must plan fine");
3811        assert!(plan.alternatives(add_id).is_some());
3812    }
3813
3814    #[test]
3815    fn compile_plan_passes_input_layouts_to_filter_chain() {
3816        // Smoke test: a non-contiguous input + strided-input pref
3817        // in the default chain prefers the strided-capable kernel.
3818        // Register two CPU kernels, one with strided caps.
3819        let mut table = KernelBindingTable::new();
3820        table.register_full(
3821            OpKind::AddElementwise,
3822            &[DType::F32, DType::F32, DType::F32],
3823            BackendId::Cpu,
3824            noop_kernel,
3825            KernelCaps::empty(),
3826            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3827            unknown_cost,
3828        );
3829        table.register_full(
3830            OpKind::AddElementwise,
3831            &[DType::F32, DType::F32, DType::F32],
3832            BackendId::Cpu,
3833            noop_kernel_b,
3834            KernelCaps::strided_input(),
3835            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3836            unknown_cost,
3837        );
3838
3839        // Build a graph where the Add's LHS input is non-contiguous.
3840        let mut g = Graph::new();
3841        let lhs = g.push(Node {
3842            op: Op::Const,
3843            inputs: vec![],
3844            shape: Shape::from_dims(&[6]),
3845            dtype: DType::F32,
3846        });
3847        // Force a non-contiguous layout on lhs by setting a custom
3848        // stride via the graph's layout side-table.
3849        let strides: StrideVec = smallvec![2isize];
3850        g.set_layout(lhs, Layout::new(Shape::from_dims(&[6]), strides, 0));
3851        let rhs = g.push(Node {
3852            op: Op::Const,
3853            inputs: vec![],
3854            shape: Shape::from_dims(&[6]),
3855            dtype: DType::F32,
3856        });
3857        let add = g.push(Node {
3858            op: Op::Add,
3859            inputs: vec![lhs, rhs],
3860            shape: Shape::from_dims(&[6]),
3861            dtype: DType::F32,
3862        });
3863        g.set_target_backend(add, BackendId::Cpu);
3864        let order = topo_order(&g, add);
3865        let opts = PlanOptions::new().without_cost_population();
3866        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
3867        let alts = plan.alternatives(add).unwrap();
3868        // Strided-input preference narrowed to the strided-capable
3869        // kernel.
3870        assert_eq!(alts.len(), 1);
3871        assert!(alts.winner().unwrap().caps.strided_input);
3872    }
3873
3874    // =====================================================================
3875    // Planner Stage 3: carry-forward placement DP
3876    // =====================================================================
3877
3878    /// Byte-aware synthetic estimator: zero same-device, otherwise
3879    /// `latency + bytes·ns_per_byte`.
3880    struct BytesEstimator {
3881        latency_ns: u64,
3882        ns_per_byte: u64,
3883    }
3884
3885    impl crate::ranker::TransferEstimator for BytesEstimator {
3886        fn estimate_transfer_ns(
3887            &self,
3888            src: DeviceLocation,
3889            dst: DeviceLocation,
3890            bytes: u64,
3891        ) -> u64 {
3892            if src == dst {
3893                return 0;
3894            }
3895            self.latency_ns
3896                .saturating_add(bytes.saturating_mul(self.ns_per_byte))
3897        }
3898    }
3899
3900    fn cost_50(
3901        _: &[Shape],
3902        _: &[DType],
3903        _: &OpParams,
3904        _: &BackendCapabilities,
3905    ) -> crate::fused::CostEstimate {
3906        crate::fused::CostEstimate {
3907            flops: 50,
3908            bytes_moved: 0,
3909            kernel_overhead_ns: 0,
3910        }
3911    }
3912    fn cost_100(
3913        _: &[Shape],
3914        _: &[DType],
3915        _: &OpParams,
3916        _: &BackendCapabilities,
3917    ) -> crate::fused::CostEstimate {
3918        crate::fused::CostEstimate {
3919            flops: 100,
3920            bytes_moved: 0,
3921            kernel_overhead_ns: 0,
3922        }
3923    }
3924    fn cost_300(
3925        _: &[Shape],
3926        _: &[DType],
3927        _: &OpParams,
3928        _: &BackendCapabilities,
3929    ) -> crate::fused::CostEstimate {
3930        crate::fused::CostEstimate {
3931            flops: 300,
3932            bytes_moved: 0,
3933            kernel_overhead_ns: 0,
3934        }
3935    }
3936    fn cost_800(
3937        _: &[Shape],
3938        _: &[DType],
3939        _: &OpParams,
3940        _: &BackendCapabilities,
3941    ) -> crate::fused::CostEstimate {
3942        crate::fused::CostEstimate {
3943            flops: 800,
3944            bytes_moved: 0,
3945            kernel_overhead_ns: 0,
3946        }
3947    }
3948    fn cost_5000(
3949        _: &[Shape],
3950        _: &[DType],
3951        _: &OpParams,
3952        _: &BackendCapabilities,
3953    ) -> crate::fused::CostEstimate {
3954        crate::fused::CostEstimate {
3955            flops: 5000,
3956            bytes_moved: 0,
3957            kernel_overhead_ns: 0,
3958        }
3959    }
3960    fn cost_100_000(
3961        _: &[Shape],
3962        _: &[DType],
3963        _: &OpParams,
3964        _: &BackendCapabilities,
3965    ) -> crate::fused::CostEstimate {
3966        crate::fused::CostEstimate {
3967            flops: 100_000,
3968            bytes_moved: 0,
3969            kernel_overhead_ns: 0,
3970        }
3971    }
3972
3973    /// Register a unary `(F32 → F32)` kernel with an explicit cost.
3974    fn register_unary_f32(
3975        table: &mut KernelBindingTable,
3976        op: OpKind,
3977        backend: BackendId,
3978        kernel: crate::kernel::KernelRef,
3979        cost: crate::kernel::CostFn,
3980    ) {
3981        table.register_full(
3982            op,
3983            &[DType::F32, DType::F32],
3984            backend,
3985            kernel,
3986            KernelCaps::empty(),
3987            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3988            cost,
3989        );
3990    }
3991
3992    fn push_f32(g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize]) -> NodeId {
3993        g.push(Node {
3994            op,
3995            inputs,
3996            shape: Shape::from_dims(dims),
3997            dtype: DType::F32,
3998        })
3999    }
4000
4001    /// Stage 3 test (a): a mid-sequence GPU segment beats all-CPU
4002    /// and all-GPU, and the per-op GPU win (700 ns) is SMALLER than
4003    /// the crossing (1000 ns) — greedy would never move (the first
4004    /// op of the migration can't justify the crossing alone), but
4005    /// the accumulated DP state amortizes one entry + one exit
4006    /// crossing over the segment's combined win.
4007    ///
4008    /// Chain: c → n1(Sqr) → n2(Neg) → n3(Neg) → n4(Neg) → n5(Sqr).
4009    /// Sqr: CPU 100 / GPU 5000 (GPU-hostile endpoints).
4010    /// Neg: CPU 800 / GPU 100 (per-op win 700 < 1000 crossing).
4011    ///
4012    /// All-CPU = 100 + 3·800 + 100 = 2600.
4013    /// Mid-GPU = 100 + 1000 + 3·100 + 1000 + 100 = 2500. ← winner
4014    /// All-GPU = 1000 + 5000 + 3·100 + 5000 + 1000 = 12300.
4015    #[test]
4016    fn dp_mid_sequence_gpu_segment_beats_all_cpu_and_all_gpu() {
4017        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4018        let mut table = KernelBindingTable::new();
4019        register_unary_f32(
4020            &mut table,
4021            OpKind::SqrElementwise,
4022            BackendId::Cpu,
4023            noop_kernel,
4024            cost_100,
4025        );
4026        register_unary_f32(
4027            &mut table,
4028            OpKind::SqrElementwise,
4029            BackendId::Cuda,
4030            noop_kernel_b,
4031            cost_5000,
4032        );
4033        register_unary_f32(
4034            &mut table,
4035            OpKind::NegElementwise,
4036            BackendId::Cpu,
4037            noop_kernel,
4038            cost_800,
4039        );
4040        register_unary_f32(
4041            &mut table,
4042            OpKind::NegElementwise,
4043            BackendId::Cuda,
4044            noop_kernel_b,
4045            cost_100,
4046        );
4047
4048        let mut g = Graph::new();
4049        let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4050        let n1 = push_f32(&mut g, Op::Sqr, vec![c], &[4]);
4051        let n2 = push_f32(&mut g, Op::Neg, vec![n1], &[4]);
4052        let n3 = push_f32(&mut g, Op::Neg, vec![n2], &[4]);
4053        let n4 = push_f32(&mut g, Op::Neg, vec![n3], &[4]);
4054        let n5 = push_f32(&mut g, Op::Sqr, vec![n4], &[4]);
4055        let order = topo_order(&g, n5);
4056
4057        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4058            if dev == DeviceLocation::Cpu {
4059                vec![BackendId::Cpu]
4060            } else {
4061                vec![BackendId::Cuda]
4062            }
4063        };
4064        let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4065            if dev == DeviceLocation::Cpu {
4066                vec![(BackendId::Cuda, cuda0)]
4067            } else {
4068                vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4069            }
4070        };
4071        let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4072            (id == c).then_some(DeviceLocation::Cpu)
4073        };
4074        let est = FlatEstimator { latency_ns: 1_000 };
4075        let cpu_caps_val = cpu_caps();
4076        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4077        let opts = PlanOptions::new()
4078            .with_pinned_device(DeviceLocation::Cpu)
4079            .with_placements_for_device(&placements_fn)
4080            .with_fallback_placements_for(&fallback_fn)
4081            .with_capabilities_for(&caps_fn)
4082            .with_transfer_estimator(&est)
4083            .with_input_residency(&residency_fn);
4084        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4085
4086        let dev_of = |id: NodeId| plan.alternatives(id).unwrap().winner().unwrap().device;
4087        assert_eq!(
4088            dev_of(n1),
4089            DeviceLocation::Cpu,
4090            "GPU-hostile entry stays CPU"
4091        );
4092        assert_eq!(dev_of(n2), cuda0, "segment start migrates");
4093        assert_eq!(dev_of(n3), cuda0, "segment interior stays GPU");
4094        assert_eq!(dev_of(n4), cuda0, "segment end stays GPU");
4095        assert_eq!(dev_of(n5), DeviceLocation::Cpu, "GPU-hostile exit returns");
4096
4097        // Transfer diagnostics on the final sets: the two crossings
4098        // are priced exactly once each, on the segment boundary
4099        // winners.
4100        let inbound = |id: NodeId| {
4101            plan.alternatives(id)
4102                .unwrap()
4103                .winner()
4104                .unwrap()
4105                .inbound_transfer_ns
4106        };
4107        assert_eq!(
4108            inbound(n2),
4109            1_000,
4110            "entry crossing priced on the first GPU op"
4111        );
4112        assert_eq!(inbound(n3), 0);
4113        assert_eq!(inbound(n4), 0);
4114        assert_eq!(inbound(n5), 1_000, "exit crossing priced on the return op");
4115
4116        // The surviving sets live on ONE device each (residency
4117        // stitch invariant).
4118        for id in [n1, n2, n3, n4, n5] {
4119            let d = dev_of(id);
4120            assert!(
4121                plan.alternatives(id)
4122                    .unwrap()
4123                    .alternatives()
4124                    .iter()
4125                    .all(|c| c.device == d),
4126                "set pruned to the DP-committed device",
4127            );
4128        }
4129    }
4130
4131    /// Stage 3 test (b): a FUSED op that is locally faster on device
4132    /// A loses to staying on B when its stranding cost exceeds its
4133    /// win — the over-move case greedy inbound pricing cannot see.
4134    ///
4135    /// Chain: c → n1(Neg) → f(Fused SoftmaxLastDim) → n2(Sqr, CPU-only).
4136    /// Estimator: 10 ns latency + 1 ns/byte. n1 output is 4 bytes;
4137    /// f's output is 1024 bytes (shapes are synthetic — compile_plan
4138    /// never executes).
4139    ///
4140    /// n1: CPU 100 000 / GPU 100 → migrates to GPU regardless.
4141    /// f:  CPU 300 / GPU 100. Arriving states: CPU = 300 + 14 = 428
4142    /// (via GPU n1), GPU = 100 + 114 = 214 — locally GPU wins, and
4143    /// greedy would commit it (inbound favors GPU: 100 + 0 < 300 +
4144    /// 14). But f's 1024-byte output must land on CPU for n2:
4145    /// GPU 214 + 1034 = 1248 vs CPU 428 → the DP keeps f on CPU.
4146    #[test]
4147    fn dp_fused_op_loses_when_stranding_exceeds_local_win() {
4148        use fuel_graph::registry::{FusedOpParams, FusedOps};
4149
4150        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4151        let mut table = KernelBindingTable::new();
4152        register_unary_f32(
4153            &mut table,
4154            OpKind::NegElementwise,
4155            BackendId::Cpu,
4156            noop_kernel,
4157            cost_100_000,
4158        );
4159        register_unary_f32(
4160            &mut table,
4161            OpKind::NegElementwise,
4162            BackendId::Cuda,
4163            noop_kernel_b,
4164            cost_100,
4165        );
4166        register_unary_f32(
4167            &mut table,
4168            OpKind::SoftmaxLastDim,
4169            BackendId::Cpu,
4170            noop_kernel,
4171            cost_300,
4172        );
4173        register_unary_f32(
4174            &mut table,
4175            OpKind::SoftmaxLastDim,
4176            BackendId::Cuda,
4177            noop_kernel_b,
4178            cost_100,
4179        );
4180        // Sqr exists ONLY on CPU — the chain's anchor.
4181        register_unary_f32(
4182            &mut table,
4183            OpKind::SqrElementwise,
4184            BackendId::Cpu,
4185            noop_kernel,
4186            cost_100,
4187        );
4188
4189        let mut g = Graph::new();
4190        let c = push_f32(&mut g, Op::Const, vec![], &[1]);
4191        let n1 = push_f32(&mut g, Op::Neg, vec![c], &[1]);
4192        let f = push_f32(
4193            &mut g,
4194            Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim),
4195            vec![n1],
4196            &[256],
4197        );
4198        let n2 = push_f32(&mut g, Op::Sqr, vec![f], &[256]);
4199        let order = topo_order(&g, n2);
4200
4201        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4202            if dev == DeviceLocation::Cpu {
4203                vec![BackendId::Cpu]
4204            } else {
4205                vec![BackendId::Cuda]
4206            }
4207        };
4208        let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4209            if dev == DeviceLocation::Cpu {
4210                vec![(BackendId::Cuda, cuda0)]
4211            } else {
4212                vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4213            }
4214        };
4215        let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4216            (id == c).then_some(DeviceLocation::Cpu)
4217        };
4218        let est = BytesEstimator {
4219            latency_ns: 10,
4220            ns_per_byte: 1,
4221        };
4222        let cpu_caps_val = cpu_caps();
4223        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4224        let opts = PlanOptions::new()
4225            .with_pinned_device(DeviceLocation::Cpu)
4226            .with_placements_for_device(&placements_fn)
4227            .with_fallback_placements_for(&fallback_fn)
4228            .with_capabilities_for(&caps_fn)
4229            .with_transfer_estimator(&est)
4230            .with_input_residency(&residency_fn);
4231        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4232
4233        let dev_of = |id: NodeId| plan.alternatives(id).unwrap().winner().unwrap().device;
4234        assert_eq!(dev_of(n1), cuda0, "the huge-win producer migrates");
4235        assert_eq!(
4236            dev_of(f),
4237            DeviceLocation::Cpu,
4238            "the locally-faster fused op stays where its output is needed",
4239        );
4240        assert_eq!(dev_of(n2), DeviceLocation::Cpu);
4241        assert!(
4242            plan.alternatives(f)
4243                .unwrap()
4244                .alternatives()
4245                .iter()
4246                .all(|c| c.device == DeviceLocation::Cpu),
4247            "fused set pruned to the committed device",
4248        );
4249    }
4250
4251    /// Stage 3 test (c): exit pricing — a final op stays on the
4252    /// realize target although moving would win locally, because
4253    /// the return crossing prices the move out.
4254    ///
4255    /// Inputs resident on GPU; realize target CPU; flat 1000 ns
4256    /// crossings. Local view: GPU 100 + 0 ≪ CPU 50 + 1000. With the
4257    /// exit: GPU 100 + 1000 = 1100 vs CPU 1050 → CPU.
4258    #[test]
4259    fn dp_exit_pricing_keeps_final_op_on_realize_target() {
4260        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4261        let mut table = KernelBindingTable::new();
4262        register_unary_f32(
4263            &mut table,
4264            OpKind::NegElementwise,
4265            BackendId::Cpu,
4266            noop_kernel,
4267            cost_50,
4268        );
4269        register_unary_f32(
4270            &mut table,
4271            OpKind::NegElementwise,
4272            BackendId::Cuda,
4273            noop_kernel_b,
4274            cost_100,
4275        );
4276
4277        let mut g = Graph::new();
4278        let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4279        let n = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4280        let order = topo_order(&g, n);
4281
4282        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4283            if dev == DeviceLocation::Cpu {
4284                vec![BackendId::Cpu]
4285            } else {
4286                vec![BackendId::Cuda]
4287            }
4288        };
4289        let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4290            if dev == DeviceLocation::Cpu {
4291                vec![(BackendId::Cuda, cuda0)]
4292            } else {
4293                vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4294            }
4295        };
4296        let residency_fn =
4297            move |id: NodeId| -> Option<DeviceLocation> { (id == c).then_some(cuda0) };
4298        let est = FlatEstimator { latency_ns: 1_000 };
4299        let cpu_caps_val = cpu_caps();
4300        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4301        let opts = PlanOptions::new()
4302            .with_pinned_device(DeviceLocation::Cpu)
4303            .with_placements_for_device(&placements_fn)
4304            .with_fallback_placements_for(&fallback_fn)
4305            .with_capabilities_for(&caps_fn)
4306            .with_transfer_estimator(&est)
4307            .with_input_residency(&residency_fn);
4308        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4309        let w = plan.alternatives(n).unwrap().winner().unwrap();
4310        assert_eq!(
4311            w.device,
4312            DeviceLocation::Cpu,
4313            "exit pricing flips the locally-winning GPU placement",
4314        );
4315        assert_eq!(
4316            w.inbound_transfer_ns, 1_000,
4317            "the GPU-resident input's crossing is priced on the CPU winner",
4318        );
4319    }
4320
4321    /// Stage 3 test (c) inverse: when the kernel gap dwarfs both
4322    /// crossings, the final op legitimately moves despite the exit.
4323    #[test]
4324    fn dp_exit_pricing_does_not_pin_when_kernel_gap_dominates() {
4325        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4326        let mut table = KernelBindingTable::new();
4327        register_unary_f32(
4328            &mut table,
4329            OpKind::NegElementwise,
4330            BackendId::Cpu,
4331            noop_kernel,
4332            cost_10_000_000,
4333        );
4334        register_unary_f32(
4335            &mut table,
4336            OpKind::NegElementwise,
4337            BackendId::Cuda,
4338            noop_kernel_b,
4339            cost_100,
4340        );
4341
4342        let mut g = Graph::new();
4343        let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4344        let n = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4345        let order = topo_order(&g, n);
4346
4347        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4348            if dev == DeviceLocation::Cpu {
4349                vec![BackendId::Cpu]
4350            } else {
4351                vec![BackendId::Cuda]
4352            }
4353        };
4354        let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4355            if dev == DeviceLocation::Cpu {
4356                vec![(BackendId::Cuda, cuda0)]
4357            } else {
4358                vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4359            }
4360        };
4361        let residency_fn =
4362            move |id: NodeId| -> Option<DeviceLocation> { (id == c).then_some(cuda0) };
4363        let est = FlatEstimator { latency_ns: 1_000 };
4364        let cpu_caps_val = cpu_caps();
4365        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4366        let opts = PlanOptions::new()
4367            .with_pinned_device(DeviceLocation::Cpu)
4368            .with_placements_for_device(&placements_fn)
4369            .with_fallback_placements_for(&fallback_fn)
4370            .with_capabilities_for(&caps_fn)
4371            .with_transfer_estimator(&est)
4372            .with_input_residency(&residency_fn);
4373        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4374        assert_eq!(
4375            plan.alternatives(n).unwrap().winner().unwrap().device,
4376            cuda0
4377        );
4378    }
4379
4380    /// Stage 3 test (d): single-DEVICE plan equality. Two backends
4381    /// co-located on one device with the full Stage-3 option set
4382    /// wired (estimator + fallback + residency) produce the same
4383    /// plan, candidate-for-candidate, as the unwired baseline — the
4384    /// DP never opens a row when only one device has candidates.
4385    #[test]
4386    fn dp_single_device_plan_equals_greedy_plan() {
4387        let mut table = KernelBindingTable::new();
4388        register_add_f32(
4389            &mut table,
4390            BackendId::Cpu,
4391            noop_kernel,
4392            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4393        );
4394        register_add_f32(
4395            &mut table,
4396            BackendId::Cuda,
4397            noop_kernel_b,
4398            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4399        );
4400        let (g, add_id) = build_add_graph();
4401        let order = topo_order(&g, add_id);
4402        // Both backends co-located at DeviceLocation::Cpu — one
4403        // device, two backends.
4404        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4405            if dev == DeviceLocation::Cpu {
4406                vec![BackendId::Cpu, BackendId::Cuda]
4407            } else {
4408                vec![]
4409            }
4410        };
4411        let fallback_fn = |_dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> { Vec::new() };
4412        let residency_fn = |_id: NodeId| -> Option<DeviceLocation> { Some(DeviceLocation::Cpu) };
4413        let cpu_caps_val = cpu_caps();
4414        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4415
4416        let base_opts = PlanOptions::new()
4417            .with_placements_for_device(&placements_fn)
4418            .with_capabilities_for(&caps_fn);
4419        let base = compile_plan(&g, &order, &table, &base_opts).expect("base");
4420
4421        let est = FlatEstimator {
4422            latency_ns: 1_000_000,
4423        };
4424        let wired_opts = PlanOptions::new()
4425            .with_placements_for_device(&placements_fn)
4426            .with_fallback_placements_for(&fallback_fn)
4427            .with_capabilities_for(&caps_fn)
4428            .with_transfer_estimator(&est)
4429            .with_input_residency(&residency_fn);
4430        let wired = compile_plan(&g, &order, &table, &wired_opts).expect("wired");
4431
4432        assert_eq!(base.alternatives.len(), wired.alternatives.len());
4433        let a = base.alternatives(add_id).unwrap();
4434        let b = wired.alternatives(add_id).unwrap();
4435        assert_eq!(a.len(), b.len(), "same candidate count");
4436        for (ca, cb) in a.alternatives().iter().zip(b.alternatives()) {
4437            assert_eq!(ca.backend, cb.backend);
4438            assert_eq!(ca.device, cb.device);
4439            assert_eq!(ca.kernel as usize, cb.kernel as usize, "same kernel ref");
4440            assert_eq!(ca.static_cost, cb.static_cost, "same Layer-1 cost");
4441            assert_eq!(cb.inbound_transfer_ns, 0, "no transfer term fires");
4442        }
4443        assert_eq!(a.context(), b.context(), "same decision context");
4444    }
4445
4446    /// Stage 3 test (e) helper: build the diamond (a → b, a → c2,
4447    /// b+c2 → d), plan it with the given crossing latency, and
4448    /// assert every kernel-bearing node committed to `expect`.
4449    fn run_diamond_regime(latency_ns: u64, expect: DeviceLocation) {
4450        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4451        let mut table = KernelBindingTable::new();
4452        for op in [
4453            OpKind::NegElementwise,
4454            OpKind::SqrElementwise,
4455            OpKind::ReluElementwise,
4456        ] {
4457            register_unary_f32(&mut table, op, BackendId::Cpu, noop_kernel, cost_100);
4458            register_unary_f32(&mut table, op, BackendId::Cuda, noop_kernel_b, cost_10);
4459        }
4460        table.register_full(
4461            OpKind::AddElementwise,
4462            &[DType::F32, DType::F32, DType::F32],
4463            BackendId::Cpu,
4464            noop_kernel,
4465            KernelCaps::empty(),
4466            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4467            cost_100,
4468        );
4469        table.register_full(
4470            OpKind::AddElementwise,
4471            &[DType::F32, DType::F32, DType::F32],
4472            BackendId::Cuda,
4473            noop_kernel_b,
4474            KernelCaps::empty(),
4475            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4476            cost_10,
4477        );
4478
4479        let mut g = Graph::new();
4480        let c0 = push_f32(&mut g, Op::Const, vec![], &[4]);
4481        let a = push_f32(&mut g, Op::Neg, vec![c0], &[4]);
4482        let b = push_f32(&mut g, Op::Sqr, vec![a], &[4]);
4483        let c2 = push_f32(&mut g, Op::Relu, vec![a], &[4]);
4484        let d = push_f32(&mut g, Op::Add, vec![b, c2], &[4]);
4485        let order = topo_order(&g, d);
4486
4487        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4488            if dev == DeviceLocation::Cpu {
4489                vec![BackendId::Cpu]
4490            } else {
4491                vec![BackendId::Cuda]
4492            }
4493        };
4494        let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4495            if dev == DeviceLocation::Cpu {
4496                vec![(BackendId::Cuda, cuda0)]
4497            } else {
4498                vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4499            }
4500        };
4501        let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4502            (id == c0).then_some(DeviceLocation::Cpu)
4503        };
4504        let est = FlatEstimator { latency_ns };
4505        let cpu_caps_val = cpu_caps();
4506        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4507        let opts = PlanOptions::new()
4508            .with_pinned_device(DeviceLocation::Cpu)
4509            .with_placements_for_device(&placements_fn)
4510            .with_fallback_placements_for(&fallback_fn)
4511            .with_capabilities_for(&caps_fn)
4512            .with_transfer_estimator(&est)
4513            .with_input_residency(&residency_fn);
4514        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4515        for id in [a, b, c2, d] {
4516            assert_eq!(
4517                plan.alternatives(id).unwrap().winner().unwrap().device,
4518                expect,
4519                "diamond join must commit a consistent placement",
4520            );
4521        }
4522    }
4523
4524    /// Stage 3 test (e): a diamond merges without panicking and
4525    /// commits a consistent placement. Both cost regimes exercised:
4526    /// transfers dominate → everything stays on CPU; kernel gap
4527    /// dominates with free transfers → everything moves to the GPU.
4528    #[test]
4529    fn dp_diamond_join_merges_consistently() {
4530        // 1 ms crossings — the 90 ns/op GPU win never pays.
4531        run_diamond_regime(1_000_000, DeviceLocation::Cpu);
4532        // Free transfers + 10× kernel gap.
4533        run_diamond_regime(0, DeviceLocation::Cuda { gpu_id: 0 });
4534    }
4535
4536    /// Stage 3 perf guard: the DP is O(nodes × devices²). A
4537    /// 1000-node chain with two devices must plan comfortably under
4538    /// a wall-clock sanity bound (expected: low milliseconds — the
4539    /// generous bound only guards against accidental quadratic
4540    /// blowups in nodes).
4541    #[test]
4542    fn dp_thousand_node_chain_plans_within_sanity_bound() {
4543        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4544        let mut table = KernelBindingTable::new();
4545        // Equal costs — ties must break toward the decision device
4546        // along the whole chain.
4547        register_unary_f32(
4548            &mut table,
4549            OpKind::NegElementwise,
4550            BackendId::Cpu,
4551            noop_kernel,
4552            cost_100,
4553        );
4554        register_unary_f32(
4555            &mut table,
4556            OpKind::NegElementwise,
4557            BackendId::Cuda,
4558            noop_kernel_b,
4559            cost_100,
4560        );
4561
4562        let mut g = Graph::new();
4563        let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4564        let mut prev = c;
4565        let mut nodes = Vec::with_capacity(1000);
4566        for _ in 0..1000 {
4567            let n = push_f32(&mut g, Op::Neg, vec![prev], &[4]);
4568            nodes.push(n);
4569            prev = n;
4570        }
4571        let order = topo_order(&g, prev);
4572
4573        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4574            if dev == DeviceLocation::Cpu {
4575                vec![BackendId::Cpu]
4576            } else {
4577                vec![BackendId::Cuda]
4578            }
4579        };
4580        let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4581            if dev == DeviceLocation::Cpu {
4582                vec![(BackendId::Cuda, cuda0)]
4583            } else {
4584                vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4585            }
4586        };
4587        let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4588            (id == c).then_some(DeviceLocation::Cpu)
4589        };
4590        let est = FlatEstimator { latency_ns: 10 };
4591        let cpu_caps_val = cpu_caps();
4592        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4593        let opts = PlanOptions::new()
4594            .with_pinned_device(DeviceLocation::Cpu)
4595            .with_placements_for_device(&placements_fn)
4596            .with_fallback_placements_for(&fallback_fn)
4597            .with_capabilities_for(&caps_fn)
4598            .with_transfer_estimator(&est)
4599            .with_input_residency(&residency_fn);
4600
4601        let start = std::time::Instant::now();
4602        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4603        let elapsed = start.elapsed();
4604        assert!(
4605            elapsed.as_secs() < 5,
4606            "1000-node DP plan took {elapsed:?} — pathological scaling",
4607        );
4608
4609        assert_eq!(plan.alternatives.len(), 1000);
4610        for &n in &nodes {
4611            assert_eq!(
4612                plan.alternatives(n).unwrap().winner().unwrap().device,
4613                DeviceLocation::Cpu,
4614                "equal-cost ties break toward the decision device end-to-end",
4615            );
4616        }
4617    }
4618
4619    /// Stage 3: a view-shaped pass-through between two DP nodes
4620    /// keeps the chain connected (the alias map) — the segment still
4621    /// migrates as one unit instead of breaking at the Reshape.
4622    #[test]
4623    fn dp_chain_connects_through_view_passthroughs() {
4624        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
4625        let mut table = KernelBindingTable::new();
4626        // Per-op win 700 < 1000 crossing; combined win 2100 > 2000 —
4627        // the segment only migrates if the chain survives the
4628        // Reshape between n1 and n2.
4629        register_unary_f32(
4630            &mut table,
4631            OpKind::NegElementwise,
4632            BackendId::Cpu,
4633            noop_kernel,
4634            cost_800,
4635        );
4636        register_unary_f32(
4637            &mut table,
4638            OpKind::NegElementwise,
4639            BackendId::Cuda,
4640            noop_kernel_b,
4641            cost_100,
4642        );
4643
4644        let mut g = Graph::new();
4645        let c = push_f32(&mut g, Op::Const, vec![], &[4]);
4646        let n1 = push_f32(&mut g, Op::Neg, vec![c], &[4]);
4647        let r = push_f32(
4648            &mut g,
4649            Op::Reshape(Shape::from_dims(&[2, 2])),
4650            vec![n1],
4651            &[2, 2],
4652        );
4653        let n2 = push_f32(&mut g, Op::Neg, vec![r], &[2, 2]);
4654        let n3 = push_f32(&mut g, Op::Neg, vec![n2], &[2, 2]);
4655        let order = topo_order(&g, n3);
4656
4657        let placements_fn = |dev: DeviceLocation| -> Vec<BackendId> {
4658            if dev == DeviceLocation::Cpu {
4659                vec![BackendId::Cpu]
4660            } else {
4661                vec![BackendId::Cuda]
4662            }
4663        };
4664        let fallback_fn = move |dev: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
4665            if dev == DeviceLocation::Cpu {
4666                vec![(BackendId::Cuda, cuda0)]
4667            } else {
4668                vec![(BackendId::Cpu, DeviceLocation::Cpu)]
4669            }
4670        };
4671        let residency_fn = move |id: NodeId| -> Option<DeviceLocation> {
4672            (id == c).then_some(DeviceLocation::Cpu)
4673        };
4674        let est = FlatEstimator { latency_ns: 1_000 };
4675        let cpu_caps_val = cpu_caps();
4676        let caps_fn = |_: BackendId| Some(&cpu_caps_val);
4677        let opts = PlanOptions::new()
4678            .with_pinned_device(DeviceLocation::Cpu)
4679            .with_placements_for_device(&placements_fn)
4680            .with_fallback_placements_for(&fallback_fn)
4681            .with_capabilities_for(&caps_fn)
4682            .with_transfer_estimator(&est)
4683            .with_input_residency(&residency_fn);
4684        let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4685
4686        // All-CPU = 2400; migrate-at-n1 = 3×100 + 1000 (entry) +
4687        // 1000 (exit) = 2300 → the whole segment moves, THROUGH the
4688        // reshape.
4689        for id in [n1, n2, n3] {
4690            assert_eq!(
4691                plan.alternatives(id).unwrap().winner().unwrap().device,
4692                cuda0,
4693                "the chain must not break at the Reshape pass-through",
4694            );
4695        }
4696        assert!(
4697            plan.alternatives(r).is_none(),
4698            "Reshape carries no plan entry"
4699        );
4700    }
4701
4702    // =====================================================================
4703    // Baracuda structural-miss telemetry: the LIVE wire-in at the dispatch
4704    // pick site (behind the `telemetry` feature).
4705    // =====================================================================
4706    #[cfg(feature = "telemetry")]
4707    mod telemetry_wiring {
4708        use super::*;
4709        use crate::telemetry::{
4710            Contiguity, FdxOperandDesc, HwStamp, StructureKeyProvider, StructureKeyToken,
4711            TelemetryConfig, TelemetryHooks, TelemetryMode, TelemetrySink,
4712        };
4713        use std::sync::Mutex;
4714
4715        /// A stub provider that echoes the `op_class` + the LIVE operand count
4716        /// into the token, so a test can prove the live operands reached the
4717        /// provider verbatim (Fuel returns the token as-is).
4718        struct StubProvider;
4719        impl StructureKeyProvider for StubProvider {
4720            fn structure_key(
4721                &self,
4722                op_class: &str,
4723                operands: &[FdxOperandDesc],
4724                _arch: &str,
4725            ) -> Option<StructureKeyToken> {
4726                Some(StructureKeyToken(format!(
4727                    "{op_class}:stub:n={}",
4728                    operands.len()
4729                )))
4730            }
4731        }
4732
4733        fn cpu_hw() -> HwStamp {
4734            HwStamp {
4735                compute_capability: None,
4736                hardware_sku: "test-cpu".into(),
4737                driver_version: "n/a".into(),
4738            }
4739        }
4740
4741        /// BORN-RED (union row 172): before this wire-in no production path
4742        /// built a contraction fact, so planning a `MatMul` left the sink's
4743        /// derived-contraction ledger empty. `Op::MatMul` now declares its
4744        /// roles and Fuel's own `sk8` derivation runs at the telemetry call.
4745        #[test]
4746        fn a_matmul_node_reaches_the_contraction_derivation() {
4747            let mut table = KernelBindingTable::new();
4748            table.register_full_with_source_generic(
4749                OpKind::MatMul,
4750                &[DType::F32, DType::F32, DType::F32],
4751                BackendId::Cpu,
4752                noop_kernel,
4753                KernelCaps::strided_input(),
4754                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4755                unknown_cost,
4756                "test-matmul",
4757                false,
4758                0,
4759                None,
4760            );
4761            let mut g = Graph::new();
4762            let mut konst = |dims: &[usize]| {
4763                g.push(Node {
4764                    op: Op::Const,
4765                    inputs: vec![],
4766                    shape: Shape::from_dims(dims),
4767                    dtype: DType::F32,
4768                })
4769            };
4770            let (lhs, rhs) = (konst(&[8, 64]), konst(&[64, 16]));
4771            let mm = g.push(Node {
4772                op: Op::MatMul,
4773                inputs: vec![lhs, rhs],
4774                shape: Shape::from_dims(&[8, 16]),
4775                dtype: DType::F32,
4776            });
4777            let order = topo_order(&g, mm);
4778            let sink = Mutex::new(TelemetrySink::new());
4779            let provider = StubProvider;
4780            let config = TelemetryConfig {
4781                mode: TelemetryMode::Coarse,
4782                out_path: None,
4783            };
4784            let hw = HwStamp {
4785                compute_capability: Some((8, 9)),
4786                hardware_sku: "test-cuda".into(),
4787                driver_version: "n/a".into(),
4788            };
4789            let hooks = TelemetryHooks {
4790                config: &config,
4791                sink: &sink,
4792                provider: &provider,
4793                hw,
4794            };
4795            let opts = PlanOptions::new()
4796                .without_cost_population()
4797                .with_pinned_device(DeviceLocation::Cpu)
4798                .with_telemetry(&hooks);
4799            let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4800            let keys = sink
4801                .into_inner()
4802                .expect("sink lock")
4803                .derived_contraction_keys();
4804            assert_eq!(keys.len(), 1, "{keys:?}");
4805            assert!(keys[0].0.starts_with("sk8|ctr|f32|cuda:sm89|"), "{keys:?}");
4806            assert_eq!(keys[0].1, 1);
4807        }
4808
4809        /// A table with ONLY a generic-fallback Add binding at
4810        /// `(AddElementwise, [F32;3], Cpu)` — a generic-only cell. The
4811        /// `is_generic = true` bit is exactly what an FKC import of a
4812        /// generic-strided contract would stamp.
4813        fn generic_only_add_table() -> KernelBindingTable {
4814            let mut table = KernelBindingTable::new();
4815            table.register_full_with_source_generic(
4816                OpKind::AddElementwise,
4817                &[DType::F32, DType::F32, DType::F32],
4818                BackendId::Cpu,
4819                noop_kernel,
4820                KernelCaps::strided_input(),
4821                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4822                unknown_cost,
4823                "baracuda-generic-strided",
4824                true, // the FKC-computed generic-fallback bit
4825                0,    // revision UNTRACKED (test binding carries no revision)
4826                None, // no declared cost-expression AST (test binding)
4827            );
4828            table
4829        }
4830
4831        /// BORN-RED: a generic-only cell + a stub provider + a sink threaded
4832        /// through `PlanOptions` ⇒ the realize/compile-plan path leaves the
4833        /// sink holding exactly ONE aggregated `MissRecord` whose `wanted`
4834        /// token reflects the LIVE operands, whose `fallback` is the generic
4835        /// binding's `ImplId`, and whose `hw` is the dispatching device's
4836        /// stamp.
4837        ///
4838        /// This was RED before the wire-in: `compile_plan` never called
4839        /// `detect_miss`, so the sink stayed empty. GREEN once the post-plan
4840        /// emission pass resolves each winner back to its binding entry and
4841        /// emits for the generic ones.
4842        #[test]
4843        fn generic_only_cell_emits_one_aggregated_miss_through_compile_plan() {
4844            let table = generic_only_add_table();
4845            let (g, add_id) = build_add_graph();
4846            let order = topo_order(&g, add_id);
4847
4848            let sink = Mutex::new(TelemetrySink::new());
4849            let provider = StubProvider;
4850            let config = TelemetryConfig {
4851                mode: TelemetryMode::Coarse,
4852                out_path: None,
4853            };
4854            let hooks = TelemetryHooks {
4855                config: &config,
4856                sink: &sink,
4857                provider: &provider,
4858                hw: cpu_hw(),
4859            };
4860            let opts = PlanOptions::new()
4861                .without_cost_population()
4862                .with_telemetry(&hooks);
4863            let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4864
4865            let sink = sink.into_inner().expect("sink lock");
4866            assert_eq!(
4867                sink.miss_cell_count(),
4868                1,
4869                "a generic-only cell must emit exactly one aggregated miss cell",
4870            );
4871            let recs = sink.miss_records();
4872            assert_eq!(recs.len(), 1);
4873            // OpKind Debug = "AddElementwise"; the Add node has TWO inputs plus
4874            // its OUTPUT operand (inputs-then-output), all of which flowed to
4875            // the provider as FDX descriptors ⇒ n=3.
4876            assert_eq!(
4877                recs[0].wanted,
4878                StructureKeyToken("AddElementwise:stub:n=3".into()),
4879                "the wanted token must reflect the live op_class + operands",
4880            );
4881            assert_eq!(recs[0].fallback.kernel_source, "baracuda-generic-strided");
4882            assert_eq!(recs[0].fallback.op, OpKind::AddElementwise);
4883            assert_eq!(recs[0].fallback.backend, BackendId::Cpu);
4884            assert_eq!(
4885                recs[0].fallback.dtypes,
4886                vec![DType::F32, DType::F32, DType::F32],
4887            );
4888            assert_eq!(recs[0].count, 1);
4889            assert_eq!(recs[0].hw, cpu_hw());
4890        }
4891
4892        /// GUARD: telemetry `Off` ⇒ zero emission and no behavior change. The
4893        /// same generic-only cell, but the config is the default (`Off`): the
4894        /// sink stays empty and the plan is unchanged (the Add still carries
4895        /// its single generic alternative). The Off gate is the first,
4896        /// branch-predictable check in the emission pass.
4897        #[test]
4898        fn telemetry_off_emits_nothing_and_does_not_change_the_plan() {
4899            let table = generic_only_add_table();
4900            let (g, add_id) = build_add_graph();
4901            let order = topo_order(&g, add_id);
4902
4903            let sink = Mutex::new(TelemetrySink::new());
4904            let provider = StubProvider;
4905            let config = TelemetryConfig::default(); // Off
4906            let hooks = TelemetryHooks {
4907                config: &config,
4908                sink: &sink,
4909                provider: &provider,
4910                hw: cpu_hw(),
4911            };
4912            let opts = PlanOptions::new()
4913                .without_cost_population()
4914                .with_telemetry(&hooks);
4915            let plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4916
4917            assert!(
4918                sink.into_inner().expect("sink lock").is_empty(),
4919                "Off mode must emit nothing",
4920            );
4921            // No behavior change: the Add still carries its generic alternative.
4922            let alts = plan.alternatives(add_id).expect("Add alternatives present");
4923            assert_eq!(alts.len(), 1);
4924            assert_eq!(alts.winner().unwrap().backend, BackendId::Cpu);
4925        }
4926
4927        /// A specialized (non-generic) winner emits NO miss: the same Add
4928        /// cell, but the binding carries `is_generic = false` (what a
4929        /// hand-written or structure-specialized registration stamps). The
4930        /// pick site reads the precomputed bool and skips emission.
4931        #[test]
4932        fn specialized_winner_emits_no_miss() {
4933            let mut table = KernelBindingTable::new();
4934            // Default (hand-written) registration ⇒ is_generic = false.
4935            register_add_f32(
4936                &mut table,
4937                BackendId::Cpu,
4938                noop_kernel,
4939                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4940            );
4941            let (g, add_id) = build_add_graph();
4942            let order = topo_order(&g, add_id);
4943
4944            let sink = Mutex::new(TelemetrySink::new());
4945            let provider = StubProvider;
4946            let config = TelemetryConfig {
4947                mode: TelemetryMode::Coarse,
4948                out_path: None,
4949            };
4950            let hooks = TelemetryHooks {
4951                config: &config,
4952                sink: &sink,
4953                provider: &provider,
4954                hw: cpu_hw(),
4955            };
4956            let opts = PlanOptions::new()
4957                .without_cost_population()
4958                .with_telemetry(&hooks);
4959            let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
4960
4961            let sink = sink.into_inner().expect("sink lock");
4962            assert!(
4963                sink.miss_records().is_empty(),
4964                "a specialized (is_generic=false) winner must emit no miss",
4965            );
4966            // The chosen signal STILL fires: a dispatch record is emitted for
4967            // every planned cell (generic or not); only the miss half is gated
4968            // on genericity.
4969            assert_eq!(
4970                sink.dispatch_cell_count(),
4971                1,
4972                "a specialized winner still emits its dispatch record",
4973            );
4974            let _ = add_id;
4975        }
4976
4977        // -----------------------------------------------------------------
4978        // Dispatch-record half (the sibling of the miss half).
4979        // -----------------------------------------------------------------
4980
4981        /// A table with TWO specialized (hand-written) Add siblings at one Cpu
4982        /// cell — distinct fn-pointers + sources. Both are planned candidates
4983        /// for the dispatch record; neither is generic, so neither emits a miss.
4984        fn two_sibling_add_table() -> KernelBindingTable {
4985            let mut table = KernelBindingTable::new();
4986            table.register_full_with_source(
4987                OpKind::AddElementwise,
4988                &[DType::F32, DType::F32, DType::F32],
4989                BackendId::Cpu,
4990                noop_kernel,
4991                KernelCaps::empty(),
4992                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
4993                unknown_cost,
4994                "portable-cpu",
4995            );
4996            table.register_full_with_source(
4997                OpKind::AddElementwise,
4998                &[DType::F32, DType::F32, DType::F32],
4999                BackendId::Cpu,
5000                noop_kernel_b,
5001                KernelCaps::empty(),
5002                PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
5003                unknown_cost,
5004                "aocl",
5005            );
5006            table
5007        }
5008
5009        /// BORN-RED (the headline): a planned cell with two candidates, a stub
5010        /// Judge measuring ONLY the winner, and Detailed-mode hooks threaded
5011        /// through `PlanOptions` ⇒ the compile-plan path leaves the sink holding
5012        /// exactly ONE aggregated `DispatchRecord` whose `chosen` matches the
5013        /// winner, whose `candidates[]` carries BOTH siblings with the measured
5014        /// one `Some(ns)` and the unmeasured one `None` (never 0).
5015        ///
5016        /// RED before the wire-in: `compile_plan` never recorded a dispatch
5017        /// record, so `dispatch_cell_count()` was 0. GREEN once the post-plan
5018        /// pass emits a `DispatchRecord` per winner and fills `candidates[]`
5019        /// from the plan-time Judge oracle.
5020        #[test]
5021        fn detailed_dispatch_record_emitted_with_per_candidate_judge_latency() {
5022            use crate::ranker::HashMapJudge;
5023            use fuel_ir::dispatch::SizeClass;
5024
5025            let table = two_sibling_add_table();
5026            let (g, add_id) = build_add_graph();
5027            let order = topo_order(&g, add_id);
5028
5029            // Measure ONLY the winner cell ("portable-cpu"); the sibling
5030            // ("aocl") is unmeasured ⇒ None (never a fabricated 0). The size
5031            // class mirrors the planner's key: first input elem_count = 3.
5032            let sc = SizeClass::from_elem_count(3);
5033            let mut judge = HashMapJudge::new();
5034            judge.insert(
5035                OpKind::AddElementwise,
5036                DType::F32,
5037                sc,
5038                BackendId::Cpu,
5039                "portable-cpu",
5040                41_230,
5041                0,
5042            );
5043
5044            let sink = Mutex::new(TelemetrySink::new());
5045            let provider = StubProvider;
5046            let config = TelemetryConfig {
5047                mode: TelemetryMode::Detailed,
5048                out_path: None,
5049            };
5050            let hooks = TelemetryHooks {
5051                config: &config,
5052                sink: &sink,
5053                provider: &provider,
5054                hw: cpu_hw(),
5055            };
5056            let opts = PlanOptions::new()
5057                .without_cost_population()
5058                .with_telemetry(&hooks)
5059                .with_judge(&judge);
5060            let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5061
5062            let sink = sink.into_inner().expect("sink lock");
5063            assert_eq!(
5064                sink.dispatch_cell_count(),
5065                1,
5066                "one planned cell ⇒ exactly one aggregated dispatch record",
5067            );
5068            assert_eq!(
5069                sink.miss_cell_count(),
5070                0,
5071                "specialized winners emit no miss"
5072            );
5073            let recs = sink.dispatch_records();
5074            assert_eq!(recs.len(), 1);
5075            let rec = &recs[0];
5076            // chosen = the winner (first-registered sibling), revision untracked.
5077            assert_eq!(rec.chosen.kernel_source, "portable-cpu");
5078            assert_eq!(rec.chosen.op, OpKind::AddElementwise);
5079            assert_eq!(rec.chosen.backend, BackendId::Cpu);
5080            assert_eq!(rec.chosen.dtypes, vec![DType::F32, DType::F32, DType::F32]);
5081            assert_eq!(
5082                rec.chosen.kernel_revision_hash, 0,
5083                "hand-written ⇒ untracked"
5084            );
5085            assert_eq!(rec.count, 1);
5086            assert_eq!(rec.hw, cpu_hw());
5087            // structure_key from the stub provider (2 inputs + the output
5088            // operand reached it, inputs-then-output ⇒ n=3).
5089            assert_eq!(
5090                rec.structure_key,
5091                Some(StructureKeyToken("AddElementwise:stub:n=3".into())),
5092            );
5093            // candidates: BOTH siblings, each with its OWN latency (a loser
5094            // keeps its own number, never the winner's).
5095            assert_eq!(rec.candidates.len(), 2, "both admitted alternatives appear");
5096            let by_src = |src: &str| {
5097                rec.candidates
5098                    .iter()
5099                    .find(|c| c.impl_id.kernel_source == src)
5100                    .unwrap_or_else(|| panic!("candidate {src} present"))
5101            };
5102            assert_eq!(
5103                by_src("portable-cpu").latency_ns,
5104                Some(41_230),
5105                "the measured winner carries its own ns",
5106            );
5107            assert_eq!(
5108                by_src("aocl").latency_ns,
5109                None,
5110                "the unmeasured sibling is None, never a fabricated 0",
5111            );
5112        }
5113
5114        /// GUARD — Coarse: the dispatch record still fires (the `chosen` signal
5115        /// for every planned cell) but carries NO `candidates[]` (no Judge
5116        /// reads), per the documented Coarse semantics.
5117        #[test]
5118        fn coarse_dispatch_record_has_no_candidates() {
5119            let table = two_sibling_add_table();
5120            let (g, add_id) = build_add_graph();
5121            let order = topo_order(&g, add_id);
5122
5123            let sink = Mutex::new(TelemetrySink::new());
5124            let provider = StubProvider;
5125            let config = TelemetryConfig {
5126                mode: TelemetryMode::Coarse,
5127                out_path: None,
5128            };
5129            let hooks = TelemetryHooks {
5130                config: &config,
5131                sink: &sink,
5132                provider: &provider,
5133                hw: cpu_hw(),
5134            };
5135            let opts = PlanOptions::new()
5136                .without_cost_population()
5137                .with_telemetry(&hooks);
5138            let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5139
5140            let sink = sink.into_inner().expect("sink lock");
5141            assert_eq!(
5142                sink.dispatch_cell_count(),
5143                1,
5144                "Coarse still emits the chosen signal"
5145            );
5146            let recs = sink.dispatch_records();
5147            assert!(
5148                recs[0].candidates.is_empty(),
5149                "Coarse omits candidates (no Judge reads)"
5150            );
5151            assert_eq!(recs[0].chosen.kernel_source, "portable-cpu");
5152            assert_eq!(recs[0].count, 1);
5153        }
5154
5155        /// GUARD — Off: neither a dispatch record nor a miss is emitted (the
5156        /// first, branch-predictable gate). The sink stays entirely empty.
5157        #[test]
5158        fn telemetry_off_emits_no_dispatch_record() {
5159            let table = two_sibling_add_table();
5160            let (g, add_id) = build_add_graph();
5161            let order = topo_order(&g, add_id);
5162
5163            let sink = Mutex::new(TelemetrySink::new());
5164            let provider = StubProvider;
5165            let config = TelemetryConfig::default(); // Off
5166            let hooks = TelemetryHooks {
5167                config: &config,
5168                sink: &sink,
5169                provider: &provider,
5170                hw: cpu_hw(),
5171            };
5172            let opts = PlanOptions::new()
5173                .without_cost_population()
5174                .with_telemetry(&hooks);
5175            let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5176
5177            assert!(
5178                sink.into_inner().expect("sink lock").is_empty(),
5179                "Off emits neither dispatch nor miss",
5180            );
5181            let _ = add_id;
5182        }
5183
5184        // -----------------------------------------------------------------
5185        // OUTPUT operand folded into the structure-key slice (Baracuda's
5186        // inputs-THEN-output OperandDesc convention).
5187        // -----------------------------------------------------------------
5188
5189        /// A recording provider: captures the exact `FdxOperandDesc` slice it
5190        /// was handed, so a test can prove the node's OUTPUT operand was folded
5191        /// in AFTER the inputs (baracuda keys on inputs-then-output).
5192        struct RecordingProvider {
5193            seen: Mutex<Vec<FdxOperandDesc>>,
5194        }
5195        impl StructureKeyProvider for RecordingProvider {
5196            fn structure_key(
5197                &self,
5198                op_class: &str,
5199                operands: &[FdxOperandDesc],
5200                _arch: &str,
5201            ) -> Option<StructureKeyToken> {
5202                *self.seen.lock().expect("record lock") = operands.to_vec();
5203                Some(StructureKeyToken(format!(
5204                    "{op_class}:n={}",
5205                    operands.len()
5206                )))
5207            }
5208        }
5209
5210        /// BORN-RED: the operand slice handed to the structure-key provider at
5211        /// the emission site must be node INPUTS followed by the node's own
5212        /// OUTPUT operand (baracuda's inputs-THEN-output `OperandDesc`
5213        /// convention). The Add cell has two inputs, so the slice must be
5214        /// length 3 with the trailing operand describing the output tensor.
5215        ///
5216        /// RED before the fix: the emission site built the slice from
5217        /// `node.inputs` only ⇒ length 2, no output operand. GREEN once the
5218        /// output desc (from the node's own layout/dtype) is appended.
5219        #[test]
5220        fn structure_key_operand_slice_folds_in_the_output() {
5221            let table = generic_only_add_table();
5222            let (g, add_id) = build_add_graph();
5223            let order = topo_order(&g, add_id);
5224
5225            let sink = Mutex::new(TelemetrySink::new());
5226            let provider = RecordingProvider {
5227                seen: Mutex::new(Vec::new()),
5228            };
5229            let config = TelemetryConfig {
5230                mode: TelemetryMode::Coarse,
5231                out_path: None,
5232            };
5233            let hooks = TelemetryHooks {
5234                config: &config,
5235                sink: &sink,
5236                provider: &provider,
5237                hw: cpu_hw(),
5238            };
5239            let opts = PlanOptions::new()
5240                .without_cost_population()
5241                .with_telemetry(&hooks);
5242            let _plan = compile_plan(&g, &order, &table, &opts).expect("compile");
5243
5244            let seen = provider.seen.into_inner().expect("record lock");
5245            // 2 inputs + 1 output ⇒ 3 operands, output LAST.
5246            assert_eq!(
5247                seen.len(),
5248                3,
5249                "operand slice must be node inputs (2) then the output (1)",
5250            );
5251            let out = seen.last().expect("output operand present");
5252            // The Add output is a contiguous [3] F32 tensor.
5253            assert_eq!(
5254                out.dtype,
5255                DType::F32,
5256                "output operand carries the node dtype"
5257            );
5258            assert_eq!(
5259                out.shape,
5260                vec![3i64],
5261                "output operand carries the node shape"
5262            );
5263            assert_eq!(
5264                out.contiguity,
5265                Contiguity::Contiguous,
5266                "the Add output is contiguous",
5267            );
5268            let _ = add_id;
5269        }
5270    }
5271}