Skip to main content

spectral_budget/
lib.rs

1//! A budget primitive for bounded sequential domains: token windows,
2//! time horizons, request counts, anything where you need to refuse
3//! work that would exceed a principled ceiling.
4//!
5//! The framing comes from the Faber–Krahn inequality on the principal
6//! eigenvalue of a bounded Laplacian: a closed domain of diameter `d`
7//! with propagation speed `c` has a slowest mode with period
8//! `T_1 ≈ 2·d/c`. Capping aggregate diameter at `k · T_1` (default
9//! `k = 3`) keeps becoming finite. The same arithmetic applies whether
10//! `d` is photon path-length, an LLM token window, or an agent
11//! reasoning depth.
12//!
13//! ## Example
14//!
15//! ```
16//! use spectral_budget::SpectralBudget;
17//!
18//! // 200 000-token context window; admit up to 3·T_1.
19//! let budget = SpectralBudget {
20//!     principal_period: 200_000.0,
21//!     ring_down_factor: 3.0,
22//! };
23//!
24//! assert!(budget.admits(400_000.0));
25//! assert!(budget.try_admit(700_000.0).is_err());
26//! ```
27
28#![cfg_attr(docsrs, feature(doc_cfg))]
29#![forbid(unsafe_code)]
30
31use std::fmt;
32
33/// A ceiling on the diameter a bounded sequential domain may reach
34/// before its becoming exceeds the principal eigenvalue of the
35/// underlying Laplacian.
36///
37/// For a closed scene of diameter `d` with wave-speed `c`, the principal
38/// period is `T_1 ≈ 2·d/c` (Faber–Krahn). The recommended ceiling is
39/// `ring_down_factor · T_1` — capturing the first few rings of the
40/// lowest mode.
41#[derive(Copy, Clone, Debug)]
42pub struct SpectralBudget {
43    /// `T_1` — period of the lowest mode of the bounded domain.
44    pub principal_period: f64,
45    /// Multiplier on `T_1` defining the admission ceiling. `3.0` by
46    /// default — three ring-down cycles of the principal mode.
47    pub ring_down_factor: f64,
48}
49
50impl SpectralBudget {
51    /// Continuous Dirichlet bound for a scene of diameter `diam_m`
52    /// (metres) with propagation speed `c` (m/s). `T_1 = 2·diam/c`.
53    /// Useful for physical (path-tracer-style) budgets.
54    pub fn for_scene_diameter(diam_m: f64, c: f64) -> Self {
55        Self {
56            principal_period: 2.0 * diam_m / c,
57            ring_down_factor: 3.0,
58        }
59    }
60
61    /// Strict admission. Returns `Ok(())` if the diameter sits within
62    /// the `ring_down_factor · principal_period` ceiling; otherwise
63    /// returns the structured violation so the caller can decide to
64    /// abort, downgrade, or surface the error.
65    #[must_use = "handle the Err variant to surface budget violations"]
66    pub fn try_admit(&self, diameter: f64) -> Result<(), BudgetError> {
67        let bound = self.ring_down_factor * self.principal_period;
68        if diameter <= bound {
69            Ok(())
70        } else {
71            Err(BudgetError::Exceeded {
72                diameter,
73                bound,
74                principal_period: self.principal_period,
75                ring_down_factor: self.ring_down_factor,
76            })
77        }
78    }
79
80    /// Boolean shortcut where the caller does not need violation
81    /// detail. Prefer [`Self::try_admit`] when you need to surface the
82    /// reason.
83    #[must_use]
84    pub fn admits(&self, diameter: f64) -> bool {
85        self.try_admit(diameter).is_ok()
86    }
87}
88
89/// Failure modes of [`SpectralBudget`]. The `Display` impl is
90/// informative enough to surface directly at a user-facing prompt.
91#[derive(Debug)]
92#[non_exhaustive]
93pub enum BudgetError {
94    /// The candidate diameter exceeded `ring_down_factor · principal_period`.
95    Exceeded {
96        /// The diameter that was rejected.
97        diameter: f64,
98        /// The admission ceiling at the time of the call.
99        bound: f64,
100        /// `T_1`, the principal period of the bounded domain.
101        principal_period: f64,
102        /// The multiplier applied to `T_1` to compute `bound`.
103        ring_down_factor: f64,
104    },
105}
106
107impl fmt::Display for BudgetError {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match self {
110            BudgetError::Exceeded {
111                diameter,
112                bound,
113                principal_period,
114                ring_down_factor,
115            } => write!(
116                f,
117                "spectral budget exceeded: diameter {diameter:.3e} > \
118                 bound {bound:.3e} (T_1 = {principal_period:.3e}, \
119                 ring-down factor = {ring_down_factor:.2})"
120            ),
121        }
122    }
123}
124
125impl std::error::Error for BudgetError {}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    #[test]
132    fn admits_within_bound() {
133        let b = SpectralBudget { principal_period: 100.0, ring_down_factor: 3.0 };
134        assert!(b.admits(0.0));
135        assert!(b.admits(100.0));
136        assert!(b.admits(300.0));
137        assert!(!b.admits(300.1));
138    }
139
140    #[test]
141    fn exceeded_carries_diagnostic_fields() {
142        let b = SpectralBudget { principal_period: 100.0, ring_down_factor: 3.0 };
143        match b.try_admit(500.0) {
144            Err(BudgetError::Exceeded { diameter, bound, principal_period, ring_down_factor }) => {
145                assert_eq!(diameter, 500.0);
146                assert_eq!(bound, 300.0);
147                assert_eq!(principal_period, 100.0);
148                assert_eq!(ring_down_factor, 3.0);
149            }
150            other => panic!("expected Exceeded, got {other:?}"),
151        }
152    }
153
154    #[test]
155    fn for_scene_diameter_matches_faber_krahn() {
156        const C: f64 = 2.998e8;
157        let b = SpectralBudget::for_scene_diameter(0.95, C);
158        assert!((b.principal_period - 2.0 * 0.95 / C).abs() < 1e-18);
159        assert_eq!(b.ring_down_factor, 3.0);
160    }
161}