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