Skip to main content

fuel_dispatch/
optimizer_trace.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! One place to read what the optimizer dropped and what the executor chose (ROADMAP rows 157, 158).
3//!
4//! Two kinds of event, both cheap and always on:
5//!
6//! - **The executor's arm choice.** Every `Op::Branch` the streaming walk resolves bumps one atomic per
7//!   arm index (`0`, `1`, `2`, and `3` for "3 or more"). No allocation, no lock.
8//! - **What the region pathfinder did with its candidates.** Candidates dropped because they overlap a
9//!   larger chosen region, branches recorded, branches collapsed to one arm, and branches
10//!   `finalize_branches` REJECTED, with the reason. Rejections used to be thrown away (`.ok().flatten()`);
11//!   the reasons are kept here, newest [`MAX_KEPT_REJECTIONS`], behind a lock that only a rejection takes.
12//!
13//! Read it with [`snapshot`]; compare two snapshots with [`TraceSnapshot::since`]. The counters are
14//! process-wide and monotonic, so a test that wants "this realize only" takes a snapshot before and after.
15//! `FUEL_PRINT_BRANCH_COUNT=1` still prints the same events as they happen.
16
17use std::collections::VecDeque;
18use std::sync::Mutex;
19use std::sync::atomic::{AtomicU64, Ordering};
20
21use fuel_ir::probe::BackendId;
22
23/// How many rejection reasons are kept (the newest).
24pub const MAX_KEPT_REJECTIONS: usize = 16;
25
26/// Number of arm-index slots: arms `0`, `1`, `2`, and slot `3` for arm 3 and above.
27pub const ARM_SLOTS: usize = 4;
28
29/// Backend slots for [`Trace::record_lookup_none`]: `Cpu`, `Cuda`, `Vulkan`, `Metal`, and slot 4 for
30/// any other backend.
31pub const BACKEND_SLOTS: usize = 5;
32
33fn backend_slot(backend: BackendId) -> usize {
34    match backend {
35        BackendId::Cpu => 0,
36        BackendId::Cuda => 1,
37        BackendId::Vulkan => 2,
38        BackendId::Metal => 3,
39        _ => 4,
40    }
41}
42
43/// The counters. The process has one ([`global`]); tests build their own so they cannot race with
44/// the rest of the test binary.
45pub struct Trace {
46    arm_chosen: [AtomicU64; ARM_SLOTS],
47    lookup_none: [AtomicU64; BACKEND_SLOTS],
48    overlap_dropped: AtomicU64,
49    recorded: AtomicU64,
50    collapsed: AtomicU64,
51    rejected: AtomicU64,
52    backlog_added_ns: AtomicU64,
53    backlog_retired_ns: AtomicU64,
54    rejections: Mutex<VecDeque<String>>,
55}
56
57/// A copy of the counters at one moment.
58#[derive(Clone, Debug, Default, PartialEq, Eq)]
59pub struct TraceSnapshot {
60    /// Branches resolved to arm `i` (slot 3 = arm 3 and above).
61    pub arm_chosen: [u64; ARM_SLOTS],
62    /// Per backend slot (`Cpu`, `Cuda`, `Vulkan`, `Metal`, other): how often the selector's runtime
63    /// lookup returned NO handle for a candidate, so the picker had no VRAM or load signal for it.
64    pub lookup_none: [u64; BACKEND_SLOTS],
65    /// Region candidates dropped because they overlap a larger chosen region.
66    pub overlap_dropped: u64,
67    /// Branches recorded by the pathfinder.
68    pub recorded: u64,
69    /// Branches that collapsed to a single arm (no decision point).
70    pub collapsed: u64,
71    /// Branches `finalize_branches` rejected.
72    pub rejected: u64,
73    /// Estimated nanoseconds the executor added to a device's backlog (row 158: every kernel it submitted
74    /// to a GPU, at the node's compile-time estimate).
75    pub backlog_added_ns: u64,
76    /// Estimated nanoseconds taken back out of a device's backlog when the realize that added them ended.
77    /// Equal to `backlog_added_ns` once every realize has returned; a gap is a leak.
78    pub backlog_retired_ns: u64,
79    /// The newest rejection reasons, oldest first (at most [`MAX_KEPT_REJECTIONS`]).
80    pub rejections: Vec<String>,
81}
82
83impl TraceSnapshot {
84    /// Counter growth since `earlier` (saturating). `rejections` is the reasons added since: the
85    /// newest `rejected` growth entries of this snapshot's kept reasons.
86    pub fn since(&self, earlier: &TraceSnapshot) -> TraceSnapshot {
87        let mut arm_chosen = [0u64; ARM_SLOTS];
88        for (i, slot) in arm_chosen.iter_mut().enumerate() {
89            *slot = self.arm_chosen[i].saturating_sub(earlier.arm_chosen[i]);
90        }
91        let mut lookup_none = [0u64; BACKEND_SLOTS];
92        for (i, slot) in lookup_none.iter_mut().enumerate() {
93            *slot = self.lookup_none[i].saturating_sub(earlier.lookup_none[i]);
94        }
95        let rejected = self.rejected.saturating_sub(earlier.rejected);
96        let keep = (rejected as usize).min(self.rejections.len());
97        TraceSnapshot {
98            arm_chosen,
99            lookup_none,
100            overlap_dropped: self.overlap_dropped.saturating_sub(earlier.overlap_dropped),
101            recorded: self.recorded.saturating_sub(earlier.recorded),
102            collapsed: self.collapsed.saturating_sub(earlier.collapsed),
103            rejected,
104            backlog_added_ns: self
105                .backlog_added_ns
106                .saturating_sub(earlier.backlog_added_ns),
107            backlog_retired_ns: self
108                .backlog_retired_ns
109                .saturating_sub(earlier.backlog_retired_ns),
110            rejections: self.rejections[self.rejections.len() - keep..].to_vec(),
111        }
112    }
113
114    /// Total branches resolved, over every arm slot.
115    pub fn branches_resolved(&self) -> u64 {
116        self.arm_chosen.iter().sum()
117    }
118}
119
120impl Trace {
121    /// An empty trace.
122    pub const fn new() -> Self {
123        Self {
124            arm_chosen: [
125                AtomicU64::new(0),
126                AtomicU64::new(0),
127                AtomicU64::new(0),
128                AtomicU64::new(0),
129            ],
130            lookup_none: [
131                AtomicU64::new(0),
132                AtomicU64::new(0),
133                AtomicU64::new(0),
134                AtomicU64::new(0),
135                AtomicU64::new(0),
136            ],
137            overlap_dropped: AtomicU64::new(0),
138            recorded: AtomicU64::new(0),
139            collapsed: AtomicU64::new(0),
140            rejected: AtomicU64::new(0),
141            backlog_added_ns: AtomicU64::new(0),
142            backlog_retired_ns: AtomicU64::new(0),
143            rejections: Mutex::new(VecDeque::new()),
144        }
145    }
146
147    /// The executor resolved a branch to arm `arm`.
148    pub fn record_arm_chosen(&self, arm: usize) {
149        self.arm_chosen[arm.min(ARM_SLOTS - 1)].fetch_add(1, Ordering::Relaxed);
150    }
151
152    /// The selector's runtime lookup returned no handle for a candidate on `backend` (it had a lookup
153    /// configured), so the picker had no VRAM or load signal for that candidate.
154    pub fn record_lookup_none(&self, backend: BackendId) {
155        self.lookup_none[backend_slot(backend)].fetch_add(1, Ordering::Relaxed);
156    }
157
158    /// The pathfinder's outcome for one `propose` pass.
159    pub fn record_regions(
160        &self,
161        overlap_dropped: usize,
162        recorded: usize,
163        collapsed: usize,
164        rejection_reasons: &[String],
165    ) {
166        self.overlap_dropped
167            .fetch_add(overlap_dropped as u64, Ordering::Relaxed);
168        self.recorded.fetch_add(recorded as u64, Ordering::Relaxed);
169        self.collapsed
170            .fetch_add(collapsed as u64, Ordering::Relaxed);
171        self.rejected
172            .fetch_add(rejection_reasons.len() as u64, Ordering::Relaxed);
173        if rejection_reasons.is_empty() {
174            return;
175        }
176        // A poisoned lock only means a reason was lost; counting must never panic.
177        if let Ok(mut kept) = self.rejections.lock() {
178            for reason in rejection_reasons {
179                if kept.len() == MAX_KEPT_REJECTIONS {
180                    kept.pop_front();
181                }
182                kept.push_back(reason.clone());
183            }
184        }
185    }
186
187    /// The executor added `ns` of estimated work to a device's backlog.
188    pub fn record_backlog_added(&self, ns: u64) {
189        let _ = self
190            .backlog_added_ns
191            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
192                Some(v.saturating_add(ns))
193            });
194    }
195
196    /// The executor took `ns` back out of a device's backlog (its realize ended or unwound).
197    pub fn record_backlog_retired(&self, ns: u64) {
198        let _ = self
199            .backlog_retired_ns
200            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
201                Some(v.saturating_add(ns))
202            });
203    }
204
205    /// Copy the counters.
206    pub fn snapshot(&self) -> TraceSnapshot {
207        let mut arm_chosen = [0u64; ARM_SLOTS];
208        for (i, slot) in arm_chosen.iter_mut().enumerate() {
209            *slot = self.arm_chosen[i].load(Ordering::Relaxed);
210        }
211        let mut lookup_none = [0u64; BACKEND_SLOTS];
212        for (i, slot) in lookup_none.iter_mut().enumerate() {
213            *slot = self.lookup_none[i].load(Ordering::Relaxed);
214        }
215        TraceSnapshot {
216            arm_chosen,
217            lookup_none,
218            overlap_dropped: self.overlap_dropped.load(Ordering::Relaxed),
219            recorded: self.recorded.load(Ordering::Relaxed),
220            collapsed: self.collapsed.load(Ordering::Relaxed),
221            rejected: self.rejected.load(Ordering::Relaxed),
222            backlog_added_ns: self.backlog_added_ns.load(Ordering::Relaxed),
223            backlog_retired_ns: self.backlog_retired_ns.load(Ordering::Relaxed),
224            rejections: self
225                .rejections
226                .lock()
227                .map(|kept| kept.iter().cloned().collect())
228                .unwrap_or_default(),
229        }
230    }
231}
232
233impl Default for Trace {
234    fn default() -> Self {
235        Self::new()
236    }
237}
238
239static GLOBAL: Trace = Trace::new();
240
241/// The process-wide trace the executor and the pathfinder write to.
242pub fn global() -> &'static Trace {
243    &GLOBAL
244}
245
246/// A copy of the process-wide counters.
247pub fn snapshot() -> TraceSnapshot {
248    GLOBAL.snapshot()
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn arm_choices_count_per_arm_and_clamp_the_tail() {
257        let t = Trace::new();
258        t.record_arm_chosen(0);
259        t.record_arm_chosen(0);
260        t.record_arm_chosen(1);
261        t.record_arm_chosen(7); // arm 3 and above share slot 3
262        let s = t.snapshot();
263        assert_eq!(s.arm_chosen, [2, 1, 0, 1]);
264        assert_eq!(s.branches_resolved(), 4);
265    }
266
267    #[test]
268    fn region_outcomes_accumulate_and_rejections_keep_their_reason() {
269        let t = Trace::new();
270        t.record_regions(5, 2, 1, &["InvalidBranch: shape".to_string()]);
271        t.record_regions(0, 1, 0, &[]);
272        let s = t.snapshot();
273        assert_eq!(
274            (s.overlap_dropped, s.recorded, s.collapsed, s.rejected),
275            (5, 3, 1, 1)
276        );
277        assert_eq!(s.rejections, vec!["InvalidBranch: shape".to_string()]);
278    }
279
280    #[test]
281    fn only_the_newest_rejection_reasons_are_kept_but_all_are_counted() {
282        let t = Trace::new();
283        let reasons: Vec<String> = (0..MAX_KEPT_REJECTIONS + 4)
284            .map(|i| format!("reason {i}"))
285            .collect();
286        t.record_regions(0, 0, 0, &reasons);
287        let s = t.snapshot();
288        assert_eq!(s.rejected as usize, MAX_KEPT_REJECTIONS + 4);
289        assert_eq!(s.rejections.len(), MAX_KEPT_REJECTIONS);
290        assert_eq!(s.rejections.first().map(String::as_str), Some("reason 4"));
291        assert_eq!(
292            s.rejections.last().map(String::as_str),
293            Some("reason 19"),
294            "the newest is kept"
295        );
296    }
297
298    #[test]
299    fn since_reports_only_the_growth_and_the_reasons_added() {
300        let t = Trace::new();
301        t.record_arm_chosen(0);
302        t.record_regions(1, 1, 0, &["old".to_string()]);
303        let before = t.snapshot();
304        t.record_arm_chosen(1);
305        t.record_arm_chosen(1);
306        t.record_regions(2, 0, 0, &["new a".to_string(), "new b".to_string()]);
307        let delta = t.snapshot().since(&before);
308        assert_eq!(delta.arm_chosen, [0, 2, 0, 0]);
309        assert_eq!(
310            (delta.overlap_dropped, delta.recorded, delta.rejected),
311            (2, 0, 2)
312        );
313        assert_eq!(
314            delta.rejections,
315            vec!["new a".to_string(), "new b".to_string()],
316            "the reasons added since, not the old one"
317        );
318    }
319
320    #[test]
321    fn lookup_misses_count_per_backend_and_show_in_since() {
322        let t = Trace::new();
323        t.record_lookup_none(BackendId::Vulkan);
324        let before = t.snapshot();
325        t.record_lookup_none(BackendId::Vulkan);
326        t.record_lookup_none(BackendId::Cpu);
327        let delta = t.snapshot().since(&before);
328        assert_eq!(delta.lookup_none, [1, 0, 1, 0, 0], "Cpu 1, Vulkan 1 since");
329        assert_eq!(t.snapshot().lookup_none, [1, 0, 2, 0, 0], "totals");
330    }
331
332    #[test]
333    fn a_fresh_trace_is_all_zero() {
334        assert_eq!(Trace::new().snapshot(), TraceSnapshot::default());
335    }
336}