Skip to main content

fuel_dispatch/
device_budget.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Where a pinned device's byte budget comes from (ROADMAP row 67, increment I2).
3//!
4//! `PlanOptions::device_budget_bytes` (I1) takes a number. This module is the policy that produces
5//! one, and says which rule produced it so a plan report never hides a guessed budget:
6//!
7//! 1. an **explicit** value from the caller wins;
8//! 2. else the [`DEVICE_BUDGET_ENV`] override (tests, or a box with a shared GPU);
9//! 3. else the **probed** free memory of the device times a reserve fraction
10//!    ([`DEFAULT_RESERVE_FRACTION`]).
11//!
12//! Nothing here is on by default. The realize path applies a budget only when
13//! [`DEVICE_BUDGET_ENV`] is set ([`device_budget_from_env`]); the probed rule is available to a
14//! caller through [`resolve_device_budget`]. The eviction pass reloads eagerly, and the delayed
15//! reload belongs to row 67 I3 (design-gated), so a default-on budget would add copies without
16//! lowering the analysed peak.
17
18/// Environment variable holding an explicit budget in bytes (decimal).
19pub const DEVICE_BUDGET_ENV: &str = "FUEL_DEVICE_BUDGET_BYTES";
20
21/// Share of the probed free memory a probed budget keeps (the rest is headroom for the driver, other
22/// processes, and allocations the analysis does not see).
23pub const DEFAULT_RESERVE_FRACTION: f64 = 0.9;
24
25/// Which rule produced a budget.
26#[derive(Debug, Clone, Copy, PartialEq)]
27pub enum BudgetSource {
28    /// The caller passed the number.
29    Explicit,
30    /// [`DEVICE_BUDGET_ENV`] supplied it.
31    Env,
32    /// `available_bytes * fraction`, from the device's live probe.
33    Probed {
34        /// The device's free bytes when probed.
35        available: u64,
36        /// The fraction of `available` kept as budget.
37        fraction: f64,
38    },
39}
40
41/// A budget and the rule that produced it.
42#[derive(Debug, Clone, Copy, PartialEq)]
43pub struct ResolvedBudget {
44    /// The budget, in bytes.
45    pub bytes: usize,
46    /// Which rule produced `bytes`.
47    pub source: BudgetSource,
48}
49
50/// Why a budget could not be resolved. A bad override is an error, never a silent fallback to the
51/// probe: the caller asked for a specific number.
52#[derive(Debug, Clone, PartialEq, thiserror::Error)]
53pub enum BudgetError {
54    /// [`DEVICE_BUDGET_ENV`] was set but is not a decimal byte count.
55    #[error("{DEVICE_BUDGET_ENV}={0:?} is not a decimal byte count")]
56    BadEnv(String),
57    /// The reserve fraction was outside `(0, 1]` or not finite.
58    #[error("reserve fraction {0} must be finite and in (0, 1]")]
59    BadFraction(f64),
60}
61
62/// Resolve a budget from its three sources. `env` is the raw value of [`DEVICE_BUDGET_ENV`]
63/// (`None` when unset); `available` is the device's free bytes (`None` when it cannot say).
64///
65/// Returns `Ok(None)` when no rule applies: nothing explicit, no override, and the device reports
66/// no usable figure (`None`, or `u64::MAX`, the "unbounded" convention of reference backends).
67/// `fraction` is validated even when an earlier rule wins, so a bad constant fails in every test
68/// run instead of only on a box that reaches the probe.
69pub fn resolve_device_budget(
70    explicit: Option<usize>,
71    env: Option<&str>,
72    available: Option<u64>,
73    fraction: f64,
74) -> Result<Option<ResolvedBudget>, BudgetError> {
75    check_fraction(fraction)?;
76    if let Some(bytes) = explicit {
77        return Ok(Some(ResolvedBudget {
78            bytes,
79            source: BudgetSource::Explicit,
80        }));
81    }
82    if let Some(raw) = env {
83        return parse_env(raw).map(Some);
84    }
85    Ok(probe(available, fraction))
86}
87
88fn check_fraction(fraction: f64) -> Result<(), BudgetError> {
89    if fraction.is_finite() && fraction > 0.0 && fraction <= 1.0 {
90        Ok(())
91    } else {
92        Err(BudgetError::BadFraction(fraction))
93    }
94}
95
96fn parse_env(raw: &str) -> Result<ResolvedBudget, BudgetError> {
97    let bytes = raw
98        .trim()
99        .parse::<usize>()
100        .map_err(|_| BudgetError::BadEnv(raw.to_string()))?;
101    Ok(ResolvedBudget {
102        bytes,
103        source: BudgetSource::Env,
104    })
105}
106
107/// `u64::MAX` is the "unbounded" convention of reference backends, not a figure to scale.
108fn probe(available: Option<u64>, fraction: f64) -> Option<ResolvedBudget> {
109    let avail = available.filter(|&a| a != u64::MAX)?;
110    Some(ResolvedBudget {
111        bytes: (avail as f64 * fraction) as usize,
112        source: BudgetSource::Probed {
113            available: avail,
114            fraction,
115        },
116    })
117}
118
119/// The opt-in the realize path uses: a budget only when [`DEVICE_BUDGET_ENV`] is set, `None` when
120/// it is unset. A value that is not decimal bytes (or not Unicode) is an error, so a typo in the
121/// override stops the run instead of silently leaving the pass off.
122pub fn device_budget_from_env() -> Result<Option<ResolvedBudget>, BudgetError> {
123    let env = match std::env::var(DEVICE_BUDGET_ENV) {
124        Ok(v) => Some(v),
125        Err(std::env::VarError::NotPresent) => None,
126        Err(std::env::VarError::NotUnicode(raw)) => {
127            return Err(BudgetError::BadEnv(raw.to_string_lossy().into_owned()));
128        }
129    };
130    resolve_device_budget(None, env.as_deref(), None, DEFAULT_RESERVE_FRACTION)
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    const F: f64 = DEFAULT_RESERVE_FRACTION;
138
139    #[test]
140    fn explicit_beats_env_and_probe() {
141        let r = resolve_device_budget(Some(7), Some("9"), Some(1000), F).unwrap();
142        assert_eq!(
143            r,
144            Some(ResolvedBudget {
145                bytes: 7,
146                source: BudgetSource::Explicit
147            })
148        );
149    }
150
151    #[test]
152    fn env_beats_probe() {
153        let r = resolve_device_budget(None, Some(" 4096 "), Some(1000), F).unwrap();
154        assert_eq!(
155            r,
156            Some(ResolvedBudget {
157                bytes: 4096,
158                source: BudgetSource::Env
159            })
160        );
161    }
162
163    #[test]
164    fn probe_keeps_the_reserve_fraction_and_records_its_inputs() {
165        let r = resolve_device_budget(None, None, Some(1000), 0.9)
166            .unwrap()
167            .unwrap();
168        assert_eq!(r.bytes, 900);
169        assert_eq!(
170            r.source,
171            BudgetSource::Probed {
172                available: 1000,
173                fraction: 0.9
174            }
175        );
176    }
177
178    #[test]
179    fn a_bad_env_value_is_an_error_not_a_fallback_to_the_probe() {
180        // Sabotage sibling of `env_beats_probe`: with a probe available, a fallback would return Some.
181        assert_eq!(
182            resolve_device_budget(None, Some("8GB"), Some(1000), F),
183            Err(BudgetError::BadEnv("8GB".into()))
184        );
185        assert!(resolve_device_budget(None, Some(""), Some(1000), F).is_err());
186        assert!(resolve_device_budget(None, Some("-1"), Some(1000), F).is_err());
187    }
188
189    #[test]
190    fn no_usable_probe_and_no_override_means_no_budget() {
191        assert_eq!(resolve_device_budget(None, None, None, F), Ok(None));
192        // Reference backends advertise "unbounded" as u64::MAX; that is not a budget.
193        assert_eq!(
194            resolve_device_budget(None, None, Some(u64::MAX), F),
195            Ok(None)
196        );
197        // Control: a finite figure on the same path does resolve.
198        assert!(
199            resolve_device_budget(None, None, Some(1), F)
200                .unwrap()
201                .is_some()
202        );
203    }
204
205    #[test]
206    fn the_fraction_is_validated_even_when_an_earlier_rule_wins() {
207        for bad in [0.0, -0.5, 1.5, f64::NAN, f64::INFINITY] {
208            assert!(
209                matches!(
210                    resolve_device_budget(Some(1), None, None, bad),
211                    Err(BudgetError::BadFraction(_))
212                ),
213                "fraction {bad}"
214            );
215        }
216        assert!(resolve_device_budget(Some(1), None, None, 1.0).is_ok());
217    }
218}