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