Skip to main content

fuel_dispatch/
residency.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Residency analysis + eviction for the pipelined executor.
3//!
4//! Ported from `fuel-graph-router::{residency_planner,
5//! residency_eviction}` (executor-unification Session 6, 2026-06-11).
6//! The legacy shape was a `GraphMutatingSchedulerRule` that emitted a
7//! three-node `Op::Copy{Cpu}` + `Op::Release` + `Op::Copy{device}`
8//! chain for the legacy `GraphExecutor<Router>`; the pipelined port
9//! emits the fused two-node form — `Op::Move{Cpu}` + reload
10//! `Op::Copy{device}` — making this pass the first production emitter
11//! of [`WorkItemKind::Move`](crate::pipelined) (shipped `b93bdb82`).
12//!
13//! ## The two halves
14//!
15//! - **Analysis** — [`ResidencyPlanner::analyze`] walks a graph's topo
16//!   order, tracks each node's live range (first use → last consumer),
17//!   and computes the peak working-set size. Pure; no graph mutation.
18//! - **Transform** — [`insert_residency_evictions`] consumes the
19//!   analysis and, while the peak exceeds a byte budget, inserts
20//!   `Op::Move{Cpu}` + reload `Op::Copy{device}` chains around the
21//!   highest-scoring candidates (`bytes × inactive_gap`). The
22//!   `derive_ordering` half of `execution_plan` (run inside both
23//!   pipelined realize paths) pins each Move after every
24//!   non-destructive reader of its source, and the executor's
25//!   `destructive_input` cleanup frees the device storage when the
26//!   Move runs.
27//!
28//! ## Const-pool byte budget (deferred — planner program)
29//!
30//! The legacy executor's `with_const_pool_limit` LRU was the only
31//! other larger-than-VRAM mechanism, and it retired with the legacy
32//! executor. Per the 2026-06-11 re-audit (gap 7), the replacement is
33//! NOT an executor-side LRU: weight residency under a byte budget is
34//! a *planning* decision, and it folds into the load-time incremental
35//! planner's residency program (`docs/session-prompts/
36//! load-time-incremental-planner.md`) — the planner prices
37//! evict/reload chains with Stage 1 `TransferCalibration` data and
38//! emits the same `Op::Move`/`Op::Copy` primitives this module does.
39//! This module is that program's substrate, not its policy.
40//!
41//! ## Known limitations (follow-up work, inherited from the port)
42//!
43//! - Only one eviction per candidate (the largest gap). Multiple gaps
44//!   would need multiple evict chains.
45//! - Greedy selection; no cost-awareness for the CPU↔device transfer
46//!   overhead vs the VRAM savings (the planner program adds pricing).
47//! - No integration with the `VulkanBackend::evict` mmap-tiering path
48//!   — that's a transparent runtime mechanism, distinct from
49//!   graph-level planning.
50
51use crate::plan::backend_for_device;
52use fuel_graph::opt::execution_plan;
53use fuel_graph::{Graph, NodeId, Op, SharedGraph, opt, topo_order_multi};
54use fuel_ir::{DeviceLocation, Error, Result};
55use std::collections::HashMap;
56
57/// One tensor's residency span. `[first_use, last_use]` are op
58/// positions in a topo order (inclusive — the tensor is live during
59/// both). `bytes` is the output storage size. `inactive_gap` is the
60/// longest stretch of ops between consecutive reads where the tensor
61/// is resident but not accessed — a strong signal for eviction
62/// viability.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct LiveRange {
65    pub node: NodeId,
66    pub bytes: usize,
67    pub first_use: usize,
68    pub last_use: usize,
69    pub inactive_gap: usize,
70}
71
72/// Structured report on a graph's residency profile.
73#[derive(Debug, Clone)]
74pub struct ResidencyReport {
75    /// Total bytes of storage summed over every reachable op's output.
76    /// Not the peak — this is cumulative if nothing were freed.
77    pub total_bytes: usize,
78    /// Maximum bytes live simultaneously at any point during a
79    /// single-device execution of the graph. The minimum VRAM
80    /// (or "primary device") required to run without spilling.
81    pub peak_bytes: usize,
82    /// Op position (index in topo order) where the peak occurs.
83    pub peak_op_index: usize,
84    /// Per-tensor live range, sorted by `bytes * inactive_gap`
85    /// descending (biggest "wasted residency" candidates first).
86    /// [`insert_residency_evictions`] consumes this list.
87    pub eviction_candidates: Vec<LiveRange>,
88}
89
90impl ResidencyReport {
91    /// Does this graph fit in a given byte budget?
92    pub fn fits_in(&self, budget: usize) -> bool {
93        self.peak_bytes <= budget
94    }
95
96    /// Byte overage relative to a budget. Zero when the graph fits.
97    pub fn overage(&self, budget: usize) -> usize {
98        self.peak_bytes.saturating_sub(budget)
99    }
100}
101
102/// Analysis-only residency planner. Computes live ranges and peak
103/// bytes for a graph, emits a [`ResidencyReport`]. Does not mutate
104/// the graph. Takes `&Graph` — the caller holds whatever lock it
105/// already has; no hidden lock acquisition.
106pub struct ResidencyPlanner;
107
108impl ResidencyPlanner {
109    /// Run the analysis. O(V + E) in the reachable subgraph. Walks a plain topological order and
110    /// counts every node's output (the single-device view the KV-pool sizing uses).
111    pub fn analyze(g: &Graph, roots: &[NodeId]) -> ResidencyReport {
112        Self::analyze_ordered(g, roots, topo_order_multi(g, roots), |_| true)
113    }
114
115    /// The analysis the eviction pass uses to decide whether `device` fits a budget: the walk is
116    /// the order the executor will actually run ([`execution_plan`], which pins each `Op::Move`
117    /// after every non-destructive reader of its source), and a node counts only while it is
118    /// resident on `device`: the output of an `Op::Move` / `Op::Copy` aimed at ANOTHER device
119    /// (the staged host copy of an eviction) is not device bytes. Without both, an eviction could
120    /// never lower the analysed peak and the pass would evict until it ran out of rounds.
121    pub fn analyze_on(g: &Graph, roots: &[NodeId], device: DeviceLocation) -> ResidencyReport {
122        let resident = |nid: NodeId| match &g.node(nid).op {
123            Op::Move { target } | Op::Copy { target } | Op::Alloc { target } => *target == device,
124            // A stamped placement on another device is not this device's bytes; an unstamped node
125            // inherits the executor's default and is counted (the conservative direction).
126            _ => g.placement(nid).is_none_or(|p| p == device),
127        };
128        Self::analyze_ordered(g, roots, execution_plan(g, roots), resident)
129    }
130
131    fn analyze_ordered(
132        g: &Graph,
133        roots: &[NodeId],
134        order: Vec<NodeId>,
135        resident: impl Fn(NodeId) -> bool,
136    ) -> ResidencyReport {
137        // 1. For every node, compute its output byte size.
138        // 2. Determine first-use (= position of the producing op in
139        //    topo order) and last-use (= position of the last
140        //    consuming op in topo order) for every producer.
141        //    Roots count as consumed at the walk's end.
142        let n = order.len();
143        let mut byte_of: HashMap<NodeId, usize> = HashMap::with_capacity(n);
144        let mut first_use: HashMap<NodeId, usize> = HashMap::with_capacity(n);
145        let mut last_use: HashMap<NodeId, usize> = HashMap::with_capacity(n);
146        // Record the set of reads per op position for inactive-gap
147        // computation below.
148        let mut reads_at: Vec<Vec<NodeId>> = vec![Vec::new(); n];
149
150        for (op_idx, &nid) in order.iter().enumerate() {
151            let node = g.node(nid);
152            let elems = node.shape.elem_count();
153            let bytes = if resident(nid) {
154                elems * node.dtype.size_in_bytes()
155            } else {
156                0
157            };
158            byte_of.insert(nid, bytes);
159            first_use.entry(nid).or_insert(op_idx);
160
161            for &input in &node.inputs {
162                last_use.insert(input, op_idx);
163                reads_at[op_idx].push(input);
164            }
165        }
166        // Roots themselves need to stay live through their own
167        // position (they're the "output" the caller asked for).
168        for &r in roots {
169            if let Some(pos) = order.iter().position(|&x| x == r) {
170                last_use.entry(r).or_insert(pos);
171            }
172        }
173
174        let (peak_bytes, peak_op_index, total_bytes) =
175            scan_peak(&order, &byte_of, &last_use, &reads_at);
176
177        let gap_of = inactive_gaps(&first_use, &last_use, &reads_at);
178
179        let cands = rank_candidates(&order, &byte_of, &first_use, &last_use, &gap_of);
180
181        ResidencyReport {
182            total_bytes,
183            peak_bytes,
184            peak_op_index,
185            eviction_candidates: cands,
186        }
187    }
188}
189
190/// Walk `order`, keeping the live-set bytes: a node goes live at its position and is freed after
191/// its last reader. Returns `(peak_bytes, peak_op_index, total_bytes)`.
192fn scan_peak(
193    order: &[NodeId],
194    byte_of: &HashMap<NodeId, usize>,
195    last_use: &HashMap<NodeId, usize>,
196    reads_at: &[Vec<NodeId>],
197) -> (usize, usize, usize) {
198    let mut live_bytes: usize = 0;
199    let mut peak_bytes: usize = 0;
200    let mut peak_op_index: usize = 0;
201    let mut total_bytes: usize = 0;
202    for (op_idx, &nid) in order.iter().enumerate() {
203        let bytes = *byte_of.get(&nid).unwrap_or(&0);
204        live_bytes += bytes;
205        total_bytes += bytes;
206        if live_bytes > peak_bytes {
207            peak_bytes = live_bytes;
208            peak_op_index = op_idx;
209        }
210        // Post-op: free the inputs whose last read is this op (not the node just produced).
211        for &input in &reads_at[op_idx] {
212            if last_use.get(&input) == Some(&op_idx) {
213                let b = *byte_of.get(&input).unwrap_or(&0);
214                live_bytes = live_bytes.saturating_sub(b);
215            }
216        }
217    }
218    (peak_bytes, peak_op_index, total_bytes)
219}
220
221/// Per node, the longest stretch of ops between consecutive reads while the tensor is live but
222/// untouched (produced -> reads -> last use). Big gap x bytes = the best eviction candidates.
223fn inactive_gaps(
224    first_use: &HashMap<NodeId, usize>,
225    last_use: &HashMap<NodeId, usize>,
226    reads_at: &[Vec<NodeId>],
227) -> HashMap<NodeId, usize> {
228    let mut gap_of: HashMap<NodeId, usize> = HashMap::with_capacity(first_use.len());
229    for (nid, &first) in first_use {
230        let mut points = vec![first];
231        points.extend(
232            reads_at
233                .iter()
234                .enumerate()
235                .filter(|(_, rs)| rs.contains(nid))
236                .map(|(i, _)| i),
237        );
238        points.push(last_use.get(nid).copied().unwrap_or(first));
239        points.sort();
240        let max_gap = points.windows(2).map(|w| w[1] - w[0]).max().unwrap_or(0);
241        gap_of.insert(*nid, max_gap);
242    }
243    gap_of
244}
245
246/// Build the eviction candidates and rank them by bytes x inactive gap, descending (ties: larger
247/// bytes first, more reclaim per evict). Zero-score nodes (hot tensors with no gap) are dropped and
248/// the list is capped for downstream consumers.
249fn rank_candidates(
250    order: &[NodeId],
251    byte_of: &HashMap<NodeId, usize>,
252    first_use: &HashMap<NodeId, usize>,
253    last_use: &HashMap<NodeId, usize>,
254    gap_of: &HashMap<NodeId, usize>,
255) -> Vec<LiveRange> {
256    let mut cands: Vec<LiveRange> = order
257        .iter()
258        .map(|&nid| LiveRange {
259            node: nid,
260            bytes: *byte_of.get(&nid).unwrap_or(&0),
261            first_use: *first_use.get(&nid).unwrap_or(&0),
262            last_use: *last_use.get(&nid).unwrap_or(&0),
263            inactive_gap: *gap_of.get(&nid).unwrap_or(&0),
264        })
265        .collect();
266    cands.sort_by(|a, b| {
267        let a_score = (a.bytes as u128) * (a.inactive_gap as u128);
268        let b_score = (b.bytes as u128) * (b.inactive_gap as u128);
269        b_score.cmp(&a_score).then(b.bytes.cmp(&a.bytes))
270    });
271    cands.retain(|c| c.bytes > 0 && c.inactive_gap > 0);
272    cands.truncate(32);
273    cands
274}
275
276/// One evict/reload chain emitted by [`insert_residency_evictions`].
277/// `move_node` is the `Op::Move { target: Cpu }` (destructive stage-
278/// to-host); `reload` is the `Op::Copy { target: src_device }` the
279/// post-gap consumers were rewired to.
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub struct EvictReload {
282    pub candidate: NodeId,
283    pub move_node: NodeId,
284    pub reload: NodeId,
285    pub src_device: DeviceLocation,
286}
287
288/// What one run of the eviction pass did, so a caller can see whether the budget was met instead
289/// of inferring it from a graph that quietly grew.
290#[derive(Debug, Clone, PartialEq)]
291#[non_exhaustive]
292pub struct EvictionOutcome {
293    /// The device whose budget this was.
294    pub device: DeviceLocation,
295    /// The budget the pass was asked to meet, in bytes.
296    pub budget_bytes: usize,
297    /// The analysed peak on `device` before any eviction.
298    pub peak_before: usize,
299    /// The analysed peak on `device` after the last chain the pass kept.
300    pub peak_after: usize,
301    /// The chains inserted, in order.
302    pub chains: Vec<EvictReload>,
303    /// Which rule produced `budget_bytes`, when the caller resolved it through
304    /// [`crate::device_budget`]; `None` for a hand-set number. Filled by `optimize_graph`.
305    pub budget_source: Option<crate::device_budget::BudgetSource>,
306}
307
308impl EvictionOutcome {
309    /// Whether the analysed peak now fits the budget.
310    pub fn fits(&self) -> bool {
311        self.peak_after <= self.budget_bytes
312    }
313}
314
315/// Graph-mutating eviction pass: while the graph's peak residency
316/// exceeds `budget_bytes`, pick the top candidate (by `bytes ×
317/// inactive_gap`) that has a realizable inactive gap and insert an
318/// `Op::Move{Cpu}` + reload `Op::Copy{device}` chain around it
319/// (via [`fuel_graph::opt::insert_evict_reload`]).
320///
321/// `placement_of` reports each candidate's resident
322/// [`DeviceLocation`] — callers on the pipelined path derive it from
323/// `graph.placement(id)` / the plan's stamped winners; `None` falls
324/// back to `Cpu` (the chain is then a same-device spill, correct but
325/// pure overhead — mirrors the legacy rule's default). The pass
326/// stamps `target_backend` on both emitted nodes (`Move` runs on the
327/// source device's backend, the reload's transfer kernel on `Cpu` —
328/// the staged copy's residency), so the chain compiles on the
329/// pipelined executor without a separate prepare pass.
330///
331/// Returns the inserted chains. Idempotent once the budget is met or
332/// no candidate has a gap ≥ 2 op positions; capped at `max_rounds`
333/// (16 is the legacy default) to prevent pathological loops. A realize root is never evicted
334/// (the caller reads its storage after the run, and a `Move` consumes it), and the pass stops at
335/// the first round that does not lower the analysed peak (see
336/// [`insert_residency_evictions_in`], which also reports the outcome).
337pub fn insert_residency_evictions(
338    graph: &SharedGraph,
339    roots: &[NodeId],
340    budget_bytes: usize,
341    max_rounds: usize,
342    placement_of: impl Fn(NodeId) -> Option<DeviceLocation>,
343) -> Result<Vec<EvictReload>> {
344    // The device whose budget this is: where the roots live (the pinned device on the production
345    // path), `Cpu` when unknown (a same-device spill, as before).
346    let device = roots
347        .first()
348        .and_then(|&r| placement_of(r))
349        .unwrap_or(DeviceLocation::Cpu);
350    let mut g = write_graph(graph)?;
351    Ok(insert_residency_evictions_in(
352        &mut g,
353        roots,
354        device,
355        budget_bytes,
356        max_rounds,
357        placement_of,
358    )?
359    .chains)
360}
361
362/// [`insert_residency_evictions`] on a graph the caller already holds mutably: what
363/// `optimize_graph` (which takes `&mut Graph`) calls when `PlanOptions::device_budget_bytes` is set.
364/// Same candidates, same stamps, and an [`EvictionOutcome`] instead of a bare list.
365///
366/// **It stops at the first round that does not lower the analysed peak.** Today the reload `Op::Copy`
367/// runs right after its `Op::Move` (nothing delays it; ROADMAP row 67 I3 adds the ordering
368/// primitive), so on a same-device budget a round cannot lower the peak, and without this stop the
369/// pass would insert a transfer pair per candidate, up to `max_rounds`, for no gain. The one chain
370/// that revealed the stall is kept (a graph cannot drop nodes) and the outcome reports
371/// `peak_after >= peak_before` and `!fits()`: the caller sees that the budget was NOT met.
372/// A realize root is never a candidate: the caller reads its storage after the run.
373pub fn insert_residency_evictions_in(
374    g: &mut Graph,
375    roots: &[NodeId],
376    device: DeviceLocation,
377    budget_bytes: usize,
378    max_rounds: usize,
379    placement_of: impl Fn(NodeId) -> Option<DeviceLocation>,
380) -> Result<EvictionOutcome> {
381    // Track candidates we've already evicted this run. Without this
382    // guard, a just-evicted candidate's new consumers (its own Move)
383    // show up as post-gap consumers in the next round, triggering
384    // infinite re-eviction.
385    let mut evicted: std::collections::HashSet<NodeId> = std::collections::HashSet::new();
386    let mut chains: Vec<EvictReload> = Vec::new();
387    let peak_before = ResidencyPlanner::analyze_on(g, roots, device).peak_bytes;
388    let mut peak = peak_before;
389
390    for _round in 0..max_rounds {
391        let report = ResidencyPlanner::analyze_on(g, roots, device);
392        if report.fits_in(budget_bytes) {
393            break;
394        }
395        // Pick the top candidate that still has a realizable gap AND
396        // hasn't been evicted already in this run.
397        let Some((cand, post_gap_consumers)) =
398            first_evictable(g, roots, &report.eviction_candidates, &evicted)
399        else {
400            break;
401        };
402        let src_device = placement_of(cand).unwrap_or(DeviceLocation::Cpu);
403        chains.push(evict_one(g, cand, src_device, &post_gap_consumers));
404        evicted.insert(cand);
405        let after = ResidencyPlanner::analyze_on(g, roots, device).peak_bytes;
406        let progressed = after < peak;
407        peak = after;
408        if !progressed {
409            break;
410        }
411    }
412    Ok(EvictionOutcome {
413        device,
414        budget_bytes,
415        peak_before,
416        peak_after: peak,
417        chains,
418        budget_source: None,
419    })
420}
421
422/// The highest-ranked candidate that was not evicted yet, is not a realize root, and has post-gap
423/// consumers to rewire.
424fn first_evictable(
425    g: &Graph,
426    roots: &[NodeId],
427    candidates: &[LiveRange],
428    evicted: &std::collections::HashSet<NodeId>,
429) -> Option<(NodeId, Vec<NodeId>)> {
430    candidates.iter().find_map(|c| {
431        if roots.contains(&c.node) || evicted.contains(&c.node) || already_evicted(g, c.node) {
432            return None;
433        }
434        match find_gap_consumers(g, c.node) {
435            Some((_pre_gap, post)) if !post.is_empty() => Some((c.node, post)),
436            _ => None,
437        }
438    })
439}
440
441/// Insert one evict/reload chain for `candidate` and stamp the transfer pair so the pipelined
442/// executor's `Op::Move` / `Op::Copy` compile arms (which need an explicit `target_backend`, the
443/// backend whose kernel runs the transfer) resolve without a prepare pass: the Move downloads
444/// from `src_device`'s backend; the reload uploads from the staged CPU copy.
445fn evict_one(
446    g: &mut Graph,
447    candidate: NodeId,
448    src_device: DeviceLocation,
449    post_gap_consumers: &[NodeId],
450) -> EvictReload {
451    let (move_id, reload_id) =
452        opt::insert_evict_reload_in(g, candidate, src_device, post_gap_consumers);
453    g.set_target_backend(move_id, backend_for_device(src_device));
454    g.set_target_backend(reload_id, backend_for_device(DeviceLocation::Cpu));
455    g.set_placement(move_id, DeviceLocation::Cpu);
456    g.set_placement(reload_id, src_device);
457    EvictReload {
458        candidate,
459        move_node: move_id,
460        reload: reload_id,
461        src_device,
462    }
463}
464
465/// Whether `candidate` already feeds an `Op::Move` (from an earlier run of this pass, or from any
466/// other transfer: ANY `Move` blocks, which can miss an optimisation but never double-moves).
467/// A second destructive consumer of the same source makes the Moves wait on each other:
468/// `execution_plan` then panics with "cycle in ordering edges". So a candidate is evicted at
469/// most once across runs, not just within one (`evicted` below only covers one run).
470fn already_evicted(g: &Graph, candidate: NodeId) -> bool {
471    (0..g.len()).any(|i| {
472        let n = g.node(NodeId(i));
473        matches!(n.op, Op::Move { .. }) && n.inputs.first() == Some(&candidate)
474    })
475}
476
477/// Find the pre-gap and post-gap consumers of `candidate` — i.e., the
478/// consumer that reads it just before its longest inactive stretch,
479/// and the consumer(s) that read it after.
480///
481/// Returns `None` if the candidate has fewer than two consumers, or if
482/// the largest gap is < 2 op positions (no meaningful window to evict
483/// into).
484fn find_gap_consumers(g: &Graph, candidate: NodeId) -> Option<(NodeId, Vec<NodeId>)> {
485    // Walk EVERY node as a synthetic root set — the pass needs to see
486    // ALL consumers of a candidate, not just those on a specific
487    // root's path.
488    let all: Vec<NodeId> = (0..g.len()).map(NodeId).collect();
489    let order = topo_order_multi(g, &all);
490
491    // Positions of candidate's consumers in topo order.
492    let mut positions: Vec<(usize, NodeId)> = Vec::new();
493    for (i, &nid) in order.iter().enumerate() {
494        if g.node(nid).inputs.contains(&candidate) {
495            positions.push((i, nid));
496        }
497    }
498
499    if positions.len() < 2 {
500        return None;
501    }
502
503    // Find the largest gap between consecutive consumer positions.
504    let mut best_gap = 0usize;
505    let mut gap_idx = 0usize;
506    for i in 0..positions.len() - 1 {
507        let gap = positions[i + 1].0 - positions[i].0;
508        if gap > best_gap {
509            best_gap = gap;
510            gap_idx = i;
511        }
512    }
513
514    if best_gap < 2 {
515        return None;
516    }
517
518    let last_before = positions[gap_idx].1;
519    let after_gap: Vec<NodeId> = positions[gap_idx + 1..].iter().map(|(_, n)| *n).collect();
520
521    Some((last_before, after_gap))
522}
523
524fn write_graph(graph: &SharedGraph) -> Result<std::sync::RwLockWriteGuard<'_, Graph>> {
525    graph
526        .write()
527        .map_err(|_| Error::Msg("residency: graph RwLock poisoned".into()).bt())
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use crate::pipelined::{PipelinedExecutor, StorageCache};
534    use fuel_graph::Node;
535    use fuel_ir::{DType, Shape, probe::BackendId};
536    use std::sync::{Arc, RwLock};
537
538    fn shared() -> SharedGraph {
539        Arc::new(RwLock::new(Graph::new()))
540    }
541
542    fn push(g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize]) -> NodeId {
543        g.push(Node {
544            op,
545            inputs,
546            shape: Shape::from_dims(dims),
547            dtype: DType::F32,
548        })
549    }
550
551    fn count_op(graph: &SharedGraph, pred: impl Fn(&Op) -> bool) -> usize {
552        let g = graph.read().unwrap();
553        (0..g.len())
554            .filter(|i| pred(&g.node(NodeId(*i)).op))
555            .count()
556    }
557
558    // ---- analysis (ported from fuel-graph-router residency_planner) ----
559
560    /// A graph with no shared consumption: each intermediate is used
561    /// exactly once by its direct successor. Peak bytes should equal
562    /// the maximum of (input + output) at any op.
563    #[test]
564    fn chain_graph_peak_is_two_live_tensors() {
565        // a = const[1024]  1024 * 4 = 4096 bytes
566        // b = relu(a)      4096 bytes
567        // c = neg(b)       4096 bytes
568        // Peak: when c is produced, a is already dead (last-use was
569        // relu), so live set is {b, c} = 8192 bytes.
570        let graph = shared();
571        let c = {
572            let mut g = graph.write().unwrap();
573            let a = push(&mut g, Op::Const, vec![], &[1024]);
574            let b = push(&mut g, Op::Relu, vec![a], &[1024]);
575            push(&mut g, Op::Neg, vec![b], &[1024])
576        };
577        let g = graph.read().unwrap();
578        let report = ResidencyPlanner::analyze(&g, &[c]);
579        assert_eq!(report.total_bytes, 4096 * 3);
580        assert_eq!(report.peak_bytes, 4096 * 2);
581    }
582
583    #[test]
584    fn shared_const_stays_live_across_multiple_uses() {
585        // a is consumed twice — by add(a, b) and (later) by neg(a) —
586        // so it stays live across the gap and shows up as an eviction
587        // candidate with a non-zero inactive_gap.
588        let graph = shared();
589        let (a, sum) = {
590            let mut g = graph.write().unwrap();
591            let a = push(&mut g, Op::Const, vec![], &[256]);
592            let b = push(&mut g, Op::Const, vec![], &[256]);
593            let ab = push(&mut g, Op::Add, vec![a, b], &[256]);
594            let na = push(&mut g, Op::Neg, vec![a], &[256]);
595            let sum = push(&mut g, Op::Add, vec![ab, na], &[256]);
596            (a, sum)
597        };
598        let g = graph.read().unwrap();
599        let report = ResidencyPlanner::analyze(&g, &[sum]);
600        let a_range = report.eviction_candidates.iter().find(|c| c.node == a);
601        assert!(
602            a_range.is_some() || report.peak_bytes > 0,
603            "expected `a` tracked with a gap OR at least some peak bytes",
604        );
605    }
606
607    #[test]
608    fn report_fits_in_and_overage() {
609        let graph = shared();
610        let b = {
611            let mut g = graph.write().unwrap();
612            let a = push(&mut g, Op::Const, vec![], &[256]);
613            push(&mut g, Op::Relu, vec![a], &[256])
614        };
615        let g = graph.read().unwrap();
616        let report = ResidencyPlanner::analyze(&g, &[b]);
617        assert!(report.fits_in(10_000));
618        assert!(!report.fits_in(1));
619        assert_eq!(report.overage(10_000), 0);
620        assert!(report.overage(1) > 0);
621    }
622
623    // ---- transform (ported from residency_eviction, Move-shaped) ----
624
625    /// Build the canonical over-budget graph used by the legacy
626    /// rule's tests:
627    ///   a    = const[4]            (two consumers, gap in between)
628    ///   b    = relu(a)
629    ///   pad  = neg(b)
630    ///   pad2 = neg(pad)
631    ///   c    = mul(pad2, a)        (reads a AGAIN, after the gap)
632    ///   out  = add(b, c)
633    /// All compute nodes stamped Cpu so the pipelined executor can
634    /// compile them.
635    fn over_budget_graph() -> (SharedGraph, NodeId, NodeId) {
636        let graph = shared();
637        let (a, out) = {
638            let mut g = graph.write().unwrap();
639            let a = push(&mut g, Op::Const, vec![], &[4]);
640            let b = push(&mut g, Op::Relu, vec![a], &[4]);
641            let pad = push(&mut g, Op::Neg, vec![b], &[4]);
642            let pad2 = push(&mut g, Op::Neg, vec![pad], &[4]);
643            let c = push(&mut g, Op::Mul, vec![pad2, a], &[4]);
644            let out = push(&mut g, Op::Add, vec![b, c], &[4]);
645            for n in [b, pad, pad2, c, out] {
646                g.set_target_backend(n, BackendId::Cpu);
647            }
648            (a, out)
649        };
650        (graph, a, out)
651    }
652
653    #[test]
654    fn eviction_is_noop_under_budget() {
655        let (graph, _a, out) = over_budget_graph();
656        let moves_before = count_op(&graph, |op| matches!(op, Op::Move { .. }));
657        let copies_before = count_op(&graph, |op| matches!(op, Op::Copy { .. }));
658
659        let chains = insert_residency_evictions(&graph, &[out], 1_000_000_000, 16, |_| None)
660            .expect("eviction pass");
661        assert!(
662            chains.is_empty(),
663            "under-budget graph should emit no chains"
664        );
665        assert_eq!(
666            count_op(&graph, |op| matches!(op, Op::Move { .. })),
667            moves_before
668        );
669        assert_eq!(
670            count_op(&graph, |op| matches!(op, Op::Copy { .. })),
671            copies_before
672        );
673    }
674
675    #[test]
676    fn eviction_emits_move_reload_chain_when_over_budget() {
677        let (graph, a, out) = over_budget_graph();
678
679        // Budget: 1 byte (effectively zero).
680        let chains =
681            insert_residency_evictions(&graph, &[out], 1, 16, |_| Some(DeviceLocation::Cpu))
682                .expect("eviction pass");
683
684        assert!(
685            !chains.is_empty(),
686            "over-budget graph should emit at least one chain"
687        );
688        assert!(
689            count_op(&graph, |op| matches!(op, Op::Move { .. })) >= 1,
690            "over-budget graph should emit at least one Op::Move",
691        );
692        assert!(
693            count_op(&graph, |op| matches!(op, Op::Copy { .. })) >= 1,
694            "each chain carries a reload Op::Copy",
695        );
696
697        // The top-scoring candidate is `a` (biggest gap × bytes among
698        // multi-consumer nodes); its chain must be Move(a) → Copy.
699        let chain = chains
700            .iter()
701            .find(|c| c.candidate == a)
702            .unwrap_or(&chains[0]);
703        let g = graph.read().unwrap();
704        assert!(matches!(
705            g.node(chain.move_node).op,
706            Op::Move {
707                target: DeviceLocation::Cpu
708            },
709        ));
710        assert_eq!(g.node(chain.reload).inputs, vec![chain.move_node]);
711        // Both stamped so the pipelined executor can compile them.
712        assert_eq!(g.target_backend(chain.move_node), Some(BackendId::Cpu));
713        assert_eq!(g.target_backend(chain.reload), Some(BackendId::Cpu));
714    }
715
716    /// `analyze_on` does not count the staged host copy of an eviction as bytes of the planned
717    /// device, and the order-blind, residency-blind `analyze` does (the second flaw the
718    /// eviction loop had: it measured a number the evictions could not move).
719    #[test]
720    fn analyze_on_does_not_count_the_staged_host_copy() {
721        let cuda = DeviceLocation::Cuda { gpu_id: 0 };
722        let graph = shared();
723        let out = {
724            let mut g = graph.write().unwrap();
725            let a = push(&mut g, Op::Const, vec![], &[4]);
726            let b = push(&mut g, Op::Relu, vec![a], &[4]);
727            let staged = push(
728                &mut g,
729                Op::Move {
730                    target: DeviceLocation::Cpu,
731                },
732                vec![a],
733                &[4],
734            );
735            push(&mut g, Op::Add, vec![b, staged], &[4])
736        };
737        let g = graph.read().unwrap();
738        let blind = ResidencyPlanner::analyze(&g, &[out]).peak_bytes;
739        let on = ResidencyPlanner::analyze_on(&g, &[out], cuda).peak_bytes;
740        assert!(
741            on < blind,
742            "device peak {on} must be below the blind peak {blind}"
743        );
744        // Control: on the CPU itself the Move{Cpu} output IS resident, so nothing is discounted.
745        let on_cpu = ResidencyPlanner::analyze_on(&g, &[out], DeviceLocation::Cpu).peak_bytes;
746        assert_eq!(on_cpu, blind);
747    }
748
749    /// CHARACTERISATION of a known limitation, not a goal: today the executor's order runs the
750    /// reload `Op::Copy` right after its `Op::Move` (nothing delays it; there is no way to ask for
751    /// "reload just before the first post-gap consumer"), so one eviction round does NOT lower the
752    /// analysed device peak on this graph (64 -> 64 bytes). ROADMAP row 67 I3 adds the ordering
753    /// primitive; when it lands this test flips to assert a drop.
754    #[test]
755    fn today_the_reload_runs_eagerly_so_the_device_peak_does_not_drop() {
756        let cuda = DeviceLocation::Cuda { gpu_id: 0 };
757        let (graph, _a, out) = over_budget_graph();
758        let before = ResidencyPlanner::analyze_on(&graph.read().unwrap(), &[out], cuda).peak_bytes;
759        let chains = insert_residency_evictions(&graph, &[out], before - 1, 16, |_| Some(cuda))
760            .expect("eviction pass");
761        assert!(!chains.is_empty(), "a budget below the peak must evict");
762        let g = graph.read().unwrap();
763        let order = fuel_graph::opt::execution_plan(&g, &[out]);
764        let pos = |n: NodeId| order.iter().position(|&x| x == n).unwrap();
765        let c = &chains[0];
766        assert_eq!(
767            pos(c.reload),
768            pos(c.move_node) + 1,
769            "the reload follows its Move immediately in the executor's order"
770        );
771        let after = ResidencyPlanner::analyze_on(&g, &[out], cuda).peak_bytes;
772        assert_eq!(after, before, "so the analysed peak is unchanged");
773    }
774
775    /// Regression: a candidate already feeding an eviction `Op::Move` is not evicted again by a
776    /// second run. Two destructive Moves of one source wait on each other and `execution_plan`
777    /// panics ("cycle in ordering edges"); the old pass only remembered candidates within one run.
778    #[test]
779    fn a_candidate_is_evicted_at_most_once_across_runs() {
780        let (graph, _a, out) = over_budget_graph();
781        let first = insert_residency_evictions(&graph, &[out], 0, 16, |_| None).expect("run 1");
782        assert!(!first.is_empty());
783        let second = insert_residency_evictions(&graph, &[out], 0, 16, |_| None).expect("run 2");
784        let evicted_before: Vec<NodeId> = first.iter().map(|c| c.candidate).collect();
785        assert!(
786            second
787                .iter()
788                .all(|c| !evicted_before.contains(&c.candidate)),
789            "run 2 re-evicted a candidate of run 1"
790        );
791        // The graph must still be orderable (this panics on a cycle).
792        let g = graph.read().unwrap();
793        let _ = fuel_graph::opt::execution_plan(&g, &[out]);
794    }
795
796    /// Correctness invariant: graph surgery for residency must be
797    /// transparent to the result. Realize the same graph WITHOUT and
798    /// WITH the eviction pass through the PRODUCTION executor and
799    /// compare bit-exactly. (The legacy twin realized through
800    /// `GraphExecutor<CpuBackend>`; this is the pipelined port.)
801    #[test]
802    fn eviction_preserves_correctness_end_to_end_on_pipelined() {
803        // a    = [-1, 2, -3, 4]
804        // b    = relu(a)  = [0, 2, 0, 4]
805        // pad  = neg(b)   = [0, -2, 0, -4]
806        // pad2 = neg(pad) = [0, 2, 0, 4]
807        // c    = pad2 * a = [0, 4, 0, 16]
808        // out  = b + c    = [0, 6, 0, 20]
809        let realize = |evict: bool| -> Vec<f32> {
810            let (graph, a, out) = over_budget_graph();
811            if evict {
812                let chains = insert_residency_evictions(&graph, &[out], 1, 16, |_| {
813                    Some(DeviceLocation::Cpu)
814                })
815                .expect("eviction pass");
816                assert!(!chains.is_empty(), "budget=1 must trigger eviction");
817            }
818            let mut inputs = StorageCache::new();
819            inputs.insert(
820                a,
821                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
822                    -1.0_f32, 2.0, -3.0, 4.0,
823                ]))),
824            );
825            let (storage, _layout) =
826                PipelinedExecutor::realize(graph, out, inputs).expect("realize");
827            let guard = storage.read().unwrap();
828            let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
829                panic!("expected CPU output");
830            };
831            c.as_slice::<f32>().unwrap().to_vec()
832        };
833
834        let baseline = realize(false);
835        let evicted = realize(true);
836        assert_eq!(
837            baseline, evicted,
838            "eviction must preserve the output bit-exactly",
839        );
840        assert_eq!(baseline, vec![0.0_f32, 6.0, 0.0, 20.0]);
841    }
842
843    /// Review finding 2 (Pip, #498): a realize root must never be evicted. The caller reads the root's
844    /// storage after the run and an `Op::Move` consumes its source. `a` is the best candidate here
845    /// (live from the start, read early and late), so making it a root is exactly the hazard.
846    #[test]
847    fn a_realize_root_is_never_evicted() {
848        let (graph, a, out) = over_budget_graph();
849        let chains =
850            insert_residency_evictions(&graph, &[a, out], 1, 16, |_| Some(DeviceLocation::Cpu))
851                .expect("eviction pass");
852        assert!(
853            chains.iter().all(|c| c.candidate != a),
854            "the root `a` was evicted: {chains:?}"
855        );
856        // Control: with `a` NOT a root it is the candidate the pass picks (so the exclusion above
857        // is what spared it, not an absence of gap).
858        let (graph, a, out) = over_budget_graph();
859        let chains =
860            insert_residency_evictions(&graph, &[out], 1, 16, |_| Some(DeviceLocation::Cpu))
861                .expect("eviction pass");
862        assert!(
863            chains.iter().any(|c| c.candidate == a),
864            "control: without the root exclusion `a` is evicted"
865        );
866    }
867
868    /// Review finding 1 (Pip, #498): a round that does not lower the analysed peak ends the pass, and
869    /// the outcome says the budget was not met. Today (no reload delay, row 67 I3) no round can, so a
870    /// same-device budget keeps ONE chain, not `max_rounds` of them, and `fits()` is false.
871    #[test]
872    fn a_round_that_does_not_lower_the_peak_stops_and_is_reported() {
873        let cuda = DeviceLocation::Cuda { gpu_id: 0 };
874        let (graph, _a, out) = over_budget_graph();
875        let mut g = graph.write().unwrap();
876        let before = ResidencyPlanner::analyze_on(&g, &[out], cuda).peak_bytes;
877        let outcome =
878            insert_residency_evictions_in(&mut g, &[out], cuda, before - 1, 16, |_| Some(cuda))
879                .expect("eviction pass");
880        assert_eq!(outcome.peak_before, before);
881        assert_eq!(
882            outcome.chains.len(),
883            1,
884            "a stalled pass must stop after the round that showed the stall, not run to max_rounds"
885        );
886        assert!(outcome.peak_after >= outcome.peak_before);
887        assert!(
888            !outcome.fits(),
889            "the budget was NOT met and the outcome must say so"
890        );
891        // Control: a budget the graph already fits reports fits() and inserts nothing.
892        let ok =
893            insert_residency_evictions_in(&mut g, &[out], cuda, usize::MAX, 16, |_| Some(cuda))
894                .expect("eviction pass");
895        assert!(ok.fits() && ok.chains.is_empty());
896    }
897
898    /// Review question 1 (Pip, #498): a post-gap consumer that reads the candidate twice has BOTH
899    /// input slots rewired to the reload (`rewrite_input` replaces every matching slot).
900    #[test]
901    fn a_candidate_read_twice_by_one_consumer_is_rewired_in_both_slots() {
902        // `late` = Where(pad2, a, a) reads `a` in two slots and sits after the long chain, so it is
903        // the post-gap consumer; `early` = Relu(a) is the pre-gap one.
904        let graph = shared();
905        let (a, pad2, late) = {
906            let mut g = graph.write().unwrap();
907            let a = push(&mut g, Op::Const, vec![], &[4]);
908            let early = push(&mut g, Op::Relu, vec![a], &[4]);
909            let pad = push(&mut g, Op::Neg, vec![early], &[4]);
910            let pad2 = push(&mut g, Op::Neg, vec![pad], &[4]);
911            let late = push(&mut g, Op::Where, vec![pad2, a, a], &[4]);
912            for n in [early, pad, pad2, late] {
913                g.set_target_backend(n, BackendId::Cpu);
914            }
915            (a, pad2, late)
916        };
917        let chains =
918            insert_residency_evictions(&graph, &[late], 1, 4, |_| Some(DeviceLocation::Cpu))
919                .expect("eviction pass");
920        let chain = chains
921            .iter()
922            .find(|c| c.candidate == a)
923            .expect("`a` is evicted");
924        let g = graph.read().unwrap();
925        assert_eq!(
926            g.node(late).inputs,
927            vec![pad2, chain.reload, chain.reload],
928            "both slots that read `a` must read the reload"
929        );
930    }
931
932    /// Idempotence guard: re-running the pass after the budget can't
933    /// be met must not grow the graph unboundedly (the `evicted` set
934    /// + `progressed` exit cover it within a run; `max_rounds` caps
935    ///
936    /// across rounds).
937    #[test]
938    fn eviction_terminates_when_budget_unreachable() {
939        let (graph, _a, out) = over_budget_graph();
940        let chains =
941            insert_residency_evictions(&graph, &[out], 0, 16, |_| None).expect("eviction pass");
942        let len_after = graph.read().unwrap().len();
943        // A second run finds the same candidates already evicted (or
944        // gapless) and makes no further progress.
945        let chains2 = insert_residency_evictions(&graph, &[out], 0, 16, |_| None)
946            .expect("second eviction pass");
947        let len_final = graph.read().unwrap().len();
948        assert!(chains.len() <= 16);
949        // The post-surgery graph rewires post-gap consumers onto the
950        // reload, so re-analysis finds at most a bounded set of new
951        // multi-consumer candidates; the key invariant is termination
952        // with bounded growth, not zero growth.
953        assert!(chains2.len() <= 16);
954        assert!(len_final >= len_after);
955        assert!(len_final - len_after <= 2 * chains2.len());
956    }
957}