microvms_domain/cost.rs
1// SPDX-License-Identifier: Apache-2.0
2//! What a run cost, and what a plan will cost, with every figure labelled.
3//!
4//! MicroVMs has no standalone pricing page. The rates appear only inside worked
5//! examples on the Lambda pricing page, which is why this module exists as data
6//! rather than as a paragraph someone re-derives: a consumer building a sandbox
7//! product should be able to ask "what did that run cost" without reading a pricing
8//! page sideways.
9//!
10//! Two rules hold everywhere below. The Python client's `cost.py` enforced both at
11//! runtime — a `TypeError` from a keyword-only field, a `NotImplemented` from
12//! `__add__`. Here they are the shape of the types, so the enforcement happens before
13//! the program runs.
14//!
15//! **Seconds are measured, dollars are estimated.** [`DurationP`] is an enum whose
16//! every variant names its provenance, so there is no unlabelled constructor to
17//! call — not one that raises, one that does not exist (COST-1). And there is no
18//! type here for an actual dollar amount, only [`EstimatedUsd`], which says so on
19//! every render. Only Cost Explorer knows the bill. That asymmetry is the point: we
20//! can time a suspension to the millisecond and still only infer its price.
21//!
22//! **Unknown is not zero.** [`Amount::Unpriced`] carries a reason and is a distinct
23//! variant, so a consumer matching on an amount has to handle it (COST-3). AWS does
24//! not publish whether the server-side image build is billed as compute, so a report
25//! that summed it as $0.00 would be lying in the direction that flatters us. A
26//! [`Total`] over any unpriced line is a *different variant*, [`Total::AtLeast`],
27//! which cannot be read without seeing the reasons beside the floor (COST-4).
28//!
29//! # What this port strengthens
30//!
31//! Three closures move up the strength ladder from the Python original.
32//!
33//! * **No negative duration.** `cost.py` validated `seconds >= 0` in
34//! `__post_init__`, because an inverted clock renders as a credit on the report.
35//! [`DurationP`] wraps [`std::time::Duration`], which cannot be negative, so the
36//! check is gone rather than moved: the only place a sign can go wrong is
37//! [`seconds_of`], the one f64 boundary, and it is fallible.
38//! * **No coercion to float.** `cost.py` omitted `__float__` and relied on the
39//! reader not writing `float(x.amount)`. [`EstimatedUsd`] has a private field, no
40//! `From`/`Into<f64>`, no `Deref`, and no `Serialize` that emits a number — the
41//! coercion is not a discouraged spelling, it is absent (COST-2).
42//! * **No x86 rate, by construction.** `pricing.py` refused to substitute the x86
43//! compute rate inside its fetch path, which meant a hand-built `RateTable` could
44//! still carry one. Here [`RateTable`]'s rate fields are private and there are
45//! exactly two ways to obtain one — the pinned [`pinned_rates`], and
46//! [`RateTable::from_catalog`], which rejects a catalog whose ARM line is missing
47//! (COST-9). No value of the type exists that was built from an x86 figure.
48//!
49//! # The table carries its own staleness
50//!
51//! [`pinned_rates`] is pinned to a retrieval date, and a table older than
52//! [`STALE_AFTER_DAYS`] attaches a warning to every report computed from it
53//! (COST-7), because a silently stale price is the same failure class as a silently
54//! stale schema. The warning is a fallback rather than the defence — it can only say
55//! that nobody has looked. [`RateCatalog`] is what looks.
56//!
57//! Every rate here is recorded in `docs/PLATFORM.md`, "What actually costs money".
58//! One of them, [`RateTable::storage_gb_month`], is derived: the API quotes snapshot
59//! storage per GB-hour and this table holds per GB-month, so it is the hourly figure
60//! times [`HOURS_PER_MONTH`]. Billing reads [`SizeClass::baseline_gb`] and never the
61//! peak (COST-5).
62
63use std::fmt;
64use std::time::Duration;
65
66use rust_decimal::Decimal;
67use rust_decimal::prelude::{FromStr, ToPrimitive};
68use rust_decimal_macros::dec;
69
70use crate::error::Error;
71use crate::region::Region;
72use crate::sizing::SizeClass;
73
74/// AWS bills storage per GB-month and defines a month as 730 hours, so a
75/// partial-month hold is that fraction of the monthly rate.
76///
77/// Spelled out because 30-day and calendar-month conventions both give
78/// plausible-looking answers that disagree with the worked examples in
79/// `docs/PLATFORM.md` by a few percent. `730 * 3600`.
80pub const SECONDS_PER_MONTH: Decimal = dec!(2628000);
81
82/// Hours in the month AWS's GB-month rate assumes, derived from
83/// [`SECONDS_PER_MONTH`] rather than written again.
84///
85/// The second 730 is where the drift got in: the pinned storage rate read `0.08`
86/// until 2026-08-07, a round number that was 1.37% low, because two places in the
87/// code held two conventions for the same month.
88pub const HOURS_PER_MONTH: Decimal = dec!(730);
89
90/// How old a rate table may get before it warns (COST-7).
91///
92/// Ninety days is the same order as the interval at which AWS has historically
93/// restructured Lambda pricing, and the cost of the warning when nothing changed is
94/// one line of output.
95pub const STALE_AFTER_DAYS: i64 = 90;
96
97/// Seconds in a day, for the one place a [`Duration`] is quoted in days.
98///
99/// Not a billing convention — AWS's month is [`SECONDS_PER_MONTH`] and nothing here
100/// derives a month from this. It exists so [`RateTable::minimum_retention_days`] reads
101/// its own unit off a name rather than off a literal beside a message.
102const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
103
104/// Snapshot storage bills at least this long however briefly the snapshot exists
105/// (COST-8).
106///
107/// One week. Why a create-and-destroy suite's floor is its image rather than its
108/// compute: a 2 GB image deleted after sixty seconds still bills about four cents.
109pub const MINIMUM_RETENTION: Duration = Duration::from_secs(7 * SECONDS_PER_DAY);
110
111// ── the two float boundaries (COST-6) ────────────────────────────────────────
112
113/// Seconds as an exact [`Decimal`], from the one representation that cannot be
114/// negative.
115///
116/// **This is a conversion site, and it is exact.** A [`Duration`] is a whole
117/// seconds count plus a nanosecond remainder, both integers, so this is integer
118/// arithmetic in decimal rather than a float being reinterpreted — the nanosecond
119/// division is by a power of ten and loses nothing.
120pub fn seconds_of(duration: Duration) -> Decimal {
121 // Nanoseconds are < 1e9 and Decimal holds 28 significant digits, so neither
122 // term can overflow and the sum is exact.
123 Decimal::from(duration.as_secs()) + Decimal::from(duration.subsec_nanos()) / dec!(1000000000)
124}
125
126/// A float from a caller, converted into the money path exactly once (COST-6).
127///
128/// **This is the only place an f64 becomes a [`Decimal`].** It goes through the
129/// float's decimal string rather than its binary value, because
130/// `Decimal::try_from(0.1f64)` carries the binary error into every downstream
131/// figure. Fallible rather than lossy: `NaN`, an infinity, and a magnitude past
132/// 28 digits have no decimal reading, and a money figure derived from one of them
133/// would be a number nobody could reconcile.
134///
135/// Named for gigabytes because that is the one quantity a caller supplies as a
136/// float — every duration arrives as a [`Duration`], which [`seconds_of`] converts
137/// exactly.
138pub fn gb_decimal(gb: f64) -> Result<Decimal, Error> {
139 if !gb.is_finite() || gb < 0.0 {
140 return Err(Error::invalid_arg(format!(
141 "{gb} GB is not a quantity that can be priced: a size must be finite and \
142 non-negative, and a negative one would render as a credit on the report"
143 )));
144 }
145 Decimal::from_str(&gb.to_string()).map_err(|source| {
146 Error::invalid_arg(format!(
147 "{gb} GB cannot be represented exactly in decimal, and money arithmetic here is \
148 decimal end to end so that a figure can be reconciled against the rate table"
149 ))
150 .with_source(source)
151 })
152}
153
154/// Seconds from a float for a figure on a report, refused when the float cannot be a duration.
155///
156/// The complement of [`gb_decimal`] for the API boundary where a report's seconds arrive as a
157/// number: a [`DurationP`], or the hold a residency comparison prices. It's
158/// [`crate::duration::of_secs_f64`] with the reason a negative span matters here in the
159/// refusal, which is why [`DurationP`] itself needs no validation: an inverted clock is refused
160/// here or it never becomes a duration. A wait or a window converts through
161/// `duration::of_secs_f64`, whose refusal claims no report.
162pub fn duration_of_secs_f64(seconds: f64) -> Result<Duration, Error> {
163 crate::duration::of_secs_f64_because(
164 seconds,
165 ", and a negative one would silently produce a credit on the report",
166 )
167}
168
169// ── display precision ────────────────────────────────────────────────────────
170
171/// Enough places to see a sub-cent figure, few enough to read a monthly one.
172///
173/// A create-and-destroy test suite's compute cost lives in the sixth decimal place
174/// while a warm pool's monthly bill lives in the second, and one fixed precision
175/// cannot show both without either lying or shouting. Half-even at the boundary,
176/// matching Python's `Decimal.quantize` default, so the two clients render the same
177/// figure the same way.
178fn render_amount(amount: Decimal) -> String {
179 let places = if amount.abs() >= Decimal::ONE { 2 } else { 6 };
180 let mut rendered = amount.round_dp(places);
181 // Fixed places rather than significant digits: a trailing zero is what says the
182 // figure was rounded to the cent rather than happening to land there.
183 rendered.rescale(places);
184 rendered.to_string()
185}
186
187/// A consumed quantity, rounded only for display.
188///
189/// Division by 730 hours yields 28 significant digits, and a line item nobody can
190/// scan is a line item nobody checks the rate table against — which is the one job
191/// the quantity column has.
192fn render_quantity(quantity: Decimal) -> String {
193 quantity.round_dp(6).normalize().to_string()
194}
195
196// ── dates, via jiff ───────────────────────────────────────────────────────────
197
198/// A calendar day, which is the only temporal resolution a rate table has.
199///
200/// A thin wrapper over [`jiff::civil::Date`] so the crate's public surface (and the
201/// py/js bindings behind it) keeps its own type. The wrapped crate replaced a
202/// hand-rolled proleptic-Gregorian day-number implementation (issue #91); the pinned
203/// tests that held that implementation to Python's `datetime` now hold jiff to the
204/// same three known values.
205#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
206pub struct CalendarDate(jiff::civil::Date);
207
208impl CalendarDate {
209 /// A date from its parts, for the literals in this file.
210 ///
211 /// `const` so [`pinned_rates`] can pin its retrieval date. jiff's `constant`
212 /// refuses an invalid literal at compile time when const-evaluated, which is
213 /// strictly better than the old non-validating constructor; anything arriving
214 /// at runtime goes through [`CalendarDate::try_from_ymd`].
215 pub const fn from_ymd(year: i32, month: u32, day: u32) -> CalendarDate {
216 CalendarDate(jiff::civil::Date::constant(
217 year as i16,
218 month as i8,
219 day as i8,
220 ))
221 }
222
223 /// A date from parts that came from outside this crate.
224 ///
225 /// The S2 boundary: a `--today` flag or a JSON field is three integers, and
226 /// `2026-02-30` would otherwise produce a day number for March 2nd and an age
227 /// two days out. The range pre-checks keep the narrowing casts from wrapping
228 /// (`month = 257` must not arrive at jiff as `1`).
229 pub fn try_from_ymd(year: i32, month: u32, day: u32) -> Result<CalendarDate, Error> {
230 let refusal = || {
231 Error::invalid_arg(format!(
232 "{year:04}-{month:02}-{day:02} is not a calendar day, so it cannot date a rate \
233 table: month must be 1-12 and day must be within that month"
234 ))
235 };
236 if !(1..=12).contains(&month) || !(1..=31).contains(&day) || i16::try_from(year).is_err() {
237 return Err(refusal());
238 }
239 jiff::civil::Date::new(year as i16, month as i8, day as i8)
240 .map(CalendarDate)
241 .map_err(|_| refusal())
242 }
243
244 /// The UTC civil day `secs` seconds after the Unix epoch falls on.
245 ///
246 /// UTC rather than local, and no tzdb: a rate table's age is measured in
247 /// ninety-day units, so the zone can only ever move the answer by a day. The time
248 /// is the caller's: this crate doesn't read the clock (ARCH-6), and
249 /// `microvms_core::prelude::CalendarDateExt::today_utc` is the one that does.
250 ///
251 /// Refuses a time past 9999-12-31, the last day the calendar holds, rather than
252 /// clamping it: the likeliest such value is a millisecond count passed as seconds,
253 /// and an age computed from a clamped or defaulted date would be wrong with no sign.
254 pub fn from_unix_secs(secs: u64) -> Result<CalendarDate, Error> {
255 // Integer division floors, and the epoch is midnight, so this is the UTC
256 // civil day without any rounding question.
257 i64::try_from(secs / 86_400)
258 .ok()
259 .and_then(Self::from_day_number)
260 .ok_or_else(|| {
261 Error::invalid_arg(format!(
262 "{secs} seconds after the Unix epoch is past 9999-12-31, the last day a \
263 rate table can be dated. A time in milliseconds looks like this: pass \
264 whole seconds"
265 ))
266 })
267 }
268
269 pub fn year(self) -> i32 {
270 i32::from(self.0.year())
271 }
272
273 pub fn month(self) -> u32 {
274 self.0.month() as u32
275 }
276
277 pub fn day(self) -> u32 {
278 self.0.day() as u32
279 }
280
281 /// Days since 1970-01-01, negative before it.
282 pub fn day_number(self) -> i64 {
283 i64::from(self.0.since(EPOCH).expect("dates are in range").get_days())
284 }
285
286 /// The inverse of [`CalendarDate::day_number`], for [`CalendarDate::from_unix_secs`].
287 /// `None` outside the calendar's range, which `Span::days` would panic on.
288 fn from_day_number(day_number: i64) -> Option<CalendarDate> {
289 let span = jiff::Span::new().try_days(day_number).ok()?;
290 EPOCH.checked_add(span).ok().map(CalendarDate)
291 }
292
293 /// Days from `earlier` to `self`, negative when `self` is the earlier one.
294 pub fn days_since(self, earlier: CalendarDate) -> i64 {
295 self.day_number() - earlier.day_number()
296 }
297}
298
299/// 1970-01-01, the zero of [`CalendarDate::day_number`]'s count.
300const EPOCH: jiff::civil::Date = jiff::civil::Date::constant(1970, 1, 1);
301
302/// ISO 8601, because that is what the Python client's `retrieved.isoformat()` puts
303/// in the report header and the two have to be diffable.
304impl fmt::Display for CalendarDate {
305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306 write!(
307 f,
308 "{:04}-{:02}-{:02}",
309 self.year(),
310 self.month(),
311 self.day()
312 )
313 }
314}
315
316// ── provenance (COST-1) ──────────────────────────────────────────────────────
317
318/// Where a duration came from. There is no third option and no default.
319///
320/// `Measured` means a clock ran. `Projected` means a caller supplied a
321/// hypothetical, which is also what an estimate's durations are and what the
322/// documented one-week storage minimum is — nobody timed that week either.
323#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
324pub enum Provenance {
325 Measured,
326 Projected,
327}
328
329impl Provenance {
330 /// The wire spelling, identical to the Python `StrEnum` member.
331 pub fn as_str(self) -> &'static str {
332 match self {
333 Provenance::Measured => "measured",
334 Provenance::Projected => "projected",
335 }
336 }
337}
338
339impl fmt::Display for Provenance {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 f.write_str(self.as_str())
342 }
343}
344
345/// Seconds, plus how we know them (COST-1).
346///
347/// The labelling rule is the enum: every way of building one of these names a
348/// provenance, because there is no other variant to reach and no
349/// `From<Duration>`/`Default` to fall into. `cost.py` achieved the same thing with
350/// a field that had no default, so `Duration(3600)` raised `TypeError` — the whole
351/// rule collapses the moment an unlabelled duration can be written, because the
352/// label that goes missing is always the weaker one, and here it cannot be written.
353///
354/// Wrapping [`std::time::Duration`] also retires the Python's negativity check: a
355/// negative duration is not a value this type can hold, so an inverted clock is
356/// caught at [`duration_of_secs_f64`] or never enters at all.
357///
358/// # Provenance cannot be omitted (COST-1)
359///
360/// "No unlabelled constructor" is a claim about what does not exist, so it is checked
361/// by programs that do not build:
362///
363/// Each carries its expected error code, because a bare `compile_fail` passes for any
364/// build failure at all — a typo in the test would leave the guard green.
365///
366/// ```compile_fail,E0277
367/// # use microvms_domain::cost::DurationP;
368/// # use std::time::Duration;
369/// // There is no `From<Duration> for DurationP`, so a bare span cannot become a
370/// // labelled one by coercion.
371/// let unlabelled: DurationP = Duration::from_secs(3600).into();
372/// ```
373///
374/// ```compile_fail,E0599
375/// # use microvms_domain::cost::DurationP;
376/// // No `Default` either. A default would have to pick a provenance, and the one it
377/// // would pick is the stronger claim.
378/// let unlabelled = DurationP::default();
379/// ```
380///
381/// The positive case, for contrast — naming the provenance is the only way in, and it
382/// is one word:
383///
384/// ```
385/// # use microvms_domain::cost::{DurationP, Provenance};
386/// # use std::time::Duration;
387/// let timed = DurationP::Measured(Duration::from_secs(3600));
388/// assert_eq!(timed.provenance(), Provenance::Measured);
389/// ```
390#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
391pub enum DurationP {
392 /// A clock ran and this is what it read.
393 Measured(Duration),
394 /// A hypothetical: an estimate's input, or a documented minimum nobody timed.
395 Projected(Duration),
396}
397
398impl DurationP {
399 /// A timed phase, from seconds a caller measured as a float.
400 ///
401 /// Fallible because the float is: see [`duration_of_secs_f64`].
402 pub fn measured_secs_f64(seconds: f64) -> Result<DurationP, Error> {
403 Ok(DurationP::Measured(duration_of_secs_f64(seconds)?))
404 }
405
406 /// A hypothetical phase, from seconds a caller supplied as a float.
407 pub fn projected_secs_f64(seconds: f64) -> Result<DurationP, Error> {
408 Ok(DurationP::Projected(duration_of_secs_f64(seconds)?))
409 }
410
411 /// The span, without its label. Named so a call site that drops the provenance
412 /// is visible as one.
413 pub fn duration(self) -> Duration {
414 match self {
415 DurationP::Measured(duration) | DurationP::Projected(duration) => duration,
416 }
417 }
418
419 /// How this duration is known.
420 pub fn provenance(self) -> Provenance {
421 match self {
422 DurationP::Measured(_) => Provenance::Measured,
423 DurationP::Projected(_) => Provenance::Projected,
424 }
425 }
426
427 /// The span as exact decimal seconds, for the money path.
428 pub fn seconds(self) -> Decimal {
429 seconds_of(self.duration())
430 }
431
432 /// The span as an f64, for a JSON envelope.
433 ///
434 /// **Lossy, and named so**, exactly like
435 /// [`ResidencyComparison::break_even_seconds_f64`]. The exact answer is
436 /// [`DurationP::seconds`]; this exists because `cli.py:743` emits a line item's
437 /// `duration.seconds` as a JSON *number* and the two clients' envelopes have to be
438 /// substitutable. Seconds, not dollars — no money figure has an f64 accessor
439 /// (COST-2), and that asymmetry is the whole rule: a consumer doing arithmetic on
440 /// a duration should not have to branch on which client produced the envelope,
441 /// while a consumer doing arithmetic on a dollar figure should be reading the
442 /// string and told so.
443 ///
444 /// (cli.py line numbers resolve at `git show 'c4d396e^:clients/python/src/microvms_agentd/cli.py'` — the retired oracle.)
445 pub fn seconds_f64(self) -> f64 {
446 self.duration().as_secs_f64()
447 }
448
449 /// True only for a timed span. Read by [`CostReport::fully_measured`].
450 pub fn is_measured(self) -> bool {
451 matches!(self, DurationP::Measured(_))
452 }
453}
454
455/// The Python's `f"{seconds:g}s ({provenance})"`, so a report line reads the same in
456/// either client.
457impl fmt::Display for DurationP {
458 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459 write!(f, "{}s ({})", self.seconds().normalize(), self.provenance())
460 }
461}
462
463// ── dollars, which are always estimates (COST-2) ─────────────────────────────
464
465/// Dollars derived from published rates. Not the bill.
466///
467/// There is deliberately no `ActualUsd` alongside this: a client that never sees an
468/// invoice cannot produce an actual. And there is deliberately **no way to get an
469/// f64 out** (COST-2) — no `From<EstimatedUsd> for f64`, no `Into`, no `Deref`, no
470/// `as_f64`. The Python original could only omit `__float__` and hope; the cheapest
471/// way to launder an estimate into a bill is `f"${float(x):.2f}"`, and the Rust
472/// equivalent does not compile.
473///
474/// [`EstimatedUsd::amount`] returns a [`Decimal`], which is one visible step and
475/// keeps the type name at the call site. A caller who genuinely needs a float
476/// reaches for `Decimal::to_f64`, which is two named steps and a `Option` — and
477/// which is a decision a reviewer can see.
478///
479/// [`Add`](std::ops::Add) is implemented only against itself, so summing an amount
480/// that might be [`Amount::Unpriced`] is a type error rather than a silent zero.
481///
482/// # The coercion does not compile (COST-2)
483///
484/// The requirement is about an impl that is *absent*, so the check has to be a
485/// program that fails to build. `compile_fail` doctests are that check, and they are
486/// run by `cargo test` like any other:
487///
488/// The error code is pinned on each one, because a bare `compile_fail` passes for
489/// *any* build failure — including a typo in the test itself, which would leave the
490/// guard green while measuring nothing.
491///
492/// ```compile_fail,E0277
493/// # use microvms_domain::cost::EstimatedUsd;
494/// # use rust_decimal_macros::dec;
495/// let estimate = EstimatedUsd::new(dec!(1.23));
496/// // No `From<EstimatedUsd> for f64`, so no `Into` either. This is the line the
497/// // Python client could only ask a reader not to write.
498/// let laundered: f64 = estimate.into();
499/// ```
500///
501/// ```compile_fail,E0614
502/// # use microvms_domain::cost::EstimatedUsd;
503/// # use rust_decimal_macros::dec;
504/// let estimate = EstimatedUsd::new(dec!(1.23));
505/// // No `Deref` and no public field: the figure comes out through `amount()`, which
506/// // names the type at the call site.
507/// let bare = *estimate;
508/// ```
509///
510/// ```compile_fail,E0308
511/// # use microvms_domain::cost::{Amount, EstimatedUsd};
512/// # use rust_decimal_macros::dec;
513/// let estimate = EstimatedUsd::new(dec!(1.23));
514/// let unknown = Amount::unpriced("no rate is published");
515/// // `Add` is implemented only against `EstimatedUsd`, so the Python's runtime
516/// // `TypeError` from `NotImplemented` is a compile error here (COST-4).
517/// let wrong = estimate + unknown;
518/// ```
519#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
520pub struct EstimatedUsd(Decimal);
521
522impl EstimatedUsd {
523 /// Zero dollars, which is a legitimate *priced* figure — a zero-length hold, a
524 /// zero-cycle comparison — and is not the same claim as [`Amount::Unpriced`].
525 pub const ZERO: EstimatedUsd = EstimatedUsd(Decimal::ZERO);
526
527 /// An estimate from a decimal figure already in the money path.
528 ///
529 /// Takes a [`Decimal`] and not an f64, so this constructor cannot be the second
530 /// float boundary: [`gb_decimal`] and [`seconds_of`] are the only two, which is
531 /// what makes COST-6's "exactly once" checkable by reading them.
532 pub fn new(amount: Decimal) -> EstimatedUsd {
533 EstimatedUsd(amount)
534 }
535
536 /// The figure, in decimal.
537 ///
538 /// The one visible step out. Deliberately not `Into<Decimal>`: an explicit call
539 /// keeps `EstimatedUsd` in the reader's view at the point the label is dropped.
540 pub fn amount(self) -> Decimal {
541 self.0
542 }
543
544 /// The figure rendered at display precision, without the estimate label.
545 ///
546 /// For a caller assembling its own sentence. [`fmt::Display`] is what carries
547 /// the label, and it is what a report renders through.
548 pub fn amount_string(self) -> String {
549 render_amount(self.0)
550 }
551
552 /// A dollar figure from a caller's decimal string — a budget, typically.
553 ///
554 /// A string and not an f64, so this is not a third float boundary beside
555 /// [`gb_decimal`] and [`seconds_of`]: the caller typed a decimal, and parsing
556 /// the text they typed keeps `0.1` meaning a tenth rather than the nearest
557 /// binary float. Negative is refused here rather than compared later, because
558 /// every total this could be compared against is non-negative and a negative
559 /// budget can only ever be a sign error the comparison would launder into
560 /// "always breached".
561 pub fn parse(text: &str) -> Result<EstimatedUsd, Error> {
562 let amount = Decimal::from_str(text.trim()).map_err(|source| {
563 Error::invalid_arg(format!(
564 "{text:?} is not a dollar figure: money arithmetic here is decimal end to \
565 end, so the value must read as a plain decimal like 1.50"
566 ))
567 .with_source(source)
568 })?;
569 if amount.is_sign_negative() {
570 return Err(Error::invalid_arg(format!(
571 "a budget cannot be negative: {text}"
572 )));
573 }
574 Ok(EstimatedUsd(amount))
575 }
576}
577
578impl std::ops::Add for EstimatedUsd {
579 type Output = EstimatedUsd;
580
581 /// Only an estimate adds to an estimate.
582 ///
583 /// There is no `Add<Amount>` and no `Add<Unpriced>`, so the Python's
584 /// `NotImplemented` — a runtime `TypeError` — becomes a compile error. This is
585 /// the last line of defence for COST-4: even a consumer that ignores
586 /// [`CostReport::is_complete`] cannot sum an unknown into a dollar figure.
587 fn add(self, other: EstimatedUsd) -> EstimatedUsd {
588 EstimatedUsd(self.0 + other.0)
589 }
590}
591
592impl std::iter::Sum for EstimatedUsd {
593 fn sum<I: Iterator<Item = EstimatedUsd>>(iter: I) -> EstimatedUsd {
594 iter.fold(EstimatedUsd::ZERO, std::ops::Add::add)
595 }
596}
597
598/// A figure copied out of a terminal loses its docstring, so the label travels in
599/// `Display` rather than sitting in the type name alone.
600impl fmt::Display for EstimatedUsd {
601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602 write!(f, "~${} (estimated)", render_amount(self.0))
603 }
604}
605
606/// What a line item's cost can be (COST-3).
607///
608/// Any consumer that matches on this has to handle the unknown case, which is the
609/// property the whole module rests on. [`Amount::Unpriced`] is distinct from
610/// `Amount::Estimated(EstimatedUsd::ZERO)` on purpose: zero is a claim about the
611/// bill, unpriced is a claim about the documentation.
612#[derive(Clone, Debug, Eq, PartialEq)]
613pub enum Amount {
614 Estimated(EstimatedUsd),
615 /// A quantity we can measure but cannot price, because no rate is published.
616 ///
617 /// The reason is a field and not optional, so the line item can say *why* rather
618 /// than just that it cannot. [`BUILD_UNPRICED_REASON`] is the one this module
619 /// raises.
620 Unpriced {
621 reason: String,
622 },
623}
624
625impl Amount {
626 /// A priced amount from a decimal figure.
627 pub fn estimated(amount: Decimal) -> Amount {
628 Amount::Estimated(EstimatedUsd::new(amount))
629 }
630
631 /// An unpriced amount, with the reason that goes on the line item.
632 pub fn unpriced(reason: impl Into<String>) -> Amount {
633 Amount::Unpriced {
634 reason: reason.into(),
635 }
636 }
637
638 /// The estimate, when there is one.
639 ///
640 /// Returns `Option` rather than defaulting to zero, which is the same decision
641 /// as `cli.py`'s JSON omitting the `usd` key entirely for an unpriced line: a
642 /// null gets summed as zero by anything permissive, and that is the one
643 /// arithmetic this module refuses to enable.
644 pub fn estimate(&self) -> Option<EstimatedUsd> {
645 match self {
646 Amount::Estimated(usd) => Some(*usd),
647 Amount::Unpriced { .. } => None,
648 }
649 }
650
651 /// The reason this could not be priced, when it could not.
652 pub fn unpriced_reason(&self) -> Option<&str> {
653 match self {
654 Amount::Estimated(_) => None,
655 Amount::Unpriced { reason } => Some(reason),
656 }
657 }
658
659 /// The stable tag `cli.py` puts in the JSON envelope's `amount.kind`.
660 pub fn kind(&self) -> &'static str {
661 match self {
662 Amount::Estimated(_) => "estimated-usd",
663 Amount::Unpriced { .. } => "unpriced",
664 }
665 }
666}
667
668impl fmt::Display for Amount {
669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670 match self {
671 Amount::Estimated(usd) => write!(f, "{usd}"),
672 Amount::Unpriced { reason } => write!(f, "unpriced — {reason}"),
673 }
674 }
675}
676
677/// One line item a total could not price: which phase it belonged to, and why.
678///
679/// The phase travels beside the reason because the two answer different questions and
680/// a reader needs both. `cost.py:339-343` renders the *phase names* in the total's
681/// parenthetical — `plus 1 unpriced (image-build)` — because a reason is a paragraph
682/// and a total is one line, while [`Total::unpriced_reasons`] still hands over the
683/// paragraphs for the consumer that wants them. Carrying only the reason, which is
684/// what this type replaced, made the phase unavailable at render time and the Rust
685/// total printed the paragraph.
686#[derive(Clone, Debug, Eq, PartialEq)]
687pub struct UnpricedLine {
688 /// The phase the line belonged to. What the total's parenthetical names.
689 pub phase: CostPhase,
690 /// Why no figure could be attached to it.
691 pub reason: String,
692}
693
694/// A report's total, which is a lower bound whenever anything is unpriced (COST-4).
695///
696/// Two variants rather than a struct with a flag, and that is the upgrade over the
697/// Python's `Total(priced, unpriced=())`: there a consumer could read `.priced` and
698/// never look at `.is_lower_bound`, so the honesty rule depended on the caller
699/// checking. Here the floor is *inside* [`Total::AtLeast`], beside the reasons, so
700/// reaching it means seeing them. A plain sum cannot express "everything we could
701/// price, plus a build AWS will not tell us the price of", and the natural way to
702/// force it to — dropping the unpriced line — is exactly the lie this module exists
703/// not to tell.
704#[derive(Clone, Debug, Eq, PartialEq)]
705pub enum Total {
706 /// Every line item was priced, so this is the whole estimate.
707 Exact(EstimatedUsd),
708 /// At least this much, plus line items with no published rate.
709 AtLeast {
710 /// The sum of the priced lines. Not the total — the total is unknowable.
711 floor: EstimatedUsd,
712 /// The lines that could not be priced, in report order.
713 ///
714 /// Non-empty by construction: [`Total::of`] answers [`Total::Exact`] when
715 /// there is nothing to name, so an `AtLeast` with an empty list — a lower
716 /// bound that will not say what it is missing — is not a value this type
717 /// holds.
718 unpriced: Vec<UnpricedLine>,
719 },
720}
721
722impl Total {
723 /// The total over a report's amounts, each labelled with the phase it came from.
724 ///
725 /// The one place a total is computed, so COST-4 holds for every consumer rather
726 /// than for the ones that remembered. An unpriced amount routes the whole answer
727 /// to [`Total::AtLeast`]; it is never skipped and never summed as zero.
728 ///
729 /// Takes `(phase, amount)` rather than a bare amount so the phase cannot go
730 /// missing on the way in: the rendered total names phases, and a `Total` built
731 /// without them could only fall back to printing reasons.
732 pub fn of<'a>(amounts: impl IntoIterator<Item = (CostPhase, &'a Amount)>) -> Total {
733 let mut floor = EstimatedUsd::ZERO;
734 let mut unpriced: Vec<UnpricedLine> = Vec::new();
735 for (phase, amount) in amounts {
736 match amount {
737 Amount::Estimated(usd) => floor = floor + *usd,
738 Amount::Unpriced { reason } => unpriced.push(UnpricedLine {
739 phase,
740 reason: reason.clone(),
741 }),
742 }
743 }
744 if unpriced.is_empty() {
745 Total::Exact(floor)
746 } else {
747 Total::AtLeast { floor, unpriced }
748 }
749 }
750
751 /// Everything that could be priced.
752 ///
753 /// Named `floor` rather than `total` on purpose: for [`Total::AtLeast`] it is a
754 /// lower bound, and a consumer reading a field called `total` would have no
755 /// reason to check which variant it came from.
756 pub fn floor(&self) -> EstimatedUsd {
757 match self {
758 Total::Exact(usd) => *usd,
759 Total::AtLeast { floor, .. } => *floor,
760 }
761 }
762
763 /// True when line items with no published rate are missing from the floor.
764 pub fn is_lower_bound(&self) -> bool {
765 matches!(self, Total::AtLeast { .. })
766 }
767
768 /// The lines that could not be priced. Empty for [`Total::Exact`].
769 pub fn unpriced_lines(&self) -> &[UnpricedLine] {
770 match self {
771 Total::Exact(_) => &[],
772 Total::AtLeast { unpriced, .. } => unpriced,
773 }
774 }
775
776 /// The reasons the unpriced lines could not be priced, in report order. Empty for
777 /// [`Total::Exact`].
778 ///
779 /// Kept beside [`Total::unpriced_lines`] because the reason is what a consumer
780 /// surfacing the *why* wants, while the rendered total names phases.
781 pub fn unpriced_reasons(&self) -> Vec<String> {
782 self.unpriced_lines()
783 .iter()
784 .map(|line| line.reason.clone())
785 .collect()
786 }
787
788 /// The distinct phase names of the unpriced lines, sorted — what the rendered
789 /// total names.
790 ///
791 /// Sorted and deduplicated to match `cost.py:342`'s
792 /// `", ".join(sorted({item.phase.value for item in self.unpriced}))`: two unpriced
793 /// lines in one phase name it once, and the order does not depend on report order.
794 pub fn unpriced_phase_names(&self) -> Vec<&'static str> {
795 let mut names: Vec<&'static str> = self
796 .unpriced_lines()
797 .iter()
798 .map(|line| line.phase.as_str())
799 .collect();
800 names.sort_unstable();
801 names.dedup();
802 names
803 }
804}
805
806/// "at least" is the whole point, so it leads.
807///
808/// The parenthetical names **phases**, not reasons, which is `cost.py:343` verbatim. A
809/// reason is a sentence explaining what AWS does not publish, and joining several of
810/// them turns a one-line total into a paragraph the two clients cannot both print.
811impl fmt::Display for Total {
812 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
813 match self {
814 Total::Exact(usd) => write!(f, "{usd}"),
815 Total::AtLeast { floor, unpriced } => write!(
816 f,
817 "at least {floor}, plus {} unpriced ({})",
818 unpriced.len(),
819 self.unpriced_phase_names().join(", ")
820 ),
821 }
822 }
823}
824
825// ── the rate table ───────────────────────────────────────────────────────────
826
827/// us-east-1 rates, pinned to when they were read and where from.
828///
829/// The three booleans and the absent increment are documented *facts* rather than
830/// settings, and they are fields because each one is a mistake someone would
831/// otherwise make in arithmetic: blending vCPU into a GB-second, adding a per-invoke
832/// charge by analogy with Lambda Functions, rounding a 200 ms exec up to a 1-second
833/// increment, or subtracting a free tier that does not exist.
834///
835/// # Why the rate fields are private (COST-9)
836///
837/// The Python's `RateTable` was a plain frozen dataclass, so anyone could construct
838/// one — which is how `pricing.py`'s ARM refusal ended up guarding only the fetch
839/// path. Here the five rates are private and there are exactly two ways to obtain a
840/// table: the pinned [`pinned_rates`], and [`RateTable::from_catalog`], which refuses a
841/// catalog missing its ARM compute line rather than substituting the x86 one. So
842/// "compute is priced from the ARM rate" is a property of the type rather than of a
843/// code path that can be bypassed.
844#[derive(Clone, Debug, Eq, PartialEq)]
845pub struct RateTable {
846 region: Region,
847 source_url: String,
848 retrieved: CalendarDate,
849 vcpu_second: Decimal,
850 gb_second: Decimal,
851 storage_gb_month: Decimal,
852 snapshot_read_gb: Decimal,
853 snapshot_write_gb: Decimal,
854 minimum_retention: Duration,
855}
856
857impl RateTable {
858 /// The region these rates price.
859 ///
860 /// Not a cosmetic label: eu-west-1 is 5.3% over us-east-1 on compute and 19% on
861 /// snapshot storage, and ap-northeast-1 is 16.4% and 20%. A caller in Tokyo
862 /// reading the us-east-1 table understates their snapshot write bill by 22.6%,
863 /// which is not a rounding difference and would never show up as staleness.
864 pub fn region(&self) -> &Region {
865 &self.region
866 }
867
868 /// Where these figures came from, as an instruction a reader can act on.
869 pub fn source_url(&self) -> &str {
870 &self.source_url
871 }
872
873 /// When they were read.
874 pub fn retrieved(&self) -> CalendarDate {
875 self.retrieved
876 }
877
878 /// Per vCPU-second, billed separately from memory.
879 pub fn vcpu_second(&self) -> Decimal {
880 self.vcpu_second
881 }
882
883 /// Per GB-second of *baseline* memory, billed separately from vCPU.
884 pub fn gb_second(&self) -> Decimal {
885 self.gb_second
886 }
887
888 /// Per GB-month of snapshot storage.
889 ///
890 /// The one derived figure: the Pricing API quotes this per GB-hour, and this
891 /// table holds per GB-month. See [`HOURS_PER_MONTH`].
892 pub fn storage_gb_month(&self) -> Decimal {
893 self.storage_gb_month
894 }
895
896 /// Per GB read on a launch or a resume.
897 pub fn snapshot_read_gb(&self) -> Decimal {
898 self.snapshot_read_gb
899 }
900
901 /// Per GB written on a suspend. Roughly 2.5x the read rate, so a cycle costed
902 /// with one rate twice is wrong in whichever direction it picked.
903 pub fn snapshot_write_gb(&self) -> Decimal {
904 self.snapshot_write_gb
905 }
906
907 /// The documented storage minimum (COST-8).
908 ///
909 /// On the rate row itself, so it applies to anything stored there.
910 pub fn minimum_retention(&self) -> Duration {
911 self.minimum_retention
912 }
913
914 /// The same minimum in whole days, which is the unit the note on a floored line
915 /// item quotes.
916 ///
917 /// Here rather than as an `as_secs() / 86_400` at the one call site, because that
918 /// spelling is a second place the seconds-to-days convention lives: the field is
919 /// the only thing that knows how long the window is, and a division written beside
920 /// the message would keep saying "7-day" after a rate row moved to a fortnight.
921 /// Truncating rather than rounding is deliberate — a floor quoted as longer than it
922 /// is would overstate the charge a reader is being told about.
923 pub fn minimum_retention_days(&self) -> u64 {
924 self.minimum_retention.as_secs() / SECONDS_PER_DAY
925 }
926
927 /// MicroVMs bills per second with no per-request charge.
928 ///
929 /// A method returning a constant rather than a field, because it is a documented
930 /// fact and not a table entry someone could edit into a different claim. The
931 /// Lambda free tier is Functions-only and no MicroVMs free tier is published.
932 pub fn per_request(&self) -> Decimal {
933 Decimal::ZERO
934 }
935
936 /// vCPU and memory are two line items, as the pricing page prices them.
937 ///
938 /// A blended GB-second figure cannot be reconciled against a Cost Explorer
939 /// breakdown that keeps them apart.
940 pub fn bills_vcpu_and_memory_separately(&self) -> bool {
941 true
942 }
943
944 /// No published free tier.
945 pub fn free_tier(&self) -> bool {
946 false
947 }
948
949 /// The minimum billing increment, which is **not published**.
950 ///
951 /// `None` means not published, not "one second". Nothing here rounds a duration
952 /// up, because inventing an increment would overcharge every short exec in a
953 /// report and there is no source for one.
954 pub fn minimum_billing_increment(&self) -> Option<Duration> {
955 None
956 }
957
958 /// How many days ago these rates were read.
959 pub fn age_days(&self, today: CalendarDate) -> i64 {
960 today.days_since(self.retrieved)
961 }
962
963 /// Whether the table is past [`STALE_AFTER_DAYS`] (COST-7).
964 pub fn is_stale(&self, today: CalendarDate) -> bool {
965 self.age_days(today) > STALE_AFTER_DAYS
966 }
967
968 /// The warning text, or `None` when the table is fresh.
969 ///
970 /// Text rather than a bool because the warning has to survive into whatever
971 /// renders it, carrying the retrieval date and the URL — a figure copied out of a
972 /// terminal loses everything else.
973 pub fn staleness(&self, today: CalendarDate) -> Option<String> {
974 if !self.is_stale(today) {
975 return None;
976 }
977 Some(format!(
978 "rate table for {} was retrieved {}, {} days ago (stale after {STALE_AFTER_DAYS}) — \
979 re-read {} before trusting these figures",
980 self.region,
981 self.retrieved,
982 self.age_days(today),
983 self.source_url,
984 ))
985 }
986}
987
988/// Read 2026-08-07, us-east-1, and recorded in `docs/PLATFORM.md` under "What
989/// actually costs money".
990///
991/// Four rates appear on the Lambda pricing page as written; `storage_gb_month` is
992/// *derived*, because the AWS Pricing API quotes snapshot storage per GB-hour and
993/// this table holds per GB-month. Change any of them and change that document in the
994/// same commit.
995///
996/// A drift check against the Pricing API — not [`STALE_AFTER_DAYS`] — is what
997/// actually tells you whether a rate moved; the staleness warning only ever said
998/// that nobody had looked. See [`RateCatalog`].
999///
1000/// Only the ARM figures are correct here and it is not a preference: MicroVMs are
1001/// ARM64-only, the x86 compute rates in the same catalog are 17.9% higher, and this
1002/// table used to hold the right ones by luck rather than by construction (COST-9).
1003///
1004/// A function rather than a `static`, because [`Region`] and the URL own heap
1005/// allocations. Cheap — five decimal copies and one small string — and called once
1006/// per report.
1007pub fn pinned_rates() -> RateTable {
1008 RateTable {
1009 region: Region::UsEast1,
1010 source_url: "https://aws.amazon.com/lambda/pricing/".to_string(),
1011 retrieved: CalendarDate::from_ymd(2026, 8, 7),
1012 vcpu_second: dec!(0.0000276944),
1013 gb_second: dec!(0.0000036667),
1014 // $0.0001111111 per GB-hour x 730 hours. Was 0.08 — a plausible-looking
1015 // round number that understated every stored GB by 1.37%, which is the whole
1016 // argument for deriving it from the API figure rather than reading a page.
1017 storage_gb_month: dec!(0.0811111030),
1018 snapshot_read_gb: dec!(0.00155),
1019 snapshot_write_gb: dec!(0.0038),
1020 minimum_retention: MINIMUM_RETENTION,
1021 }
1022}
1023
1024// ── the catalog, and the ARM-only rule (COST-9) ───────────────────────────────
1025
1026/// One rate the catalog has to carry, and what it fills.
1027///
1028/// The Python held this as `pricing.MICROVM_LINES`, a tuple of `RateLine` records
1029/// naming a `group`, a `usagetype`, a `unit`, and — for the two compute lines — an
1030/// `x86_group` probed only when the ARM line was missing. Same shape here, as a
1031/// closed enum: the catalog has five lines this client reads, and a sixth is not a
1032/// value that exists.
1033#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1034pub enum CatalogLine {
1035 VcpuSecond,
1036 MemoryGbSecond,
1037 /// Quoted per GB-**hour** by the API. Converted once, in
1038 /// [`RateTable::from_catalog`].
1039 SnapshotStorageGbHour,
1040 SnapshotReadGb,
1041 SnapshotWriteGb,
1042}
1043
1044impl CatalogLine {
1045 /// Every line, in the order the Python's `MICROVM_LINES` declares them.
1046 pub const ALL: [CatalogLine; 5] = [
1047 CatalogLine::VcpuSecond,
1048 CatalogLine::MemoryGbSecond,
1049 CatalogLine::SnapshotStorageGbHour,
1050 CatalogLine::SnapshotReadGb,
1051 CatalogLine::SnapshotWriteGb,
1052 ];
1053
1054 /// The region-independent `group` attribute, which is what a fetch filters on.
1055 ///
1056 /// `usagetype` carries a location prefix in every region except us-east-1
1057 /// (`Lambda-MicroVM-vCPU-Second-ARM` is `USW2-Lambda-MicroVM-vCPU-Second-ARM` in
1058 /// us-west-2), so comparing raw usage types across regions matches nothing and
1059 /// yields a table of holes rather than an error. `group` does not.
1060 pub fn group(self) -> &'static str {
1061 match self {
1062 CatalogLine::VcpuSecond => "AWS-Lambda-MicroVM-vCPU-Second-ARM",
1063 CatalogLine::MemoryGbSecond => "AWS-Lambda-MicroVM-Memory-GB-Second-ARM",
1064 CatalogLine::SnapshotStorageGbHour => "AWS-Lambda-MicroVM-Snapshot-Storage-GB-Hour",
1065 CatalogLine::SnapshotReadGb => "AWS-Lambda-MicroVM-Snapshot-Read-GB",
1066 CatalogLine::SnapshotWriteGb => "AWS-Lambda-MicroVM-Snapshot-Write-GB",
1067 }
1068 }
1069
1070 /// The [`RateTable`] field this fills, as the Python's `RateLine.field` spells
1071 /// it — so a drift report names the same thing in both clients.
1072 pub fn field(self) -> &'static str {
1073 match self {
1074 CatalogLine::VcpuSecond => "vcpu_second",
1075 CatalogLine::MemoryGbSecond => "gb_second",
1076 CatalogLine::SnapshotStorageGbHour => "storage_gb_month",
1077 CatalogLine::SnapshotReadGb => "snapshot_read_gb",
1078 CatalogLine::SnapshotWriteGb => "snapshot_write_gb",
1079 }
1080 }
1081
1082 /// The unit the API must report for this line.
1083 ///
1084 /// Checked rather than assumed. It is the only signal available if AWS restates
1085 /// storage per GB-month: the number would change by 730x and every arithmetic
1086 /// check downstream would still pass, because they all read the same table.
1087 pub fn unit(self) -> &'static str {
1088 match self {
1089 CatalogLine::VcpuSecond => "vCPU-Seconds",
1090 CatalogLine::MemoryGbSecond => "GB-Seconds",
1091 CatalogLine::SnapshotStorageGbHour => "GB-Hours",
1092 CatalogLine::SnapshotReadGb | CatalogLine::SnapshotWriteGb => "GB",
1093 }
1094 }
1095
1096 /// The x86 sibling, for the two compute lines that have one (COST-9).
1097 ///
1098 /// Named so the refusal can say what it is refusing. MicroVMs are ARM64-only —
1099 /// the `Architecture` shape is `enum: ['ARM_64']` with no other member — so the
1100 /// x86 rate can never apply, and it is 17.9% higher. Snapshot lines have no
1101 /// architecture variant, so there is nothing to refuse.
1102 pub fn x86_group(self) -> Option<&'static str> {
1103 match self {
1104 CatalogLine::VcpuSecond => Some("AWS-Lambda-MicroVM-vCPU-Second"),
1105 CatalogLine::MemoryGbSecond => Some("AWS-Lambda-MicroVM-Memory-GB-Second"),
1106 CatalogLine::SnapshotStorageGbHour
1107 | CatalogLine::SnapshotReadGb
1108 | CatalogLine::SnapshotWriteGb => None,
1109 }
1110 }
1111
1112 /// True for storage, quoted per GB-hour where [`RateTable`] holds per GB-month.
1113 pub fn is_per_hour(self) -> bool {
1114 matches!(self, CatalogLine::SnapshotStorageGbHour)
1115 }
1116}
1117
1118/// A priced line item as the catalog states it: a group, a unit, and one USD figure.
1119///
1120/// The USD figure is a [`Decimal`] and not an f64 because the API quotes it as a
1121/// string with ten significant digits — parsing it as a float and converting back
1122/// would lose exactly the precision the string was carrying.
1123#[derive(Clone, Debug, Eq, PartialEq)]
1124pub struct CatalogEntry {
1125 /// The region-independent `group`. Compared against [`CatalogLine::group`].
1126 pub group: String,
1127 /// The unit the API reported. Compared against [`CatalogLine::unit`].
1128 pub unit: String,
1129 /// The rate, in USD per that unit.
1130 pub usd: Decimal,
1131}
1132
1133/// What a rate source offers for one region, before it becomes a [`RateTable`].
1134///
1135/// This is the parse boundary COST-9 lives at. A transport — the Pricing API, a
1136/// recorded fixture, a `mise run live:rates` dump — assembles one of these, and
1137/// [`RateTable::from_catalog`] is the only door from here into a priced report. So
1138/// the ARM refusal cannot be bypassed by building a table directly, which is what it
1139/// could be in the Python.
1140///
1141/// Deliberately holds *every* entry the source offered, including the x86 compute
1142/// rates. A catalog that filtered them out could not tell "the ARM line is gone and
1143/// the x86 one is right there" from "the whole catalog is empty", and those are
1144/// different repairs: work out what AWS renamed, versus check the region.
1145#[derive(Clone, Debug, Default, Eq, PartialEq)]
1146pub struct RateCatalog {
1147 entries: Vec<CatalogEntry>,
1148}
1149
1150impl RateCatalog {
1151 /// An empty catalog, to add entries to.
1152 pub fn new() -> RateCatalog {
1153 RateCatalog {
1154 entries: Vec::new(),
1155 }
1156 }
1157
1158 /// Records one priced line.
1159 #[must_use]
1160 pub fn with_entry(
1161 mut self,
1162 group: impl Into<String>,
1163 unit: impl Into<String>,
1164 usd: Decimal,
1165 ) -> RateCatalog {
1166 self.entries.push(CatalogEntry {
1167 group: group.into(),
1168 unit: unit.into(),
1169 usd,
1170 });
1171 self
1172 }
1173
1174 /// Every entry for a group. Normally exactly one.
1175 fn matching(&self, group: &str) -> Vec<&CatalogEntry> {
1176 self.entries
1177 .iter()
1178 .filter(|entry| entry.group == group)
1179 .collect()
1180 }
1181
1182 /// Whether the catalog offered nothing at all.
1183 pub fn is_empty(&self) -> bool {
1184 self.entries.is_empty()
1185 }
1186}
1187
1188impl RateTable {
1189 /// A table for one region, built from a catalog — or a refusal (COST-9).
1190 ///
1191 /// All or nothing. A partial table would price a run at less than it costs, and
1192 /// the caller has no way to see which field was quietly left at a stale value.
1193 ///
1194 /// Four ways this refuses, each a way the catalog could change and still parse:
1195 /// a missing ARM compute line whose x86 sibling is present (the substitution that
1196 /// would look entirely healthy and inflate every estimate by 17.9%), a missing
1197 /// line with no sibling, a restated unit, and two products where there was one.
1198 pub fn from_catalog(
1199 region: Region,
1200 source_url: impl Into<String>,
1201 retrieved: CalendarDate,
1202 catalog: &RateCatalog,
1203 ) -> Result<RateTable, Error> {
1204 let mut rates: Vec<Decimal> = Vec::with_capacity(CatalogLine::ALL.len());
1205 for line in CatalogLine::ALL {
1206 let matches = catalog.matching(line.group());
1207 let entry = match matches.as_slice() {
1208 [] => return Err(missing_line_error(®ion, line, catalog)),
1209 [only] => *only,
1210 many => {
1211 return Err(Error::invalid_arg(format!(
1212 "{} in {region} returned {} products where one group in one region has \
1213 always been one product; the catalog gained a dimension this client \
1214 does not know how to choose between, and picking one would silently \
1215 select a rate",
1216 line.group(),
1217 many.len(),
1218 )));
1219 }
1220 };
1221 if entry.unit != line.unit() {
1222 return Err(Error::invalid_arg(format!(
1223 "{} in {region} is now quoted per {:?}, not {:?}; the conversion into the \
1224 rate table no longer holds and every downstream figure would still look \
1225 plausible",
1226 line.group(),
1227 entry.unit,
1228 line.unit(),
1229 )));
1230 }
1231 // The API quotes storage per GB-hour. Converting here rather than at
1232 // every use site keeps `RateTable` one convention deep, which is the
1233 // whole reason `SECONDS_PER_MONTH` exists.
1234 rates.push(if line.is_per_hour() {
1235 entry.usd * HOURS_PER_MONTH
1236 } else {
1237 entry.usd
1238 });
1239 }
1240 Ok(RateTable {
1241 region,
1242 source_url: source_url.into(),
1243 retrieved,
1244 vcpu_second: rates[0],
1245 gb_second: rates[1],
1246 storage_gb_month: rates[2],
1247 snapshot_read_gb: rates[3],
1248 snapshot_write_gb: rates[4],
1249 // The catalog prices line items and says nothing about a one-week storage
1250 // minimum, a per-request charge, a billing increment, or a free tier. So
1251 // a fetched table is authoritative on *rates* and still hand-read on
1252 // *rules*, and dropping the retention floor here would understate a
1253 // create-and-destroy suite by four orders of magnitude.
1254 minimum_retention: MINIMUM_RETENTION,
1255 })
1256 }
1257}
1258
1259/// The error for a line the catalog does not have (COST-9).
1260///
1261/// Split out because the ARM case needs to say more than "missing": the x86 sibling
1262/// is right there, 17.9% higher, the same shape, and it parses. The tempting fix is
1263/// to use it, and every estimate would inflate while nothing said so — so the message
1264/// names the rate it is refusing and the magnitude of the error that substituting it
1265/// would introduce.
1266fn missing_line_error(region: &Region, line: CatalogLine, catalog: &RateCatalog) -> Error {
1267 if catalog.is_empty() {
1268 return Error::invalid_arg(format!(
1269 "the rate catalog has no MicroVM line items for {region} at all, so {} cannot be \
1270 filled. Measured 2026-08-07, pricing coverage and service availability coincide: a \
1271 region that does not price MicroVMs does not run them either, and answers \
1272 lambda-microvms with AccessDeniedException and a null message that reads exactly \
1273 like an IAM problem it is not. Check the region before auditing a policy",
1274 line.field(),
1275 ));
1276 }
1277 let Some(x86_group) = line.x86_group() else {
1278 return Error::invalid_arg(format!(
1279 "{region} prices MicroVMs but has no {} line item, so {} cannot be filled",
1280 line.group(),
1281 line.field(),
1282 ));
1283 };
1284 match catalog.matching(x86_group).first() {
1285 Some(sibling) => Error::invalid_arg(format!(
1286 "{region} has no {}, only the x86 rate {x86_group} at ${}. MicroVMs are ARM64-only \
1287 — the Architecture shape is enum ['ARM_64'] with no other member — so the x86 rate \
1288 can never apply and is not substituted for {}; doing so would overstate every \
1289 compute figure by roughly 18%",
1290 line.group(),
1291 sibling.usd,
1292 line.field(),
1293 )),
1294 None => Error::invalid_arg(format!(
1295 "{region} has neither {} nor {x86_group}, so {} cannot be filled",
1296 line.group(),
1297 line.field(),
1298 )),
1299 }
1300}
1301
1302// ── phases and billing lines ─────────────────────────────────────────────────
1303
1304/// The line items AWS bills, spelled as separately as AWS bills them.
1305///
1306/// vCPU and memory are two entries rather than one blended GB-second because that is
1307/// how the pricing page prices them, and a blended figure cannot be reconciled
1308/// against a Cost Explorer breakdown that keeps them apart.
1309#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1310pub enum BillingLine {
1311 Vcpu,
1312 Memory,
1313 SnapshotStorage,
1314 SnapshotRead,
1315 SnapshotWrite,
1316}
1317
1318impl BillingLine {
1319 /// The wire spelling, identical to the Python `StrEnum` member.
1320 pub fn as_str(self) -> &'static str {
1321 match self {
1322 BillingLine::Vcpu => "vcpu",
1323 BillingLine::Memory => "memory",
1324 BillingLine::SnapshotStorage => "snapshot-storage",
1325 BillingLine::SnapshotRead => "snapshot-read",
1326 BillingLine::SnapshotWrite => "snapshot-write",
1327 }
1328 }
1329}
1330
1331impl fmt::Display for BillingLine {
1332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1333 f.write_str(self.as_str())
1334 }
1335}
1336
1337/// The lifecycle a sandbox goes through, as the phases that cost money.
1338#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1339pub enum CostPhase {
1340 ImageBuild,
1341 ImageStorage,
1342 Launch,
1343 Running,
1344 Suspended,
1345 Suspend,
1346 Resume,
1347}
1348
1349impl CostPhase {
1350 /// Every phase, in lifecycle order.
1351 ///
1352 /// Public because a caller that has to *judge* a phase string needs the list to
1353 /// refuse with, and the two bindings each grew their own copy of this array before
1354 /// it existed here — a parallel table that would have gone stale the first time a
1355 /// phase was added. [`CostPhase::from_str`] is the reader; the round-trip test below
1356 /// is what stops a variant being added to the enum and forgotten here.
1357 pub const ALL: [CostPhase; 7] = [
1358 CostPhase::ImageBuild,
1359 CostPhase::ImageStorage,
1360 CostPhase::Launch,
1361 CostPhase::Running,
1362 CostPhase::Suspended,
1363 CostPhase::Suspend,
1364 CostPhase::Resume,
1365 ];
1366
1367 /// The wire spelling, identical to the Python `StrEnum` member.
1368 pub fn as_str(self) -> &'static str {
1369 match self {
1370 CostPhase::ImageBuild => "image-build",
1371 CostPhase::ImageStorage => "image-storage",
1372 CostPhase::Launch => "launch",
1373 CostPhase::Running => "running",
1374 CostPhase::Suspended => "suspended",
1375 CostPhase::Suspend => "suspend",
1376 CostPhase::Resume => "resume",
1377 }
1378 }
1379}
1380
1381impl FromStr for CostPhase {
1382 type Err = Error;
1383
1384 /// A phase from its wire spelling, refusing anything else with the whole list.
1385 ///
1386 /// Here rather than in each caller because the callers are *bindings*: a Python or
1387 /// JS `report.by_phase("running")` has a bare string where Rust has a variant, so
1388 /// something has to judge it. Both bindings did, each with its own seven-element
1389 /// array — two parallel tables over a closed set, which is one table too many and
1390 /// two too many to keep in step with the enum. This is the single reader, and the
1391 /// list it offers on a refusal is [`CostPhase::ALL`] rather than a written-out
1392 /// sentence, so a phase added to the enum appears in the message without an edit.
1393 ///
1394 /// Note the asymmetry with [`Region::from_str`](crate::Region): a region's refusal
1395 /// exists because an unlisted region is a *plausible* value this client has no
1396 /// evidence for, and there is an opt-in. A phase has no opt-in and needs none — the
1397 /// set is closed by the billing model, so an unrecognized spelling is a typo and
1398 /// nothing more.
1399 fn from_str(phase: &str) -> Result<CostPhase, Error> {
1400 CostPhase::ALL
1401 .into_iter()
1402 .find(|candidate| candidate.as_str() == phase)
1403 .ok_or_else(|| {
1404 let offered = CostPhase::ALL
1405 .iter()
1406 .map(|candidate| candidate.as_str())
1407 .collect::<Vec<_>>()
1408 .join(", ");
1409 Error::invalid_arg(format!(
1410 "{phase:?} is not a cost phase; the phases are {offered}"
1411 ))
1412 })
1413 }
1414}
1415
1416/// `pad` rather than `write_str`, because a phase is a column.
1417///
1418/// `write_str` ignores the formatter's width entirely, so `{:<14}` on a phase silently
1419/// produced a ragged table — every plain-text line's dollar figure started at a
1420/// different offset, and the fix looks like it is already there in the format string.
1421/// [`fmt::Formatter::pad`] is the one spelling that honours width, precision, and
1422/// alignment; `write!(f, "{}", ...)` here would recurse straight back into this
1423/// impl and drop the width again.
1424impl fmt::Display for CostPhase {
1425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1426 f.pad(self.as_str())
1427 }
1428}
1429
1430/// One phase's one billing line: what was consumed, and what that costs.
1431///
1432/// `quantity` and `unit` are kept beside `amount` so a reader can check the
1433/// arithmetic against the rate table instead of trusting the total, which is the only
1434/// defence against a rate that drifts out of date without anyone noticing.
1435#[derive(Clone, Debug, Eq, PartialEq)]
1436pub struct LineItem {
1437 pub phase: CostPhase,
1438 /// `None` only for a phase with no published rate to attribute it to.
1439 pub line: Option<BillingLine>,
1440 pub quantity: Decimal,
1441 pub unit: String,
1442 pub amount: Amount,
1443 pub duration: Option<DurationP>,
1444 pub note: String,
1445}
1446
1447impl LineItem {
1448 /// The quantity at display precision, for a CLI column.
1449 pub fn quantity_string(&self) -> String {
1450 render_quantity(self.quantity)
1451 }
1452}
1453
1454impl fmt::Display for LineItem {
1455 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1456 let consumed = format!("{} {}", self.quantity_string(), self.unit);
1457 let head = format!("{:<14} {:<26} {}", self.phase, consumed, self.amount);
1458 if self.note.is_empty() {
1459 f.write_str(&head)
1460 } else {
1461 write!(f, "{head} [{}]", self.note)
1462 }
1463 }
1464}
1465
1466// ── the report ───────────────────────────────────────────────────────────────
1467
1468/// Per-phase attribution for one sandbox, measured or projected.
1469///
1470/// Holds the rate table it was computed against rather than reaching for the pinned
1471/// default, so a report stays readable — and reproducible — after [`pinned_rates`] is
1472/// updated.
1473#[derive(Clone, Debug, Eq, PartialEq)]
1474pub struct CostReport {
1475 label: String,
1476 size: SizeClass,
1477 rates: RateTable,
1478 items: Vec<LineItem>,
1479 staleness: Option<String>,
1480}
1481
1482impl CostReport {
1483 /// What this report is of, for a header.
1484 pub fn label(&self) -> &str {
1485 &self.label
1486 }
1487
1488 /// The class every compute figure here was billed at (COST-5).
1489 pub fn size(&self) -> SizeClass {
1490 self.size
1491 }
1492
1493 /// The table these figures were computed against.
1494 pub fn rates(&self) -> &RateTable {
1495 &self.rates
1496 }
1497
1498 /// Every line item, in lifecycle order.
1499 pub fn items(&self) -> &[LineItem] {
1500 &self.items
1501 }
1502
1503 /// The staleness warning, when the table was stale at computation time (COST-7).
1504 ///
1505 /// Carried on the report because the warning has to survive into whatever renders
1506 /// it: a library caller with a log filter and a CLI that only wrote stderr would
1507 /// each lose it on their own.
1508 pub fn staleness(&self) -> Option<&str> {
1509 self.staleness.as_deref()
1510 }
1511
1512 /// The line items with a published rate.
1513 pub fn priced(&self) -> impl Iterator<Item = &LineItem> {
1514 self.items
1515 .iter()
1516 .filter(|item| item.amount.estimate().is_some())
1517 }
1518
1519 /// The line items with no published rate.
1520 pub fn unpriced(&self) -> impl Iterator<Item = &LineItem> {
1521 self.items
1522 .iter()
1523 .filter(|item| item.amount.unpriced_reason().is_some())
1524 }
1525
1526 /// The total, which is a lower bound whenever anything is unpriced (COST-4).
1527 pub fn total(&self) -> Total {
1528 Total::of(self.items.iter().map(|item| (item.phase, &item.amount)))
1529 }
1530
1531 /// False whenever any phase has no published rate. See [`Total`].
1532 pub fn is_complete(&self) -> bool {
1533 self.unpriced().next().is_none()
1534 }
1535
1536 /// True only if every duration was timed. An estimate is never this (COST-10).
1537 pub fn fully_measured(&self) -> bool {
1538 let mut durations = self
1539 .items
1540 .iter()
1541 .filter_map(|item| item.duration)
1542 .peekable();
1543 durations.peek().is_some() && durations.all(DurationP::is_measured)
1544 }
1545
1546 /// The line items belonging to one phase.
1547 pub fn by_phase(&self, phase: CostPhase) -> impl Iterator<Item = &LineItem> {
1548 self.items.iter().filter(move |item| item.phase == phase)
1549 }
1550
1551 /// Plain text for a CLI. Leads with what the dollars are, not the dollars.
1552 ///
1553 /// The header is not decoration: a figure copied out of a terminal loses its
1554 /// docstring, so the estimate label and the retrieval date travel with it.
1555 pub fn render(&self) -> String {
1556 let mut lines = vec![
1557 format!("{} — {}", self.label, self.size),
1558 format!(
1559 "dollars are estimates derived from published {} rates (retrieved {}); only Cost \
1560 Explorer knows the bill",
1561 self.rates.region, self.rates.retrieved,
1562 ),
1563 ];
1564 if let Some(warning) = &self.staleness {
1565 lines.push(format!("WARNING: {warning}"));
1566 }
1567 lines.extend(self.items.iter().map(|item| format!(" {item}")));
1568 lines.push(format!("total: {}", self.total()));
1569 lines.join("\n")
1570 }
1571}
1572
1573// ── the line builders ────────────────────────────────────────────────────────
1574
1575/// Compute for one phase, as two line items (COST-5).
1576///
1577/// Both figures read `baseline_*`. Our line bills the minimum floor: the baseline is
1578/// always paid while the VM runs. The peak is provisioned from the start — the guest
1579/// reports it and can use all of it at any moment — and usage above the baseline is
1580/// real and billed by AWS by consumption, per second. This client cannot observe that
1581/// consumption, so it is left out rather than guessed at — our figure is the floor of
1582/// the real bill, which is what the report's own header ("only Cost Explorer knows
1583/// the bill") warns about. See [`crate::sizing`], whose 2 GB class reports 8 GB in
1584/// the guest: reading the peak would overstate the memory line exactly 4x.
1585fn compute_lines(
1586 size: SizeClass,
1587 duration: DurationP,
1588 rates: &RateTable,
1589 phase: CostPhase,
1590) -> Result<[LineItem; 2], Error> {
1591 let seconds = duration.seconds();
1592 // `baseline_gb` and `baseline_vcpu` are the accessors whose doc comments say they
1593 // are the billed figures; `peak_gb`/`peak_vcpu` are deliberately not reachable
1594 // from here. Both cross the float boundary through `gb_decimal` (COST-6).
1595 let vcpu = gb_decimal(size.baseline_vcpu())?;
1596 let memory = gb_decimal(size.baseline_gb())?;
1597 Ok([
1598 LineItem {
1599 phase,
1600 line: Some(BillingLine::Vcpu),
1601 quantity: vcpu * seconds,
1602 unit: "vCPU-seconds".to_string(),
1603 amount: Amount::estimated(vcpu * seconds * rates.vcpu_second()),
1604 duration: Some(duration),
1605 note: format!("{vcpu} vCPU baseline"),
1606 },
1607 LineItem {
1608 phase,
1609 line: Some(BillingLine::Memory),
1610 quantity: memory * seconds,
1611 unit: "GB-seconds".to_string(),
1612 amount: Amount::estimated(memory * seconds * rates.gb_second()),
1613 duration: Some(duration),
1614 note: format!("{memory} GB baseline, billed separately from vCPU"),
1615 },
1616 ])
1617}
1618
1619/// Snapshot storage for a hold, with the documented minimum retention applied
1620/// (COST-8).
1621///
1622/// The minimum is on the rate row itself, so it applies to anything stored there.
1623/// `docs/PLATFORM.md` demonstrates it only for images — a 2 GB image deleted after
1624/// sixty seconds still bills about four cents — and says nothing about a suspend
1625/// snapshot released early, so the note names which case is documented and which is
1626/// the rate row read at face value. Not applying it would understate the one line item
1627/// that dominates a create-and-destroy suite, by four orders of magnitude.
1628fn storage_line(
1629 phase: CostPhase,
1630 gb: Decimal,
1631 held: DurationP,
1632 rates: &RateTable,
1633) -> Result<LineItem, Error> {
1634 let floor = seconds_of(rates.minimum_retention());
1635 let held_seconds = held.seconds();
1636 let billed = held_seconds.max(floor);
1637 let quantity = gb * billed / SECONDS_PER_MONTH;
1638 let mut note = format!("{} GB held {held}", gb.normalize());
1639 if billed > held_seconds {
1640 // The day count comes off the rate row rather than out of a division here: the
1641 // field is the only thing that knows how long the window is, and `as_secs() /
1642 // 86_400` beside the message is a second convention that would keep saying
1643 // "7-day" after the row moved.
1644 note.push_str(&format!(
1645 "; billed {}-day minimum retention ({floor}s) instead",
1646 rates.minimum_retention_days(),
1647 ));
1648 }
1649 Ok(LineItem {
1650 phase,
1651 line: Some(BillingLine::SnapshotStorage),
1652 quantity,
1653 unit: "GB-months".to_string(),
1654 amount: Amount::estimated(quantity * rates.storage_gb_month()),
1655 duration: Some(held),
1656 note,
1657 })
1658}
1659
1660/// A snapshot write or read, billed per GB moved with no time component.
1661fn transfer_line(
1662 phase: CostPhase,
1663 line: BillingLine,
1664 gb: Decimal,
1665 count: u32,
1666 rates: &RateTable,
1667 note_suffix: &str,
1668) -> LineItem {
1669 let rate = if line == BillingLine::SnapshotWrite {
1670 rates.snapshot_write_gb()
1671 } else {
1672 rates.snapshot_read_gb()
1673 };
1674 let quantity = gb * Decimal::from(count);
1675 LineItem {
1676 phase,
1677 line: Some(line),
1678 quantity,
1679 unit: "GB".to_string(),
1680 amount: Amount::estimated(quantity * rate),
1681 duration: None,
1682 note: format!("{count} x {} GB{note_suffix}", gb.normalize()),
1683 }
1684}
1685
1686/// Why the image build has no price.
1687///
1688/// Not a caveat in a doc comment: it is the [`Amount::Unpriced`] reason that appears
1689/// on the line item and in every total that contains it. The build starts a real
1690/// MicroVM to run the Dockerfile, so it plausibly is billed, but AWS does not say and
1691/// we have not measured it.
1692pub const BUILD_UNPRICED_REASON: &str = "AWS does not publish whether the server-side image build is billed as compute; the build \
1693 runs a real MicroVM, so treating it as free would understate the run";
1694
1695/// The image build: a real phase with a real duration and no published rate (COST-3).
1696///
1697/// An untimed build still gets a line. Omitting it would leave the report looking
1698/// complete, and the report being visibly incomplete is the whole point of the phase
1699/// appearing at all.
1700fn build_line(duration: Option<DurationP>) -> LineItem {
1701 LineItem {
1702 phase: CostPhase::ImageBuild,
1703 line: None,
1704 quantity: duration.map_or(Decimal::ZERO, DurationP::seconds),
1705 unit: if duration.is_some() {
1706 "seconds".to_string()
1707 } else {
1708 "seconds (untimed)".to_string()
1709 },
1710 amount: Amount::unpriced(BUILD_UNPRICED_REASON),
1711 duration,
1712 note: "unknown, not zero — see docs/PLATFORM.md, 'Not published'".to_string(),
1713 }
1714}
1715
1716// ── the reports ──────────────────────────────────────────────────────────────
1717
1718/// What to attribute cost to, for one sandbox's lifecycle.
1719///
1720/// A struct rather than eleven parameters, because the Python's keyword-only
1721/// signature has no direct Rust equivalent and eleven positional arguments is how a
1722/// caller passes `image_gb` where `snapshot_gb` was meant. `Default` gives the same
1723/// "pass only the phases that happened" ergonomics as the Python's defaults.
1724///
1725/// Every duration is a [`DurationP`], so a report built from timed phases and one
1726/// built from a plan are the same shape and are told apart by their own contents
1727/// rather than by which function produced them.
1728#[derive(Clone, Debug, Default, PartialEq)]
1729pub struct RunUsage {
1730 /// Wall-clock time in RUNNING. Bills at baseline whether or not anything is
1731 /// executing — unlike AgentCore Runtime there is no free I/O wait, which is why
1732 /// suspension rather than idleness is the lever.
1733 pub running: Option<DurationP>,
1734 /// Time held suspended. Pays storage only: a suspended VM is frozen.
1735 pub suspended: Option<DurationP>,
1736 /// How long the image build took, if it was timed. Always unpriced (COST-3).
1737 pub image_build: Option<DurationP>,
1738 /// The image's size. Passing this adds both an image-storage line *and* the
1739 /// unpriced build line: an image that has storage cost was built, and the build's
1740 /// price is unknown, so a create-and-destroy report is never complete. A caller
1741 /// reusing an existing image passes `None` and pays neither.
1742 pub image_gb: Option<f64>,
1743 /// How long the image was retained. Defaults to the documented minimum, marked
1744 /// [`Provenance::Projected`] — nobody timed that week either.
1745 pub image_retained: Option<DurationP>,
1746 /// Each cycle pays a snapshot write plus a read.
1747 pub suspend_resume_cycles: u32,
1748 /// The suspend snapshot's size. Defaults to the baseline memory footprint, which
1749 /// is what `docs/PLATFORM.md`'s own worked figures use ("a suspended 2 GB VM pays
1750 /// about $0.16 a month" is 2 GB at the storage rate). Whether a suspend snapshot
1751 /// is baseline-sized or peak-sized is not documented; override it if you have
1752 /// measured otherwise.
1753 pub snapshot_gb: Option<f64>,
1754 /// Whether a launch happened. A launch reads a snapshot.
1755 pub launched: bool,
1756}
1757
1758impl RunUsage {
1759 /// A usage record for a sandbox that launched, with no phase attributed yet.
1760 ///
1761 /// `launched: true` matches the Python's default, and it is the right default:
1762 /// almost every report is of a VM that ran, and the comparison path that does not
1763 /// launch says so explicitly.
1764 pub fn launched() -> RunUsage {
1765 RunUsage {
1766 launched: true,
1767 ..RunUsage::default()
1768 }
1769 }
1770
1771 /// Whether this usage implies a launch: running time, or an image of non-zero size.
1772 ///
1773 /// The rule every surface applies when its caller doesn't say (#255). A launch reads a
1774 /// snapshot, so claiming one that didn't happen adds a transfer line. A zero-sized image
1775 /// isn't one: `Some(0.0)` claims no snapshot read the run never paid for, which is the
1776 /// retired Python CLI's `bool(running_sec or image_gb)`.
1777 pub fn infer_launched(&self) -> bool {
1778 self.running
1779 .is_some_and(|running| !running.duration().is_zero())
1780 || implies_an_image(self.image_gb)
1781 }
1782}
1783
1784/// Whether `image_gb` names an image that was built: set, and not zero.
1785fn implies_an_image(image_gb: Option<f64>) -> bool {
1786 image_gb.is_some_and(|gb| gb != 0.0)
1787}
1788
1789/// The label a run's report carries when its caller names none: the CLI's `cost` and both
1790/// bindings' `run_report`.
1791pub const DEFAULT_RUN_LABEL: &str = "run";
1792
1793/// The label an estimate carries when its caller names none: the CLI's `cost --estimate` and
1794/// both bindings' `estimate_run` (#255).
1795///
1796/// Not "plan": the label is the report's own name for itself, a consumer reads it to tell a
1797/// plan from a receipt, and the surfaces' reports have to be substitutable.
1798pub const DEFAULT_ESTIMATE_LABEL: &str = "estimate";
1799
1800/// Per-phase attribution for one sandbox's lifecycle.
1801///
1802/// `today` decides staleness (COST-7) and is a parameter rather than a clock read, so
1803/// a report is a pure function of its inputs and a test does not have to travel in
1804/// time. A binary passes `CalendarDate::today_utc()` from `microvms_core::prelude`.
1805pub fn run_report(
1806 size: SizeClass,
1807 usage: &RunUsage,
1808 rates: &RateTable,
1809 today: CalendarDate,
1810 label: impl Into<String>,
1811) -> Result<CostReport, Error> {
1812 let snapshot = match usage.snapshot_gb {
1813 Some(gb) => gb_decimal(gb)?,
1814 None => gb_decimal(size.baseline_gb())?,
1815 };
1816 let image_gb = usage.image_gb.map(gb_decimal).transpose()?;
1817 let mut items: Vec<LineItem> = Vec::new();
1818
1819 if let Some(image_gb) = image_gb {
1820 items.push(build_line(usage.image_build));
1821 let held = usage
1822 .image_retained
1823 .unwrap_or(DurationP::Projected(rates.minimum_retention()));
1824 items.push(storage_line(
1825 CostPhase::ImageStorage,
1826 image_gb,
1827 held,
1828 rates,
1829 )?);
1830 } else if usage.image_build.is_some() {
1831 items.push(build_line(usage.image_build));
1832 }
1833
1834 if usage.launched {
1835 // A launch reads a snapshot at the same per-GB rate as a resume. Which
1836 // snapshot's size that read covers is not documented, so it uses the image
1837 // when the caller named one and the memory footprint otherwise.
1838 let read_gb = image_gb.unwrap_or(snapshot);
1839 items.push(transfer_line(
1840 CostPhase::Launch,
1841 BillingLine::SnapshotRead,
1842 read_gb,
1843 1,
1844 rates,
1845 "; 'launch or resume' shares one rate, and which snapshot a launch reads is \
1846 undocumented",
1847 ));
1848 }
1849
1850 if let Some(running) = usage.running {
1851 items.extend(compute_lines(size, running, rates, CostPhase::Running)?);
1852 }
1853
1854 if let Some(suspended) = usage.suspended {
1855 // No compute line at all: a suspended VM is frozen, so it pays storage only.
1856 // Not a compute line multiplied by zero, which would reappear the moment
1857 // someone changed how a duration is derived.
1858 items.push(storage_line(
1859 CostPhase::Suspended,
1860 snapshot,
1861 suspended,
1862 rates,
1863 )?);
1864 }
1865
1866 if usage.suspend_resume_cycles > 0 {
1867 items.push(transfer_line(
1868 CostPhase::Suspend,
1869 BillingLine::SnapshotWrite,
1870 snapshot,
1871 usage.suspend_resume_cycles,
1872 rates,
1873 "",
1874 ));
1875 items.push(transfer_line(
1876 CostPhase::Resume,
1877 BillingLine::SnapshotRead,
1878 snapshot,
1879 usage.suspend_resume_cycles,
1880 rates,
1881 "",
1882 ));
1883 }
1884
1885 Ok(CostReport {
1886 label: label.into(),
1887 size,
1888 rates: rates.clone(),
1889 items,
1890 staleness: rates.staleness(today),
1891 })
1892}
1893
1894/// A plan's phases, in plain seconds, before anything is spent.
1895///
1896/// Separate from [`RunUsage`] on purpose (COST-10): its fields are `f64` seconds
1897/// rather than [`DurationP`], so there is no field an accidentally-`Measured`
1898/// duration could be written into. The wrapping happens in [`estimate_run`], in one
1899/// place, and every one of them is [`Provenance::Projected`].
1900#[derive(Clone, Copy, Debug, Default, PartialEq)]
1901pub struct PlanUsage {
1902 pub running_seconds: f64,
1903 pub suspended_seconds: f64,
1904 pub image_gb: Option<f64>,
1905 pub image_retained_seconds: Option<f64>,
1906 pub suspend_resume_cycles: u32,
1907 pub snapshot_gb: Option<f64>,
1908 pub launched: bool,
1909}
1910
1911impl PlanUsage {
1912 /// A plan for a sandbox that launches, with no phase attributed yet.
1913 pub fn launched() -> PlanUsage {
1914 PlanUsage {
1915 launched: true,
1916 ..PlanUsage::default()
1917 }
1918 }
1919
1920 /// Whether this plan implies a launch: running time, or an image of non-zero size.
1921 ///
1922 /// [`RunUsage::infer_launched`]'s rule over seconds: suspended time alone is a VM that
1923 /// was already running, so it reads no launch snapshot.
1924 pub fn infer_launched(&self) -> bool {
1925 self.running_seconds > 0.0 || implies_an_image(self.image_gb)
1926 }
1927}
1928
1929/// What a plan will cost, before spending anything (COST-10).
1930///
1931/// Takes plain seconds and marks every one of them [`Provenance::Projected`], so the
1932/// resulting report can never claim to be measured. That is the difference between
1933/// this and [`run_report`]: not the arithmetic, which is shared — it delegates — but
1934/// what the durations admit about themselves.
1935pub fn estimate_run(
1936 size: SizeClass,
1937 plan: &PlanUsage,
1938 rates: &RateTable,
1939 today: CalendarDate,
1940 label: impl Into<String>,
1941) -> Result<CostReport, Error> {
1942 // Zero seconds means "this phase did not happen", matching the Python's
1943 // `if running_seconds else None`. A zero-length phase priced at zero would put a
1944 // line on the report claiming a measurement nobody took.
1945 let projected = |seconds: f64| -> Result<Option<DurationP>, Error> {
1946 if seconds == 0.0 {
1947 return Ok(None);
1948 }
1949 Ok(Some(DurationP::projected_secs_f64(seconds)?))
1950 };
1951 let usage = RunUsage {
1952 running: projected(plan.running_seconds)?,
1953 suspended: projected(plan.suspended_seconds)?,
1954 // No `image_build` duration: a plan has not built anything, so there is
1955 // nothing to have timed. The unpriced build line still appears whenever
1956 // `image_gb` is set, because the image will have to be built.
1957 image_build: None,
1958 image_gb: plan.image_gb,
1959 image_retained: plan
1960 .image_retained_seconds
1961 .map(DurationP::projected_secs_f64)
1962 .transpose()?,
1963 suspend_resume_cycles: plan.suspend_resume_cycles,
1964 snapshot_gb: plan.snapshot_gb,
1965 launched: plan.launched,
1966 };
1967 run_report(size, &usage, rates, today, label)
1968}
1969
1970// ── running versus suspended ─────────────────────────────────────────────────
1971
1972/// Running versus suspended for the same VM over the same wall time.
1973///
1974/// The gap is roughly two orders of magnitude over a month, which is the entire
1975/// argument for a warm suspended pool. `cycles` is here so the argument stays honest:
1976/// each suspend/resume pays a snapshot write plus a read, and a pool that churns
1977/// spends more on transitions than it saves on residency. The conclusion to draw is
1978/// "avoid churn", not "avoid residency".
1979///
1980/// Both sides exclude image build and storage. They are the same for either choice,
1981/// and leaving them in would dilute the ratio the comparison exists to show — and drag
1982/// an unpriced build into a figure whose whole job is to be comparable.
1983#[derive(Clone, Debug, Eq, PartialEq)]
1984pub struct ResidencyComparison {
1985 size: SizeClass,
1986 hold: DurationP,
1987 cycles: u32,
1988 running: CostReport,
1989 suspended: CostReport,
1990 rates: RateTable,
1991}
1992
1993impl ResidencyComparison {
1994 pub fn size(&self) -> SizeClass {
1995 self.size
1996 }
1997
1998 /// The wall time both sides cover. Always [`Provenance::Projected`]: a comparison
1999 /// is a hypothetical about a hold nobody has taken yet.
2000 pub fn hold(&self) -> DurationP {
2001 self.hold
2002 }
2003
2004 pub fn cycles(&self) -> u32 {
2005 self.cycles
2006 }
2007
2008 /// The report for leaving the VM running.
2009 pub fn running(&self) -> &CostReport {
2010 &self.running
2011 }
2012
2013 /// The report for suspending it, transitions included.
2014 pub fn suspended(&self) -> &CostReport {
2015 &self.suspended
2016 }
2017
2018 /// How many times more the running VM costs.
2019 ///
2020 /// Zero-safe by construction: snapshot storage always has the minimum-retention
2021 /// floor (COST-8), so the denominator is never zero. Both totals are
2022 /// [`Total::Exact`] because both sides exclude the unpriced build, which is what
2023 /// makes reading their floors sound here.
2024 pub fn ratio(&self) -> Decimal {
2025 self.running.total().floor().amount() / self.suspended.total().floor().amount()
2026 }
2027
2028 /// One suspend/resume: a snapshot write plus a read, per GB.
2029 ///
2030 /// Without it the honest conclusion inverts — "suspend constantly" reads as free.
2031 pub fn per_cycle(&self) -> Result<EstimatedUsd, Error> {
2032 let gb = gb_decimal(self.size.baseline_gb())?;
2033 Ok(EstimatedUsd::new(
2034 gb * (self.rates.snapshot_write_gb() + self.rates.snapshot_read_gb()),
2035 ))
2036 }
2037
2038 /// How long a VM must stay suspended for the cycle to pay for itself.
2039 ///
2040 /// Below this, suspending and resuming costs more than having left the VM running
2041 /// — which is the number a pool scheduler actually needs, and the one a bare "100x
2042 /// cheaper" headline hides.
2043 ///
2044 /// Returns a [`Decimal`] where the Python returned a `float`, so the seconds
2045 /// figure stays in the same representation as the money it was derived from. See
2046 /// [`ResidencyComparison::break_even_seconds_f64`] for the lossy step, which is
2047 /// named as one.
2048 pub fn break_even_seconds(&self) -> Result<Decimal, Error> {
2049 let vcpu = gb_decimal(self.size.baseline_vcpu())?;
2050 let gb = gb_decimal(self.size.baseline_gb())?;
2051 let running_per_sec = vcpu * self.rates.vcpu_second() + gb * self.rates.gb_second();
2052 let storage_per_sec = gb * self.rates.storage_gb_month() / SECONDS_PER_MONTH;
2053 let floor_sec = seconds_of(self.rates.minimum_retention());
2054 let churn = self.per_cycle()?.amount();
2055 // Inside the minimum-retention window the storage charge is a constant, so the
2056 // equation is linear in the hold; past it storage grows with the hold and the
2057 // slope changes. Solve the constant branch first and only take the other if the
2058 // answer falls outside the window.
2059 let candidate = (churn + floor_sec * storage_per_sec) / running_per_sec;
2060 if candidate > floor_sec {
2061 return Ok(churn / (running_per_sec - storage_per_sec));
2062 }
2063 Ok(candidate)
2064 }
2065
2066 /// The break-even hold as an f64, for a JSON envelope.
2067 ///
2068 /// **Lossy, and named so.** The exact answer is
2069 /// [`ResidencyComparison::break_even_seconds`]; this exists because `cli.py` emits
2070 /// `breakEvenSeconds` as a JSON number and the two clients have to agree on it.
2071 /// Seconds, not dollars — no money figure has an f64 accessor (COST-2).
2072 pub fn break_even_seconds_f64(&self) -> Result<f64, Error> {
2073 let exact = self.break_even_seconds()?;
2074 exact.to_f64().ok_or_else(|| {
2075 Error::invalid_arg(format!(
2076 "the break-even hold of {exact}s does not fit in an f64, so it cannot be reported \
2077 as a JSON number"
2078 ))
2079 })
2080 }
2081
2082 /// Plain text for a CLI, ending with the conclusion the numbers support.
2083 pub fn render(&self) -> Result<String, Error> {
2084 Ok([
2085 format!("{} held {}", self.size, self.hold),
2086 format!(" running: {}", self.running.total()),
2087 format!(
2088 " suspended: {} ({} cycle(s) included)",
2089 self.suspended.total(),
2090 self.cycles,
2091 ),
2092 format!(
2093 " ratio: {}x cheaper suspended",
2094 self.ratio().round_dp(1)
2095 ),
2096 format!(
2097 " per cycle: {} — break-even hold {}s, so avoid churn rather than residency",
2098 self.per_cycle()?,
2099 self.break_even_seconds()?.round_dp(0),
2100 ),
2101 ]
2102 .join("\n"))
2103 }
2104}
2105
2106/// The suspend/resume cycles [`compare_residency`] prices when the caller names none: one,
2107/// the fewest that make a suspension more than a termination.
2108pub const DEFAULT_RESIDENCY_CYCLES: u32 = 1;
2109
2110/// The warm-pool argument, with its own counter-argument attached.
2111///
2112/// `cycles` should be at least 1: a suspension that is never resumed is a
2113/// termination, and pricing it as free transitions is how a pool design that churns
2114/// every few seconds looks affordable on paper. Zero is accepted rather than refused
2115/// because a caller comparing pure residency has a legitimate question, and the
2116/// per-cycle figure is on the comparison either way.
2117pub fn compare_residency(
2118 size: SizeClass,
2119 hold: Duration,
2120 cycles: u32,
2121 rates: &RateTable,
2122 today: CalendarDate,
2123) -> Result<ResidencyComparison, Error> {
2124 let hold = DurationP::Projected(hold);
2125 let running = run_report(
2126 size,
2127 &RunUsage {
2128 running: Some(hold),
2129 launched: false,
2130 ..RunUsage::default()
2131 },
2132 rates,
2133 today,
2134 "left running",
2135 )?;
2136 let suspended = run_report(
2137 size,
2138 &RunUsage {
2139 suspended: Some(hold),
2140 suspend_resume_cycles: cycles,
2141 launched: false,
2142 ..RunUsage::default()
2143 },
2144 rates,
2145 today,
2146 "suspended",
2147 )?;
2148 Ok(ResidencyComparison {
2149 size,
2150 hold,
2151 cycles,
2152 running,
2153 suspended,
2154 rates: rates.clone(),
2155 })
2156}
2157
2158// ── the budget gate (#77, #270) ──────────────────────────────────────────────
2159
2160/// What a breached budget does: report it, or refuse the plan. There is no default.
2161///
2162/// The total a budget is compared against is a lower bound whenever a line is unpriced
2163/// (COST-4), so a breach found from one has already been exceeded by an unknown margin.
2164/// Whether that warrants a warning or a refusal depends on what the caller is gating (a
2165/// dashboard wants the report either way, a CI gate wants the refusal), and a default would
2166/// quietly make that judgement for them. So [`Budget::new`] takes one, and so does every
2167/// surface: `cost --max-cost` requires `--on-breach`.
2168#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2169pub enum OnBreach {
2170 /// Report as usual, with the breach as a warning.
2171 Warn,
2172 /// Report as usual, then refuse: the budget the caller set does not hold.
2173 Abort,
2174}
2175
2176impl OnBreach {
2177 /// Every judgement, for a surface that publishes the closed set.
2178 pub const ALL: [OnBreach; 2] = [OnBreach::Warn, OnBreach::Abort];
2179
2180 /// `"warn"` or `"abort"`, the spelling every surface takes and reports.
2181 pub fn as_str(self) -> &'static str {
2182 match self {
2183 OnBreach::Warn => "warn",
2184 OnBreach::Abort => "abort",
2185 }
2186 }
2187}
2188
2189impl FromStr for OnBreach {
2190 type Err = Error;
2191
2192 fn from_str(text: &str) -> Result<OnBreach, Error> {
2193 OnBreach::ALL
2194 .into_iter()
2195 .find(|judgement| judgement.as_str() == text)
2196 .ok_or_else(|| {
2197 Error::invalid_arg(format!(
2198 "{text:?} is not a judgement on a breach: it's \"warn\" or \"abort\", and \
2199 there is no default, because a breach of a lower-bound total has already \
2200 been exceeded by an unknown margin"
2201 ))
2202 })
2203 }
2204}
2205
2206/// A ceiling on a report's total, and what a breach of it does.
2207#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2208pub struct Budget {
2209 /// The ceiling, as the caller wrote it ([`EstimatedUsd::parse`] keeps its scale).
2210 pub max: EstimatedUsd,
2211 /// What a breach does; see [`OnBreach`].
2212 pub on_breach: OnBreach,
2213}
2214
2215impl Budget {
2216 /// A budget of `max`, whose breach does `on_breach`.
2217 pub fn new(max: EstimatedUsd, on_breach: OnBreach) -> Budget {
2218 Budget { max, on_breach }
2219 }
2220
2221 /// The verdict on `report`: its total's floor against the ceiling.
2222 ///
2223 /// The floor is the whole estimate when every line priced and a lower bound otherwise,
2224 /// and the verdict says which: a breach of a lower bound is a breach by at least the
2225 /// overage, and staying under one proves nothing about the true figure. An empty report
2226 /// is an exact zero, not a lower bound: nothing on it is unpriced.
2227 pub fn check(&self, report: &CostReport) -> BudgetVerdict {
2228 let total = report.total();
2229 BudgetVerdict {
2230 budget: *self,
2231 floor: total.floor(),
2232 unpriced: total.unpriced_phase_names(),
2233 }
2234 }
2235}
2236
2237/// A report's total judged against a [`Budget`].
2238#[derive(Clone, Debug, Eq, PartialEq)]
2239pub struct BudgetVerdict {
2240 budget: Budget,
2241 floor: EstimatedUsd,
2242 unpriced: Vec<&'static str>,
2243}
2244
2245impl BudgetVerdict {
2246 /// The budget judged against.
2247 pub fn budget(&self) -> Budget {
2248 self.budget
2249 }
2250
2251 /// The total's floor: the whole estimate when [`Self::is_lower_bound`] is false.
2252 pub fn floor(&self) -> EstimatedUsd {
2253 self.floor
2254 }
2255
2256 /// Whether the floor is a lower bound, because a line on the report is unpriced.
2257 pub fn is_lower_bound(&self) -> bool {
2258 !self.unpriced.is_empty()
2259 }
2260
2261 /// The phases whose lines are unpriced, sorted: what the floor leaves out.
2262 pub fn unpriced_phases(&self) -> &[&'static str] {
2263 &self.unpriced
2264 }
2265
2266 /// Whether the floor is over the ceiling. At the ceiling is within it.
2267 pub fn breached(&self) -> bool {
2268 self.floor > self.budget.max
2269 }
2270
2271 /// Whether the caller's judgement refuses this report: breached, with
2272 /// [`OnBreach::Abort`].
2273 pub fn aborts(&self) -> bool {
2274 self.breached() && self.budget.on_breach == OnBreach::Abort
2275 }
2276
2277 /// How far the floor is over the ceiling, when it is: at least this much for a lower
2278 /// bound.
2279 pub fn overage(&self) -> Option<EstimatedUsd> {
2280 self.breached()
2281 .then(|| EstimatedUsd::new(self.floor.amount() - self.budget.max.amount()))
2282 }
2283
2284 /// `"exact"` or `"lower-bound"`: what the floor is.
2285 pub fn basis(&self) -> &'static str {
2286 if self.is_lower_bound() {
2287 "lower-bound"
2288 } else {
2289 "exact"
2290 }
2291 }
2292
2293 /// One line for a human: the figure, the ceiling, and what an unpriced line leaves open.
2294 ///
2295 /// An under-budget verdict from a lower bound says so, because "within budget" without
2296 /// that half would be the report lying by omission, the figure COST-4 keeps honest.
2297 pub fn render(&self) -> String {
2298 let floor = self.floor.amount_string();
2299 let caveat = if self.unpriced.is_empty() {
2300 String::new()
2301 } else {
2302 format!(
2303 ", and {} line(s) are unpriced ({}), so the true figure is larger by an \
2304 unknown margin",
2305 self.unpriced.len(),
2306 self.unpriced.join(", ")
2307 )
2308 };
2309 match self.overage() {
2310 Some(overage) => format!(
2311 "budget: the {} total ${floor} exceeds --max-cost ${} by {}${}{caveat}",
2312 if self.unpriced.is_empty() {
2313 "estimated"
2314 } else {
2315 "priced-floor"
2316 },
2317 self.budget.max.amount_string(),
2318 if self.unpriced.is_empty() {
2319 ""
2320 } else {
2321 "at least "
2322 },
2323 overage.amount_string(),
2324 ),
2325 None if self.unpriced.is_empty() => format!(
2326 "budget: the estimated total ${floor} is within --max-cost ${}",
2327 self.max_figure()
2328 ),
2329 None => format!(
2330 "budget: the priced floor ${floor} is within --max-cost ${}, but that floor is \
2331 a lower bound{caveat}",
2332 self.max_figure()
2333 ),
2334 }
2335 }
2336
2337 /// The dense line: `budget`, the ceiling, the basis, `breached` or `within`, and the
2338 /// overage or `-`.
2339 pub fn render_dense(&self) -> String {
2340 format!(
2341 "budget\t{}\t{}\t{}\t{}",
2342 self.max_figure(),
2343 self.basis(),
2344 if self.breached() {
2345 "breached"
2346 } else {
2347 "within"
2348 },
2349 self.overage()
2350 .map_or_else(|| "-".to_string(), EstimatedUsd::amount_string),
2351 )
2352 }
2353
2354 /// The verdict as JSON: `maxUsd`, `onBreach`, `basis`, `breached` and
2355 /// `overageAtLeastUsd`, dollars as strings.
2356 pub fn to_json(&self) -> serde_json::Value {
2357 serde_json::json!({
2358 "maxUsd": self.max_figure(),
2359 "onBreach": self.budget.on_breach.as_str(),
2360 "basis": self.basis(),
2361 "breached": self.breached(),
2362 "overageAtLeastUsd": self.overage().map(EstimatedUsd::amount_string),
2363 })
2364 }
2365
2366 /// The ceiling at the scale the caller typed it (`1.50` stays `1.50`), where
2367 /// [`EstimatedUsd::amount_string`] would restate it at report precision.
2368 fn max_figure(&self) -> String {
2369 self.budget.max.amount().to_string()
2370 }
2371}
2372
2373// ── the report as JSON ───────────────────────────────────────────────────────
2374//
2375// One shape for every surface: the CLI's `cost --json` report, Python's `to_dict` and
2376// TypeScript's `toJson` all come from these (#255). They used to be written three times and had
2377// drifted: only the CLI's carried `size.headroomMib`.
2378//
2379// Two rules make the shape load-bearing rather than conventional.
2380//
2381// An unpriced line has **no `usd` key at all**, not a null: a null is summed as zero by
2382// anything permissive, and a consumer summing the column would produce an invoice that
2383// flatters us. It's the same decision `Amount::estimate` makes by returning `Option` instead of
2384// defaulting to zero.
2385//
2386// Every **dollar** figure crosses as a string, never a number: `Decimal` to `f64` is a lossy
2387// step for a figure whose exactness is the point of the type. Every **seconds** figure crosses
2388// as a number (`breakEvenSeconds`, a line's `duration.seconds`, a comparison's `holdSeconds`),
2389// through an accessor named `_f64` so the lossy step is visible. The split is which consumer is
2390// protected: a caller summing dollars must not do float arithmetic on money, and a caller
2391// comparing a duration with a timeout must not find it quoted.
2392//
2393// A dollar string prints at the scale the arithmetic produced (`Decimal::to_string`), so its
2394// trailing zeros can differ from the retired Python client's for the same figure. The values
2395// are equal, and a consumer comparing two reports parses both sides as decimals. Rescaling to
2396// fixed places would round a figure whose exactness is why it's a string; the fixed-places
2397// rendering the human column wants is `render_amount`. A **rate** is the exception, asserted
2398// byte for byte by `every_rate_byte_matches_the_python_literal`, because a rate is a
2399// transcription and a derived figure isn't.
2400
2401impl LineItem {
2402 /// The line as JSON: `phase`, `line`, `quantity`, `unit`, `amount`, `duration`, `note`.
2403 ///
2404 /// The keys are the retired Python client's `_line_to_dict`, because the live suite reads
2405 /// them and every surface's output has to be substitutable. `amount` is
2406 /// `{"kind": "estimated-usd", "usd": "<decimal>"}` or `{"kind": "unpriced", "reason":
2407 /// "..."}`, with no `usd` key.
2408 pub fn to_json(&self) -> serde_json::Value {
2409 let amount = match &self.amount {
2410 Amount::Estimated(usd) => serde_json::json!({
2411 "kind": "estimated-usd",
2412 "usd": usd.amount().to_string(),
2413 }),
2414 Amount::Unpriced { reason } => serde_json::json!({
2415 "kind": "unpriced",
2416 "reason": reason,
2417 }),
2418 };
2419 serde_json::json!({
2420 "phase": self.phase.as_str(),
2421 "line": self.line.map(|line| line.as_str()),
2422 "quantity": self.quantity.to_string(),
2423 "unit": self.unit,
2424 "amount": amount,
2425 "duration": self.duration.map(|duration| serde_json::json!({
2426 // A number, for the reason the section comment gives.
2427 "seconds": duration.seconds_f64(),
2428 "provenance": duration.provenance().as_str(),
2429 })),
2430 "note": self.note,
2431 })
2432 }
2433}
2434
2435impl CostReport {
2436 /// The report as JSON, keeping every label it carries.
2437 ///
2438 /// The keys are the retired Python client's `report_to_dict` verbatim, plus one added
2439 /// since (#99): `size.headroomMib`. A new key is safe where a rename isn't, because the
2440 /// live suite asserts presence, never absence.
2441 pub fn to_json(&self) -> serde_json::Value {
2442 let size = self.size;
2443 let total = self.total();
2444 serde_json::json!({
2445 "label": self.label,
2446 "size": {
2447 "baselineMib": size.baseline_mib(),
2448 "baselineVcpu": size.baseline_vcpu(),
2449 "peakMib": size.peak_mib(),
2450 "peakVcpu": size.peak_vcpu(),
2451 // Static, from the table row: the headroom is provisioned from the start, so it
2452 // is a property of the class, read through the accessor for TRAP-13's reason
2453 // (the 4x regularity is AWS's, not ours).
2454 "headroomMib": size.headroom_mib(),
2455 // `Display` names both numbers or neither: naming only the peak invites
2456 // budgeting for memory nobody is billed for.
2457 "describe": size.to_string(),
2458 },
2459 "rates": {
2460 "region": self.rates.region().as_str(),
2461 "retrieved": self.rates.retrieved().to_string(),
2462 "sourceUrl": self.rates.source_url(),
2463 },
2464 // Not "cost": these are estimates derived from published rates, and the field name
2465 // is the only place that distinction survives a copy-paste.
2466 "estimated": true,
2467 "fullyMeasured": self.fully_measured(),
2468 "complete": self.is_complete(),
2469 "staleness": self.staleness(),
2470 "items": self.items.iter().map(LineItem::to_json).collect::<Vec<_>>(),
2471 "total": {
2472 // The floor, as a string. `AtLeast`'s floor and `Exact`'s figure are the same
2473 // field on purpose: a consumer that ignores `isLowerBound` gets a number that
2474 // is never an over-statement.
2475 "priced": total.floor().amount().to_string(),
2476 "isLowerBound": total.is_lower_bound(),
2477 "render": total.to_string(),
2478 },
2479 })
2480 }
2481}
2482
2483impl ResidencyComparison {
2484 /// The comparison as JSON: both reports in [`CostReport::to_json`]'s shape, with the
2485 /// per-cycle cost and the break-even hold that keep the argument honest.
2486 pub fn to_json(&self) -> Result<serde_json::Value, Error> {
2487 Ok(serde_json::json!({
2488 "holdSeconds": self.hold.seconds_f64(),
2489 "cycles": self.cycles,
2490 "running": self.running.to_json(),
2491 "suspended": self.suspended.to_json(),
2492 "ratio": self.ratio().to_string(),
2493 "perCycleUsd": self.per_cycle()?.amount().to_string(),
2494 // The one f64 figure that isn't a line's seconds, through the accessor named for
2495 // its lossy step.
2496 "breakEvenSeconds": self.break_even_seconds_f64()?,
2497 "render": self.render()?,
2498 }))
2499 }
2500}
2501
2502#[cfg(test)]
2503mod tests {
2504 use proptest::prelude::*;
2505
2506 use super::*;
2507 use crate::error::ErrorKind;
2508
2509 /// A month as AWS's GB-month rate defines it. Every "per month" figure in
2510 /// `docs/PLATFORM.md` is this many seconds, not 30 days.
2511 const MONTH: Duration = Duration::from_secs(730 * 3600);
2512
2513 /// The epoch is day zero, each day starts at a multiple of 86,400 seconds, and the
2514 /// last second of a day stays on that day.
2515 #[test]
2516 fn a_unix_time_floors_to_its_utc_day() {
2517 let day = |secs| {
2518 CalendarDate::from_unix_secs(secs)
2519 .expect("in range")
2520 .to_string()
2521 };
2522 assert_eq!(day(0), "1970-01-01");
2523 assert_eq!(day(86_399), "1970-01-01");
2524 assert_eq!(day(86_400), "1970-01-02");
2525 // 2026-09-25T00:00:00Z, and the second before it.
2526 assert_eq!(day(1_790_294_400), "2026-09-25");
2527 assert_eq!(day(1_790_294_399), "2026-09-24");
2528 assert_eq!(
2529 CalendarDate::from_unix_secs(0)
2530 .expect("in range")
2531 .day_number(),
2532 0
2533 );
2534 // The calendar's last second, 9999-12-31T23:59:59Z, and the one after it.
2535 assert_eq!(day(253_402_300_799), "9999-12-31");
2536 }
2537
2538 /// Past the calendar's end is a refusal, never a panic or a quiet epoch: the same
2539 /// 2026-09-25 in milliseconds, the first second of year 10000, and the largest input.
2540 #[test]
2541 fn a_unix_time_past_the_calendar_is_refused() {
2542 for secs in [1_790_294_400_000, 253_402_300_800, u64::MAX] {
2543 let error = CalendarDate::from_unix_secs(secs).expect_err("past 9999-12-31");
2544 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{secs}");
2545 assert!(error.to_string().contains("milliseconds"), "{error}");
2546 }
2547 }
2548
2549 /// A date the pinned table is fresh on, so a staleness warning in a test that is
2550 /// not about staleness is a failure rather than noise.
2551 fn fresh_day() -> CalendarDate {
2552 CalendarDate::from_ymd(2026, 8, 8)
2553 }
2554
2555 /// The pinned table, which every arithmetic test computes against.
2556 fn rates() -> RateTable {
2557 pinned_rates()
2558 }
2559
2560 /// A budget parses from the text the caller typed, exactly.
2561 ///
2562 /// `0.1` as text is a tenth; `0.1f64` is not. The assertion against `dec!` is
2563 /// what pins that the parse goes through the string rather than through a float
2564 /// on the way.
2565 #[test]
2566 fn a_budget_parses_from_the_text_the_caller_typed() {
2567 assert_eq!(
2568 EstimatedUsd::parse("1.50").expect("a plain decimal"),
2569 EstimatedUsd::new(dec!(1.50))
2570 );
2571 assert_eq!(
2572 EstimatedUsd::parse(" 0.1 ").expect("whitespace is not meaning"),
2573 EstimatedUsd::new(dec!(0.1))
2574 );
2575 assert_eq!(
2576 EstimatedUsd::parse("0").expect("zero is a legitimate budget"),
2577 EstimatedUsd::ZERO
2578 );
2579 }
2580
2581 /// Non-decimal text and a negative figure are both refused as invalid arguments.
2582 ///
2583 /// Negative is refused at the parse rather than at a comparison, because a
2584 /// negative budget compared against any non-negative total reads as "always
2585 /// breached" — a sign error laundered into a confident verdict.
2586 #[test]
2587 fn a_budget_that_does_not_read_as_money_is_refused() {
2588 // `1.5e3` is absent on purpose: `Decimal::from_str` reads scientific
2589 // notation exactly, so it is a legitimate spelling rather than a refusal.
2590 for text in ["abc", "", "$1.50", "-0.01"] {
2591 let error = EstimatedUsd::parse(text).expect_err(text);
2592 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{text}");
2593 }
2594 }
2595
2596 /// One phase's amount, asserting it was priced at all.
2597 fn priced(report: &CostReport, phase: CostPhase) -> Decimal {
2598 let items: Vec<&LineItem> = report.by_phase(phase).collect();
2599 assert_eq!(items.len(), 1, "{phase} should have exactly one line item");
2600 items[0]
2601 .amount
2602 .estimate()
2603 .unwrap_or_else(|| panic!("{phase} should be priced"))
2604 .amount()
2605 }
2606
2607 /// A report of one running phase, which is the shape most arithmetic tests want.
2608 fn running_report(size: SizeClass, duration: DurationP) -> CostReport {
2609 run_report(
2610 size,
2611 &RunUsage {
2612 running: Some(duration),
2613 launched: false,
2614 ..RunUsage::default()
2615 },
2616 &rates(),
2617 fresh_day(),
2618 "run",
2619 )
2620 .expect("a running phase at a documented size prices")
2621 }
2622
2623 // -- the rate table --------------------------------------------------------
2624
2625 /// Every rate as a literal, transcribed from `docs/PLATFORM.md`, "What actually
2626 /// costs money", us-east-1. Asserted literally rather than computed, because the
2627 /// whole value of pinning a rate table is that it can be diffed against the page
2628 /// it came from — and against the Python client's own copy of these literals in
2629 /// `test_cost.py`.
2630 ///
2631 /// `storage_gb_month` is the one derived value: the Pricing API quotes snapshot
2632 /// storage per GB-hour, and $0.0001111111 x 730 is $0.0811111030. It read 0.08
2633 /// until 2026-08-07, which was 1.37% low.
2634 #[test]
2635 fn every_rate_byte_matches_the_python_literal() {
2636 let rates = rates();
2637 assert_eq!(rates.region(), &Region::UsEast1);
2638 assert_eq!(rates.vcpu_second(), dec!(0.0000276944));
2639 assert_eq!(rates.gb_second(), dec!(0.0000036667));
2640 assert_eq!(rates.storage_gb_month(), dec!(0.0811111030));
2641 assert_eq!(rates.snapshot_read_gb(), dec!(0.00155));
2642 assert_eq!(rates.snapshot_write_gb(), dec!(0.0038));
2643 assert_eq!(rates.minimum_retention(), Duration::from_secs(604_800));
2644 assert_eq!(rates.retrieved(), CalendarDate::from_ymd(2026, 8, 7));
2645 assert!(rates.source_url().contains("aws.amazon.com"));
2646 // Scale as well as value: `0.0038` and `0.00380000` are numerically equal to
2647 // `Decimal` but not the same transcription, and the point of this test is that
2648 // it is a transcription check.
2649 assert_eq!(rates.snapshot_write_gb().to_string(), "0.0038");
2650 assert_eq!(rates.storage_gb_month().to_string(), "0.0811111030");
2651 }
2652
2653 /// The storage rate is the hourly figure times a 730-hour month, asserted through
2654 /// [`HOURS_PER_MONTH`] rather than against a literal — the defect it replaced was
2655 /// a second month convention, not a typo.
2656 #[test]
2657 fn the_storage_rate_is_the_hourly_figure_times_a_seven_hundred_thirty_hour_month() {
2658 assert_eq!(SECONDS_PER_MONTH / dec!(3600), HOURS_PER_MONTH);
2659 assert_eq!(HOURS_PER_MONTH, dec!(730));
2660 assert_eq!(rates().storage_gb_month(), dec!(0.0001111111) * dec!(730));
2661 assert_ne!(
2662 rates().storage_gb_month(),
2663 dec!(0.08),
2664 "the old hand-read value was 1.37% low"
2665 );
2666 }
2667
2668 /// Four arithmetic mistakes someone would otherwise make by analogy with Lambda
2669 /// Functions: one blended GB-second, a per-invoke charge, a rounded-up billing
2670 /// increment, and a free tier. `None` for the increment is "not published" —
2671 /// distinct from one second, which would overcharge every sub-second exec.
2672 #[test]
2673 fn the_documented_billing_facts_are_data_not_prose() {
2674 let rates = rates();
2675 assert!(rates.bills_vcpu_and_memory_separately());
2676 assert_eq!(rates.per_request(), Decimal::ZERO);
2677 assert!(!rates.free_tier());
2678 assert_eq!(rates.minimum_billing_increment(), None);
2679 }
2680
2681 // -- staleness (COST-7) ----------------------------------------------------
2682
2683 /// COST-7. A silently stale price is the same failure class as a silently stale
2684 /// schema, which this repo already fails CI on.
2685 #[test]
2686 fn a_rate_table_past_ninety_days_attaches_a_warning_to_the_report() {
2687 let rates = rates();
2688 let just_past = CalendarDate::from_ymd(2026, 11, 6);
2689 assert_eq!(just_past.days_since(rates.retrieved()), 91);
2690 assert!(rates.is_stale(just_past));
2691
2692 let report = run_report(
2693 SizeClass::Mib2048,
2694 &RunUsage {
2695 running: Some(DurationP::Measured(Duration::from_secs(60))),
2696 launched: false,
2697 ..RunUsage::default()
2698 },
2699 &rates,
2700 just_past,
2701 "run",
2702 )
2703 .expect("a stale table still prices");
2704 let warning = report
2705 .staleness()
2706 .expect("a report from a stale table carries the warning");
2707 assert!(warning.contains("91 days ago"), "{warning}");
2708 assert!(warning.contains("stale after 90"), "{warning}");
2709 // The URL travels with it: a figure copied out of a terminal loses everything
2710 // else, so the warning has to say what to re-read.
2711 assert!(warning.contains(rates.source_url()), "{warning}");
2712 }
2713
2714 /// The complement. A warning that fires on a fresh table is a warning everyone
2715 /// learns to filter, and then the stale case goes unseen too. Ninety days exactly
2716 /// is fresh — the Python's comparison is `>`, not `>=`.
2717 #[test]
2718 fn a_fresh_rate_table_is_silent_and_ninety_days_exactly_is_still_fresh() {
2719 let rates = rates();
2720 let ninety = CalendarDate::from_ymd(2026, 11, 5);
2721 assert_eq!(ninety.days_since(rates.retrieved()), 90);
2722 assert!(!rates.is_stale(ninety));
2723 assert_eq!(rates.staleness(ninety), None);
2724
2725 let report = running_report(
2726 SizeClass::Mib2048,
2727 DurationP::Measured(Duration::from_secs(60)),
2728 );
2729 assert_eq!(report.staleness(), None);
2730 }
2731
2732 // -- dates -----------------------------------------------------------------
2733
2734 /// The day-number algorithm against three known values, since every age in this
2735 /// module is a subtraction of two of them. A hand-rolled date is only acceptable
2736 /// if it is pinned.
2737 #[test]
2738 fn the_day_number_agrees_with_the_gregorian_calendar() {
2739 assert_eq!(CalendarDate::from_ymd(1970, 1, 1).day_number(), 0);
2740 // Both verified against Python's `datetime.date` in this session.
2741 assert_eq!(CalendarDate::from_ymd(2026, 8, 7).day_number(), 20_672);
2742 assert_eq!(CalendarDate::from_ymd(2024, 2, 29).day_number(), 19_782);
2743 assert_eq!(CalendarDate::from_ymd(1969, 12, 31).day_number(), -1);
2744 // A leap year's February really has 29 days in the arithmetic, not just in
2745 // the validator.
2746 assert_eq!(
2747 CalendarDate::from_ymd(2024, 3, 1).days_since(CalendarDate::from_ymd(2024, 2, 28)),
2748 2
2749 );
2750 assert_eq!(
2751 CalendarDate::from_ymd(2023, 3, 1).days_since(CalendarDate::from_ymd(2023, 2, 28)),
2752 1
2753 );
2754 }
2755
2756 /// The pinned literals really are calendar days. [`CalendarDate::from_ymd`] is
2757 /// `const` and therefore cannot validate, so this is where that is made good.
2758 #[test]
2759 fn the_pinned_dates_are_real_calendar_days() {
2760 for (year, month, day) in [(2026, 8, 7), (2026, 8, 8), (2026, 11, 5), (2026, 11, 6)] {
2761 CalendarDate::try_from_ymd(year, month, day)
2762 .unwrap_or_else(|err| panic!("{year}-{month}-{day} should be a real day: {err}"));
2763 }
2764 }
2765
2766 /// The S2 boundary refuses what the `const` constructor cannot: `2026-02-30`
2767 /// would otherwise produce March 2nd's day number and an age two days out.
2768 #[test]
2769 fn a_date_that_is_not_a_calendar_day_is_refused() {
2770 for (year, month, day) in [
2771 (2026, 2, 30),
2772 (2026, 13, 1),
2773 (2026, 0, 1),
2774 (2026, 1, 0),
2775 (2026, 1, 32),
2776 (2023, 2, 29),
2777 ] {
2778 let err = CalendarDate::try_from_ymd(year, month, day)
2779 .expect_err("only calendar days date a rate table");
2780 assert_eq!(err.kind(), ErrorKind::InvalidArg, "{year}-{month}-{day}");
2781 }
2782 assert!(
2783 CalendarDate::try_from_ymd(2024, 2, 29).is_ok(),
2784 "a leap day"
2785 );
2786 }
2787
2788 /// `Display` is ISO 8601 because that is what the Python's `retrieved.isoformat()`
2789 /// puts in the report header, and the two clients' output has to be diffable.
2790 #[test]
2791 fn a_date_renders_as_iso_eight_six_oh_one() {
2792 assert_eq!(CalendarDate::from_ymd(2026, 8, 7).to_string(), "2026-08-07");
2793 assert_eq!(
2794 CalendarDate::from_ymd(2026, 12, 31).to_string(),
2795 "2026-12-31"
2796 );
2797 }
2798
2799 // -- measured versus estimated (COST-1, COST-2) -----------------------------
2800
2801 /// COST-1, the runtime half. The compile-fail half is the doctests on
2802 /// [`DurationP`] — this is the part a `match` can see: the label is on the value,
2803 /// so a consumer can refuse to print an estimate as a receipt.
2804 #[test]
2805 fn a_duration_carries_how_it_is_known() {
2806 let timed = DurationP::Measured(Duration::from_secs(60));
2807 let planned = DurationP::Projected(Duration::from_secs(60));
2808 assert_eq!(timed.provenance(), Provenance::Measured);
2809 assert_eq!(planned.provenance(), Provenance::Projected);
2810 assert!(timed.is_measured());
2811 assert!(!planned.is_measured());
2812 // Same span, different claim. The two are not equal, so a set or a comparison
2813 // cannot silently treat a projection as a timing.
2814 assert_ne!(timed, planned);
2815 assert_eq!(timed.duration(), planned.duration());
2816 assert_eq!(timed.to_string(), "60s (measured)");
2817 assert_eq!(planned.to_string(), "60s (projected)");
2818 }
2819
2820 /// An inverted clock would silently render as a credit on the report. The Python
2821 /// checked this in `__post_init__`; here the check is at the f64 boundary, because
2822 /// past it a negative duration is not representable.
2823 #[test]
2824 fn a_negative_or_non_finite_duration_is_refused_at_the_float_boundary() {
2825 for seconds in [-1.0, -0.001, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
2826 let err = DurationP::measured_secs_f64(seconds)
2827 .expect_err("only a finite non-negative float is a duration");
2828 assert_eq!(err.kind(), ErrorKind::InvalidArg, "{seconds}");
2829 assert!(
2830 err.to_string().contains("credit on the report"),
2831 "must name why: {err}"
2832 );
2833 }
2834 assert_eq!(
2835 DurationP::measured_secs_f64(60.5)
2836 .expect("a plain float is a duration")
2837 .seconds(),
2838 dec!(60.5)
2839 );
2840 }
2841
2842 /// COST-2's runtime half: the label is in `Display`, because a figure copied out of
2843 /// a terminal loses its type name.
2844 #[test]
2845 fn every_dollar_figure_renders_as_an_estimate() {
2846 assert_eq!(
2847 EstimatedUsd::new(dec!(1.23)).to_string(),
2848 "~$1.23 (estimated)"
2849 );
2850 let report = running_report(SizeClass::Mib2048, DurationP::Measured(MONTH));
2851 let text = report.render();
2852 assert!(text.contains("estimates derived from published"), "{text}");
2853 assert!(text.contains("only Cost Explorer knows the bill"), "{text}");
2854 // The retrieval date travels too, so a pasted figure can be dated.
2855 assert!(text.contains("2026-08-07"), "{text}");
2856 }
2857
2858 /// The asymmetry is the point: we can time a phase exactly and still only infer its
2859 /// price, so there is no `ActualUsd` for a measured duration to produce.
2860 #[test]
2861 fn a_measured_second_still_yields_an_estimated_dollar() {
2862 let report = running_report(
2863 SizeClass::Mib2048,
2864 DurationP::Measured(Duration::from_secs(3600)),
2865 );
2866 assert!(report.fully_measured());
2867 assert!(
2868 report
2869 .items()
2870 .iter()
2871 .all(|item| item.amount.estimate().is_some())
2872 );
2873 assert!(report.total().to_string().contains("estimated"));
2874 }
2875
2876 /// The distinction survives into the report rather than stopping at the duration,
2877 /// which is what lets a consumer refuse to print an estimate as a receipt.
2878 #[test]
2879 fn an_estimate_is_never_fully_measured_and_a_timed_run_is() {
2880 let projected = estimate_run(
2881 SizeClass::Mib2048,
2882 &PlanUsage {
2883 running_seconds: 3600.0,
2884 ..PlanUsage::default()
2885 },
2886 &rates(),
2887 fresh_day(),
2888 "estimate",
2889 )
2890 .expect("a plan prices");
2891 assert!(!projected.fully_measured());
2892 assert!(
2893 running_report(
2894 SizeClass::Mib2048,
2895 DurationP::Measured(Duration::from_secs(3600))
2896 )
2897 .fully_measured()
2898 );
2899 }
2900
2901 /// Display precision: sub-cent figures need six places and monthly ones need two,
2902 /// and one fixed precision cannot show both without lying or shouting. Half-even at
2903 /// the boundary, matching Python's `quantize` default, so the two clients render
2904 /// the same figure identically.
2905 #[test]
2906 fn a_sub_cent_figure_and_a_monthly_one_each_render_readably() {
2907 assert_eq!(
2908 EstimatedUsd::new(dec!(0.0000276944)).amount_string(),
2909 "0.000028"
2910 );
2911 assert_eq!(EstimatedUsd::new(dec!(92.0512345)).amount_string(), "92.05");
2912 // Exactly one dollar crosses to two places: `>= 1`, as the Python has it.
2913 assert_eq!(EstimatedUsd::new(Decimal::ONE).amount_string(), "1.00");
2914 assert_eq!(
2915 EstimatedUsd::new(dec!(0.999999)).amount_string(),
2916 "0.999999"
2917 );
2918 // Half-even, not half-up: 0.125 rounds down to 0.12 and 0.135 rounds up to
2919 // 0.14. `Decimal::rescale` would answer 0.13 for the first.
2920 assert_eq!(EstimatedUsd::new(dec!(1.125)).amount_string(), "1.12");
2921 assert_eq!(EstimatedUsd::new(dec!(1.135)).amount_string(), "1.14");
2922 // Trailing zeros are kept: they say the figure was rounded to the cent rather
2923 // than happening to land there.
2924 assert_eq!(EstimatedUsd::new(dec!(2)).amount_string(), "2.00");
2925 }
2926
2927 // -- unknown is not zero (COST-3, COST-4) ----------------------------------
2928
2929 /// COST-3. AWS does not publish whether the server-side build is billed as
2930 /// compute. The build starts a real MicroVM, so reporting $0.00 would understate
2931 /// the run in the direction that flatters us.
2932 #[test]
2933 fn the_image_build_is_unpriced_rather_than_free() {
2934 let report = run_report(
2935 SizeClass::Mib2048,
2936 &RunUsage {
2937 image_gb: Some(2.0),
2938 image_build: Some(DurationP::Measured(Duration::from_secs(300))),
2939 ..RunUsage::launched()
2940 },
2941 &rates(),
2942 fresh_day(),
2943 "run",
2944 )
2945 .expect("a build prices as unpriced");
2946 let build: Vec<&LineItem> = report.by_phase(CostPhase::ImageBuild).collect();
2947 assert_eq!(build.len(), 1);
2948 let reason = build[0]
2949 .amount
2950 .unpriced_reason()
2951 .expect("the build has no published rate");
2952 assert!(reason.contains("does not publish"), "{reason}");
2953 assert_eq!(
2954 build[0].line, None,
2955 "no billing line exists to attribute it to"
2956 );
2957 // The distinction this requirement is about: not zero dollars.
2958 assert_eq!(build[0].amount.estimate(), None);
2959 assert_ne!(
2960 build[0].amount,
2961 Amount::Estimated(EstimatedUsd::ZERO),
2962 "unpriced is a claim about the documentation, zero is a claim about the bill"
2963 );
2964 assert_eq!(build[0].amount.kind(), "unpriced");
2965 }
2966
2967 /// COST-4. A plain sum cannot express "everything priceable, plus a build whose
2968 /// price AWS withholds", and the natural way to force it to is to drop the line.
2969 /// The `AtLeast` variant is what makes dropping it unrepresentable.
2970 #[test]
2971 fn an_unpriced_line_makes_the_total_a_lower_bound_that_names_it() {
2972 let report = run_report(
2973 SizeClass::Mib2048,
2974 &RunUsage {
2975 image_gb: Some(2.0),
2976 image_build: Some(DurationP::Measured(Duration::from_secs(300))),
2977 ..RunUsage::launched()
2978 },
2979 &rates(),
2980 fresh_day(),
2981 "run",
2982 )
2983 .expect("a build prices");
2984 assert!(!report.is_complete());
2985 let total = report.total();
2986 assert!(total.is_lower_bound());
2987 assert!(matches!(total, Total::AtLeast { .. }));
2988 // The reasons are named, not merely counted (COST-4's "naming its unpriced
2989 // line items").
2990 assert_eq!(total.unpriced_reasons().len(), 1);
2991 assert!(total.unpriced_reasons()[0].contains("does not publish"));
2992 let rendered = total.to_string();
2993 assert!(rendered.starts_with("at least "), "{rendered}");
2994 assert!(rendered.contains("1 unpriced"), "{rendered}");
2995
2996 // The floor is the sum of the priced lines and nothing else: the unpriced line
2997 // is neither summed as zero nor allowed to poison the figure.
2998 let expected: EstimatedUsd = report
2999 .priced()
3000 .map(|item| item.amount.estimate().expect("priced"))
3001 .sum();
3002 assert_eq!(total.floor(), expected);
3003 }
3004
3005 /// The rendered lower bound is the oracle's string, character for character.
3006 ///
3007 /// The Python is the contract here and the two divergences it catches are the ones a
3008 /// re-derivation would not: the parenthetical names **phases** where the Rust used to
3009 /// join reasons — a hundred-and-ninety-character sentence about what AWS does not
3010 /// publish, in the field a reader scans for "which phase" — and the separator is
3011 /// `", "` rather than `"; "`.
3012 ///
3013 /// The expected string is copied from the oracle rather than assembled here. What its
3014 /// `run_report` printed for a 2048 MiB size with 3600 s running, a 300 s measured image
3015 /// build, and a 2 GB image:
3016 ///
3017 /// ```text
3018 /// at least ~$0.166533 (estimated), plus 1 unpriced (image-build)
3019 /// ```
3020 ///
3021 /// A transcript rather than a command: that client was deleted once this one had driven
3022 /// the live suite green, and git history is where the code behind the figure lives.
3023 ///
3024 /// **Falsification** — restore `unpriced.join("; ")` over the reasons in
3025 /// [`Total`]'s `Display` and this is red on the whole parenthetical while every
3026 /// figure, count, and `isLowerBound` still agrees. Verified.
3027 #[test]
3028 fn the_rendered_lower_bound_is_the_oracles_string_verbatim() {
3029 let report = run_report(
3030 SizeClass::Mib2048,
3031 &RunUsage {
3032 running: Some(DurationP::Measured(Duration::from_secs(3600))),
3033 image_build: Some(DurationP::Measured(Duration::from_secs(300))),
3034 image_gb: Some(2.0),
3035 ..RunUsage::launched()
3036 },
3037 &rates(),
3038 fresh_day(),
3039 "run",
3040 )
3041 .expect("a build prices");
3042 assert_eq!(
3043 report.total().to_string(),
3044 "at least ~$0.166533 (estimated), plus 1 unpriced (image-build)"
3045 );
3046
3047 // Two unpriced lines in the same phase name it once, and two phases read sorted
3048 // rather than in report order — `sorted({...})` in the oracle is a set.
3049 let amounts = [
3050 (CostPhase::Running, Amount::unpriced("second")),
3051 (CostPhase::ImageBuild, Amount::unpriced("first")),
3052 (CostPhase::ImageBuild, Amount::unpriced("also first")),
3053 ];
3054 let total = Total::of(amounts.iter().map(|(phase, amount)| (*phase, amount)));
3055 assert_eq!(total.unpriced_phase_names(), ["image-build", "running"]);
3056 assert_eq!(
3057 total.to_string(),
3058 "at least ~$0.000000 (estimated), plus 3 unpriced (image-build, running)",
3059 "three lines, two names — the count is lines and the parenthetical is phases"
3060 );
3061 // The reasons are still reachable, in report order, for the consumer that wants
3062 // the paragraph the total has no room for.
3063 assert_eq!(total.unpriced_reasons(), ["second", "first", "also first"]);
3064 }
3065
3066 /// **Every phase round-trips through its own spelling**, and nothing else parses.
3067 ///
3068 /// The forward direction is the one that matters for the bindings: `by_phase("running")`
3069 /// has to find the same variant the report attributed the line to, so `from_str` must be
3070 /// the exact inverse of `as_str` for all seven. The reverse — an unknown spelling — is
3071 /// refused *with the whole list*, because the failure this replaces was a Python caller
3072 /// typing `"suspending"` and getting an empty result set back rather than an error.
3073 ///
3074 /// `ALL` is asserted to be complete by exhaustion rather than by a length check: the
3075 /// `match` below has no wildcard arm, so adding a variant to [`CostPhase`] fails to
3076 /// compile here until it is added to `ALL` too. A `len() == 7` assertion would only have
3077 /// caught the same mistake after someone changed the number.
3078 ///
3079 /// **Falsification** — drop `CostPhase::Suspend` from `ALL` and the exhaustive match
3080 /// leaves it unreachable, so the round-trip assertion goes red on `"suspend"`; return
3081 /// `Ok(CostPhase::Running)` for an unknown string and the refusal assertion goes red.
3082 /// Verified; see the report at the end of this task.
3083 #[test]
3084 fn every_phase_parses_back_from_its_display_and_nothing_else_does() {
3085 for phase in CostPhase::ALL {
3086 // Both spellings, because `Display` pads and `as_str` does not — a `from_str`
3087 // written against the padded form would fail on every column-formatted string a
3088 // caller copied out of a report.
3089 assert_eq!(
3090 phase.as_str().parse::<CostPhase>().expect("a known phase"),
3091 phase,
3092 "{} did not round-trip through as_str",
3093 phase.as_str()
3094 );
3095 assert_eq!(
3096 phase
3097 .to_string()
3098 .parse::<CostPhase>()
3099 .expect("a known phase"),
3100 phase,
3101 "{phase} did not round-trip through Display"
3102 );
3103 // And the exhaustive match: a variant added to the enum but not to `ALL` fails
3104 // to compile at this arm rather than silently going unparseable.
3105 match phase {
3106 CostPhase::ImageBuild
3107 | CostPhase::ImageStorage
3108 | CostPhase::Launch
3109 | CostPhase::Running
3110 | CostPhase::Suspended
3111 | CostPhase::Suspend
3112 | CostPhase::Resume => {}
3113 }
3114 }
3115 assert_eq!(
3116 CostPhase::ALL.len(),
3117 7,
3118 "the seven phases the billing model has"
3119 );
3120
3121 // The near-misses a caller actually types: a lifecycle state that is not a cost
3122 // phase, the underscore spelling, and the empty string.
3123 for wrong in ["suspending", "image_build", "RUNNING", "", "total"] {
3124 let error = wrong
3125 .parse::<CostPhase>()
3126 .expect_err("only the seven spellings parse");
3127 assert_eq!(error.kind(), ErrorKind::InvalidArg);
3128 let message = error.to_string();
3129 for phase in CostPhase::ALL {
3130 assert!(
3131 message.contains(phase.as_str()),
3132 "the refusal has to offer every phase so a typo is self-correcting, \
3133 {phase} missing from: {message}"
3134 );
3135 }
3136 }
3137 }
3138
3139 /// Every rendered line's amount starts at the same column.
3140 ///
3141 /// The plain-text report is a table, and the phase column is what aligns it. `{:<14}`
3142 /// in [`LineItem`]'s `Display` is not enough on its own: a `Display` impl written as
3143 /// `f.write_str(...)` ignores the formatter's width outright, so the format string
3144 /// reads as padded while the output is ragged — `image-build` and `launch` differ by
3145 /// six characters and the dollar figures walk. The oracle's own render puts the
3146 /// amount at column 44 on all seven lines of this same report, checked with
3147 /// `line.index('~$')` on `cost.py`'s `CostReport.render()`.
3148 ///
3149 /// The assertion is that the columns *agree* rather than that they equal 44, because
3150 /// the widths belong to `LineItem` and a deliberate change there should not have to
3151 /// come here — but a phase that stops padding is not a deliberate change.
3152 ///
3153 /// **Falsification** — put `f.write_str(self.as_str())` back in [`CostPhase`]'s
3154 /// `Display` and this is red with two distinct offsets. Verified.
3155 #[test]
3156 fn every_rendered_line_puts_its_amount_in_the_same_column() {
3157 let report = run_report(
3158 SizeClass::Mib2048,
3159 &RunUsage {
3160 running: Some(DurationP::Measured(Duration::from_secs(3600))),
3161 image_build: Some(DurationP::Measured(Duration::from_secs(300))),
3162 image_gb: Some(2.0),
3163 suspend_resume_cycles: 1,
3164 ..RunUsage::launched()
3165 },
3166 &rates(),
3167 fresh_day(),
3168 "run",
3169 )
3170 .expect("a report");
3171 let text = report.render();
3172 // The phases whose names differ most: `image-storage` is thirteen characters and
3173 // `launch` is six, so an unpadded phase column shows up as a seven-column shift.
3174 let offsets: Vec<(usize, &str)> = text
3175 .lines()
3176 .filter(|line| line.starts_with(" "))
3177 .map(|line| {
3178 let amount = line
3179 .find("~$")
3180 .or_else(|| line.find("unpriced"))
3181 .unwrap_or_else(|| panic!("every line has an amount: {line}"));
3182 (amount, line)
3183 })
3184 .collect();
3185 assert!(offsets.len() >= 7, "{text}");
3186 let (first, first_line) = offsets[0];
3187 for (offset, line) in &offsets {
3188 assert_eq!(
3189 *offset, first,
3190 "the amount column has to agree across lines:\n{first_line}\n{line}"
3191 );
3192 }
3193 // And the phase is genuinely padded rather than the widths happening to cancel.
3194 assert_eq!(
3195 format!("{:<14}|", CostPhase::Launch),
3196 "launch |",
3197 "a phase in a width-bearing format slot has to pad"
3198 );
3199 }
3200
3201 /// A lower bound that will not say what it is missing is not a value [`Total`]
3202 /// holds: an empty reason list routes to [`Total::Exact`].
3203 #[test]
3204 fn a_total_over_only_priced_lines_is_exact_and_names_nothing() {
3205 let amounts = [Amount::estimated(dec!(1)), Amount::estimated(dec!(2))];
3206 let total = Total::of(amounts.iter().map(|amount| (CostPhase::Running, amount)));
3207 assert_eq!(total, Total::Exact(EstimatedUsd::new(dec!(3))));
3208 assert!(!total.is_lower_bound());
3209 assert!(total.unpriced_reasons().is_empty());
3210 assert_eq!(total.to_string(), "~$3.00 (estimated)");
3211 // The degenerate case: no lines at all is exactly zero, not a lower bound.
3212 assert_eq!(
3213 Total::of(std::iter::empty()),
3214 Total::Exact(EstimatedUsd::ZERO)
3215 );
3216 }
3217
3218 /// The complement of the build test: a run against an existing image pays no build,
3219 /// so incompleteness is a property of the phases present rather than a permanent
3220 /// disclaimer nobody reads.
3221 #[test]
3222 fn a_report_with_no_image_is_complete() {
3223 let report = running_report(
3224 SizeClass::Mib2048,
3225 DurationP::Measured(Duration::from_secs(60)),
3226 );
3227 assert!(report.is_complete());
3228 assert!(!report.total().is_lower_bound());
3229 assert!(matches!(report.total(), Total::Exact(_)));
3230 }
3231
3232 // -- per-phase attribution (COST-5, COST-8) ---------------------------------
3233
3234 /// Two entries rather than one blended GB-second, because that is how the pricing
3235 /// page prices them and a blended figure cannot be reconciled against a Cost
3236 /// Explorer breakdown that keeps them apart.
3237 #[test]
3238 fn running_bills_vcpu_and_memory_as_two_separate_lines() {
3239 let report = running_report(
3240 SizeClass::Mib2048,
3241 DurationP::Measured(Duration::from_secs(3600)),
3242 );
3243 let lines: Vec<Option<BillingLine>> = report
3244 .by_phase(CostPhase::Running)
3245 .map(|item| item.line)
3246 .collect();
3247 assert_eq!(lines, [Some(BillingLine::Vcpu), Some(BillingLine::Memory)]);
3248 }
3249
3250 /// COST-5. `sizing` locks that billing follows the baseline; this locks that cost
3251 /// obeys it. The 2 GB class reports 8 GB in the guest, so reading the peak would
3252 /// overstate the memory line exactly 4x — and the assertion below is against the
3253 /// baseline figure spelled out, so a peak-reading implementation is off by that 4x
3254 /// rather than merely different.
3255 #[test]
3256 fn running_bills_the_baseline_and_never_the_peak() {
3257 let size = SizeClass::Mib2048;
3258 let report = running_report(size, DurationP::Measured(Duration::from_secs(3600)));
3259 let rates = rates();
3260
3261 let memory: Vec<&LineItem> = report
3262 .by_phase(CostPhase::Running)
3263 .filter(|item| item.line == Some(BillingLine::Memory))
3264 .collect();
3265 assert_eq!(
3266 memory[0].amount.estimate().expect("priced").amount(),
3267 dec!(2) * dec!(3600) * rates.gb_second()
3268 );
3269 let vcpu: Vec<&LineItem> = report
3270 .by_phase(CostPhase::Running)
3271 .filter(|item| item.line == Some(BillingLine::Vcpu))
3272 .collect();
3273 assert_eq!(
3274 vcpu[0].amount.estimate().expect("priced").amount(),
3275 dec!(1) * dec!(3600) * rates.vcpu_second()
3276 );
3277
3278 // Named explicitly, so the failure message says which figure was read: the
3279 // peak is 8 GB / 4 vCPU for this class.
3280 assert_eq!(memory[0].quantity, dec!(2) * dec!(3600));
3281 assert_ne!(
3282 memory[0].quantity,
3283 gb_decimal(size.peak_gb()).expect("a documented peak") * dec!(3600),
3284 "the memory line must read baseline_gb, not peak_gb"
3285 );
3286 assert_ne!(
3287 vcpu[0].quantity,
3288 gb_decimal(size.peak_vcpu()).expect("a documented peak") * dec!(3600),
3289 "the vcpu line must read baseline_vcpu, not peak_vcpu"
3290 );
3291 }
3292
3293 /// COST-5 across the whole table, since one class cannot distinguish a baseline
3294 /// read from a peak read that happens to agree. No shipped class's baseline equals
3295 /// another's peak in a way that would let a peak-reading implementation pass.
3296 #[test]
3297 fn every_size_class_bills_its_own_baseline() {
3298 let rates = rates();
3299 for size in SizeClass::ALL {
3300 let report = running_report(size, DurationP::Measured(Duration::from_secs(1)));
3301 let memory: Vec<&LineItem> = report
3302 .by_phase(CostPhase::Running)
3303 .filter(|item| item.line == Some(BillingLine::Memory))
3304 .collect();
3305 let expected = gb_decimal(size.baseline_gb()).expect("a documented baseline");
3306 assert_eq!(memory[0].quantity, expected, "{size:?}");
3307 assert_eq!(
3308 memory[0].amount.estimate().expect("priced").amount(),
3309 expected * rates.gb_second(),
3310 "{size:?}"
3311 );
3312 }
3313 }
3314
3315 /// `docs/PLATFORM.md`: "roughly $100 a month to leave the same VM running at
3316 /// baseline". An order-of-magnitude anchor on the compute rates, independent of the
3317 /// exact rate literals above — the two would have to be wrong together.
3318 #[test]
3319 fn a_month_of_running_costs_about_a_hundred_dollars() {
3320 let report = running_report(SizeClass::Mib2048, DurationP::Projected(MONTH));
3321 let total = report.total().floor().amount();
3322 assert!(
3323 dec!(80) < total && total < dec!(120),
3324 "a month at baseline should be roughly $100, got {total}"
3325 );
3326 }
3327
3328 /// A suspended guest is frozen rather than stopped, so there is no compute line at
3329 /// all — not a compute line multiplied by zero, which would reappear the moment
3330 /// someone changed how a duration is derived.
3331 #[test]
3332 fn a_suspended_vm_pays_storage_and_no_compute() {
3333 let report = run_report(
3334 SizeClass::Mib2048,
3335 &RunUsage {
3336 suspended: Some(DurationP::Measured(MONTH)),
3337 launched: false,
3338 ..RunUsage::default()
3339 },
3340 &rates(),
3341 fresh_day(),
3342 "suspended",
3343 )
3344 .expect("a suspended hold prices");
3345 let lines: Vec<Option<BillingLine>> = report
3346 .by_phase(CostPhase::Suspended)
3347 .map(|item| item.line)
3348 .collect();
3349 assert_eq!(lines, [Some(BillingLine::SnapshotStorage)]);
3350 assert!(
3351 !report
3352 .items()
3353 .iter()
3354 .any(|item| item.line == Some(BillingLine::Vcpu)
3355 || item.line == Some(BillingLine::Memory)),
3356 "a frozen VM has no compute line at all"
3357 );
3358 // "about $0.16 a month" for a suspended 2 GB VM.
3359 let total = report.total().floor().amount();
3360 assert!(dec!(0.10) < total && total < dec!(0.25), "{total}");
3361 }
3362
3363 /// COST-8. The line item that dominates a create-and-destroy suite.
3364 /// `docs/PLATFORM.md`: a 2 GB image deleted sixty seconds after creation still bills
3365 /// about a week, "roughly four cents". Not applying the minimum understates the
3366 /// floor by four orders of magnitude and makes the compute look like the cost
3367 /// driver.
3368 #[test]
3369 fn image_storage_bills_the_one_week_minimum_for_a_sixty_second_image() {
3370 let rates = rates();
3371 let report = run_report(
3372 SizeClass::Mib2048,
3373 &RunUsage {
3374 image_gb: Some(2.0),
3375 image_build: Some(DurationP::Measured(Duration::from_secs(300))),
3376 image_retained: Some(DurationP::Measured(Duration::from_secs(60))),
3377 launched: false,
3378 ..RunUsage::default()
3379 },
3380 &rates,
3381 fresh_day(),
3382 "build",
3383 )
3384 .expect("a held image prices");
3385 let week = dec!(604800);
3386 assert_eq!(
3387 priced(&report, CostPhase::ImageStorage),
3388 dec!(2) * week / SECONDS_PER_MONTH * rates.storage_gb_month()
3389 );
3390 let amount = priced(&report, CostPhase::ImageStorage);
3391 assert!(
3392 dec!(0.03) < amount && amount < dec!(0.05),
3393 "roughly four cents, got {amount}"
3394 );
3395 // The floor must be visible, not just applied: a reader checking the quantity
3396 // column against the rate table needs to know why it says a week.
3397 let storage: Vec<&LineItem> = report.by_phase(CostPhase::ImageStorage).collect();
3398 assert!(
3399 storage[0].note.contains("minimum retention"),
3400 "{}",
3401 storage[0].note
3402 );
3403 assert!(storage[0].note.contains("604800s"), "{}", storage[0].note);
3404 // And the duration on the line is still the *measured* sixty seconds — the
3405 // floor changes what is billed, not what was observed.
3406 assert_eq!(
3407 storage[0].duration,
3408 Some(DurationP::Measured(Duration::from_secs(60)))
3409 );
3410 }
3411
3412 /// The note's day count is the rate row's own, not a division written beside the
3413 /// message.
3414 ///
3415 /// The two halves are one requirement: `minimum_retention_days` reports what
3416 /// `minimum_retention` holds, and the note quotes *that* rather than a second
3417 /// convention. Asserted against a table whose floor is deliberately **not** a week,
3418 /// which is the only input that separates the field from the literal — a hand-rolled
3419 /// `as_secs() / 86_400` at the call site passes the seven-day case and then keeps
3420 /// saying "7-day" here.
3421 ///
3422 /// **Falsification** — put `rates.minimum_retention().as_secs() / 86_400` back in
3423 /// `storage_line` and this stays green; hard-code either `7` or the week's seconds and
3424 /// it goes red naming the wrong day count. Verified: replacing the accessor's body
3425 /// with `7` fails the first assertion, and writing `"; billed 7-day minimum retention
3426 /// ({floor}s) instead"` fails the note assertion with `7-day` against a 14-day row.
3427 #[test]
3428 fn the_retention_note_reads_its_day_count_off_the_rate_row() {
3429 let week = rates();
3430 assert_eq!(week.minimum_retention_days(), 7);
3431 assert_eq!(
3432 week.minimum_retention(),
3433 Duration::from_secs(week.minimum_retention_days() * 24 * 60 * 60),
3434 "the days accessor and the duration must describe the same window"
3435 );
3436
3437 // A fortnight, which no rate table ships — the point is that nothing but the
3438 // field decides what the note says.
3439 let mut fortnight = week.clone();
3440 fortnight.minimum_retention = Duration::from_secs(14 * 24 * 60 * 60);
3441 assert_eq!(fortnight.minimum_retention_days(), 14);
3442
3443 let item = storage_line(
3444 CostPhase::ImageStorage,
3445 dec!(2),
3446 DurationP::Measured(Duration::from_secs(60)),
3447 &fortnight,
3448 )
3449 .expect("a floored hold prices");
3450 assert!(
3451 item.note.contains("14-day minimum retention"),
3452 "the note must quote the row's own window: {}",
3453 item.note
3454 );
3455 assert!(
3456 !item.note.contains("7-day"),
3457 "a second day-count convention survived in the message: {}",
3458 item.note
3459 );
3460 }
3461
3462 /// The floor is a floor, not a flat fee. A month-long hold that billed one week
3463 /// would understate a warm pool's storage by more than 4x.
3464 #[test]
3465 fn a_long_hold_bills_actual_time_rather_than_the_minimum() {
3466 let rates = rates();
3467 let report = run_report(
3468 SizeClass::Mib2048,
3469 &RunUsage {
3470 image_gb: Some(2.0),
3471 image_retained: Some(DurationP::Measured(MONTH)),
3472 launched: false,
3473 ..RunUsage::default()
3474 },
3475 &rates,
3476 fresh_day(),
3477 "build",
3478 )
3479 .expect("a long hold prices");
3480 assert_eq!(
3481 priced(&report, CostPhase::ImageStorage),
3482 dec!(2) * rates.storage_gb_month(),
3483 );
3484 let storage: Vec<&LineItem> = report.by_phase(CostPhase::ImageStorage).collect();
3485 assert!(
3486 !storage[0].note.contains("minimum retention"),
3487 "the note must not claim a floor that was not applied: {}",
3488 storage[0].note
3489 );
3490 }
3491
3492 /// The floor applies to a suspend snapshot too, because the minimum is on the rate
3493 /// row rather than on the image phase. `docs/PLATFORM.md` demonstrates it only for
3494 /// images, which is what the note distinguishes.
3495 #[test]
3496 fn a_briefly_held_suspend_snapshot_bills_the_same_floor() {
3497 let report = run_report(
3498 SizeClass::Mib2048,
3499 &RunUsage {
3500 suspended: Some(DurationP::Measured(Duration::from_secs(30))),
3501 launched: false,
3502 ..RunUsage::default()
3503 },
3504 &rates(),
3505 fresh_day(),
3506 "suspended",
3507 )
3508 .expect("a brief suspension prices");
3509 let items: Vec<&LineItem> = report.by_phase(CostPhase::Suspended).collect();
3510 assert!(
3511 items[0].note.contains("minimum retention"),
3512 "{}",
3513 items[0].note
3514 );
3515 assert_eq!(
3516 priced(&report, CostPhase::Suspended),
3517 dec!(2) * dec!(604800) / SECONDS_PER_MONTH * rates().storage_gb_month(),
3518 );
3519 }
3520
3521 /// Asymmetric rates — the write is ~2.5x the read — so a cycle costed with one rate
3522 /// twice is wrong in whichever direction it picked.
3523 #[test]
3524 fn a_suspend_resume_cycle_bills_a_write_and_a_read() {
3525 let rates = rates();
3526 let report = run_report(
3527 SizeClass::Mib2048,
3528 &RunUsage {
3529 suspend_resume_cycles: 1,
3530 launched: false,
3531 ..RunUsage::default()
3532 },
3533 &rates,
3534 fresh_day(),
3535 "cycle",
3536 )
3537 .expect("a cycle prices");
3538 assert_eq!(
3539 priced(&report, CostPhase::Suspend),
3540 dec!(2) * rates.snapshot_write_gb()
3541 );
3542 assert_eq!(
3543 priced(&report, CostPhase::Resume),
3544 dec!(2) * rates.snapshot_read_gb()
3545 );
3546 assert_ne!(
3547 rates.snapshot_write_gb(),
3548 rates.snapshot_read_gb(),
3549 "the two rates differ, which is why the two lines must not share one"
3550 );
3551 // "about $0.011 for a 2 GB VM" per cycle.
3552 let total = report.total().floor().amount();
3553 assert!(dec!(0.010) < total && total < dec!(0.012), "{total}");
3554 }
3555
3556 /// The churn argument only works if churn actually accumulates.
3557 #[test]
3558 fn cycles_scale_the_transition_cost() {
3559 let cycles_cost = |count: u32| {
3560 run_report(
3561 SizeClass::Mib2048,
3562 &RunUsage {
3563 suspend_resume_cycles: count,
3564 launched: false,
3565 ..RunUsage::default()
3566 },
3567 &rates(),
3568 fresh_day(),
3569 "cycle",
3570 )
3571 .expect("a cycle prices")
3572 .total()
3573 .floor()
3574 .amount()
3575 };
3576 assert_eq!(cycles_cost(10), cycles_cost(1) * dec!(10));
3577 // Zero cycles is zero lines, not a zero-priced line: nothing happened.
3578 assert_eq!(cycles_cost(0), Decimal::ZERO);
3579 }
3580
3581 /// A smaller baseline is a real cost lever, which is what makes the CLI's
3582 /// adequate-over-cheap default a deliberate trade rather than an oversight. 512 MiB
3583 /// to 8192 MiB is 16x on both vCPU and memory.
3584 #[test]
3585 fn a_smaller_baseline_is_a_real_cost_lever() {
3586 let small = running_report(SizeClass::Mib512, DurationP::Projected(MONTH))
3587 .total()
3588 .floor()
3589 .amount();
3590 let large = running_report(SizeClass::Mib8192, DurationP::Projected(MONTH))
3591 .total()
3592 .floor()
3593 .amount();
3594 assert_eq!(large, small * dec!(16));
3595 }
3596
3597 // -- estimate mode (COST-10) ------------------------------------------------
3598
3599 /// COST-10. An estimate is spent before the money is, so nothing in it can claim to
3600 /// have been timed.
3601 #[test]
3602 fn an_estimate_labels_every_duration_projected() {
3603 let report = estimate_run(
3604 SizeClass::Mib2048,
3605 &PlanUsage {
3606 running_seconds: 3600.0,
3607 suspended_seconds: 600.0,
3608 image_gb: Some(2.0),
3609 ..PlanUsage::launched()
3610 },
3611 &rates(),
3612 fresh_day(),
3613 "estimate",
3614 )
3615 .expect("a plan prices");
3616 let durations: Vec<DurationP> = report
3617 .items()
3618 .iter()
3619 .filter_map(|item| item.duration)
3620 .collect();
3621 assert!(
3622 !durations.is_empty(),
3623 "the estimate must attribute durations, not just totals"
3624 );
3625 for duration in durations {
3626 assert_eq!(
3627 duration.provenance(),
3628 Provenance::Projected,
3629 "every duration in a plan is projected"
3630 );
3631 }
3632 assert!(!report.fully_measured());
3633 }
3634
3635 /// Same rates, same phases: only the labels differ. If the two paths could disagree
3636 /// numerically, the label would be hiding a second implementation.
3637 #[test]
3638 fn an_estimate_and_a_measured_run_agree_on_the_arithmetic() {
3639 let projected = estimate_run(
3640 SizeClass::Mib2048,
3641 &PlanUsage {
3642 running_seconds: 3600.0,
3643 ..PlanUsage::default()
3644 },
3645 &rates(),
3646 fresh_day(),
3647 "estimate",
3648 )
3649 .expect("a plan prices");
3650 let measured = running_report(
3651 SizeClass::Mib2048,
3652 DurationP::Measured(Duration::from_secs(3600)),
3653 );
3654 assert_eq!(projected.total(), measured.total());
3655 // The line items agree on everything except the label, which is the claim.
3656 let strip = |report: &CostReport| -> Vec<(CostPhase, Option<BillingLine>, Decimal)> {
3657 report
3658 .items()
3659 .iter()
3660 .map(|item| (item.phase, item.line, item.quantity))
3661 .collect()
3662 };
3663 assert_eq!(strip(&projected), strip(&measured));
3664 assert!(!projected.fully_measured() && measured.fully_measured());
3665 }
3666
3667 /// A plan's fields are seconds, so there is no field a `Measured` duration could be
3668 /// written into — and a zero-length phase is an absent phase rather than a line
3669 /// claiming a measurement nobody took.
3670 #[test]
3671 fn a_plan_with_no_phases_has_no_durations_at_all() {
3672 let report = estimate_run(
3673 SizeClass::Mib2048,
3674 &PlanUsage::default(),
3675 &rates(),
3676 fresh_day(),
3677 "estimate",
3678 )
3679 .expect("an empty plan prices");
3680 assert!(report.items().is_empty());
3681 assert_eq!(report.total(), Total::Exact(EstimatedUsd::ZERO));
3682 // `fully_measured` is false for a report with no durations, not vacuously true
3683 // — an empty report must not read as a receipt.
3684 assert!(!report.fully_measured());
3685 }
3686
3687 /// An image on a plan still drags the unpriced build line in, because an image that
3688 /// has storage cost has to be built and the build's price is unknown. So a
3689 /// create-and-destroy estimate is never complete either.
3690 #[test]
3691 fn an_estimate_with_an_image_is_a_lower_bound_too() {
3692 let report = estimate_run(
3693 SizeClass::Mib2048,
3694 &PlanUsage {
3695 image_gb: Some(2.0),
3696 ..PlanUsage::launched()
3697 },
3698 &rates(),
3699 fresh_day(),
3700 "estimate",
3701 )
3702 .expect("a plan with an image prices");
3703 assert!(!report.is_complete());
3704 assert!(report.total().is_lower_bound());
3705 // The build line has no duration: a plan has not built anything, so there is
3706 // nothing to have timed, and inventing a projected build time would be a
3707 // number with no source.
3708 let build: Vec<&LineItem> = report.by_phase(CostPhase::ImageBuild).collect();
3709 assert_eq!(build[0].duration, None);
3710 assert_eq!(build[0].unit, "seconds (untimed)");
3711 }
3712
3713 /// A cost figure for a size the platform would refuse never gets produced — it would
3714 /// look like an answer. The refusal is `sizing`'s (TRAP-10) and this is the seam
3715 /// showing it is reachable from here.
3716 #[test]
3717 fn an_off_table_baseline_never_reaches_a_cost_figure() {
3718 let err =
3719 SizeClass::from_baseline_mib(1500).expect_err("1500 MiB is not a documented baseline");
3720 assert_eq!(err.kind(), ErrorKind::InvalidArg);
3721 assert!(
3722 err.to_string()
3723 .contains("not a documented size class baseline")
3724 );
3725 // And the accepted case really does select the class the caller named.
3726 let size = SizeClass::from_baseline_mib(1024).expect("1024 MiB is documented");
3727 assert_eq!(size.baseline_gb(), 1.0);
3728 }
3729
3730 /// A size a caller supplies as a float still has to be a number. The one f64
3731 /// boundary is fallible for this reason (COST-6).
3732 #[test]
3733 fn a_non_finite_or_negative_size_is_refused_at_the_float_boundary() {
3734 for gb in [-1.0, f64::NAN, f64::INFINITY] {
3735 let err = gb_decimal(gb).expect_err("only a finite non-negative size prices");
3736 assert_eq!(err.kind(), ErrorKind::InvalidArg, "{gb}");
3737 }
3738 // A magnitude no decimal can hold is refused rather than saturated: a saturated
3739 // figure is a plausible-looking number, which is the only kind nobody checks.
3740 assert!(gb_decimal(1e30).is_err());
3741 // And the boundary is exact where it succeeds — via the decimal string, not the
3742 // binary value, so 0.1 is 0.1 and not 0.1000000000000000055511151231257827.
3743 assert_eq!(gb_decimal(0.1).expect("0.1 is representable"), dec!(0.1));
3744 assert_eq!(gb_decimal(0.25).expect("0.25 is representable"), dec!(0.25));
3745 }
3746
3747 // -- the ARM-only rule (COST-9) --------------------------------------------
3748
3749 /// The catalog as the Pricing API returned it on 2026-08-07 for us-east-1: seven
3750 /// MicroVM line items, including the two x86 compute rates a MicroVM can never be
3751 /// billed at. They are here precisely so a test can prove we do not reach for them.
3752 fn recorded_catalog() -> RateCatalog {
3753 RateCatalog::new()
3754 .with_entry(
3755 "AWS-Lambda-MicroVM-vCPU-Second-ARM",
3756 "vCPU-Seconds",
3757 dec!(0.0000276944),
3758 )
3759 .with_entry(
3760 "AWS-Lambda-MicroVM-vCPU-Second",
3761 "vCPU-Seconds",
3762 dec!(0.0000326557),
3763 )
3764 .with_entry(
3765 "AWS-Lambda-MicroVM-Memory-GB-Second-ARM",
3766 "GB-Seconds",
3767 dec!(0.0000036667),
3768 )
3769 .with_entry(
3770 "AWS-Lambda-MicroVM-Memory-GB-Second",
3771 "GB-Seconds",
3772 dec!(0.0000043235),
3773 )
3774 .with_entry(
3775 "AWS-Lambda-MicroVM-Snapshot-Storage-GB-Hour",
3776 "GB-Hours",
3777 dec!(0.0001111111),
3778 )
3779 .with_entry(
3780 "AWS-Lambda-MicroVM-Snapshot-Read-GB",
3781 "GB",
3782 dec!(0.0015467699),
3783 )
3784 .with_entry(
3785 "AWS-Lambda-MicroVM-Snapshot-Write-GB",
3786 "GB",
3787 dec!(0.0037977138),
3788 )
3789 }
3790
3791 /// The same catalog without one group, for the refusal cases.
3792 fn without(group: &str) -> RateCatalog {
3793 let mut catalog = RateCatalog::new();
3794 for line in CatalogLine::ALL {
3795 for candidate in [line.group()].into_iter().chain(line.x86_group()) {
3796 if candidate == group {
3797 continue;
3798 }
3799 let entry = recorded_catalog()
3800 .matching(candidate)
3801 .first()
3802 .map(|entry| (*entry).clone());
3803 if let Some(entry) = entry {
3804 catalog = catalog.with_entry(entry.group, entry.unit, entry.usd);
3805 }
3806 }
3807 }
3808 catalog
3809 }
3810
3811 /// The recorded catalog fills a table, and the pinned rates agree with it within the
3812 /// rounding of the pinned figures. This is the offline half of `mise run live:rates`
3813 /// — a hand-edit to [`pinned_rates`] fails here rather than waiting for someone to
3814 /// have credentials.
3815 #[test]
3816 fn the_recorded_catalog_fills_a_table_that_matches_the_pinned_one() {
3817 let fetched = RateTable::from_catalog(
3818 Region::UsEast1,
3819 "aws pricing api",
3820 CalendarDate::from_ymd(2026, 8, 7),
3821 &recorded_catalog(),
3822 )
3823 .expect("the recorded catalog is complete");
3824 // The compute rates are exact: the pinned table holds the API's own figures.
3825 assert_eq!(fetched.vcpu_second(), rates().vcpu_second());
3826 assert_eq!(fetched.gb_second(), rates().gb_second());
3827 // Storage went through the GB-hour to GB-month conversion and lands exactly on
3828 // the pinned literal, which is what makes that literal checkable offline.
3829 assert_eq!(fetched.storage_gb_month(), rates().storage_gb_month());
3830 // The snapshot rates are pinned as three-significant-figure roundings, so they
3831 // agree within the 0.5% drift tolerance rather than exactly.
3832 for (fetched, pinned) in [
3833 (fetched.snapshot_read_gb(), rates().snapshot_read_gb()),
3834 (fetched.snapshot_write_gb(), rates().snapshot_write_gb()),
3835 ] {
3836 let relative = (fetched - pinned).abs() / pinned;
3837 assert!(relative < dec!(0.005), "{fetched} vs {pinned}");
3838 assert_ne!(fetched, pinned, "the pinned figure really is a rounding");
3839 }
3840 // A fetched table is authoritative on rates and still hand-read on rules.
3841 assert_eq!(fetched.minimum_retention(), MINIMUM_RETENTION);
3842 }
3843
3844 /// COST-9, the falsification. The one substitution that would look entirely
3845 /// healthy: the x86 rate parses, is the same shape, and is 17.9% higher. Every
3846 /// estimate would inflate and nothing would say so.
3847 #[test]
3848 fn a_catalog_with_only_the_x86_compute_line_is_refused_not_substituted() {
3849 let catalog = without("AWS-Lambda-MicroVM-vCPU-Second-ARM");
3850 let err = RateTable::from_catalog(
3851 Region::UsEast1,
3852 "aws pricing api",
3853 CalendarDate::from_ymd(2026, 8, 7),
3854 &catalog,
3855 )
3856 .expect_err("a missing ARM line is refused, never substituted");
3857 assert_eq!(err.kind(), ErrorKind::InvalidArg);
3858 let message = err.to_string();
3859 assert!(message.contains("ARM64-only"), "{message}");
3860 assert!(
3861 message.contains("0.0000326557"),
3862 "the error must name the rate it refuses to substitute: {message}"
3863 );
3864 assert!(message.contains("18%"), "{message}");
3865 assert!(message.contains("vcpu_second"), "{message}");
3866 }
3867
3868 /// The same for memory, since two compute lines means two chances to substitute.
3869 #[test]
3870 fn the_memory_line_refuses_its_x86_sibling_too() {
3871 let err = RateTable::from_catalog(
3872 Region::UsEast1,
3873 "aws pricing api",
3874 CalendarDate::from_ymd(2026, 8, 7),
3875 &without("AWS-Lambda-MicroVM-Memory-GB-Second-ARM"),
3876 )
3877 .expect_err("a missing ARM memory line is refused");
3878 let message = err.to_string();
3879 assert!(message.contains("ARM64-only"), "{message}");
3880 assert!(message.contains("0.0000043235"), "{message}");
3881 assert!(message.contains("gb_second"), "{message}");
3882 }
3883
3884 /// The x86 probe is a courtesy, not a requirement: with neither line present the
3885 /// error still has to say which field cannot be filled.
3886 #[test]
3887 fn both_compute_rates_missing_still_names_the_field() {
3888 let mut catalog = without("AWS-Lambda-MicroVM-Memory-GB-Second-ARM");
3889 catalog = {
3890 let mut rebuilt = RateCatalog::new();
3891 for entry in catalog.entries.iter() {
3892 if entry.group != "AWS-Lambda-MicroVM-Memory-GB-Second" {
3893 rebuilt = rebuilt.with_entry(&*entry.group, &*entry.unit, entry.usd);
3894 }
3895 }
3896 rebuilt
3897 };
3898 let err = RateTable::from_catalog(
3899 Region::UsEast1,
3900 "aws pricing api",
3901 CalendarDate::from_ymd(2026, 8, 7),
3902 &catalog,
3903 )
3904 .expect_err("neither compute line means no table");
3905 let message = err.to_string();
3906 assert!(message.contains("gb_second"), "{message}");
3907 assert!(message.contains("neither"), "{message}");
3908 }
3909
3910 /// Snapshot lines have no architecture variant, so there is nothing to refuse — and
3911 /// the message must not claim otherwise, or a reader goes looking for an ARM line
3912 /// that never existed.
3913 #[test]
3914 fn a_missing_snapshot_rate_names_no_x86_sibling() {
3915 let err = RateTable::from_catalog(
3916 Region::UsEast1,
3917 "aws pricing api",
3918 CalendarDate::from_ymd(2026, 8, 7),
3919 &without("AWS-Lambda-MicroVM-Snapshot-Write-GB"),
3920 )
3921 .expect_err("a missing snapshot rate means no table");
3922 let message = err.to_string();
3923 assert!(message.contains("snapshot_write_gb"), "{message}");
3924 assert!(!message.contains("ARM64-only"), "{message}");
3925 }
3926
3927 /// An empty catalog is the *region*, not the catalog, and it is a different repair:
3928 /// check the region versus work out what AWS renamed. Measured, an unpriced region
3929 /// answers `AccessDeniedException` with a null message, which is why this message
3930 /// carries the IAM caveat.
3931 #[test]
3932 fn an_empty_catalog_reads_as_an_unpriced_region_not_a_renamed_line() {
3933 let err = RateTable::from_catalog(
3934 Region::unlisted("eu-central-1"),
3935 "aws pricing api",
3936 CalendarDate::from_ymd(2026, 8, 7),
3937 &RateCatalog::new(),
3938 )
3939 .expect_err("an empty catalog means no table");
3940 let message = err.to_string();
3941 assert!(message.contains("AccessDeniedException"), "{message}");
3942 assert!(message.contains("null message"), "{message}");
3943 assert!(
3944 message.contains("before auditing a policy"),
3945 "the caveat that saves someone reading an IAM policy that is fine: {message}"
3946 );
3947 assert!(!message.contains("ARM64-only"), "{message}");
3948 }
3949
3950 /// A restated unit is refused rather than silently rescaled. It is the only signal
3951 /// available if AWS restates storage per GB-month: the number moves 730x and every
3952 /// arithmetic check downstream still passes, because they all read the same table.
3953 #[test]
3954 fn a_restated_unit_is_refused_rather_than_silently_rescaled() {
3955 let catalog = without("AWS-Lambda-MicroVM-Snapshot-Storage-GB-Hour").with_entry(
3956 "AWS-Lambda-MicroVM-Snapshot-Storage-GB-Hour",
3957 "GB-Months",
3958 dec!(0.0001111111),
3959 );
3960 let err = RateTable::from_catalog(
3961 Region::UsEast1,
3962 "aws pricing api",
3963 CalendarDate::from_ymd(2026, 8, 7),
3964 &catalog,
3965 )
3966 .expect_err("a restated unit is refused");
3967 let message = err.to_string();
3968 assert!(message.contains("quoted per \"GB-Months\""), "{message}");
3969 assert!(message.contains("still look plausible"), "{message}");
3970 }
3971
3972 /// A tiered rate cannot be flattened into one number, and picking the first would
3973 /// silently choose one.
3974 #[test]
3975 fn two_products_for_one_group_is_refused_rather_than_arbitrated() {
3976 let catalog = recorded_catalog().with_entry(
3977 "AWS-Lambda-MicroVM-vCPU-Second-ARM",
3978 "vCPU-Seconds",
3979 dec!(0.0000999999),
3980 );
3981 let err = RateTable::from_catalog(
3982 Region::UsEast1,
3983 "aws pricing api",
3984 CalendarDate::from_ymd(2026, 8, 7),
3985 &catalog,
3986 )
3987 .expect_err("two products for one group is refused");
3988 assert!(err.to_string().contains("silently select a rate"), "{err}");
3989 }
3990
3991 /// A fetched table drops straight into a report, which is the point of returning a
3992 /// [`RateTable`] rather than a map: every figure is computed against whatever table
3993 /// it was handed, so a regional table needs no second arithmetic path. Tokyo's
3994 /// compute is 16.4% over Virginia's.
3995 #[test]
3996 fn a_regional_table_needs_no_second_arithmetic_path() {
3997 let tokyo_catalog = RateCatalog::new()
3998 .with_entry(
3999 "AWS-Lambda-MicroVM-vCPU-Second-ARM",
4000 "vCPU-Seconds",
4001 dec!(0.0000322421),
4002 )
4003 .with_entry(
4004 "AWS-Lambda-MicroVM-Memory-GB-Second-ARM",
4005 "GB-Seconds",
4006 dec!(0.0000042688),
4007 )
4008 .with_entry(
4009 "AWS-Lambda-MicroVM-Snapshot-Storage-GB-Hour",
4010 "GB-Hours",
4011 dec!(0.0001333333),
4012 )
4013 .with_entry(
4014 "AWS-Lambda-MicroVM-Snapshot-Read-GB",
4015 "GB",
4016 dec!(0.0018548941),
4017 )
4018 .with_entry(
4019 "AWS-Lambda-MicroVM-Snapshot-Write-GB",
4020 "GB",
4021 dec!(0.0046556039),
4022 );
4023 let tokyo = RateTable::from_catalog(
4024 Region::ApNortheast1,
4025 "aws pricing api",
4026 fresh_day(),
4027 &tokyo_catalog,
4028 )
4029 .expect("Tokyo's catalog is complete");
4030 assert!(tokyo.vcpu_second() / rates().vcpu_second() > dec!(1.16));
4031 assert!(tokyo.snapshot_write_gb() / rates().snapshot_write_gb() > dec!(1.22));
4032
4033 let here = run_report(
4034 SizeClass::Mib2048,
4035 &RunUsage {
4036 running: Some(DurationP::Measured(Duration::from_secs(3600))),
4037 launched: false,
4038 ..RunUsage::default()
4039 },
4040 &tokyo,
4041 fresh_day(),
4042 "run",
4043 )
4044 .expect("a Tokyo report prices");
4045 let there = running_report(
4046 SizeClass::Mib2048,
4047 DurationP::Measured(Duration::from_secs(3600)),
4048 );
4049 assert!(here.total().floor() > there.total().floor());
4050 assert!(here.render().contains("ap-northeast-1"));
4051 }
4052
4053 /// The catalog line metadata is the Python's `MICROVM_LINES`, field for field, so a
4054 /// drift report names the same thing in both clients.
4055 #[test]
4056 fn the_catalog_lines_match_the_python_rate_line_table() {
4057 let described: Vec<(&str, &str, &str, Option<&str>)> = CatalogLine::ALL
4058 .iter()
4059 .map(|line| (line.field(), line.group(), line.unit(), line.x86_group()))
4060 .collect();
4061 assert_eq!(
4062 described,
4063 [
4064 (
4065 "vcpu_second",
4066 "AWS-Lambda-MicroVM-vCPU-Second-ARM",
4067 "vCPU-Seconds",
4068 Some("AWS-Lambda-MicroVM-vCPU-Second")
4069 ),
4070 (
4071 "gb_second",
4072 "AWS-Lambda-MicroVM-Memory-GB-Second-ARM",
4073 "GB-Seconds",
4074 Some("AWS-Lambda-MicroVM-Memory-GB-Second")
4075 ),
4076 (
4077 "storage_gb_month",
4078 "AWS-Lambda-MicroVM-Snapshot-Storage-GB-Hour",
4079 "GB-Hours",
4080 None
4081 ),
4082 (
4083 "snapshot_read_gb",
4084 "AWS-Lambda-MicroVM-Snapshot-Read-GB",
4085 "GB",
4086 None
4087 ),
4088 (
4089 "snapshot_write_gb",
4090 "AWS-Lambda-MicroVM-Snapshot-Write-GB",
4091 "GB",
4092 None
4093 ),
4094 ]
4095 );
4096 // Only the storage line converts, because only it is quoted per hour.
4097 assert!(CatalogLine::SnapshotStorageGbHour.is_per_hour());
4098 assert_eq!(
4099 CatalogLine::ALL
4100 .iter()
4101 .filter(|line| line.is_per_hour())
4102 .count(),
4103 1
4104 );
4105 }
4106
4107 // -- the warm-pool comparison ----------------------------------------------
4108
4109 /// The comparison at the shape every golden figure below was recorded against.
4110 fn month_comparison() -> ResidencyComparison {
4111 compare_residency(SizeClass::Mib2048, MONTH, 1, &rates(), fresh_day())
4112 .expect("a month-long comparison prices")
4113 }
4114
4115 /// The whole argument for a warm suspended pool, and the reason the strategy memo
4116 /// can decline to build the scheduler and still hand over the numbers.
4117 #[test]
4118 fn suspended_is_two_orders_of_magnitude_cheaper_than_running() {
4119 assert!(month_comparison().ratio() > dec!(100));
4120 }
4121
4122 /// Without the per-cycle cost the honest conclusion inverts: "suspend constantly"
4123 /// reads as free when each cycle pays a write plus a read.
4124 #[test]
4125 fn the_comparison_includes_the_per_cycle_cost() {
4126 let comparison = month_comparison();
4127 let rates = rates();
4128 assert_eq!(
4129 comparison.per_cycle().expect("a documented size").amount(),
4130 dec!(2) * (rates.snapshot_write_gb() + rates.snapshot_read_gb())
4131 );
4132 let rendered = comparison.render().expect("a comparison renders");
4133 assert!(rendered.contains("avoid churn"), "{rendered}");
4134 assert!(rendered.contains("break-even hold"), "{rendered}");
4135 }
4136
4137 /// **The golden.** The break-even hold at 2 GB, pinned against the Python oracle
4138 /// rather than against a re-derivation: its `compare_residency(size=2048,
4139 /// hold_seconds=730*3600, cycles=1).break_even_seconds` printed
4140 /// `1371.2916483478837` when it was run in the session that wrote this test.
4141 ///
4142 /// Worth recording that the task packet predicted ≈1357s. The oracle decides, and it
4143 /// says 1371.29 — a re-derivation would have been the wrong check here, because it
4144 /// is exactly what would have agreed with a plausible wrong number.
4145 ///
4146 /// The two clients agree to 22 significant digits and diverge only past that:
4147 /// `rust_decimal` saturates at 28 digits of scale where Python's `Decimal` context
4148 /// is unbounded. So the exact figure is asserted to a tolerance well inside a
4149 /// second, and the f64 form — which is what `cli.py` emits as `breakEvenSeconds` —
4150 /// is asserted to agree with the Python's float exactly.
4151 #[test]
4152 fn the_break_even_hold_at_two_gigabytes_matches_the_python_oracle() {
4153 let comparison = month_comparison();
4154 let exact = comparison.break_even_seconds().expect("a documented size");
4155 let oracle = dec!(1371.291648347883680961978771);
4156 assert!(
4157 (exact - oracle).abs() < dec!(0.000000001),
4158 "the Rust figure {exact} must match the Python oracle {oracle}"
4159 );
4160 // The f64 the CLI emits, byte-identical to the Python's.
4161 assert_eq!(
4162 comparison
4163 .break_even_seconds_f64()
4164 .expect("a documented size"),
4165 1371.2916483478837
4166 );
4167 // And the other recorded figures from the same oracle run, so a change to any
4168 // one of them is visible here rather than only in the break-even.
4169 assert_eq!(
4170 comparison.per_cycle().expect("a documented size").amount(),
4171 dec!(0.01070)
4172 );
4173 assert_eq!(comparison.ratio().round_dp(4), dec!(532.3380));
4174 }
4175
4176 /// The break-even is the number a pool scheduler needs, and this is what makes it
4177 /// meaningful rather than merely reproducible: just under it, a cycle loses money;
4178 /// just over, it saves. The test asserts the *verdict* the figure predicts, because a
4179 /// test that only pinned 1371.29 would pass against a formula that computed a number
4180 /// with no relation to the crossover.
4181 #[test]
4182 fn churn_below_break_even_costs_more_than_leaving_the_vm_running() {
4183 let break_even = month_comparison()
4184 .break_even_seconds()
4185 .expect("a documented size");
4186 assert!(break_even > Decimal::ZERO);
4187
4188 let suspended_beats_running = |hold: Duration| {
4189 let comparison = compare_residency(SizeClass::Mib2048, hold, 1, &rates(), fresh_day())
4190 .expect("a comparison prices");
4191 comparison.suspended().total().floor() < comparison.running().total().floor()
4192 };
4193 let at = |factor: Decimal| {
4194 Duration::from_secs_f64(
4195 (break_even * factor)
4196 .to_f64()
4197 .expect("the break-even hold fits in an f64"),
4198 )
4199 };
4200 assert!(
4201 !suspended_beats_running(at(dec!(0.9))),
4202 "just under the break-even hold, a cycle must lose money"
4203 );
4204 assert!(
4205 suspended_beats_running(at(dec!(1.1))),
4206 "just over it, a cycle must save"
4207 );
4208 }
4209
4210 /// Image build and storage are identical either way, so including them would shrink
4211 /// the ratio the comparison exists to show — and drag an unpriced build into a figure
4212 /// whose whole job is to be comparable.
4213 #[test]
4214 fn the_comparison_excludes_the_image_so_the_ratio_is_not_diluted() {
4215 let comparison = month_comparison();
4216 for report in [comparison.running(), comparison.suspended()] {
4217 let phases: Vec<CostPhase> = report.items().iter().map(|item| item.phase).collect();
4218 assert!(!phases.contains(&CostPhase::ImageBuild), "{phases:?}");
4219 assert!(!phases.contains(&CostPhase::ImageStorage), "{phases:?}");
4220 assert!(report.is_complete());
4221 // No launch either: a launch read would be paid on the running side only and
4222 // would tilt the ratio it is not part of.
4223 assert!(!phases.contains(&CostPhase::Launch), "{phases:?}");
4224 }
4225 }
4226
4227 /// The hold on a comparison is always projected: a comparison is a hypothetical
4228 /// about a hold nobody has taken yet, so neither side may read as a receipt.
4229 #[test]
4230 fn a_comparison_is_never_a_measured_report() {
4231 let comparison = month_comparison();
4232 assert_eq!(comparison.hold().provenance(), Provenance::Projected);
4233 assert!(!comparison.running().fully_measured());
4234 assert!(!comparison.suspended().fully_measured());
4235 }
4236
4237 /// The ratio's denominator can never be zero, because snapshot storage always has
4238 /// the minimum-retention floor (COST-8). The degenerate input — a zero-length hold —
4239 /// is the case that would divide by zero without it.
4240 #[test]
4241 fn a_zero_length_hold_still_has_a_finite_ratio() {
4242 let comparison =
4243 compare_residency(SizeClass::Mib2048, Duration::ZERO, 1, &rates(), fresh_day())
4244 .expect("a zero hold prices");
4245 assert!(comparison.suspended().total().floor().amount() > Decimal::ZERO);
4246 // Running for zero seconds costs nothing, so the ratio is zero rather than
4247 // undefined — and suspending a VM for no time is a pure loss, which is what the
4248 // break-even figure is about.
4249 assert_eq!(comparison.ratio(), Decimal::ZERO);
4250 }
4251
4252 // -- properties ------------------------------------------------------------
4253
4254 /// A plausible span, in seconds. Weighted rather than uniform, for the reason
4255 /// T-W2-2 measured: a uniform draw over the whole domain essentially never lands in
4256 /// the band where the interesting branch is reachable. Here the band that matters is
4257 /// the minimum-retention window, since that is where the storage floor applies and
4258 /// where the break-even formula changes slope.
4259 fn plausible_seconds() -> impl Strategy<Value = u64> {
4260 prop_oneof![
4261 // Inside the retention window, where the storage floor binds.
4262 4 => 0u64..604_800,
4263 // Past it, where storage grows with the hold.
4264 3 => 604_800u64..(730 * 3600 * 12),
4265 // The neighbourhood of the floor itself, where an off-by-one in the `max`
4266 // would hide.
4267 2 => 604_795u64..=604_805,
4268 // A long tail, so nothing above goes unchecked.
4269 1 => 0u64..u32::MAX as u64,
4270 ]
4271 }
4272
4273 proptest! {
4274 /// COST-4, as a property over every combination of priced and unpriced lines: a
4275 /// total is `AtLeast` exactly when an unpriced line is present, its floor is the
4276 /// sum of the priced ones and nothing else, and every unpriced reason is named.
4277 ///
4278 /// The verdict is computed from the generated input rather than read off the
4279 /// answer, which is what makes this catch a `Total::of` that dropped the
4280 /// unpriced line: such an implementation answers `Exact` where `documented`
4281 /// says `AtLeast`.
4282 ///
4283 /// The parenthetical is checked against a reference built the oracle's way —
4284 /// `", ".join(sorted({phase}))` — so a `Display` that reaches for reasons, report
4285 /// order, or the wrong separator disagrees on some generated input rather than
4286 /// only on the one report a hand-written test happens to build.
4287 #[test]
4288 fn a_total_is_a_lower_bound_exactly_when_something_is_unpriced(
4289 figures in prop::collection::vec(
4290 (
4291 prop::sample::select(&[
4292 CostPhase::ImageBuild,
4293 CostPhase::Running,
4294 CostPhase::Suspended,
4295 ][..]),
4296 prop_oneof![
4297 (0u64..1_000_000).prop_map(|cents| Amount::estimated(
4298 Decimal::from(cents) / dec!(100)
4299 )),
4300 "[a-z ]{1,20}".prop_map(Amount::unpriced),
4301 ],
4302 ),
4303 0..12,
4304 ),
4305 ) {
4306 let expected_floor: Decimal = figures
4307 .iter()
4308 .filter_map(|(_, amount)| amount.estimate())
4309 .map(EstimatedUsd::amount)
4310 .sum();
4311 let expected_reasons: Vec<String> = figures
4312 .iter()
4313 .filter_map(|(_, amount)| amount.unpriced_reason())
4314 .map(str::to_string)
4315 .collect();
4316 let expected_names: Vec<&str> = {
4317 let mut names: Vec<&str> = figures
4318 .iter()
4319 .filter(|(_, amount)| amount.unpriced_reason().is_some())
4320 .map(|(phase, _)| phase.as_str())
4321 .collect();
4322 names.sort_unstable();
4323 names.dedup();
4324 names
4325 };
4326
4327 let total = Total::of(figures.iter().map(|(phase, amount)| (*phase, amount)));
4328 prop_assert_eq!(total.is_lower_bound(), !expected_reasons.is_empty());
4329 prop_assert_eq!(total.floor().amount(), expected_floor);
4330 prop_assert_eq!(total.unpriced_reasons(), expected_reasons.as_slice());
4331 prop_assert_eq!(total.unpriced_phase_names(), expected_names.as_slice());
4332 match &total {
4333 Total::Exact(_) => prop_assert!(expected_reasons.is_empty()),
4334 Total::AtLeast { unpriced, .. } => prop_assert!(!unpriced.is_empty()),
4335 }
4336 // The rendering says which it is, since that is what a reader sees.
4337 prop_assert_eq!(
4338 total.to_string().starts_with("at least "),
4339 total.is_lower_bound()
4340 );
4341 if total.is_lower_bound() {
4342 prop_assert_eq!(
4343 total.to_string(),
4344 format!(
4345 "at least {}, plus {} unpriced ({})",
4346 total.floor(),
4347 expected_reasons.len(),
4348 expected_names.join(", ")
4349 )
4350 );
4351 }
4352 }
4353
4354 /// COST-6, over the whole arithmetic: a report's figures are exactly what the
4355 /// rate table times the quantities says they are, with no precision lost. The
4356 /// reference is recomputed in `Decimal` from the same inputs, so a float
4357 /// intermediate anywhere in the compute path disagrees.
4358 #[test]
4359 fn compute_figures_are_exactly_the_decimal_reference(
4360 seconds in plausible_seconds(),
4361 class_index in 0usize..5,
4362 ) {
4363 let size = SizeClass::ALL[class_index];
4364 let rates = rates();
4365 let duration = Duration::from_secs(seconds);
4366 let report = run_report(
4367 size,
4368 &RunUsage {
4369 running: Some(DurationP::Measured(duration)),
4370 launched: false,
4371 ..RunUsage::default()
4372 },
4373 &rates,
4374 fresh_day(),
4375 "run",
4376 )?;
4377
4378 let exact_seconds = Decimal::from(seconds);
4379 let vcpu = gb_decimal(size.baseline_vcpu())?;
4380 let memory = gb_decimal(size.baseline_gb())?;
4381 let expected_vcpu = vcpu * exact_seconds * rates.vcpu_second();
4382 let expected_memory = memory * exact_seconds * rates.gb_second();
4383
4384 let mut lines = report.by_phase(CostPhase::Running);
4385 let vcpu_line = lines.next().expect("a vcpu line");
4386 let memory_line = lines.next().expect("a memory line");
4387 prop_assert_eq!(vcpu_line.amount.estimate().expect("priced").amount(), expected_vcpu);
4388 prop_assert_eq!(memory_line.amount.estimate().expect("priced").amount(), expected_memory);
4389 // And the total is the sum of exactly those two, not a re-derivation.
4390 prop_assert_eq!(
4391 report.total(),
4392 Total::Exact(EstimatedUsd::new(expected_vcpu + expected_memory))
4393 );
4394 // COST-5 as a property: the quantity is the baseline times the seconds, and
4395 // for every class the peak figure is a different number.
4396 prop_assert_eq!(memory_line.quantity, memory * exact_seconds);
4397 if seconds > 0 {
4398 prop_assert_ne!(
4399 memory_line.quantity,
4400 gb_decimal(size.peak_gb())? * exact_seconds
4401 );
4402 }
4403 }
4404
4405 /// COST-8 as a property: storage bills `max(held, one week)` for every hold,
4406 /// and the note says so exactly when the floor bound. A `max` written the wrong
4407 /// way round passes at long holds and fails inside the window, which is why the
4408 /// generator is weighted towards it.
4409 #[test]
4410 fn storage_bills_the_greater_of_the_hold_and_the_retention_floor(
4411 seconds in plausible_seconds(),
4412 ) {
4413 let rates = rates();
4414 let report = run_report(
4415 SizeClass::Mib2048,
4416 &RunUsage {
4417 suspended: Some(DurationP::Measured(Duration::from_secs(seconds))),
4418 launched: false,
4419 ..RunUsage::default()
4420 },
4421 &rates,
4422 fresh_day(),
4423 "suspended",
4424 )?;
4425 let floor = seconds_of(rates.minimum_retention());
4426 let billed = Decimal::from(seconds).max(floor);
4427 let expected = dec!(2) * billed / SECONDS_PER_MONTH;
4428
4429 let items: Vec<&LineItem> = report.by_phase(CostPhase::Suspended).collect();
4430 prop_assert_eq!(items[0].quantity, expected);
4431 prop_assert_eq!(
4432 items[0].amount.estimate().expect("priced").amount(),
4433 expected * rates.storage_gb_month()
4434 );
4435 // The verdict on the note, computed from the input: it claims the floor
4436 // exactly when the floor was what bound.
4437 prop_assert_eq!(
4438 items[0].note.contains("minimum retention"),
4439 Decimal::from(seconds) < floor
4440 );
4441 // Never below the floor's own charge, which is the failure this requirement
4442 // is about — understating a create-and-destroy suite by four orders of
4443 // magnitude.
4444 prop_assert!(items[0].quantity >= dec!(2) * floor / SECONDS_PER_MONTH);
4445 }
4446
4447 /// COST-10 as a property: whatever a plan contains, every duration in the
4448 /// resulting report is projected and the report is never fully measured.
4449 #[test]
4450 fn every_duration_in_a_plan_is_projected(
4451 running in 0u64..1_000_000,
4452 suspended in 0u64..1_000_000,
4453 retained in prop::option::of(1u64..1_000_000),
4454 cycles in 0u32..5,
4455 image in prop::option::of(0.5f64..64.0),
4456 ) {
4457 let report = estimate_run(
4458 SizeClass::Mib2048,
4459 &PlanUsage {
4460 running_seconds: running as f64,
4461 suspended_seconds: suspended as f64,
4462 image_gb: image,
4463 image_retained_seconds: retained.map(|seconds| seconds as f64),
4464 suspend_resume_cycles: cycles,
4465 snapshot_gb: None,
4466 launched: true,
4467 },
4468 &rates(),
4469 fresh_day(),
4470 "estimate",
4471 )?;
4472 for item in report.items() {
4473 if let Some(duration) = item.duration {
4474 prop_assert_eq!(duration.provenance(), Provenance::Projected);
4475 }
4476 }
4477 prop_assert!(!report.fully_measured());
4478 // An image drags the unpriced build in, so the total's shape is decided by
4479 // whether one was named — the verdict, computed from the input.
4480 prop_assert_eq!(report.total().is_lower_bound(), image.is_some());
4481 }
4482
4483 /// The measured and projected paths are one arithmetic. If they could disagree
4484 /// numerically, the label would be hiding a second implementation.
4485 #[test]
4486 fn a_plan_and_a_timed_run_of_the_same_shape_price_identically(
4487 running in 1u64..1_000_000,
4488 cycles in 0u32..5,
4489 ) {
4490 let projected = estimate_run(
4491 SizeClass::Mib2048,
4492 &PlanUsage {
4493 running_seconds: running as f64,
4494 suspend_resume_cycles: cycles,
4495 ..PlanUsage::default()
4496 },
4497 &rates(),
4498 fresh_day(),
4499 "estimate",
4500 )?;
4501 let measured = run_report(
4502 SizeClass::Mib2048,
4503 &RunUsage {
4504 running: Some(DurationP::Measured(Duration::from_secs(running))),
4505 suspend_resume_cycles: cycles,
4506 launched: false,
4507 ..RunUsage::default()
4508 },
4509 &rates(),
4510 fresh_day(),
4511 "run",
4512 )?;
4513 prop_assert_eq!(projected.total(), measured.total());
4514 prop_assert!(!projected.fully_measured());
4515 }
4516
4517 /// The float boundary is exact where it succeeds (COST-6). Every f64 that has a
4518 /// decimal reading gets that reading, not its binary approximation — which is
4519 /// what `Decimal::try_from(0.1f64)` would give.
4520 #[test]
4521 fn the_float_boundary_reads_the_decimal_spelling_not_the_binary_value(
4522 gb in 0.0f64..1_000_000.0,
4523 ) {
4524 let converted = gb_decimal(gb)?;
4525 prop_assert_eq!(converted.to_string(), gb.to_string());
4526 prop_assert!(converted >= Decimal::ZERO);
4527 }
4528
4529 /// The staleness verdict is a comparison against ninety days and nothing else,
4530 /// over a range of retrieval ages. Computed from the input, so an off-by-one at
4531 /// the boundary fails.
4532 #[test]
4533 fn staleness_is_the_ninety_day_verdict_and_carries_the_age(
4534 age_days in -10i64..400,
4535 ) {
4536 let rates = rates();
4537 let today = CalendarDate::from_day_number(
4538 rates.retrieved().day_number() + age_days
4539 )
4540 .expect("in range");
4541 prop_assert_eq!(rates.age_days(today), age_days);
4542 prop_assert_eq!(rates.is_stale(today), age_days > STALE_AFTER_DAYS);
4543 match rates.staleness(today) {
4544 Some(warning) => {
4545 prop_assert!(age_days > STALE_AFTER_DAYS);
4546 let expected = format!("{age_days} days ago");
4547 prop_assert!(warning.contains(&expected), "{}", warning);
4548 }
4549 None => prop_assert!(age_days <= STALE_AFTER_DAYS),
4550 }
4551 // And the report carries whatever the table said.
4552 let report = run_report(
4553 SizeClass::Mib2048,
4554 &RunUsage {
4555 running: Some(DurationP::Measured(Duration::from_secs(60))),
4556 launched: false,
4557 ..RunUsage::default()
4558 },
4559 &rates,
4560 today,
4561 "run",
4562 )?;
4563 prop_assert_eq!(report.staleness().is_some(), age_days > STALE_AFTER_DAYS);
4564 }
4565
4566 /// The date round trip, which is what licenses a hand-rolled calendar: every day
4567 /// number is a date whose day number is itself, across four centuries.
4568 #[test]
4569 fn a_day_number_round_trips_through_its_calendar_date(
4570 day_number in -30_000i64..30_000,
4571 ) {
4572 let date = CalendarDate::from_day_number(day_number).expect("in range");
4573 prop_assert_eq!(date.day_number(), day_number);
4574 // And the parts are a real calendar day, so the validator agrees with the
4575 // arithmetic.
4576 prop_assert!(
4577 CalendarDate::try_from_ymd(date.year(), date.month(), date.day()).is_ok(),
4578 "{date} is not a calendar day"
4579 );
4580 }
4581 }
4582
4583 // ── the report as JSON (#255) ─────────────────────────────────────────
4584
4585 /// A create-and-destroy run: timed running and build, and an image whose retention
4586 /// nobody timed.
4587 fn a_create_and_destroy_report() -> CostReport {
4588 run_report(
4589 SizeClass::Mib2048,
4590 &RunUsage {
4591 running: Some(DurationP::Measured(Duration::from_secs(3600))),
4592 image_gb: Some(2.0),
4593 image_build: Some(DurationP::Measured(Duration::from_secs(600))),
4594 ..RunUsage::launched()
4595 },
4596 &pinned_rates(),
4597 fresh_day(),
4598 "run img",
4599 )
4600 .expect("a report")
4601 }
4602
4603 /// Running time or a non-zero image implies a launch, and nothing else does: suspended
4604 /// time alone is a VM that was already up, and a zero-sized image is no image (#255).
4605 ///
4606 /// **Falsification**: `verify/guards/faults/cost-defaults.toml` entry
4607 /// `domain-infer-launched-zero-image` counts `Some(0.0)` as an image, and the zero-image
4608 /// rows go red.
4609 #[test]
4610 fn a_launch_is_inferred_from_running_time_or_a_real_image_only() {
4611 let plans = [
4612 (PlanUsage::default(), false),
4613 (
4614 PlanUsage {
4615 running_seconds: 60.0,
4616 ..PlanUsage::default()
4617 },
4618 true,
4619 ),
4620 (
4621 PlanUsage {
4622 suspended_seconds: 3600.0,
4623 ..PlanUsage::default()
4624 },
4625 false,
4626 ),
4627 (
4628 PlanUsage {
4629 suspend_resume_cycles: 2,
4630 ..PlanUsage::default()
4631 },
4632 false,
4633 ),
4634 (
4635 PlanUsage {
4636 image_gb: Some(2.0),
4637 ..PlanUsage::default()
4638 },
4639 true,
4640 ),
4641 (
4642 PlanUsage {
4643 image_gb: Some(0.0),
4644 ..PlanUsage::default()
4645 },
4646 false,
4647 ),
4648 ];
4649 for (plan, launched) in plans {
4650 assert_eq!(plan.infer_launched(), launched, "{plan:?}");
4651 }
4652 let runs = [
4653 (RunUsage::default(), false),
4654 (
4655 RunUsage {
4656 running: Some(DurationP::Measured(Duration::from_secs(60))),
4657 ..RunUsage::default()
4658 },
4659 true,
4660 ),
4661 (
4662 RunUsage {
4663 running: Some(DurationP::Measured(Duration::ZERO)),
4664 ..RunUsage::default()
4665 },
4666 false,
4667 ),
4668 (
4669 RunUsage {
4670 suspended: Some(DurationP::Measured(Duration::from_secs(60))),
4671 ..RunUsage::default()
4672 },
4673 false,
4674 ),
4675 (
4676 RunUsage {
4677 image_gb: Some(2.0),
4678 ..RunUsage::default()
4679 },
4680 true,
4681 ),
4682 (
4683 RunUsage {
4684 image_gb: Some(0.0),
4685 ..RunUsage::default()
4686 },
4687 false,
4688 ),
4689 ];
4690 for (usage, launched) in runs {
4691 assert_eq!(usage.infer_launched(), launched, "{usage:?}");
4692 }
4693 }
4694
4695 /// **The unpriced line has no `usd` key at all.**
4696 ///
4697 /// Not a null, which anything permissive sums as zero, and the build is the one phase
4698 /// AWS does not publish a rate for, so this is the field that stops a create-and-destroy
4699 /// report from reading as compute-only.
4700 ///
4701 /// **Falsification**: `verify/guards/faults/cost-defaults.toml` entry
4702 /// `domain-report-json-usd-null` emits `"usd": null` for the unpriced arm, and this test is
4703 /// red on the key's presence while every total still looks right.
4704 #[test]
4705 fn an_unpriced_line_omits_the_usd_key_rather_than_reporting_zero() {
4706 let json = a_create_and_destroy_report().to_json();
4707 let items = json["items"].as_array().expect("items");
4708 let build = items
4709 .iter()
4710 .find(|item| item["phase"] == "image-build")
4711 .expect("the build line is always present when an image is");
4712 assert_eq!(build["amount"]["kind"], "unpriced");
4713 assert!(
4714 build["amount"].get("usd").is_none(),
4715 "a null would be summed as zero: {build}"
4716 );
4717 assert!(
4718 build["amount"]["reason"]
4719 .as_str()
4720 .expect("a reason")
4721 .contains("does not publish"),
4722 "{build}"
4723 );
4724 // And the total says it is a floor rather than a figure.
4725 assert_eq!(json["total"]["isLowerBound"], true);
4726 assert!(
4727 json["total"]["render"]
4728 .as_str()
4729 .expect("a render")
4730 .contains("at least"),
4731 "{}",
4732 json["total"]["render"]
4733 );
4734 assert_eq!(json["complete"], false);
4735 }
4736
4737 /// Every dollar figure is a string, and every priced line has one. Every *seconds*
4738 /// figure is a number.
4739 ///
4740 /// A JSON number for a dollar figure is a `Decimal` that went through an f64, which is the
4741 /// exactness the type exists to hold. Asserted over every item so a single unconverted
4742 /// field fails.
4743 ///
4744 /// The seconds half is the same assertion pointed the other way, and it is pinned here
4745 /// rather than left implicit because the two rules look contradictory side by side and the
4746 /// natural "tidy-up" is to make them agree. The Python oracle's `cli.py:743` emitted
4747 /// `duration.seconds` as a float, so a string here is a field a consumer has to branch on
4748 /// by client, which is exactly the substitutability `breakEvenSeconds` was already a
4749 /// number to preserve.
4750 ///
4751 /// The oracle's recorded output for `cost --json --running-sec=3600`, read off
4752 /// `data.report.items[0].duration.seconds`:
4753 ///
4754 /// ```text
4755 /// 3600.0
4756 /// ```
4757 ///
4758 /// A transcript rather than a command, because that client was deleted once this one had
4759 /// driven the live suite green. The figure is what it printed; git history is where the
4760 /// code that printed it is.
4761 ///
4762 /// **Falsification**: put `.to_string()` back on either seconds field and the matching
4763 /// arm here is red while every dollar assertion stays green, which is what says the two
4764 /// halves are independent. `verify/guards/faults/cost-defaults.toml` entry
4765 /// `domain-report-json-seconds-string` does it to a line's seconds.
4766 #[test]
4767 fn every_dollar_is_a_string_and_every_seconds_figure_is_a_number() {
4768 let json = a_create_and_destroy_report().to_json();
4769 let mut durations = 0;
4770 for item in json["items"].as_array().expect("items") {
4771 if let Some(usd) = item["amount"].get("usd") {
4772 assert!(usd.is_string(), "{item}");
4773 usd.as_str()
4774 .expect("a string")
4775 .parse::<f64>()
4776 .expect("still parses as a figure");
4777 }
4778 assert!(item["quantity"].is_string(), "{item}");
4779 if !item["duration"].is_null() {
4780 durations += 1;
4781 assert!(
4782 item["duration"]["seconds"].is_number(),
4783 "a number, matching cli.py:743: {item}"
4784 );
4785 }
4786 }
4787 assert!(
4788 durations > 0,
4789 "vacuous unless a duration was present: {json}"
4790 );
4791 assert!(json["total"]["priced"].is_string());
4792
4793 // The exact values, so this is parity rather than merely a type check. Checked against
4794 // the oracle on this same report shape (`600` for the timed build and `604800.0` for
4795 // the retention floor), read through `as_f64` because the oracle's build figure is a
4796 // JSON int where its retention figure is a float, and both are numbers.
4797 let seconds: Vec<f64> = json["items"]
4798 .as_array()
4799 .expect("items")
4800 .iter()
4801 .filter(|item| !item["duration"].is_null())
4802 .map(|item| item["duration"]["seconds"].as_f64().expect("a number"))
4803 .collect();
4804 assert!(seconds.contains(&600.0), "{seconds:?}");
4805 assert!(seconds.contains(&604_800.0), "{seconds:?}");
4806
4807 // And `holdSeconds` on the comparison, which is the second field `cli.py` (`:2189`)
4808 // emits as a number and the one a scheduler compares against a timeout.
4809 let comparison = compare_residency(
4810 SizeClass::Mib2048,
4811 Duration::from_secs(3600),
4812 1,
4813 &pinned_rates(),
4814 fresh_day(),
4815 )
4816 .expect("a comparison")
4817 .to_json()
4818 .expect("renders");
4819 assert_eq!(comparison["holdSeconds"].as_f64(), Some(3600.0));
4820 assert!(comparison["breakEvenSeconds"].is_number());
4821 // The money beside it stays a string, which is the whole point of the split.
4822 assert!(comparison["perCycleUsd"].is_string());
4823 }
4824
4825 /// A measured run labels the phases a clock timed measured, and the one nobody timed
4826 /// projected.
4827 ///
4828 /// The mixed case is the interesting one and my first draft got it wrong by asserting every
4829 /// duration on a measured report is measured. It is not: `image-storage`'s duration defaults
4830 /// to the documented one-week minimum retention, and core marks it
4831 /// `Projected` because, in its own words, "nobody timed that week either". So a
4832 /// create-and-destroy report is honestly a mixture, and `fullyMeasured` is `false` for it.
4833 ///
4834 /// Worth pinning precisely because the wrong version reads better: "a measured report is
4835 /// measured" is the assertion someone would write, and it would force the retention default
4836 /// to lie about a week nobody observed.
4837 #[test]
4838 fn a_measured_report_labels_the_timed_phases_measured_and_the_retention_projected() {
4839 let measured = a_create_and_destroy_report().to_json();
4840 let labelled: Vec<(&str, &str)> = measured["items"]
4841 .as_array()
4842 .expect("items")
4843 .iter()
4844 .filter(|item| !item["duration"].is_null())
4845 .map(|item| {
4846 (
4847 item["phase"].as_str().unwrap_or_default(),
4848 item["duration"]["provenance"].as_str().unwrap_or_default(),
4849 )
4850 })
4851 .collect();
4852 assert!(
4853 labelled.contains(&("running", "measured")),
4854 "a clock timed the run: {labelled:?}"
4855 );
4856 assert!(
4857 labelled.contains(&("image-build", "measured")),
4858 "a clock timed the build: {labelled:?}"
4859 );
4860 assert!(
4861 labelled.contains(&("image-storage", "projected")),
4862 "nobody timed the one-week retention floor: {labelled:?}"
4863 );
4864 assert_eq!(
4865 measured["fullyMeasured"], false,
4866 "a report carrying a projected retention is not fully measured"
4867 );
4868
4869 let estimate = estimate_run(
4870 SizeClass::Mib2048,
4871 &PlanUsage {
4872 running_seconds: 3600.0,
4873 ..PlanUsage::launched()
4874 },
4875 &pinned_rates(),
4876 fresh_day(),
4877 DEFAULT_ESTIMATE_LABEL,
4878 )
4879 .expect("an estimate");
4880 let json = estimate.to_json();
4881 assert_eq!(json["fullyMeasured"], false);
4882 // *Every* duration, with no exception, which is the difference from the measured report
4883 // above: an estimate has nothing a clock touched.
4884 for item in json["items"].as_array().expect("items") {
4885 if !item["duration"].is_null() {
4886 assert_eq!(item["duration"]["provenance"], "projected", "{item}");
4887 }
4888 }
4889
4890 // And a report whose only phase *was* timed is fully measured, so the flag is a real
4891 // comparison rather than something that is always false.
4892 let timed_only = run_report(
4893 SizeClass::Mib2048,
4894 &RunUsage {
4895 running: Some(DurationP::Measured(Duration::from_secs(60))),
4896 ..RunUsage::launched()
4897 },
4898 &pinned_rates(),
4899 fresh_day(),
4900 "run",
4901 )
4902 .expect("a report");
4903 assert_eq!(timed_only.to_json()["fullyMeasured"], true);
4904 // And `estimated: true` is on both, because dollars are always estimates.
4905 assert_eq!(measured["estimated"], true);
4906 assert_eq!(json["estimated"], true);
4907 }
4908
4909 /// The report's key set is `cli.py`'s `report_to_dict` key for key, plus the one
4910 /// addition since that client retired: `headroomMib` (issue #99).
4911 ///
4912 /// Pinned because the conformance oracle reads these names: a rename here is a driver
4913 /// that reports every cost check as missing rather than as wrong. It's every surface's
4914 /// shape since #255, when the bindings' hand-written copies lacked `headroomMib`.
4915 ///
4916 /// **Falsification**: `verify/guards/faults/cost-defaults.toml` entry
4917 /// `domain-report-json-headroom` drops `headroomMib`, and the size keys go red.
4918 #[test]
4919 fn the_report_json_carries_the_pythons_key_set() {
4920 let json = a_create_and_destroy_report().to_json();
4921 let mut keys: Vec<&String> = json.as_object().expect("object").keys().collect();
4922 keys.sort();
4923 assert_eq!(
4924 keys,
4925 [
4926 "complete",
4927 "estimated",
4928 "fullyMeasured",
4929 "items",
4930 "label",
4931 "rates",
4932 "size",
4933 "staleness",
4934 "total",
4935 ]
4936 );
4937 let mut size_keys: Vec<&String> =
4938 json["size"].as_object().expect("object").keys().collect();
4939 size_keys.sort();
4940 assert_eq!(
4941 size_keys,
4942 [
4943 "baselineMib",
4944 "baselineVcpu",
4945 "describe",
4946 "headroomMib",
4947 "peakMib",
4948 "peakVcpu"
4949 ]
4950 );
4951 let mut item_keys: Vec<&String> = json["items"][0]
4952 .as_object()
4953 .expect("object")
4954 .keys()
4955 .collect();
4956 item_keys.sort();
4957 assert_eq!(
4958 item_keys,
4959 [
4960 "amount", "duration", "line", "note", "phase", "quantity", "unit"
4961 ]
4962 );
4963 }
4964
4965 /// A comparison carries its own counter-argument: the per-cycle cost and the break-even
4966 /// hold.
4967 ///
4968 /// Without them "100x cheaper suspended" reads as "suspend constantly", and a pool that
4969 /// churns every few seconds spends more on transitions than it saves on residency.
4970 #[test]
4971 fn a_comparison_carries_the_per_cycle_cost_and_the_break_even_hold() {
4972 let comparison = compare_residency(
4973 SizeClass::Mib2048,
4974 Duration::from_secs(3600),
4975 1,
4976 &pinned_rates(),
4977 fresh_day(),
4978 )
4979 .expect("a comparison");
4980 let json = comparison.to_json().expect("renders");
4981 assert!(json["perCycleUsd"].is_string());
4982 assert!(
4983 json["ratio"].is_string(),
4984 "the ratio is not money but is decimal"
4985 );
4986 let break_even = json["breakEvenSeconds"].as_f64().expect("a number");
4987 assert!(break_even > 0.0, "{break_even}");
4988 assert!(
4989 json["render"]
4990 .as_str()
4991 .expect("a render")
4992 .contains("avoid churn"),
4993 "the conclusion the numbers support has to travel with them"
4994 );
4995 }
4996
4997 /// A staleness warning survives into the envelope.
4998 ///
4999 /// The warning has to reach whatever renders it: a library caller with a log filter and a
5000 /// CLI that only wrote stderr would each lose it on their own, which is why core carries
5001 /// it on the report.
5002 #[test]
5003 fn a_stale_rate_table_puts_its_warning_in_the_envelope() {
5004 let rates = pinned_rates();
5005 let retrieved = rates.retrieved();
5006 // A day past the ninety-day window, computed from the table's own date so this test
5007 // cannot go stale.
5008 let stale_day =
5009 CalendarDate::try_from_ymd(retrieved.year() + 1, retrieved.month(), retrieved.day())
5010 .expect("a real day one year on");
5011 let report = run_report(
5012 SizeClass::Mib2048,
5013 &RunUsage {
5014 running: Some(DurationP::Measured(Duration::from_secs(60))),
5015 ..RunUsage::launched()
5016 },
5017 &rates,
5018 stale_day,
5019 "run",
5020 )
5021 .expect("a report");
5022 let json = report.to_json();
5023 assert!(json["staleness"].is_string(), "{json}");
5024 assert!(
5025 json["staleness"].as_str().expect("text").contains("days"),
5026 "{json}"
5027 );
5028 }
5029
5030 // ── the budget gate (#270) ────────────────────────────────────────────
5031
5032 /// A report with only priced lines: an hour running at the default size.
5033 fn an_exact_report() -> CostReport {
5034 running_report(
5035 SizeClass::Mib2048,
5036 DurationP::Measured(Duration::from_secs(3600)),
5037 )
5038 }
5039
5040 /// Each judgement over each side of the ceiling, on an exact total and on a lower bound:
5041 /// a breach aborts only under `Abort`, at the ceiling is within, and a lower bound says so
5042 /// whichever side it lands on (#270).
5043 ///
5044 /// **Falsification**: `verify/guards/faults/cost-defaults.toml` entries
5045 /// `domain-budget-abort-ignores-the-judgement` (a breach aborts under `Warn` too) and
5046 /// `domain-budget-at-the-ceiling-breaches` (`>=` for `>`) each turn a row red.
5047 #[test]
5048 fn a_budget_verdict_follows_the_judgement_and_the_total_it_was_given() {
5049 let exact = an_exact_report();
5050 let floor = exact.total().floor();
5051 let lower = a_create_and_destroy_report();
5052 assert!(lower.total().is_lower_bound());
5053 let lower_floor = lower.total().floor();
5054 let over = |figure: EstimatedUsd| EstimatedUsd::new(figure.amount() - dec!(0.001));
5055 let rows = [
5056 (&exact, floor, OnBreach::Abort, false, false, "exact"),
5057 (&exact, over(floor), OnBreach::Warn, true, false, "exact"),
5058 (&exact, over(floor), OnBreach::Abort, true, true, "exact"),
5059 (
5060 &lower,
5061 over(lower_floor),
5062 OnBreach::Warn,
5063 true,
5064 false,
5065 "lower-bound",
5066 ),
5067 (
5068 &lower,
5069 over(lower_floor),
5070 OnBreach::Abort,
5071 true,
5072 true,
5073 "lower-bound",
5074 ),
5075 (
5076 &lower,
5077 lower_floor,
5078 OnBreach::Abort,
5079 false,
5080 false,
5081 "lower-bound",
5082 ),
5083 ];
5084 for (report, max, on_breach, breached, aborts, basis) in rows {
5085 let verdict = Budget::new(max, on_breach).check(report);
5086 let row = format!("{} under {} ({basis})", max.amount(), on_breach.as_str());
5087 assert_eq!(verdict.breached(), breached, "breached: {row}");
5088 assert_eq!(verdict.aborts(), aborts, "aborts: {row}");
5089 assert_eq!(verdict.basis(), basis, "basis: {row}");
5090 assert_eq!(verdict.overage().is_some(), breached, "overage: {row}");
5091 assert_eq!(verdict.to_json()["breached"], breached, "{row}");
5092 assert_eq!(verdict.to_json()["onBreach"], on_breach.as_str(), "{row}");
5093 }
5094 let breach = Budget::new(over(lower_floor), OnBreach::Warn).check(&lower);
5095 assert_eq!(breach.overage(), Some(EstimatedUsd::new(dec!(0.001))));
5096 assert!(
5097 breach.render().contains("by at least"),
5098 "{}",
5099 breach.render()
5100 );
5101 assert!(
5102 breach.render().contains("unknown margin"),
5103 "{}",
5104 breach.render()
5105 );
5106 let within = Budget::new(lower_floor, OnBreach::Warn).check(&lower);
5107 assert!(
5108 within.render().contains("that floor is a lower bound"),
5109 "{}",
5110 within.render()
5111 );
5112 assert_eq!(within.unpriced_phases(), ["image-build"]);
5113 // An exact total under the ceiling says it's the estimate and claims no lower bound.
5114 let exact_within = Budget::new(floor, OnBreach::Warn).check(&exact);
5115 assert!(exact_within.unpriced_phases().is_empty());
5116 let text = exact_within.render();
5117 assert!(text.starts_with("budget: the estimated total $"), "{text}");
5118 assert!(!text.contains("lower bound"), "{text}");
5119 }
5120
5121 /// An empty report is an exact zero, not a lower bound: nothing on it is unpriced, so a
5122 /// zero ceiling holds it, and the dense line says `exact`.
5123 #[test]
5124 fn an_empty_report_is_judged_as_an_exact_zero() {
5125 let empty = run_report(
5126 SizeClass::Mib2048,
5127 &RunUsage::default(),
5128 &pinned_rates(),
5129 fresh_day(),
5130 DEFAULT_RUN_LABEL,
5131 )
5132 .expect("an empty report");
5133 let verdict = Budget::new(EstimatedUsd::ZERO, OnBreach::Abort).check(&empty);
5134 assert!(!verdict.is_lower_bound());
5135 assert!(!verdict.breached());
5136 assert_eq!(verdict.render_dense(), "budget\t0\texact\twithin\t-");
5137 }
5138
5139 /// A judgement parses from its spelling and nothing else, so a surface taking a string
5140 /// can't default one in by accident.
5141 #[test]
5142 fn a_judgement_parses_from_its_spelling_only() {
5143 for judgement in OnBreach::ALL {
5144 assert_eq!(judgement.as_str().parse::<OnBreach>().ok(), Some(judgement));
5145 }
5146 for bad in ["", "Warn", "abort ", "fail"] {
5147 let error = bad.parse::<OnBreach>().expect_err("not a judgement");
5148 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{bad:?}");
5149 }
5150 }
5151}