budget_machines 0.4.4-x86_64-linux

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3b69e7f27a247683f824acbb915e9f012741ecd2b44d4ef7418b1d2930b4db33
4
+ data.tar.gz: 4431c2a15cb46614afe235e878742f38fc93faa37e4a8a7dffbfc8e8fbde5749
5
+ SHA512:
6
+ metadata.gz: a67bdced716e8a925e296a5bfcadc6be5bf0570f62418995b071666548c225b3d4d4f6478a0fabef546c5f5743b1eaa681d46a62477042ae6b1b85cd7ff78f01
7
+ data.tar.gz: 22c2ae668931bd0b8a89b6e5d93df22d363edbc25866e7172f10ff3e722e056e206a53cf1b142392907cf97a14a44173534ab1f46cb2198c11829fbfbc12bec1
data/CHANGELOG.md ADDED
@@ -0,0 +1,76 @@
1
+ # Changelog
2
+
3
+ ## [0.4.4](https://github.com/seuros/budget_machines/compare/budget_machines/v0.4.3...budget_machines/v0.4.4) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * fix wrapped classes at load so building a value runs no Ruby ([0e1ee89](https://github.com/seuros/budget_machines/commit/0e1ee8914a28c20d1edc4bd613a17f8e79033c4d))
9
+
10
+ ## [0.4.3](https://github.com/seuros/budget_machines/compare/budget_machines/v0.4.2...budget_machines/v0.4.3) (2026-11-16)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * deny runtime indexing in the budget core and use matryona registry! ([7144843](https://github.com/seuros/budget_machines/commit/71448431417b61e69606e791738ff7747cc90c57))
16
+
17
+ ## [0.4.2](https://github.com/seuros/budget_machines/compare/budget_machines/v0.4.1...budget_machines/v0.4.2) (2026-11-14)
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * **deps:** require matryona-machines >= 0.4 and read standings and samples through names_only tables ([35a80c6](https://github.com/seuros/budget_machines/commit/35a80c6ff26785feacd96628ef4d17fb3654e634))
23
+
24
+ ## [0.4.1](https://github.com/seuros/budget_machines/compare/budget_machines/v0.4.0...budget_machines/v0.4.1) (2026-11-14)
25
+
26
+
27
+ ### Bug Fixes
28
+
29
+ * **deps:** require matryona-machines >= 0.3 and read standing with which ([44f508e](https://github.com/seuros/budget_machines/commit/44f508ed48730c5da31043002048b509a7cbfe73))
30
+
31
+ ## [0.4.0](https://github.com/seuros/budget_machines/compare/budget_machines/v0.3.0...budget_machines/v0.4.0) (2026-11-14)
32
+
33
+
34
+ ### ⚠ BREAKING CHANGES
35
+
36
+ * build the binding on matryona-machines 0.2; read every value from the struct; compiler-checked state, change, policy and refusal symbols
37
+
38
+ ### Features
39
+
40
+ * build the binding on matryona-machines 0.2; read every value from the struct; compiler-checked state, change, policy and refusal symbols ([9fbe6ac](https://github.com/seuros/budget_machines/commit/9fbe6ac909a740ad330633d27ad9128d41745449))
41
+
42
+ ## [0.3.0](https://github.com/seuros/budget_machines/compare/budget_machines/v0.2.0...budget_machines/v0.3.0) (2026-11-14)
43
+
44
+
45
+ ### ⚠ BREAKING CHANGES
46
+
47
+ * seal and validate every value, private Account/Decision fields, derive Decision#measured?, clone-then-keep roll/evaluate
48
+
49
+ ### Features
50
+
51
+ * seal and validate every value, private Account/Decision fields, derive Decision#measured?, clone-then-keep roll/evaluate ([8ccb894](https://github.com/seuros/budget_machines/commit/8ccb894896018e4b531361f5e2a1f321cf1a13cd))
52
+
53
+ ## [0.2.0](https://github.com/seuros/budget_machines/compare/budget_machines/v0.1.2...budget_machines/v0.2.0) (2026-11-13)
54
+
55
+
56
+ ### ⚠ BREAKING CHANGES
57
+
58
+ * see CONVENTIONS: one exhaustive Refusal per crate, Result from every mutator, honoured idempotent repeats, Ruby mirrors the core. No compatibility aliases. Ruby gains Objective, Counts, Rule, Windows, Verdict, Standing and Sample values; Monitor arguments are required; times are Integer nanoseconds.
59
+
60
+ ### Features
61
+
62
+ * Refusal without alias, Duration evaluation instants, Ruby mirrors the core types ([0f2792d](https://github.com/seuros/budget_machines/commit/0f2792d88b01d6f7f331f1383aa5c779010f7a24))
63
+
64
+ ## [0.1.2](https://github.com/seuros/budget_machines/compare/budget_machines/v0.1.1...budget_machines/v0.1.2) (2026-11-13)
65
+
66
+
67
+ ### Features
68
+
69
+ * rename Refused to Refusal, keep deprecated alias ([cca679d](https://github.com/seuros/budget_machines/commit/cca679ddb53a8a45d626d141965cd255e45d6b7c))
70
+
71
+ ## [0.1.1](https://github.com/seuros/budget_machines/compare/budget_machines-v0.1.0...budget_machines/v0.1.1) (2026-11-12)
72
+
73
+
74
+ ### Features
75
+
76
+ * initial extraction ([8a0d71a](https://github.com/seuros/budget_machines/commit/8a0d71a7a80ccb3c2fda733ed1aaf0623e88c4c5))
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdelkader Boudih
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,306 @@
1
+ # BudgetMachines
2
+
3
+ > 99.9% is not a compliment. It is a spending limit. 📉
4
+
5
+ Error-budget arithmetic for Ruby. You tell it your objective and hand it good and total counts. A ledger tells you how many failures the period can still afford, or how far past the limit you are. A monitor takes a long window and a short window per rule and tells you whether the budget is burning fast enough to wake someone, and when it has stopped. All of it in integers, so the answer is the same on every machine, and "we have no data" is never quietly rounded to "we are fine".
6
+
7
+ ## Quick Start
8
+
9
+ ```bash
10
+ gem 'budget_machines'
11
+ ```
12
+
13
+ ```ruby
14
+ BM = BudgetMachines
15
+
16
+ slo = BM::Objective.new(999, 1000) # 99.9% of requests succeed
17
+
18
+ ledger = BM::Ledger.new(slo, 0) # accounted per 30-day period, this is number 0
19
+ ledger.record(0, BM::Counts.new(99_950, 100_000)) # good, total for the window just closed
20
+ ledger.account.standing # => Standing::Within(remaining: 50), 50 failures left
21
+
22
+ monitor = BM::Monitor.new(slo, :hold, 0) # objective, no-data policy, minimum events per window
23
+ monitor.add_rule(BM::Rule.new(14_400, 14_400, 2)) # page: burning at 14.4x, severity 2
24
+ monitor.add_rule(BM::Rule.new(6_000, 6_000, 1)) # ticket: burning at 6x, severity 1
25
+
26
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
27
+ read = ->(good, total) { BM::Sample::Counts.new(BM::Counts.new(good, total)) }
28
+ verdict = monitor.evaluate(now, [
29
+ BM::Windows.new(read.(98_000, 100_000), read.(9_700, 10_000)), # rule 0: long 1h, short 5m
30
+ BM::Windows.new(read.(598_000, 600_000), read.(49_800, 50_000)) # rule 1: long 6h, short 30m
31
+ ])
32
+ verdict.decisions.first.change # => :raised
33
+ verdict.worst # => 0, go page someone
34
+ ```
35
+
36
+ Two objects and a handful of frozen values. `BM` is only an alias to keep the lines short; don't `include BudgetMachines` at the top level, where a bare `Monitor` is Ruby's own. Every value has the name and the fields of the Rust type it mirrors: `Objective`, `Counts`, `Rule`, `Sample`, `Windows`, `Account`, `Standing`, `Decision`, `Verdict`. Every number is an Integer, and the instant you pass to `evaluate` is Integer nanoseconds of monotonic time. Burn rates and thresholds are in thousandths: `14_400` is 14.4 times the sustainable rate.
37
+
38
+ ## A Message to the Resistance
39
+
40
+ So you have an SLO. Somebody put "99.9%" on a slide, everybody nodded, and then you had to turn it into an alert. You wrote `error_rate > 0.001 for 5m`. It paged you at 3 a.m. for forty failed requests on a night with no traffic. So you raised the threshold. Then a slow leak ate the entire month's budget over nine days at a rate that never crossed it, and you learned about it from a customer.
41
+
42
+ So you read the chapter. Burn rates, two windows per alert, a fast one and a slow one. You wrote it as a query. The query divides one float by another and compares the result to `14.4`, and on the day traffic drops to zero it divides zero by zero, gets `NaN`, compares `NaN > 14.4`, gets false, and resolves the page for an outage that is so complete nothing is being counted any more.
43
+
44
+ The piece you keep rebuilding is small. How many failures does this objective allow in this many events? How fast is this window spending them? Are both windows over the line, and is it still over the line now? And what do you say when a window has nothing in it? That arithmetic is this gem.
45
+
46
+ ## Chapter 1: Stardate 2026.316, the AMS Beyer
47
+
48
+ > **AMS Beyer**, NCC-4225, *Beyer*-class reliability tender.
49
+ > A fleet that never spends its budget is flying too slowly. A fleet that never counts it is already out.
50
+
51
+ The tender doesn't repair anything. It keeps the books. Every ship in the fleet has an agreed number of bad jumps per thousand, and the tender knows how many each one has left this cycle and how quickly it is going through them. When a ship stops reporting, the tender does not write down zero failures. It writes down "no report", which is a different column.
52
+
53
+ On a bridge somewhere, a cadet volunteers:
54
+
55
+ ```ruby
56
+ def alert?(errors, requests)
57
+ errors / requests.to_f > 0.001
58
+ end
59
+ ```
60
+
61
+ "Run it with no requests," says the tender's purser. "Then tell me whether the ship is healthy or missing."
62
+
63
+ ## The Flight Plan
64
+
65
+ Each rule in a monitor is in one of three states:
66
+
67
+ ```mermaid
68
+ stateDiagram-v2
69
+ [*] --> no_data
70
+ no_data --> quiet: both windows measured, not both burning
71
+ no_data --> firing: both windows at or over the fire threshold
72
+ quiet --> firing: both windows at or over the fire threshold
73
+ firing --> quiet: either window under the clear threshold
74
+ firing --> firing: a window is missing, policy is hold or fire
75
+ quiet --> no_data: a window is missing, policy is reset
76
+ firing --> no_data: a window is missing, policy is reset
77
+ quiet --> firing: a window is missing, policy is fire
78
+ no_data --> firing: a window is missing, policy is fire
79
+ ```
80
+
81
+ And the afternoon the payment API started failing one request in fifty:
82
+
83
+ ```mermaid
84
+ sequenceDiagram
85
+ participant Q as Your metrics query
86
+ participant M as Monitor
87
+ participant L as Ledger
88
+ participant P as Your pager
89
+
90
+ Q->>M: evaluate(t1, 1h calm, 5m burning 20x)
91
+ M-->>Q: quiet. One window is not enough.
92
+ Q->>M: evaluate(t2, 1h burning 20x, 5m burning 30x)
93
+ M-->>Q: firing, change raised
94
+ Q->>P: page
95
+ Q->>L: record(period, counts)
96
+ L-->>Q: exhausted, 1,900 over
97
+ Note over Q: fix deployed
98
+ Q->>M: evaluate(t3, 1h burning 18x, 5m calm)
99
+ M-->>Q: quiet, change cleared
100
+ Q->>P: resolve
101
+ Note over M: the 1h window is still hot. The 5m one says it's over.
102
+ ```
103
+
104
+ ## How the Budget Works
105
+
106
+ ### The objective
107
+
108
+ An `Objective` is two Integers: `good` of every `per` events. `Counts` is a window: `good` of `total`.
109
+
110
+ ```ruby
111
+ slo = BM::Objective.new(999, 1000)
112
+ slo.tolerated # => 1 failure per 1,000
113
+ slo.allowance(100_000) # => 100 failures allowed in 100,000
114
+ slo.burn_milli(BM::Counts.new(9_856, 10_000)) # => 14400, i.e. 14.4x
115
+ slo.burn_milli_of(144, 10_000) # => 14400, from bad and total
116
+ slo.burn_milli(BM::Counts.new(0, 0)) # => nil, no events is not a rate
117
+ slo.burns_at_least(BM::Counts.new(9_856, 10_000), 14_400) # => true, exact, no division
118
+
119
+ BM::Counts.new(995, 1000).bad # => 5
120
+ ```
121
+
122
+ A burn rate of `1000` spends the budget exactly as fast as the objective allows. `999, 1000` and `9_990, 10_000` are the same objective. `Objective.new(1000, 1000)` raises `RangeError`: a 100% target has no budget to account. So does `Counts.new(2, 1)`: more good events than events.
123
+
124
+ ### Record
125
+
126
+ ```ruby
127
+ ledger = BM::Ledger.new(BM::Objective.new(99, 100), 7) # 99%, period 7
128
+
129
+ ledger.record(7, BM::Counts.new(995, 1000)) # => :ok
130
+ ledger.record(6, BM::Counts.new(10, 10)) # => :stale_period, nothing added
131
+ ledger.counts # => Counts(good: 995, total: 1000)
132
+ ```
133
+
134
+ `record` adds a window's counts to the current period. The period is a number you choose and advance. Counts for any other period are refused. A sum that would not fit in 64 bits is refused with `:overflow`.
135
+
136
+ When your source gives you the running total instead of a delta, use `replace`:
137
+
138
+ ```ruby
139
+ ledger.replace(7, BM::Counts.new(995, 1000)) # => :ok, the period now holds exactly this
140
+ ```
141
+
142
+ `record` answers `:ok`, or refuses with `:stale_period` or `:overflow`. `replace` answers `:ok`, or refuses with `:stale_period`.
143
+
144
+ ### Account
145
+
146
+ ```ruby
147
+ account = ledger.account
148
+ account.counts # => Counts(good: 995, total: 1000)
149
+ account.allowance # => 10 failures 1,000 events may contain at 99%
150
+ account.standing # => Standing::Within(remaining: 5)
151
+ account.consumed_milli # => 500 half the budget
152
+
153
+ case account.standing
154
+ in BM::Standing::Within[remaining:] then "#{remaining} failures left"
155
+ in BM::Standing::Exhausted[overspent:] then "#{overspent} over"
156
+ in :no_data then 'nothing observed'
157
+ end
158
+
159
+ BM::Ledger.new(BM::Objective.new(99, 100), 7).account.standing # => :no_data
160
+ ```
161
+
162
+ An `Account` has exactly the fields of the core's: `period`, `counts`, `base`, `allowance`, `standing`, `consumed_milli`. `standing` is one of three values, one per variant of the core's `Standing`: `Standing::Within` carries `remaining`, `Standing::Exhausted` carries `overspent`, and the unit variant `NoData` is the symbol `:no_data`, because an empty period has nothing to report. Ask by matching `standing` (`case account.standing in BM::Standing::Within`), as a Rust caller matches the enum: there are no Ruby-only predicates. An empty period has a `nil` `consumed_milli`.
163
+
164
+ The allowance grows with traffic, so one failure in the first ten requests of a period is exhausted. If you'd rather budget against the traffic you expect:
165
+
166
+ ```ruby
167
+ ledger = BM::Ledger.new(BM::Objective.new(999, 1000), 0)
168
+ ledger.record(0, BM::Counts.new(9, 10))
169
+ ledger.account.standing # => Standing::Exhausted(overspent: 1)
170
+ ledger.account_against(100_000).standing # => Standing::Within(remaining: 99)
171
+ ledger.account_against(5) # => :below_observed
172
+ ```
173
+
174
+ `account` always answers an `Account`. `account_against` answers an `Account`, or refuses with `:below_observed`.
175
+
176
+ ### Roll
177
+
178
+ ```ruby
179
+ closed = ledger.roll(1) # => the Account period 0 ended with
180
+ ledger.account.standing # => :no_data
181
+ ledger.roll(1) # => :stale_period
182
+ ```
183
+
184
+ `roll` closes the period, hands you its final account, and starts the next one empty. The new period must be greater than the current one. Nothing rolls on its own. `roll` answers the closed `Account`, or refuses with `:stale_period`.
185
+
186
+ ### Rules
187
+
188
+ ```ruby
189
+ monitor = BM::Monitor.new(BM::Objective.new(999, 1000), :hold, 0)
190
+ monitor.add_rule(BM::Rule.new(14_400, 14_400, 2)) # => 0
191
+ monitor.add_rule(BM::Rule.new(6_000, 3_000, 1)) # => 1
192
+ monitor.rule(1) # => Rule(fire_milli: 6000, clear_milli: 3000, severity: 1)
193
+ monitor.state(1) # => :no_data, never measured
194
+ monitor.size # => 2
195
+ ```
196
+
197
+ `Monitor.new` takes the objective, the no-data policy and the minimum events a window needs to count as measured. All three are required, as they are in the core: there is no default policy to forget you chose.
198
+
199
+ A `Rule` is a fire threshold, a clear threshold and a severity. It fires when the long window and the short window both burn at the fire threshold or more. Once firing, it stays firing until either window drops below the clear threshold. Give both the same value for the textbook rule, or a lower clear threshold if you'd like an alert that doesn't flap around the line. A monitor holds `BudgetMachines::CAPACITY` rules, which is 8. `add_rule` answers the new rule's index, or refuses with `:full`.
200
+
201
+ ### Evaluate
202
+
203
+ ```ruby
204
+ read = ->(good, total) { BM::Sample::Counts.new(BM::Counts.new(good, total)) }
205
+ hot = read.(9_800, 10_000) # burning at 20x
206
+ calm = read.(10_000, 10_000)
207
+ windows = ->(long, short) { BM::Windows.new(long, short) }
208
+
209
+ minute = 60_000_000_000 # instants are Integer nanoseconds
210
+ t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
211
+
212
+ monitor.evaluate(t0, [windows.(hot, calm), windows.(hot, calm)]).decisions.map(&:state)
213
+ # => [:quiet, :quiet]
214
+
215
+ verdict = monitor.evaluate(t0 + minute, [windows.(hot, hot), windows.(hot, hot)])
216
+ page, ticket = verdict.decisions
217
+ page.state # => :firing
218
+ page.change # => :raised
219
+ page.long_milli # => 20000
220
+ page.since == t0 + minute # => true, the instant it started firing
221
+ verdict.worst # => 0, the firing rule with the highest severity
222
+ monitor.last == t0 + minute # => true
223
+
224
+ slower = read.(9_950, 10_000)
225
+ monitor.evaluate(t0 + (2 * minute), [windows.(hot, calm), windows.(hot, slower)]).decisions.map(&:change)
226
+ # => [:cleared, :none] rule 1 is at 5x: under its fire line, over its clear line
227
+ ```
228
+
229
+ You pass the instant and one `Windows` per rule, in rule order. A `Windows` is a `long` and a `short` reading, and a reading is the core's `Sample`: a `Sample::Counts` wrapping a `Counts`, or `:no_data`. The instant is Integer nanoseconds from a monotonic clock, `Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)`; `since` and `last` come back in the same unit. The monitor never sees a window length: you choose the windows and bring their counts. You get a `Verdict`: one `Decision` per rule in `decisions`, and `worst`, the index of the firing rule with the highest severity. `change` is `:raised` or `:cleared` on the evaluation where the alert starts or stops, and `:none` otherwise, so you can page on edges without keeping your own copy of the state.
230
+
231
+ `evaluate` answers a `Verdict`, or refuses with `:time_regression` or `:shape`.
232
+
233
+ ### No data
234
+
235
+ A window reading can be `:no_data`. It also counts as missing when its total is zero, or below the `min_total` you configured.
236
+
237
+ ```ruby
238
+ monitor = BM::Monitor.new(BM::Objective.new(999, 1000), :hold, 100)
239
+ monitor.add_rule(BM::Rule.new(14_400, 14_400, 2))
240
+
241
+ decision = monitor.evaluate(t0, [BM::Windows.new(read.(9_800, 10_000), :no_data)]).decisions.first
242
+ decision.measured? # => false
243
+ decision.state # => :no_data, it has never been measured
244
+ decision.short_milli # => nil
245
+ ```
246
+
247
+ The policy decides what a rule does when it can't be measured:
248
+
249
+ - `:hold` keeps the state it had. A firing alert keeps firing through a scrape gap.
250
+ - `:reset` puts it back to `:no_data`. A firing alert clears, and says so with `:cleared`.
251
+ - `:fire` treats silence as an outage.
252
+
253
+ Whichever you pick, `measured?` is `false` on that decision, so a state the policy chose is never mistaken for one the numbers chose. It is not a stored field: a decision was measured exactly when both burn rates are known, as in the core's `Decision::measured`.
254
+
255
+ ### Time only moves forward
256
+
257
+ ```ruby
258
+ monitor.evaluate(t0 + minute, [windows.(hot, hot)])
259
+ monitor.evaluate(t0, [windows.(hot, hot)]) # => :time_regression
260
+ monitor.evaluate(t0 + (2 * minute), []) # => :shape, one Windows per rule
261
+ ```
262
+
263
+ A refused evaluation changes no alert state. Evaluating the same instant twice is allowed.
264
+
265
+ ## The Rules of the Tender
266
+
267
+ - **Time is Integer nanoseconds.** The `now` of `evaluate`, `Decision#since` and `Monitor#last` are instants of a monotonic clock in nanoseconds. A Float or anything else that isn't an Integer raises `TypeError`; negative or past `2**64-1` raises `RangeError`. A ledger period is not time: it is an opaque number you advance.
268
+ - **Everything is an Integer.** Counts, periods and instants are in `0..2**64-1`. Objectives and thresholds are in `0..2**32-1`. Severity is `0..255`. Floats, nil and strings raise `TypeError`, and so does an Array where a `Counts`, `Objective`, `Rule`, `Sample::Counts` or `Windows` belongs, or `nil` where a window reading belongs. Out of range, `good > total`, a 100% objective, a clear threshold above the fire threshold, or a Symbol outside the listed ones (a policy of `:panic`, a window reading of `:quiet`) raises `RangeError` when the value is built, so an invalid one never exists.
269
+ - **Ruby mirrors Rust.** Every `Data` value has the name and the fields, in order, of the core's struct. An enum's unit variant is a symbol and a variant that carries something is a `Data` named after it: the no-data policy is `:hold`, `:reset` or `:fire`; a rule's state is `:no_data`, `:quiet` or `:firing`; a change is `:none`, `:raised` or `:cleared`; a window reading is `:no_data` or a `Sample::Counts`; a standing is `:no_data`, a `Standing::Within` or a `Standing::Exhausted`.
270
+ - **Refusals don't raise.** `:stale_period`, `:overflow`, `:below_observed`, `:full`, `:shape` and `:time_regression` are answers, and the object is exactly as it was before you asked.
271
+ - **Every answer, by method.**
272
+
273
+ | Method | Honoured | Refused |
274
+ | --- | --- | --- |
275
+ | `Ledger#record(period, counts)` | `:ok` | `:stale_period`, `:overflow` |
276
+ | `Ledger#replace(period, counts)` | `:ok` | `:stale_period` |
277
+ | `Ledger#roll(period)` | the closed `Account` | `:stale_period` |
278
+ | `Ledger#account_against(planned_total)` | an `Account` | `:below_observed` |
279
+ | `Monitor#add_rule(rule)` | the rule's index (Integer) | `:full` |
280
+ | `Monitor#evaluate(now, windows)` | a `Verdict` | `:time_regression`, `:shape` |
281
+
282
+ Those six symbols are every variant of the core's `Refusal`, and each is reachable. There is no catch-all symbol.
283
+ - **Which answers record the clock.** Only `Monitor#evaluate` takes a clock. Every honoured `evaluate` records `now` as `Monitor#last`, because every `Verdict` is the rules' state as of `now`: a later evaluation at an earlier instant would judge older readings after newer ones. A refusal records nothing. The ledger has no clock: its period is an opaque number.
284
+ - **Values are valid or do not exist.** Every `Data` value validates through the core when it is built, by you or by the gem: `Counts`, `Objective` and `Rule` through their constructors, `Account`, `Decision` and `Verdict` through constructors that refuse what no ledger or evaluation could produce (an allowance above its base, a standing the counts do not give, a raised edge that isn't firing, a `worst` that names a quiet rule). A wrong type raises `TypeError`, a value the core rejects (including an unknown Symbol) raises `RangeError`. What you pass and what you get back compare `==`. Every value class is sealed: `allocate` is undefined and subclassing raises `TypeError`, so nothing skips the check.
285
+ - **The binding never loses work.** Every conversion happens before the core is called, and the classes are resolved once, at load. Building an answer runs Ruby code (`new`), so `roll` and `evaluate` decide on a copy, build the answer, and keep the copy only if the object is still unfrozen and unchanged: if building raises, nothing is applied; if it freezes the object, `FrozenError`; if it re-enters and changes the object, `RuntimeError`, and the outer call is not applied.
286
+ - **The binding trusts no value it reads.** Sealing stops accidents, not reflection: a named subclass's constant is bound before `inherited` raises, and `Marshal.load` skips `initialize`. So every value passed in must be an instance of exactly the gem's class (a subclass raises `TypeError`), and its fields are rebuilt through the core's constructor (a forged field raises `RangeError`). A forged value never reaches the core.
287
+ - **No floats inside.** Thresholds are compared by cross-multiplying in 128 bits. Reported burn rates are rounded down to the thousandth. Decisions never use the rounded number.
288
+ - **No data is not zero.** An empty window has a `nil` burn rate. An empty period has no standing.
289
+ - **Frozen means frozen.** `freeze` a ledger or a monitor and anything that would change it raises `FrozenError`. Reading still works.
290
+
291
+ ## What You Think You're Doing vs Reality
292
+
293
+ ### You Think: "Zero errors in the window, so the alert can clear."
294
+ ### Reality: Zero requests in the window, because the load balancer is on fire.
295
+
296
+ Zero failures out of ten thousand and zero failures out of zero look identical once you've divided. They aren't the same fact. The first is a measurement. The second is the absence of one, and it shows up most reliably during the outages you most wanted to hear about. The monitor keeps them apart and makes you say, once, in the constructor, what silence means for you.
297
+
298
+ ## What's Yours
299
+
300
+ This is the initial release of a policy core, and the API will change. It does arithmetic and remembers which alerts are firing. It does not collect metrics, run queries, know what time it is, send pages, or decide what a good request is. You bring the counts for each window, exact, from wherever you keep them, and you choose the window lengths. `window_machines` can give you the window boundaries. You decide when a compliance period ends and call `roll`. State lives in your process and is gone when it exits, so persist what you can't afford to recompute. If an empty budget should shed load or open a breaker, that is your coordinator reading an `Account` and telling `shed_machines` or `breaker_machines` what to do. This gem will not do it behind your back.
301
+
302
+ ## License
303
+
304
+ MIT License. See [LICENSE.txt](LICENSE.txt) for details.
305
+
306
+ **Remember: the budget is there to be spent. Just not by accident, and not all on a Tuesday.**
@@ -0,0 +1,55 @@
1
+ # Changelog
2
+
3
+ ## [0.6.1](https://github.com/seuros/budget_machines/compare/budget-machines-v0.6.0...budget-machines-v0.6.1) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * deny runtime indexing in the budget core and use matryona registry! ([7144843](https://github.com/seuros/budget_machines/commit/71448431417b61e69606e791738ff7747cc90c57))
9
+
10
+ ## [0.6.0](https://github.com/seuros/budget_machines/compare/budget-machines-v0.5.0...budget-machines-v0.6.0) (2026-11-14)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * build the binding on matryona-machines 0.2; read every value from the struct; compiler-checked state, change, policy and refusal symbols
16
+
17
+ ### Features
18
+
19
+ * build the binding on matryona-machines 0.2; read every value from the struct; compiler-checked state, change, policy and refusal symbols ([9fbe6ac](https://github.com/seuros/budget_machines/commit/9fbe6ac909a740ad330633d27ad9128d41745449))
20
+
21
+ ## [0.5.0](https://github.com/seuros/budget_machines/compare/budget-machines-v0.4.0...budget-machines-v0.5.0) (2026-11-14)
22
+
23
+
24
+ ### ⚠ BREAKING CHANGES
25
+
26
+ * seal and validate every value, private Account/Decision fields, derive Decision#measured?, clone-then-keep roll/evaluate
27
+
28
+ ### Features
29
+
30
+ * seal and validate every value, private Account/Decision fields, derive Decision#measured?, clone-then-keep roll/evaluate ([8ccb894](https://github.com/seuros/budget_machines/commit/8ccb894896018e4b531361f5e2a1f321cf1a13cd))
31
+
32
+ ## [0.4.0](https://github.com/seuros/budget_machines/compare/budget-machines-v0.3.0...budget-machines-v0.4.0) (2026-11-13)
33
+
34
+
35
+ ### ⚠ BREAKING CHANGES
36
+
37
+ * see CONVENTIONS: one exhaustive Refusal per crate, Result from every mutator, honoured idempotent repeats, Ruby mirrors the core. No compatibility aliases. Ruby gains Objective, Counts, Rule, Windows, Verdict, Standing and Sample values; Monitor arguments are required; times are Integer nanoseconds.
38
+
39
+ ### Features
40
+
41
+ * Refusal without alias, Duration evaluation instants, Ruby mirrors the core types ([0f2792d](https://github.com/seuros/budget_machines/commit/0f2792d88b01d6f7f331f1383aa5c779010f7a24))
42
+
43
+ ## [0.3.0](https://github.com/seuros/budget_machines/compare/budget-machines-v0.2.0...budget-machines-v0.3.0) (2026-11-13)
44
+
45
+
46
+ ### Features
47
+
48
+ * rename Refused to Refusal, keep deprecated alias ([cca679d](https://github.com/seuros/budget_machines/commit/cca679ddb53a8a45d626d141965cd255e45d6b7c))
49
+
50
+ ## [0.2.0](https://github.com/seuros/budget_machines/compare/budget-machines-v0.1.0...budget-machines-v0.2.0) (2026-11-12)
51
+
52
+
53
+ ### Features
54
+
55
+ * initial extraction ([8a0d71a](https://github.com/seuros/budget_machines/commit/8a0d71a7a80ccb3c2fda733ed1aaf0623e88c4c5))
@@ -0,0 +1,82 @@
1
+ # budget-machines
2
+
3
+ > **AMS Beyer**, NCC-4225, *Beyer*-class reliability tender.
4
+
5
+ Engine-room flight manual: count what the objective tolerates, and say when it
6
+ is being spent too fast.
7
+
8
+ Allocation-free `no_std` SLO error-budget accounting and multi-window burn-rate
9
+ alerting. All arithmetic is integer: objectives are exact ratios, burn rates
10
+ are thousandths (`MILLI`), and every threshold comparison is a division-free
11
+ 128-bit cross-multiplication, so two machines never disagree about an alert.
12
+
13
+ The caller supplies everything: exact good/total counts for each window, the
14
+ instant of each evaluation, and the number of the compliance period. The crate
15
+ has no clock, no storage and no query engine, and it never rolls a period over
16
+ on its own.
17
+
18
+ - `Objective` is `good` of every `per` events. A 100% objective is refused: it
19
+ has no budget to account.
20
+ - `Ledger` accumulates one compliance period. `record` adds a window, `replace`
21
+ takes an authoritative reading, `roll` closes the period. A stale period or
22
+ an overflowing sum is refused and changes nothing. `account` reports the
23
+ whole bad events tolerated, what is left or overspent, and the consumed
24
+ fraction; `account_against` does it against a planned period total.
25
+ - `Monitor<R>` holds up to `R` rules. A `Rule` fires when the long and the
26
+ short window both burn at its threshold or more, and clears when either
27
+ falls below its clear threshold. `evaluate` returns one `Decision` per rule
28
+ and the worst firing rule; a backwards instant or the wrong number of window
29
+ pairs is refused and changes nothing.
30
+ - Time is a `core::time::Duration` since an epoch the caller picks: the `now`
31
+ of `evaluate`, `Monitor::last` and `Decision::since`. The monitor never sees
32
+ a window length; the caller chooses the windows and brings their counts. A
33
+ ledger period is an opaque `u64` the caller advances, not a clock.
34
+
35
+ `Account`, `Decision` and `Verdict` are what the core returns. Their fields
36
+ are private behind readers, and each also has a validating `new` that answers
37
+ `None` for fields no ledger or evaluation could produce, so a binding can hold
38
+ a rebuilt value to the same rule: an
39
+ account's base covers its observed total, its allowance does not exceed the
40
+ base, its standing is the one its counts and allowance give and its consumed
41
+ fraction is consistent with both; a decision's edge lands in the right state
42
+ at a recorded instant and one with both burn rates was measured, so it is
43
+ `Quiet` or `Firing`; a verdict holds
44
+ at most `R` decisions and its `worst` names a firing one exactly when one
45
+ fires. The allowance is computed in 64 bits without narrowing, so nothing
46
+ saturates there.
47
+
48
+ `evaluate` records `now` whenever it is honoured: every verdict is the rules'
49
+ state as of that instant. A refusal records nothing. The ledger has no clock.
50
+
51
+ No data is a state, not a zero. An empty period stands at `Standing::NoData`. A
52
+ window that is `Sample::NoData`, empty, or below the monitor's minimum total is
53
+ not measured, and the monitor's `OnNoData` policy (`Hold`, `Reset`, `Fire`)
54
+ decides the rule's state; `Decision::measured` says which happened. It is not
55
+ a stored flag: a decision was measured exactly when both burn rates are known.
56
+
57
+ ```rust
58
+ use core::time::Duration;
59
+
60
+ use budget_machines::{Counts, Ledger, Monitor, Objective, OnNoData, Rule, Sample, Standing, Windows};
61
+
62
+ let slo = Objective::new(999, 1000).expect("below 100%");
63
+
64
+ let mut ledger = Ledger::new(slo, 0);
65
+ assert_eq!(ledger.account().standing(), Standing::NoData);
66
+ ledger.record(0, Counts::new(99_950, 100_000).expect("good <= total")).expect("current period");
67
+ assert_eq!(ledger.account().standing(), Standing::Within { remaining: 50 });
68
+
69
+ let mut monitor = Monitor::<4>::new(slo, OnNoData::Hold, 0);
70
+ let page = monitor.add_rule(Rule::new(14_400, 14_400, 2).expect("thresholds")).expect("room");
71
+ let window = |good, total| Sample::Counts(Counts::new(good, total).expect("good <= total"));
72
+ let burning = Windows { long: window(98_000, 100_000), short: window(9_700, 10_000) };
73
+ // `now` is monotonic time since an epoch the caller picks.
74
+ let now = Duration::from_secs(60);
75
+ let verdict = monitor.evaluate(now, &[burning]).expect("time moved forward");
76
+ assert_eq!(verdict.worst(), Some(page));
77
+ assert_eq!(verdict.decisions()[page].since(), Some(now));
78
+ ```
79
+
80
+ This is a policy core. It does not collect metrics, page anyone, or decide what
81
+ a good event is. Shedding load or opening a breaker because a budget is gone is
82
+ a coordinator's decision, made outside this crate.
@@ -0,0 +1,2 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'ffi/extconf'
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BudgetMachines
4
+ VERSION = '0.4.4'
5
+ end
@@ -0,0 +1,158 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'budget_machines/version'
4
+
5
+ # Error-budget accounting and burn-rate alerting. Every value mirrors the Rust
6
+ # core's type of the same name, field for field.
7
+ module BudgetMachines
8
+ # Every value below validates through the core when built, by hand or by the
9
+ # gem alike: a non-Integer (or other wrong type) raises TypeError, a value
10
+ # the core's constructor rejects raises RangeError.
11
+
12
+ # Exact good and total event counts for one window: `Counts::new`, both in
13
+ # 0..2**64-1 with `good <= total`.
14
+ Counts = Data.define(:good, :total) do
15
+ def initialize(good:, total:)
16
+ good, total = BudgetMachines.__send__(:__counts, good, total)
17
+ super
18
+ end
19
+
20
+ def bad = total - good
21
+
22
+ # Component-wise sum, or nil when either would pass 2**64-1.
23
+ def checked_add(other) = BudgetMachines.__send__(:__checked_add, self, other)
24
+ end
25
+
26
+ # Service-level objective as an exact ratio: `good` of every `per` events,
27
+ # both in 0..2**32-1 with `good < per`.
28
+ Objective = Data.define(:good, :per) do
29
+ def initialize(good:, per:)
30
+ good, per = BudgetMachines.__send__(:__objective, good, per)
31
+ super
32
+ end
33
+
34
+ def tolerated = per - good
35
+
36
+ def allowance(total) = BudgetMachines.__send__(:__allowance, self, total)
37
+
38
+ def burn_milli_of(bad, total) = BudgetMachines.__send__(:__burn_milli_of, self, bad, total)
39
+
40
+ def burn_milli(counts) = BudgetMachines.__send__(:__burn_milli, self, counts)
41
+
42
+ def burns_at_least(counts, threshold_milli)
43
+ BudgetMachines.__send__(:__burns_at_least, self, counts, threshold_milli)
44
+ end
45
+ end
46
+
47
+ # Where a period stands against its allowance: :no_data when no events were
48
+ # observed this period, or one of the two values below.
49
+ module Standing
50
+ # Bad events are within the allowance; `remaining` (0..2**64-1) are still tolerated.
51
+ Within = Data.define(:remaining) do
52
+ def initialize(remaining:)
53
+ remaining = BudgetMachines.__send__(:__remaining, remaining)
54
+ super
55
+ end
56
+ end
57
+
58
+ # Bad events exceed the allowance by `overspent` (0..2**64-1).
59
+ Exhausted = Data.define(:overspent) do
60
+ def initialize(overspent:)
61
+ overspent = BudgetMachines.__send__(:__overspent, overspent)
62
+ super
63
+ end
64
+ end
65
+ end
66
+
67
+ # One compliance period's budget: `Account::new`, which refuses fields no
68
+ # ledger could produce (see the README).
69
+ Account = Data.define(:period, :counts, :base, :allowance, :standing, :consumed_milli) do
70
+ def initialize(period:, counts:, base:, allowance:, standing:, consumed_milli:)
71
+ period, counts, base, allowance, standing, consumed_milli =
72
+ BudgetMachines.__send__(:__account, period, counts, base, allowance, standing, consumed_milli)
73
+ super
74
+ end
75
+ end
76
+
77
+ # One window's reading: :no_data when the caller has none, or a
78
+ # Sample::Counts carrying exact counts.
79
+ module Sample
80
+ # Exact counts for the window.
81
+ Counts = Data.define(:counts) do
82
+ def initialize(counts:)
83
+ counts = BudgetMachines.__send__(:__sample, counts)
84
+ super
85
+ end
86
+ end
87
+ end
88
+
89
+ # The long and short window readings one rule is judged on. Each is a
90
+ # Sample: :no_data or a Sample::Counts.
91
+ Windows = Data.define(:long, :short) do
92
+ def initialize(long:, short:)
93
+ long, short = BudgetMachines.__send__(:__windows, long, short)
94
+ super
95
+ end
96
+ end
97
+
98
+ # A burn-rate rule: fire at `fire_milli`, clear below `clear_milli`, with
99
+ # `0 < clear_milli <= fire_milli` (both 0..2**32-1) and `severity` in 0..255.
100
+ Rule = Data.define(:fire_milli, :clear_milli, :severity) do
101
+ def initialize(fire_milli:, clear_milli:, severity:)
102
+ fire_milli, clear_milli, severity = BudgetMachines.__send__(:__rule, fire_milli, clear_milli, severity)
103
+ super
104
+ end
105
+ end
106
+
107
+ # One rule's outcome. `state` is :no_data, :quiet or :firing; `change` is
108
+ # :none, :raised or :cleared. `since` is the instant the rule entered
109
+ # `state`, in Integer nanoseconds as passed to `Monitor#evaluate`, or nil if
110
+ # it never left its start. `Decision::new` refuses fields no evaluation could
111
+ # produce.
112
+ Decision = Data.define(:state, :change, :long_milli, :short_milli, :since) do
113
+ def initialize(state:, change:, long_milli:, short_milli:, since:)
114
+ state, change, long_milli, short_milli, since =
115
+ BudgetMachines.__send__(:__decision, state, change, long_milli, short_milli, since)
116
+ super
117
+ end
118
+
119
+ # Both windows had data, so both burn rates are known; false when the
120
+ # no-data policy decided `state`.
121
+ def measured? = !long_milli.nil? && !short_milli.nil?
122
+ end
123
+
124
+ # Every rule's decision for one evaluation, in rule order (a frozen Array of
125
+ # at most CAPACITY), and the index of the firing rule with the highest
126
+ # severity (nil when nothing fires). `Verdict::new` refuses a `worst` that
127
+ # does not name a firing decision, or nil while one fires.
128
+ Verdict = Data.define(:decisions, :worst) do
129
+ def initialize(decisions:, worst:)
130
+ decisions, worst = BudgetMachines.__send__(:__verdict, decisions, worst)
131
+ super
132
+ end
133
+ end
134
+
135
+ # Sealed: no bare allocation or subclass can skip the validation above.
136
+ # Sealing stops accidents, not reflection (a subclass constant is bound
137
+ # before `inherited` raises, `Marshal.load` skips `initialize`), so the
138
+ # binding also checks every value it reads for its exact class and rebuilds
139
+ # it through the core.
140
+ [
141
+ Counts, Objective, Standing::Within, Standing::Exhausted, Account, Sample::Counts, Windows, Rule,
142
+ Decision, Verdict
143
+ ].each do |value|
144
+ value.singleton_class.undef_method(:allocate)
145
+ value.define_singleton_method(:inherited) { |_| raise TypeError, "#{value} cannot be subclassed" }
146
+ end
147
+
148
+ # Native is required: no algorithm fallback. It resolves the classes above
149
+ # once, so they are defined first.
150
+ require 'budget_machines_native/budget_machines_native'
151
+
152
+ HOOKS = %i[
153
+ __allowance __burn_milli_of __burn_milli __burns_at_least __counts __checked_add __objective
154
+ __rule __remaining __overspent __sample __windows __account __decision __verdict
155
+ ].freeze
156
+ private_class_method(*HOOKS)
157
+ private_constant :HOOKS
158
+ end
@@ -0,0 +1,183 @@
1
+ module BudgetMachines
2
+ VERSION: String
3
+ CAPACITY: Integer
4
+ MILLI: Integer
5
+
6
+ type state = :no_data | :quiet | :firing
7
+ type change = :none | :raised | :cleared
8
+ type on_no_data = :hold | :reset | :fire
9
+ # Every symbol that means "this call was not honoured and changed nothing".
10
+ # Each method below lists exactly the ones it can answer.
11
+ type refusal = :stale_period | :overflow | :below_observed | :full | :shape | :time_regression
12
+ # A window reading: :no_data when the caller has none, or exact counts.
13
+ type sample = :no_data | Sample::Counts
14
+
15
+ # Every Data value validates through the core when built, by hand or by the
16
+ # gem: a wrong type raises TypeError, a value the core rejects RangeError.
17
+
18
+ # `good <= total`, both in 0..2**64-1; anything else raises TypeError or RangeError.
19
+ class Counts < Data
20
+ attr_reader good: Integer
21
+ attr_reader total: Integer
22
+ def self.new: (Integer good, Integer total) -> Counts
23
+ | (good: Integer, total: Integer) -> Counts
24
+ def bad: () -> Integer
25
+ # nil when a sum would pass 2**64-1; TypeError unless `other` is a Counts.
26
+ def checked_add: (Counts other) -> Counts?
27
+ end
28
+
29
+ # `good < per`, both in 0..2**32-1; anything else raises TypeError or RangeError.
30
+ class Objective < Data
31
+ attr_reader good: Integer
32
+ attr_reader per: Integer
33
+ def self.new: (Integer good, Integer per) -> Objective
34
+ | (good: Integer, per: Integer) -> Objective
35
+ def tolerated: () -> Integer
36
+ def allowance: (Integer total) -> Integer
37
+ def burn_milli_of: (Integer bad, Integer total) -> Integer?
38
+ def burn_milli: (Counts counts) -> Integer?
39
+ def burns_at_least: (Counts counts, Integer threshold_milli) -> bool
40
+ end
41
+
42
+ module Sample
43
+ class Counts < Data
44
+ attr_reader counts: BudgetMachines::Counts
45
+ def self.new: (BudgetMachines::Counts counts) -> Counts
46
+ | (counts: BudgetMachines::Counts) -> Counts
47
+ end
48
+ end
49
+
50
+ module Standing
51
+ # 0..2**64-1, like Exhausted's `overspent`.
52
+ class Within < Data
53
+ attr_reader remaining: Integer
54
+ def self.new: (Integer remaining) -> Within
55
+ | (remaining: Integer) -> Within
56
+ end
57
+
58
+ class Exhausted < Data
59
+ attr_reader overspent: Integer
60
+ def self.new: (Integer overspent) -> Exhausted
61
+ | (overspent: Integer) -> Exhausted
62
+ end
63
+ end
64
+
65
+ type standing = :no_data | Standing::Within | Standing::Exhausted
66
+
67
+ # `Account::new`: RangeError for fields no ledger could produce (base below
68
+ # the observed total, allowance above the base, a standing the counts and
69
+ # allowance do not give, a consumed_milli inconsistent with them).
70
+ class Account < Data
71
+ attr_reader period: Integer
72
+ attr_reader counts: Counts
73
+ attr_reader base: Integer
74
+ attr_reader allowance: Integer
75
+ attr_reader standing: standing
76
+ attr_reader consumed_milli: Integer?
77
+ def self.new: (Integer period, Counts counts, Integer base, Integer allowance, standing standing,
78
+ Integer? consumed_milli) -> Account
79
+ | (period: Integer, counts: Counts, base: Integer, allowance: Integer, standing: standing,
80
+ consumed_milli: Integer?) -> Account
81
+ end
82
+
83
+ # A Symbol other than :no_data raises RangeError; any other type TypeError.
84
+ class Windows < Data
85
+ attr_reader long: sample
86
+ attr_reader short: sample
87
+ def self.new: (sample long, sample short) -> Windows
88
+ | (long: sample, short: sample) -> Windows
89
+ end
90
+
91
+ # `0 < clear_milli <= fire_milli`, both in 0..2**32-1; `severity` in 0..255.
92
+ class Rule < Data
93
+ attr_reader fire_milli: Integer
94
+ attr_reader clear_milli: Integer
95
+ attr_reader severity: Integer
96
+ def self.new: (Integer fire_milli, Integer clear_milli, Integer severity) -> Rule
97
+ | (fire_milli: Integer, clear_milli: Integer, severity: Integer) -> Rule
98
+ end
99
+
100
+ # `Decision::new`: RangeError for an edge into the wrong state or without its
101
+ # instant, both rates (a measurement) with state :no_data, or an unknown
102
+ # state/change Symbol.
103
+ class Decision < Data
104
+ attr_reader state: state
105
+ attr_reader change: change
106
+ attr_reader long_milli: Integer?
107
+ attr_reader short_milli: Integer?
108
+ # Instant the rule entered `state`, Integer nanoseconds; nil if it never changed.
109
+ attr_reader since: Integer?
110
+ def self.new: (state state, change change, Integer? long_milli, Integer? short_milli,
111
+ Integer? since) -> Decision
112
+ | (state: state, change: change, long_milli: Integer?, short_milli: Integer?,
113
+ since: Integer?) -> Decision
114
+ # Both burn rates known; false when the no-data policy decided `state`.
115
+ def measured?: () -> bool
116
+ end
117
+
118
+ # `Verdict::new`: RangeError for more than CAPACITY decisions, a `worst`
119
+ # that is not a firing decision's index, or nil while one fires.
120
+ class Verdict < Data
121
+ # Frozen.
122
+ attr_reader decisions: Array[Decision]
123
+ attr_reader worst: Integer?
124
+ def self.new: (Array[Decision] decisions, Integer? worst) -> Verdict
125
+ | (decisions: Array[Decision], worst: Integer?) -> Verdict
126
+ end
127
+
128
+ class Ledger
129
+ def self.new: (Objective objective, Integer period) -> Ledger
130
+ def objective: () -> Objective
131
+ def period: () -> Integer
132
+ def counts: () -> Counts
133
+ # Honoured: :ok. Refused: :stale_period, :overflow.
134
+ def record: (Integer period, Counts counts) -> (:ok | :stale_period | :overflow)
135
+ # Honoured: :ok. Refused: :stale_period.
136
+ def replace: (Integer period, Counts counts) -> (:ok | :stale_period)
137
+ # Honoured: the closed period's Account. Refused: :stale_period.
138
+ def roll: (Integer period) -> (Account | :stale_period)
139
+ def account: () -> Account
140
+ # A pure query. Refused: :below_observed.
141
+ def account_against: (Integer planned_total) -> (Account | :below_observed)
142
+ end
143
+
144
+ class Monitor
145
+ def self.new: (Objective objective, on_no_data policy, Integer min_total) -> Monitor
146
+ # Honoured: the rule's index. Refused: :full.
147
+ def add_rule: (Rule rule) -> (Integer | :full)
148
+ def size: () -> Integer
149
+ def empty?: () -> bool
150
+ def capacity: () -> Integer
151
+ def objective: () -> Objective
152
+ def rule: (Integer index) -> Rule?
153
+ def state: (Integer index) -> state?
154
+ # Instant of the latest accepted evaluation, Integer nanoseconds.
155
+ def last: () -> Integer?
156
+ def worst: () -> Integer?
157
+ # `now` is Integer nanoseconds of monotonic time. Honoured: a Verdict,
158
+ # and `now` is recorded (every verdict is the rules' state as of `now`).
159
+ # Refused: :time_regression, :shape, recording nothing.
160
+ def evaluate: (Integer now, Array[Windows] windows) -> (Verdict | :time_regression | :shape)
161
+ end
162
+
163
+ # Private native hooks: each Data value's `initialize` validates its fields
164
+ # through one and stores what it answers; the Objective and Counts query
165
+ # methods delegate to the rest.
166
+ private def self.__counts: (Integer good, Integer total) -> [Integer, Integer]
167
+ private def self.__checked_add: (Counts left, Counts right) -> Counts?
168
+ private def self.__objective: (Integer good, Integer per) -> [Integer, Integer]
169
+ private def self.__allowance: (Objective objective, Integer total) -> Integer
170
+ private def self.__burn_milli_of: (Objective objective, Integer bad, Integer total) -> Integer?
171
+ private def self.__burn_milli: (Objective objective, Counts counts) -> Integer?
172
+ private def self.__burns_at_least: (Objective objective, Counts counts, Integer threshold_milli) -> bool
173
+ private def self.__remaining: (Integer remaining) -> Integer
174
+ private def self.__overspent: (Integer overspent) -> Integer
175
+ private def self.__account: (Integer period, Counts counts, Integer base, Integer allowance, standing standing,
176
+ Integer? consumed_milli) -> [Integer, Counts, Integer, Integer, standing, Integer?]
177
+ private def self.__sample: (Counts counts) -> Counts
178
+ private def self.__windows: (sample long, sample short) -> [sample, sample]
179
+ private def self.__rule: (Integer fire_milli, Integer clear_milli, Integer severity) -> [Integer, Integer, Integer]
180
+ private def self.__decision: (state state, change change, Integer? long_milli, Integer? short_milli,
181
+ Integer? since) -> [state, change, Integer?, Integer?, Integer?]
182
+ private def self.__verdict: (Array[Decision] decisions, Integer? worst) -> [Array[Decision], Integer?]
183
+ end
metadata ADDED
@@ -0,0 +1,61 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: budget_machines
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.4.4
5
+ platform: x86_64-linux
6
+ authors:
7
+ - Abdelkader Boudih
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-16 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Exact integer error-budget accounting and multi-window burn-rate decisions
14
+ from supplied counts; not a metrics store or alert pipeline.
15
+ email:
16
+ - oss@seuros.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - CHANGELOG.md
22
+ - LICENSE.txt
23
+ - README.md
24
+ - ext/budget_machines_native/core/CHANGELOG.md
25
+ - ext/budget_machines_native/core/README.md
26
+ - ext/budget_machines_native/extconf.rb
27
+ - lib/budget_machines.rb
28
+ - lib/budget_machines/version.rb
29
+ - lib/budget_machines_native/budget_machines_native.so
30
+ - sig/budget_machines.rbs
31
+ homepage: https://github.com/seuros/budget_machines
32
+ licenses:
33
+ - MIT
34
+ metadata:
35
+ source_code_uri: https://github.com/seuros/budget_machines
36
+ rubygems_mfa_required: 'true'
37
+ cargo_crate_name: budget_machines_native
38
+ cargo_manifest_path: ext/budget_machines_native/ffi/Cargo.toml
39
+ post_install_message:
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '4.0'
48
+ - - "<"
49
+ - !ruby/object:Gem::Version
50
+ version: 4.1.dev
51
+ required_rubygems_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: '0'
56
+ requirements: []
57
+ rubygems_version: 3.5.23
58
+ signing_key:
59
+ specification_version: 4
60
+ summary: SLO error-budget and burn-rate alert policies with a native Rust core
61
+ test_files: []