Skip to main content

fuel_dispatch/
compiled.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Compiled-node representation. Phase 7.5 B4 (interface only).
3//!
4//! A [`CompiledNode`] is the output of dispatch resolution: a Node
5//! plus its resolved kernel function pointer plus its `OpParams`.
6//! The executor consumes these and runs them.
7//!
8//! ## Design intent: pipelined compile + execute (deferred)
9//!
10//! The original B-plan called for pipelined compilation: a compiler
11//! thread that walks the graph in topological order, resolves
12//! kernels per node, and pushes [`CompiledNode`] entries onto a
13//! `crossbeam::channel`. An executor thread consumes the channel,
14//! looks up inputs from the graph's storage map (blocking when
15//! inputs aren't yet realized), calls the kernel, and stores the
16//! output back. Time-to-first-token wins because the compiler runs
17//! ahead of the executor.
18//!
19//! Today's "compile" step is just a `KernelBindingTable` lookup —
20//! roughly nanoseconds per node. There's no meaningful work to
21//! overlap with execution. Pipelining adds `std::thread` +
22//! `crossbeam::channel` + lifecycle handling for zero current win.
23//!
24//! When compile grows beyond trivial — residency-aware planning,
25//! transfer-cost minimization, kernel auto-tuning, dynamic-shape
26//! specialization — pipelining lands as a follow-up. The
27//! interfaces in this module ([`CompiledNode`] +
28//! [`compile_node`] + [`execute_compiled`]) are designed so the
29//! threaded variant slots in without changing call sites.
30
31use std::sync::{Arc, RwLock};
32
33#[cfg_attr(not(feature = "cuda"), allow(unused_imports))]
34use fuel_ir::Error;
35use fuel_ir::dispatch::OpKind;
36use fuel_ir::probe::BackendId;
37use fuel_ir::{DType, Layout, Result};
38
39use crate::kernel::{KernelBindingTable, KernelCaps, KernelDTypes, KernelRef, OpParams};
40use fuel_graph::{Graph, NodeId};
41use fuel_memory::Storage;
42
43/// A graph node plus its resolved kernel function pointer and
44/// op-specific parameters. Produced by [`compile_node`]; consumed
45/// by [`execute_compiled`].
46#[derive(Debug, Clone)]
47pub struct CompiledNode {
48    /// The op family this node implements.
49    pub op: OpKind,
50    /// Per-operand dtypes used as the binding-table lookup key.
51    /// Inputs in order, then outputs. For uniform-precision ops the
52    /// list is `[T, T, ..., T]`; for mixed-precision ops it carries
53    /// the distinguishing combo. The output dtype is always the last
54    /// entry.
55    pub dtypes: KernelDTypes,
56    /// Which backend's kernel was selected.
57    pub backend: BackendId,
58    /// Resolved kernel function pointer. Looked up once at compile
59    /// time; the executor calls this directly.
60    pub kernel: KernelRef,
61    /// Capability flags registered alongside the kernel. The executor
62    /// consults `caps.strided_input` to decide whether to skip
63    /// auto-Contiguize for non-contiguous inputs.
64    pub caps: KernelCaps,
65    /// Op-specific parameters. Most ops use `OpParams::None`;
66    /// reductions / conv / slice carry their config here.
67    pub op_params: OpParams,
68    /// Estimated cost of ONE launch of this kernel in nanoseconds, built once when the node is compiled
69    /// (the binding entry's static cost through the backend's throughput prior, the same composite the
70    /// route picker ranks arms with). `0` means "no estimate": a CPU node, or no cost function or
71    /// capabilities for its backend. The executor adds it to the device's backlog when the node is
72    /// submitted to a GPU ([`crate::dispatch::BacklogLedger`], ROADMAP row 158); a `0` adds nothing, so a
73    /// device the executor cannot price is never reported idle.
74    pub est_ns: u64,
75}
76
77impl CompiledNode {
78    /// The output dtype — last entry in `dtypes`. Convenience accessor
79    /// for callers that only need the output type (e.g. shape inference,
80    /// allocation).
81    pub fn output_dtype(&self) -> DType {
82        *self
83            .dtypes
84            .last()
85            .expect("CompiledNode::dtypes must have at least one entry (the output)")
86    }
87}
88
89/// Opt-in per-`(OpKind, BackendId)` host-time accounting for kernel launches
90/// ([`execute_compiled_with_wait_hint`]). Off by default (one relaxed atomic load
91/// per launch). What it measures: wall time of the kernel call on the HOST. A
92/// kernel that only enqueues work (Vulkan batches into a command buffer, CUDA
93/// launches on a stream) is charged its enqueue cost, NOT its device time; a
94/// kernel that blocks (CPU math, a host-to-device upload, a forced flush) is
95/// charged all of it. Device time lands wherever the realize finally waits, so
96/// compare the per-op sum with the caller's own wall clock around a step.
97pub mod op_profile {
98    use std::collections::HashMap;
99    use std::sync::Mutex;
100    use std::sync::atomic::{AtomicBool, Ordering};
101    use std::time::Duration;
102
103    use fuel_ir::dispatch::OpKind;
104    use fuel_ir::probe::BackendId;
105
106    static ENABLED: AtomicBool = AtomicBool::new(false);
107    static PHASES: Mutex<Option<HashMap<&'static str, (u64, Duration)>>> = Mutex::new(None);
108
109    /// Times a named phase of a realize from `start` until it is dropped, when
110    /// accounting is on (a no-op otherwise: one relaxed atomic load). Phases are
111    /// hierarchical by NAME only: an outer phase's time includes the inner ones
112    /// nested inside it, so rows of [`take_phases`] are not additive.
113    pub struct PhaseTimer(Option<(&'static str, std::time::Instant)>);
114
115    impl PhaseTimer {
116        pub fn start(name: &'static str) -> Self {
117            Self(enabled().then(|| (name, std::time::Instant::now())))
118        }
119    }
120
121    impl Drop for PhaseTimer {
122        fn drop(&mut self) {
123            if let Some((name, t0)) = self.0.take() {
124                let mut g = PHASES.lock().unwrap_or_else(|p| p.into_inner());
125                let e = g
126                    .get_or_insert_with(HashMap::new)
127                    .entry(name)
128                    .or_insert((0, Duration::ZERO));
129                e.0 += 1;
130                e.1 += t0.elapsed();
131            }
132        }
133    }
134
135    /// Drain the phase totals: `(phase, entries, total time)`, longest first.
136    pub fn take_phases() -> Vec<(&'static str, u64, Duration)> {
137        let mut g = PHASES.lock().unwrap_or_else(|p| p.into_inner());
138        let mut v: Vec<_> = g
139            .take()
140            .unwrap_or_default()
141            .into_iter()
142            .map(|(k, (n, d))| (k, n, d))
143            .collect();
144        v.sort_by_key(|row| std::cmp::Reverse(row.2));
145        v
146    }
147
148    static TRACE: AtomicBool = AtomicBool::new(false);
149    static TRACE_ROWS: Mutex<Vec<LaunchRow>> = Mutex::new(Vec::new());
150
151    /// One kernel launch, in launch order (see [`set_trace`]).
152    #[derive(Clone, Debug)]
153    pub struct LaunchRow {
154        /// `OpKind` rendered with `Debug`.
155        pub op: String,
156        /// The kernel's backend, rendered with `Debug`.
157        pub backend: String,
158        /// Where the first input lives (`Cpu`, `Vulkan`, `Cuda`, `Metal`, `?`).
159        pub src: &'static str,
160        /// Where the first output lives.
161        pub dst: &'static str,
162        /// Byte length of the first input.
163        pub bytes: usize,
164        /// Host wall time of the launch.
165        pub dt: Duration,
166    }
167
168    fn kind(s: &std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>) -> (&'static str, usize) {
169        let Ok(g) = s.try_read() else {
170            return ("?", 0);
171        };
172        let k = match &g.inner {
173            fuel_memory::BackendStorage::Cpu(_) => "Cpu",
174            #[cfg(feature = "cuda")]
175            fuel_memory::BackendStorage::Cuda(_) => "Cuda",
176            #[cfg(feature = "vulkan")]
177            fuel_memory::BackendStorage::Vulkan(_) => "Vulkan",
178            #[allow(unreachable_patterns)]
179            _ => "Other",
180        };
181        (k, g.len_bytes())
182    }
183    /// `(op, backend)` rendered with `Debug` -> (launches, total host time).
184    type Totals = HashMap<(String, String), (u64, Duration)>;
185
186    static TOTALS: Mutex<Option<Totals>> = Mutex::new(None);
187
188    /// Turn accounting on or off. Does not clear what was recorded.
189    pub fn set_enabled(on: bool) {
190        ENABLED.store(on, Ordering::Relaxed);
191    }
192
193    /// Also keep every launch as a [`LaunchRow`], in order (implies the
194    /// accounting path). For a one-step anatomy, not for long runs: one row per
195    /// launch. Does not clear what was recorded.
196    pub fn set_trace(on: bool) {
197        TRACE.store(on, Ordering::Relaxed);
198    }
199
200    /// Drain the launch trace.
201    pub fn take_trace() -> Vec<LaunchRow> {
202        std::mem::take(&mut *TRACE_ROWS.lock().unwrap_or_else(|p| p.into_inner()))
203    }
204
205    /// Whether accounting (or tracing) is on.
206    pub fn enabled() -> bool {
207        ENABLED.load(Ordering::Relaxed) || TRACE.load(Ordering::Relaxed)
208    }
209
210    pub(super) fn record_launch(
211        compiled: &super::CompiledNode,
212        inputs: &[std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>],
213        outputs: &[std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>],
214        dt: Duration,
215    ) {
216        record(compiled.op, compiled.backend, dt);
217        if TRACE.load(Ordering::Relaxed) {
218            let (src, bytes) = inputs.first().map_or(("?", 0), kind);
219            let dst = outputs.first().map_or("?", |o| kind(o).0);
220            TRACE_ROWS
221                .lock()
222                .unwrap_or_else(|p| p.into_inner())
223                .push(LaunchRow {
224                    op: format!("{:?}", compiled.op),
225                    backend: format!("{:?}", compiled.backend),
226                    src,
227                    dst,
228                    bytes,
229                    dt,
230                });
231        }
232    }
233
234    pub(super) fn record(op: OpKind, backend: BackendId, dt: Duration) {
235        let mut g = TOTALS.lock().unwrap_or_else(|p| p.into_inner());
236        let e = g
237            .get_or_insert_with(HashMap::new)
238            .entry((format!("{op:?}"), format!("{backend:?}")))
239            .or_insert((0, Duration::ZERO));
240        e.0 += 1;
241        e.1 += dt;
242    }
243
244    /// Drain the totals: `(op, backend, launches, total host time)`, longest first.
245    pub fn take() -> Vec<(String, String, u64, Duration)> {
246        let mut g = TOTALS.lock().unwrap_or_else(|p| p.into_inner());
247        let mut v: Vec<_> = g
248            .take()
249            .unwrap_or_default()
250            .into_iter()
251            .map(|((op, be), (n, d))| (op, be, n, d))
252            .collect();
253        v.sort_by_key(|row| std::cmp::Reverse(row.3));
254        v
255    }
256}
257
258/// Resolve a node's kernel from the binding table and return a
259/// [`CompiledNode`] ready for execution. Production-correct: surfaces
260/// `NoBackendForOp` if the table doesn't have a binding for the
261/// requested triple.
262///
263/// Today this is one HashMap lookup. When dispatch grows more
264/// sophisticated (residency-aware, cost-aware, auto-tuning), the
265/// added work happens here. The interface stays the same.
266pub fn compile_node(
267    op: OpKind,
268    dtypes: &[DType],
269    backend: BackendId,
270    op_params: OpParams,
271    bindings: &KernelBindingTable,
272) -> Result<CompiledNode> {
273    let (kernel, caps) = bindings.lookup_with_caps(op, dtypes, backend)?;
274    Ok(CompiledNode {
275        op,
276        dtypes: KernelDTypes::from_slice(dtypes),
277        backend,
278        kernel,
279        caps,
280        op_params,
281        est_ns: 0,
282    })
283}
284
285/// The static estimate for one launch of `op` on `backend`, in nanoseconds: the first-registered binding's
286/// cost function (the entry [`compile_node`] picks) through the backend's throughput prior
287/// ([`crate::ranker::cost::default_backend_rates`]), the SAME composite the route picker ranks arms with
288/// when the Judge has no measurement for the cell. A cost is never invented: `0` for a CPU node (no queue
289/// to estimate), for no binding, and for a backend with no registered capabilities.
290///
291/// Static only, on purpose: the compile path does not query the Judge per node, so where the Judge HAS a
292/// measured latency for an arm the picker compares that measurement against a backlog in static units.
293/// That mismatch is the estimate's error bar, stated in ROADMAP row 158.
294pub fn estimate_static_ns(
295    op: OpKind,
296    dtypes: &[DType],
297    shapes: &[fuel_ir::Shape],
298    backend: BackendId,
299    op_params: &OpParams,
300    bindings: &KernelBindingTable,
301) -> u64 {
302    if backend == BackendId::Cpu {
303        return 0;
304    }
305    let Some(entry) = bindings.lookup_alternatives(op, dtypes, backend).first() else {
306        return 0;
307    };
308    let registry = crate::dispatch::global_registry();
309    let Some(caps) = registry.backends().iter().find(|c| c.backend_id == backend) else {
310        return 0;
311    };
312    let cost = match entry.cost_expr {
313        Some(expr) => crate::fkc::cost_estimate(expr, op, shapes, dtypes, op_params)
314            .unwrap_or_else(|_| (entry.cost)(shapes, dtypes, op_params, caps)),
315        None => (entry.cost)(shapes, dtypes, op_params, caps),
316    };
317    let (compute_rate, bandwidth) = crate::ranker::cost::default_backend_rates(backend);
318    crate::ranker::cost::composite_ns(&cost, compute_rate, bandwidth)
319}
320
321/// The `(kernel_source, kernel_revision_hash)` identity of the kernel the
322/// executor dispatches for `node`, derived from the SAME graph stamp +
323/// registry the executor resolves through: `op_to_op_kind` +
324/// `build_lookup_dtypes` + `graph.target_backend` → the first-registered
325/// binding at `(op, dtypes, backend)` (the entry [`compile_node`]'s
326/// `lookup_with_caps` picks). `None` when the node has no dispatch mapping
327/// (view/structural op) or no registered binding.
328///
329/// Both fields come from the ONE `find()` — the same
330/// [`BindingEntry`](crate::kernel::BindingEntry) — so
331/// the tag and the revision describe the same kernel by construction; a
332/// second lookup keyed on the tag could not disambiguate variant siblings
333/// that share it, which is precisely the collapse the revision exists to
334/// prevent. This is the post-realize attribution the bridge reports for the
335/// Judge. Step D moved it off the plan's `AlternativeSet::winner()`: the
336/// production realize path dispatches via the binding-table lookup (no plan),
337/// so the first-registered binding IS the matching attribution.
338pub fn dispatched_kernel_ident(
339    graph: &Graph,
340    node: NodeId,
341    bindings: &KernelBindingTable,
342) -> Option<(&'static str, u64)> {
343    let n = graph.node(node);
344    let op = crate::pipelined::op_to_op_kind(&n.op)?;
345    let dtypes = crate::pipelined::build_lookup_dtypes(graph, n);
346    let backend = graph.target_backend(node)?;
347    // Mirror `lookup_with_caps`'s dense-safe pick: skip baked-broadcast
348    // siblings so the attribution matches the kernel the executor actually
349    // dispatches (path 1a).
350    bindings
351        .lookup_alternatives(op, &dtypes, backend)
352        .iter()
353        .find(|e| !e.caps.requires_broadcast)
354        .map(|e| (e.kernel_source, e.kernel_revision_hash))
355}
356
357/// Run a compiled node against the given inputs/outputs. The output
358/// `Storage`s must be pre-allocated (the executor's responsibility,
359/// using the node's shape + dtype).
360///
361/// `layouts` parallels `inputs.append(outputs)` and carries the
362/// stride/shape/offset metadata that stride-aware kernels consume.
363/// Today's contiguous-only kernels ignore it; the executor's
364/// auto-Contiguize pass guarantees every input layout is
365/// `Layout::contiguous(shape)` before this is called.
366///
367/// Production-correct: surfaces kernel errors as `Result`; never
368/// panics on dispatch mismatch (the wrapper functions handle that).
369pub fn execute_compiled(
370    compiled: &CompiledNode,
371    inputs: &[Arc<RwLock<Storage>>],
372    outputs: &mut [Arc<RwLock<Storage>>],
373    layouts: &[Layout],
374) -> Result<CompletionHandle> {
375    // Conservative default: `true` reproduces the pre-"event only where
376    // waited" behavior byte-for-byte (every CUDA node gets an Event). Callers
377    // that know a node will never be individually waited mid-walk (the
378    // `pipelined` executor's wait-set pre-scan) should call
379    // [`execute_compiled_with_wait_hint`] instead.
380    execute_compiled_with_wait_hint(compiled, inputs, outputs, layouts, true)
381}
382
383/// Step E A4b open question #4 — "event only where waited". Identical to
384/// [`execute_compiled`] except the caller supplies `will_be_waited`: whether
385/// ANY later step in this realize will individually wait this node's
386/// completion handle before the realize-end drain (today: the cross-device
387/// `Copy`/`Move` producer wait, `wait_producer_handle` in `pipelined.rs`).
388///
389/// `will_be_waited == false` lets `produce_pending` skip the CUDA
390/// `Event`/in-flight-counter machinery entirely and return
391/// [`CompletionHandle::Ready`] immediately — the kernel is still launched on
392/// the device stream exactly as before; only the completion-observation
393/// bookkeeping is elided. Same-device consumers stay correct because CUDA has
394/// one stream per device: stream order alone guarantees a later same-device
395/// kernel doesn't start before this one's writes land, with no host-side wait
396/// required. Cutting the event is safe PROVIDED the caller's wait-set is
397/// conservative (a producer that turns out to be waited must always pass
398/// `true`) — `pipelined.rs`'s pre-scan is exactly that: built from the SAME
399/// Copy/Move nodes the mid-walk wait consults.
400///
401/// `will_be_waited == true` is byte-identical to the pre-elision path.
402pub fn execute_compiled_with_wait_hint(
403    compiled: &CompiledNode,
404    inputs: &[Arc<RwLock<Storage>>],
405    outputs: &mut [Arc<RwLock<Storage>>],
406    layouts: &[Layout],
407    will_be_waited: bool,
408) -> Result<CompletionHandle> {
409    let profile_start = op_profile::enabled().then(std::time::Instant::now);
410    let launched = (compiled.kernel)(inputs, outputs, layouts, &compiled.op_params);
411    if let Some(t0) = profile_start {
412        op_profile::record_launch(compiled, inputs, outputs, t0.elapsed());
413    }
414    launched?;
415    // Step E A4b-1: the kernel has *enqueued* its work (CUDA: launched on the
416    // device stream and returned without a per-op sync, per A3; CPU/Vulkan: see
417    // below). Produce a completion handle FROM THE OUTPUT STORAGE — the kernel
418    // reaches the device via the `Storage`, not an executor-held backend, so the
419    // output's `BackendStorage` is where we find the device/stream to record a
420    // signal on. The executor stores this handle and defers the wait to a
421    // dependency / realize-end boundary instead of `wait`ing inline here.
422    produce_pending(compiled.backend, outputs, will_be_waited)
423}
424
425/// Step E A4b-1: build the [`CompletionHandle`] for a just-launched kernel by
426/// inspecting `outputs[0]`'s backend storage.
427///
428/// - **CUDA, `will_be_waited`** → [`CompletionHandle::Pending`] wrapping an
429///   [`Event`] recorded on the output's device stream (signals when this
430///   kernel + all prior stream work completes; one stream per device makes a
431///   per-node event a sufficient stream marker — A4b-1 §1.2).
432/// - **CUDA, NOT `will_be_waited`** (A4b open question #4 — "event only
433///   where waited") → [`CompletionHandle::Ready`], with NO `cuEventCreate` /
434///   `cuEventRecord` and NO in-flight-counter increment. The kernel already
435///   launched (line above); only the completion-observation bookkeeping is
436///   skipped, because nothing will ever individually wait THIS node's
437///   handle — the realize-end drain now does one blanket
438///   `cuStreamSynchronize` per active CUDA device instead
439///   (`pipelined::sync_active_cuda_devices`), which flushes elided work too
440///   (single stream per device ⇒ stream order already makes it complete by
441///   then).
442/// - **CPU** → [`CompletionHandle::Ready`] (the kernel computed in-process; the
443///   work is already done).
444/// - **Vulkan** → [`CompletionHandle::Ready`]. The per-op compute path keeps
445///   RECORDING into the deferred batch and returns `Ready` during the walk (no
446///   per-op handle, no eager submit — eager submission at sub-DAG boundaries is
447///   A4b-4). A4b-2's async split lives at the executor's realize-end drain
448///   (`drain_vulkan_pending`): it `submit_pending`s the open batch (the per-batch
449///   fence) then waits it through a `VulkanCompletion` handle — byte-identical to
450///   A2's atomic submit+wait, just split. The A2 lazy-batch model still carries
451///   intra-walk Vulkan correctness (same-queue order + the eviction `force_flush`).
452///
453/// Multi-output kernels share one backing buffer (one `BackendStorage`), so
454/// `outputs[0]` is the device handle for every slot — a single event covers them.
455fn produce_pending(
456    _backend: BackendId,
457    outputs: &[Arc<RwLock<Storage>>],
458    will_be_waited: bool,
459) -> Result<CompletionHandle> {
460    // `_backend` (= `compiled.backend`) records the *intent*; we read the
461    // device truth off the output storage's variant instead, which is robust
462    // even where the backend stamp and the realized storage could ever diverge.
463    #[cfg(not(feature = "cuda"))]
464    let _ = (outputs, will_be_waited);
465    #[cfg(feature = "cuda")]
466    {
467        if will_be_waited {
468            if let Some(out0) = outputs.first() {
469                let guard = out0.read().map_err(|_| {
470                    Error::Msg("output storage lock poisoned recording completion".into()).bt()
471                })?;
472                if let fuel_memory::BackendStorage::Cuda(cuda_bytes) = &guard.inner {
473                    // Step E B1: this is the single CUDA async-submit site — the kernel
474                    // was just enqueued on the device stream. The completion handle's
475                    // lifetime IS the in-flight window, so `CudaCompletion::new`
476                    // increments the per-device in-flight counter here and the handle's
477                    // `Drop` decrements it (covering wait, drain, AND the eviction-drop
478                    // path uniformly — see the type docs). The device location keys the
479                    // counter.
480                    let loc = cuda_bytes.device().location();
481                    let ev = cuda_bytes.record_completion_event()?;
482                    return Ok(CompletionHandle::Pending(Box::new(CudaCompletion::new(
483                        ev, loc,
484                    ))));
485                }
486            }
487        }
488    }
489    Ok(CompletionHandle::Ready)
490}
491
492/// Step E A4b-1: a CUDA [`Completion`] over a recorded [`Event`]. `wait` is a
493/// blocking host wait (`cuEventSynchronize`) on the event — which fires after
494/// the producing kernel and every prior op on the (single per-device) stream.
495///
496/// Step E B1: carries the producing op's [`DeviceLocation`] and owns one slot
497/// of the process-wide in-flight counter. [`CudaCompletion::new`] (called at the
498/// async-submit site, `produce_pending`) increments; [`Drop`] decrements. Putting
499/// the decrement in `Drop` — NOT in `wait` — is what makes the counter BALANCE:
500/// every path that ends this handle's life decrements exactly once and only once:
501///   - `wait(self: Box<Self>)` synchronizes the event (a `&self` read) then the
502///     `Box` drops → one dec;
503///   - the executor's `drain_handles` / `wait_producer_handle` consume the handle
504///     via `wait` → the same one dec;
505///   - the eviction path `handles.remove(&destroyed)` DROPS the handle WITHOUT
506///     waiting → still one dec (via `Drop`);
507///   - an error (`?`) unwinding the realize loop drops the still-owned handles →
508///     one dec each.
509/// `wait` deliberately does not touch the counter, so no path double-counts.
510#[cfg(feature = "cuda")]
511struct CudaCompletion {
512    ev: fuel_cuda_backend::Event,
513    loc: fuel_ir::DeviceLocation,
514}
515
516#[cfg(feature = "cuda")]
517impl CudaCompletion {
518    /// Build the handle for a just-enqueued CUDA op and register it as one
519    /// in-flight op on `loc`. The matching decrement is in [`Drop`].
520    fn new(ev: fuel_cuda_backend::Event, loc: fuel_ir::DeviceLocation) -> Self {
521        crate::dispatch::inflight_inc(loc);
522        Self { ev, loc }
523    }
524}
525
526#[cfg(feature = "cuda")]
527impl Drop for CudaCompletion {
528    fn drop(&mut self) {
529        // The single in-flight decrement — fires on wait-consume, drain, OR
530        // eviction-drop, so the counter returns to baseline once every handle
531        // is gone. Relaxed + saturating (a hint, never a correctness gate).
532        crate::dispatch::inflight_dec(self.loc);
533    }
534}
535
536#[cfg(feature = "cuda")]
537impl Completion for CudaCompletion {
538    fn wait(self: Box<Self>) -> Result<()> {
539        use fuel_cuda_backend::WrapErr;
540        // cuEventSynchronize: blocks the host until the event completes; surfaces
541        // a sticky async kernel fault on this stream as the mapped `Err`. The
542        // in-flight decrement is NOT here — it rides the `Box`'s `Drop` (which
543        // runs as this method returns), so the eviction-drop path also decrements.
544        self.ev.synchronize().w()
545    }
546}
547
548/// A node's completion signal, returned by [`execute_compiled`]. Step E
549/// Phase A1 foundation: today every dispatch is synchronous, so this is always
550/// [`CompletionHandle::Ready`] (the work finished before the call returned) and
551/// callers `wait` it immediately — byte-identical to the prior `Result<()>`.
552/// Phases A2/A3 add an async GPU path that returns [`CompletionHandle::Pending`]
553/// carrying a device fence/event the executor defers the wait on.
554///
555/// `#[must_use]`: dropping a `Pending` handle without `wait`ing would leak
556/// un-awaited async work (harmless for today's `Ready`, a correctness bug once
557/// A2/A3 land) — callers must `wait` it or thread it to the executor.
558#[must_use = "a CompletionHandle must be waited on (or threaded to the executor) — dropping a Pending handle leaks async work"]
559pub enum CompletionHandle {
560    /// The work finished synchronously before [`execute_compiled`] returned —
561    /// [`wait`](CompletionHandle::wait) is a no-op.
562    Ready,
563    /// The work was enqueued asynchronously; [`wait`](CompletionHandle::wait)
564    /// blocks until the carried device signal fires. (No producers until A2/A3.)
565    Pending(Box<dyn Completion>),
566}
567
568impl CompletionHandle {
569    /// Block until this node's work has finished. No-op for [`Ready`].
570    ///
571    /// [`Ready`]: CompletionHandle::Ready
572    pub fn wait(self) -> Result<()> {
573        match self {
574            CompletionHandle::Ready => Ok(()),
575            CompletionHandle::Pending(c) => c.wait(),
576        }
577    }
578}
579
580/// An async-dispatch completion signal — a backend's wrapper over a CUDA event
581/// / Vulkan fence so the executor can defer the wait past the submit point
582/// (Step E Phase A2/A3). No implementors today; all dispatch is synchronous.
583pub trait Completion: Send {
584    /// Block until the enqueued work this handle represents has finished.
585    fn wait(self: Box<Self>) -> Result<()>;
586}
587
588#[cfg(test)]
589mod op_profile_tests {
590    use super::op_profile;
591    use fuel_ir::dispatch::OpKind;
592    use fuel_ir::probe::BackendId;
593    use std::time::Duration;
594
595    /// The only test that touches the process-global totals.
596    #[test]
597    fn totals_sum_per_key_sort_longest_first_and_drain() {
598        let _ = op_profile::take();
599        op_profile::record(
600            OpKind::AddElementwise,
601            BackendId::Cpu,
602            Duration::from_millis(2),
603        );
604        op_profile::record(
605            OpKind::AddElementwise,
606            BackendId::Cpu,
607            Duration::from_millis(3),
608        );
609        op_profile::record(OpKind::MatMul, BackendId::Cpu, Duration::from_millis(1));
610        op_profile::record(OpKind::MatMul, BackendId::Vulkan, Duration::from_millis(9));
611        let rows = op_profile::take();
612        let got: Vec<(&str, &str, u64, u128)> = rows
613            .iter()
614            .map(|(o, b, n, d)| (o.as_str(), b.as_str(), *n, d.as_millis()))
615            .collect();
616        assert_eq!(
617            got,
618            vec![
619                ("MatMul", "Vulkan", 1, 9),
620                ("AddElementwise", "Cpu", 2, 5),
621                ("MatMul", "Cpu", 1, 1),
622            ]
623        );
624        assert!(op_profile::take().is_empty(), "take() drains");
625    }
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631    use crate::dispatch::register_cpu_kernels;
632
633    /// E2E with the compile/execute split: register CPU kernels,
634    /// compile a node, execute it. Same shape as B5's e2e test but
635    /// goes through the CompiledNode interface.
636    #[test]
637    fn compile_then_execute_add_f32() {
638        let mut bindings = KernelBindingTable::new();
639        register_cpu_kernels(&mut bindings);
640
641        let compiled = compile_node(
642            OpKind::AddElementwise,
643            &[DType::F32, DType::F32, DType::F32],
644            BackendId::Cpu,
645            OpParams::None,
646            &bindings,
647        )
648        .expect("compile");
649
650        assert_eq!(compiled.op, OpKind::AddElementwise);
651        assert_eq!(compiled.output_dtype(), DType::F32);
652        assert_eq!(compiled.backend, BackendId::Cpu);
653
654        let lhs = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
655        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
656        let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 3).unwrap();
657        let inputs = vec![Arc::new(RwLock::new(lhs)), Arc::new(RwLock::new(rhs))];
658        let mut outputs = vec![Arc::new(RwLock::new(out))];
659
660        let layout_3 = Layout::contiguous(fuel_ir::Shape::from(vec![3]));
661        let layouts = vec![layout_3.clone(), layout_3.clone(), layout_3];
662        execute_compiled(&compiled, &inputs, &mut outputs, &layouts)
663            .expect("execute")
664            .wait()
665            .expect("wait");
666
667        let out_guard = outputs[0].read().unwrap();
668        if let fuel_memory::BackendStorage::Cpu(c) = &out_guard.inner {
669            let typed: &[f32] = c.as_slice().unwrap();
670            assert_eq!(typed, &[6.0, 8.0, 10.0]);
671        }
672    }
673
674    /// Step E A4b-1 behavior-preservation: a CPU kernel's `execute_compiled`
675    /// returns `CompletionHandle::Ready` — `produce_pending` must NOT turn the
676    /// (synchronous, in-process) CPU path into a `Pending` handle. The CUDA arm
677    /// (Pending) is covered by the live `cuda_async_realize_live` gate.
678    #[test]
679    fn execute_compiled_cpu_is_ready_not_pending() {
680        let mut bindings = KernelBindingTable::new();
681        register_cpu_kernels(&mut bindings);
682        let compiled = compile_node(
683            OpKind::AddElementwise,
684            &[DType::F32, DType::F32, DType::F32],
685            BackendId::Cpu,
686            OpParams::None,
687            &bindings,
688        )
689        .expect("compile");
690
691        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
692        let rhs = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
693        let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 2).unwrap();
694        let inputs = vec![Arc::new(RwLock::new(lhs)), Arc::new(RwLock::new(rhs))];
695        let mut outputs = vec![Arc::new(RwLock::new(out))];
696        let l = Layout::contiguous(fuel_ir::Shape::from(vec![2]));
697        let layouts = vec![l.clone(), l.clone(), l];
698
699        let handle = execute_compiled(&compiled, &inputs, &mut outputs, &layouts).expect("execute");
700        assert!(
701            matches!(handle, CompletionHandle::Ready),
702            "CPU execute_compiled must return Ready (A4b-1 behavior-preserving)",
703        );
704        handle.wait().expect("wait");
705    }
706
707    /// A4b open question #4 — "event only where waited": the wait-hint entry
708    /// point computes and returns Ready on CPU under BOTH hints (the hint only
709    /// gates the CUDA event machinery), and the elided (`false`) hint must not
710    /// change the computed bytes.
711    #[test]
712    fn execute_compiled_with_wait_hint_cpu_ready_and_correct_under_both_hints() {
713        let mut bindings = KernelBindingTable::new();
714        register_cpu_kernels(&mut bindings);
715        let compiled = compile_node(
716            OpKind::AddElementwise,
717            &[DType::F32, DType::F32, DType::F32],
718            BackendId::Cpu,
719            OpParams::None,
720            &bindings,
721        )
722        .expect("compile");
723
724        for hint in [true, false] {
725            let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
726            let rhs = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
727            let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 2).unwrap();
728            let inputs = vec![Arc::new(RwLock::new(lhs)), Arc::new(RwLock::new(rhs))];
729            let mut outputs = vec![Arc::new(RwLock::new(out))];
730            let l = Layout::contiguous(fuel_ir::Shape::from(vec![2]));
731            let layouts = vec![l.clone(), l.clone(), l];
732
733            let handle =
734                execute_compiled_with_wait_hint(&compiled, &inputs, &mut outputs, &layouts, hint)
735                    .expect("execute");
736            assert!(
737                matches!(handle, CompletionHandle::Ready),
738                "CPU path returns Ready regardless of the wait hint ({hint})",
739            );
740            handle.wait().expect("wait");
741
742            let out_guard = outputs[0].read().unwrap();
743            if let fuel_memory::BackendStorage::Cpu(c) = &out_guard.inner {
744                let typed: &[f32] = c.as_slice().unwrap();
745                assert_eq!(typed, &[4.0, 6.0], "bytes identical under hint={hint}");
746            }
747        }
748    }
749
750    /// Step E A1: the completion-handle contract — `Ready.wait()` is a no-op
751    /// success; `Pending(c).wait()` delegates to the boxed `Completion`.
752    #[test]
753    fn completion_handle_ready_is_noop_pending_delegates() {
754        use std::sync::Arc as StdArc;
755        use std::sync::atomic::{AtomicBool, Ordering};
756
757        CompletionHandle::Ready.wait().expect("Ready.wait() is Ok");
758
759        struct Flag(StdArc<AtomicBool>);
760        impl Completion for Flag {
761            fn wait(self: Box<Self>) -> Result<()> {
762                self.0.store(true, Ordering::SeqCst);
763                Ok(())
764            }
765        }
766        let waited = StdArc::new(AtomicBool::new(false));
767        CompletionHandle::Pending(Box::new(Flag(waited.clone())))
768            .wait()
769            .expect("Pending.wait() is Ok");
770        assert!(
771            waited.load(Ordering::SeqCst),
772            "Pending.wait() must run the boxed Completion",
773        );
774    }
775
776    /// compile_node surfaces NoBackendForOp on missing binding.
777    #[test]
778    fn compile_node_errors_on_missing_binding() {
779        let bindings = KernelBindingTable::new(); // empty
780        let result = compile_node(
781            OpKind::AddElementwise,
782            &[DType::F32, DType::F32, DType::F32],
783            BackendId::Cpu,
784            OpParams::None,
785            &bindings,
786        );
787        assert!(result.is_err());
788    }
789}