budget_machines 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,251 @@
1
+ //! Error-budget accounting for one compliance period at a time.
2
+
3
+ use crate::{Counts, MILLI, Objective, Refusal};
4
+
5
+ /// `consumed_milli` of an account that spent exactly its allowance.
6
+ const SPENT: u64 = MILLI as u64;
7
+
8
+ /// Where the period stands against its allowance.
9
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10
+ pub enum Standing {
11
+ /// No events were observed this period. Not healthy, not exhausted: unknown.
12
+ NoData,
13
+ /// Bad events are within the allowance.
14
+ Within {
15
+ /// Whole bad events still tolerated.
16
+ remaining: u64,
17
+ },
18
+ /// Bad events exceed the allowance.
19
+ Exhausted {
20
+ /// Bad events beyond the allowance.
21
+ overspent: u64,
22
+ },
23
+ }
24
+
25
+ /// A period's budget, computed exactly from its counts.
26
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
27
+ pub struct Account {
28
+ period: u64,
29
+ counts: Counts,
30
+ base: u64,
31
+ allowance: u64,
32
+ standing: Standing,
33
+ consumed_milli: Option<u64>,
34
+ }
35
+
36
+ impl Account {
37
+ /// An account rebuilt from its fields, or `None` when no ledger could
38
+ /// have produced it. The objective is not part of an account, so only
39
+ /// what holds for every objective is checked: `base` covers the observed
40
+ /// total; `allowance` does not exceed `base`, since a tolerated fraction
41
+ /// is at most one; `standing` is the one `counts` and
42
+ /// `allowance` give; `consumed_milli` is absent exactly when `base` is
43
+ /// zero, is zero when nothing was bad, at most `1000` within the
44
+ /// allowance and at least `1000` beyond it.
45
+ #[must_use]
46
+ pub const fn new(
47
+ period: u64,
48
+ counts: Counts,
49
+ base: u64,
50
+ allowance: u64,
51
+ standing: Standing,
52
+ consumed_milli: Option<u64>,
53
+ ) -> Option<Self> {
54
+ let bad = counts.bad();
55
+ let shaped = base >= counts.total() && allowance <= base;
56
+ let consumed = match consumed_milli {
57
+ None => base == 0,
58
+ Some(milli) => base > 0 && (bad > 0 || milli == 0),
59
+ };
60
+ let consistent = match standing {
61
+ Standing::NoData => counts.total() == 0,
62
+ Standing::Within { remaining } => {
63
+ counts.total() > 0
64
+ && bad <= allowance
65
+ && remaining == allowance - bad
66
+ && matches!(consumed_milli, None | Some(0..=SPENT))
67
+ }
68
+ Standing::Exhausted { overspent } => {
69
+ counts.total() > 0
70
+ && bad > allowance
71
+ && overspent == bad - allowance
72
+ && matches!(consumed_milli, Some(SPENT..))
73
+ }
74
+ };
75
+ if !(shaped && consumed && consistent) {
76
+ return None;
77
+ }
78
+ Some(Self {
79
+ period,
80
+ counts,
81
+ base,
82
+ allowance,
83
+ standing,
84
+ consumed_milli,
85
+ })
86
+ }
87
+
88
+ /// Period the counts belong to.
89
+ #[must_use]
90
+ pub const fn period(&self) -> u64 {
91
+ self.period
92
+ }
93
+
94
+ /// Good and total events observed in the period.
95
+ #[must_use]
96
+ pub const fn counts(&self) -> Counts {
97
+ self.counts
98
+ }
99
+
100
+ /// Total the allowance was computed against: observed, or the plan.
101
+ #[must_use]
102
+ pub const fn base(&self) -> u64 {
103
+ self.base
104
+ }
105
+
106
+ /// Whole bad events tolerated among `base` events.
107
+ #[must_use]
108
+ pub const fn allowance(&self) -> u64 {
109
+ self.allowance
110
+ }
111
+
112
+ /// Verdict; `NoData` whenever nothing was observed.
113
+ #[must_use]
114
+ pub const fn standing(&self) -> Standing {
115
+ self.standing
116
+ }
117
+
118
+ /// Budget consumed in thousandths (`1000` is all of it), rounded down and
119
+ /// saturating. `None` when `base` is zero.
120
+ #[must_use]
121
+ pub const fn consumed_milli(&self) -> Option<u64> {
122
+ self.consumed_milli
123
+ }
124
+ }
125
+
126
+ /// Accumulates caller-supplied counts for the current compliance period.
127
+ ///
128
+ /// The period is an opaque number the caller advances; the ledger has no clock
129
+ /// and never rolls over on its own.
130
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
131
+ pub struct Ledger {
132
+ objective: Objective,
133
+ period: u64,
134
+ counts: Counts,
135
+ }
136
+
137
+ impl Ledger {
138
+ /// Empty ledger for `period`.
139
+ #[must_use]
140
+ pub const fn new(objective: Objective, period: u64) -> Self {
141
+ Self {
142
+ objective,
143
+ period,
144
+ counts: Counts { good: 0, total: 0 },
145
+ }
146
+ }
147
+
148
+ /// The objective being accounted.
149
+ #[must_use]
150
+ pub const fn objective(&self) -> Objective {
151
+ self.objective
152
+ }
153
+
154
+ /// Current period.
155
+ #[must_use]
156
+ pub const fn period(&self) -> u64 {
157
+ self.period
158
+ }
159
+
160
+ /// Counts accumulated in the current period.
161
+ #[must_use]
162
+ pub const fn counts(&self) -> Counts {
163
+ self.counts
164
+ }
165
+
166
+ /// Add a window's counts to the current period.
167
+ ///
168
+ /// # Errors
169
+ /// [`Refusal::StalePeriod`] when `period` is not the current one, and
170
+ /// [`Refusal::Overflow`] when a sum would not fit in 64 bits.
171
+ pub const fn record(&mut self, period: u64, counts: Counts) -> Result<(), Refusal> {
172
+ if period != self.period {
173
+ return Err(Refusal::StalePeriod);
174
+ }
175
+ let Some(sum) = self.counts.checked_add(counts) else {
176
+ return Err(Refusal::Overflow);
177
+ };
178
+ self.counts = sum;
179
+ Ok(())
180
+ }
181
+
182
+ /// Replace the current period's counts with an authoritative reading.
183
+ ///
184
+ /// # Errors
185
+ /// [`Refusal::StalePeriod`] when `period` is not the current one.
186
+ pub const fn replace(&mut self, period: u64, counts: Counts) -> Result<(), Refusal> {
187
+ if period != self.period {
188
+ return Err(Refusal::StalePeriod);
189
+ }
190
+ self.counts = counts;
191
+ Ok(())
192
+ }
193
+
194
+ /// Close the current period and start `period` empty, returning the closed
195
+ /// period's final account.
196
+ ///
197
+ /// # Errors
198
+ /// [`Refusal::StalePeriod`] unless `period` is greater than the current one.
199
+ pub fn roll(&mut self, period: u64) -> Result<Account, Refusal> {
200
+ if period <= self.period {
201
+ return Err(Refusal::StalePeriod);
202
+ }
203
+ let closed = self.account();
204
+ self.period = period;
205
+ self.counts = Counts::default();
206
+ Ok(closed)
207
+ }
208
+
209
+ /// Budget against the events observed so far.
210
+ #[must_use]
211
+ pub fn account(&self) -> Account {
212
+ self.against(self.counts.total())
213
+ }
214
+
215
+ /// Budget against a planned period total, for a budget that should not
216
+ /// shrink to nothing while the period is young.
217
+ ///
218
+ /// # Errors
219
+ /// [`Refusal::BelowObserved`] when the plan is smaller than the total
220
+ /// already observed.
221
+ pub fn account_against(&self, planned_total: u64) -> Result<Account, Refusal> {
222
+ if planned_total < self.counts.total() {
223
+ return Err(Refusal::BelowObserved);
224
+ }
225
+ Ok(self.against(planned_total))
226
+ }
227
+
228
+ fn against(&self, base: u64) -> Account {
229
+ let allowance = self.objective.allowance(base);
230
+ let bad = self.counts.bad();
231
+ let standing = if self.counts.total() == 0 {
232
+ Standing::NoData
233
+ } else if bad > allowance {
234
+ Standing::Exhausted {
235
+ overspent: bad - allowance,
236
+ }
237
+ } else {
238
+ Standing::Within {
239
+ remaining: allowance - bad,
240
+ }
241
+ };
242
+ Account {
243
+ period: self.period,
244
+ counts: self.counts,
245
+ base,
246
+ allowance,
247
+ standing,
248
+ consumed_milli: self.objective.burn_milli_of(bad, base),
249
+ }
250
+ }
251
+ }
@@ -0,0 +1,180 @@
1
+ #![no_std]
2
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
3
+ #![doc = include_str!("../README.md")]
4
+
5
+ mod ledger;
6
+ mod monitor;
7
+
8
+ pub use ledger::{Account, Ledger, Standing};
9
+ pub use monitor::{Change, Decision, Monitor, OnNoData, Rule, Sample, State, Verdict, Windows};
10
+
11
+ /// Fixed-point scale of every burn rate: `1000` is a burn rate of exactly 1.
12
+ pub const MILLI: u32 = 1000;
13
+
14
+ /// A refused call. The receiver is left exactly as it was.
15
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
+ pub enum Refusal {
17
+ /// The period is not the ledger's current one, or does not move forward.
18
+ StalePeriod,
19
+ /// The sum would not fit in 64 bits.
20
+ Overflow,
21
+ /// The planned total is smaller than the total already observed.
22
+ BelowObserved,
23
+ /// Every rule slot is taken.
24
+ Full,
25
+ /// The number of window pairs differs from the number of rules.
26
+ Shape,
27
+ /// The evaluation instant is earlier than the previous one.
28
+ TimeRegression,
29
+ }
30
+
31
+ impl core::fmt::Display for Refusal {
32
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
33
+ f.write_str(match self {
34
+ Self::StalePeriod => "the period is not current or does not move forward",
35
+ Self::Overflow => "the sum does not fit in 64 bits",
36
+ Self::BelowObserved => "the planned total is below the observed total",
37
+ Self::Full => "every rule slot is taken",
38
+ Self::Shape => "the number of window pairs differs from the number of rules",
39
+ Self::TimeRegression => "the instant precedes the previous evaluation",
40
+ })
41
+ }
42
+ }
43
+
44
+ impl core::error::Error for Refusal {}
45
+
46
+ /// Exact good and total event counts for one window, supplied by the caller.
47
+ #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
48
+ pub struct Counts {
49
+ good: u64,
50
+ total: u64,
51
+ }
52
+
53
+ impl Counts {
54
+ /// `None` when `good` exceeds `total`.
55
+ #[must_use]
56
+ pub const fn new(good: u64, total: u64) -> Option<Self> {
57
+ if good > total {
58
+ return None;
59
+ }
60
+ Some(Self { good, total })
61
+ }
62
+
63
+ /// Events that met the objective.
64
+ #[must_use]
65
+ pub const fn good(self) -> u64 {
66
+ self.good
67
+ }
68
+
69
+ /// All valid events.
70
+ #[must_use]
71
+ pub const fn total(self) -> u64 {
72
+ self.total
73
+ }
74
+
75
+ /// Events that missed the objective.
76
+ #[must_use]
77
+ pub const fn bad(self) -> u64 {
78
+ // `new` refuses good > total and `checked_add` keeps both sums exact.
79
+ self.total - self.good
80
+ }
81
+
82
+ /// Component-wise sum, or `None` when either would overflow.
83
+ #[must_use]
84
+ pub const fn checked_add(self, other: Self) -> Option<Self> {
85
+ let (Some(good), Some(total)) = (
86
+ self.good.checked_add(other.good),
87
+ self.total.checked_add(other.total),
88
+ ) else {
89
+ return None;
90
+ };
91
+ Some(Self { good, total })
92
+ }
93
+ }
94
+
95
+ /// Service-level objective as an exact ratio: `good` of every `per` events.
96
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
97
+ pub struct Objective {
98
+ good: u32,
99
+ per: u32,
100
+ }
101
+
102
+ impl Objective {
103
+ /// `None` unless `good < per`: a 100% objective has no error budget, so
104
+ /// neither a burn rate nor an allowance is defined for it.
105
+ #[must_use]
106
+ pub const fn new(good: u32, per: u32) -> Option<Self> {
107
+ if good >= per {
108
+ return None;
109
+ }
110
+ Some(Self { good, per })
111
+ }
112
+
113
+ /// Target numerator.
114
+ #[must_use]
115
+ pub const fn good(self) -> u32 {
116
+ self.good
117
+ }
118
+
119
+ /// Target denominator.
120
+ #[must_use]
121
+ pub const fn per(self) -> u32 {
122
+ self.per
123
+ }
124
+
125
+ /// Bad events tolerated per `per` events; never zero.
126
+ #[must_use]
127
+ pub const fn tolerated(self) -> u32 {
128
+ self.per - self.good
129
+ }
130
+
131
+ /// Whole bad events the objective tolerates among `total` events:
132
+ /// `floor(total * tolerated / per)`.
133
+ #[must_use]
134
+ pub const fn allowance(self, total: u64) -> u64 {
135
+ // total = whole * per + rest, so the allowance is
136
+ // whole * tolerated + floor(rest * tolerated / per). tolerated < per
137
+ // keeps the first product at most `total`, and rest < per < 2^32
138
+ // keeps the second within 64 bits: nothing to saturate or narrow.
139
+ let (per, tolerated) = (self.per as u64, self.tolerated() as u64);
140
+ let (whole, rest) = (total / per, total % per);
141
+ whole * tolerated + rest * tolerated / per
142
+ }
143
+
144
+ /// Burn rate of `bad` events against a base of `total`, in thousandths,
145
+ /// rounded down and saturating at `u64::MAX`. `None` when `total` is zero:
146
+ /// no events is no data, not a burn rate of zero.
147
+ #[must_use]
148
+ pub fn burn_milli_of(self, bad: u64, total: u64) -> Option<u64> {
149
+ if total == 0 {
150
+ return None;
151
+ }
152
+ // bad < 2^64, per < 2^32, MILLI < 2^10: the product fits in 106 bits.
153
+ let spent = u128::from(bad) * u128::from(self.per) * u128::from(MILLI);
154
+ let budget = u128::from(total) * u128::from(self.tolerated());
155
+ Some(u64::try_from(spent / budget).unwrap_or(u64::MAX))
156
+ }
157
+
158
+ /// Burn rate of a window in thousandths; see [`Objective::burn_milli_of`].
159
+ #[must_use]
160
+ pub fn burn_milli(self, counts: Counts) -> Option<u64> {
161
+ self.burn_milli_of(counts.bad(), counts.total())
162
+ }
163
+
164
+ /// Exact test of `burn rate >= threshold_milli / 1000`, without division.
165
+ /// An empty window burns at no rate, so it never reaches a threshold.
166
+ #[must_use]
167
+ pub fn burns_at_least(self, counts: Counts, threshold_milli: u32) -> bool {
168
+ if counts.total() == 0 {
169
+ return false;
170
+ }
171
+ let spent = u128::from(counts.bad()) * u128::from(self.per) * u128::from(MILLI);
172
+ // 2^32 * 2^64 * 2^32 is the largest product and still fits in 128 bits.
173
+ let bar =
174
+ u128::from(threshold_milli) * u128::from(counts.total()) * u128::from(self.tolerated());
175
+ spent >= bar
176
+ }
177
+ }
178
+
179
+ #[cfg(test)]
180
+ mod tests;