boundgraph-core 0.1.0

Core primitives for the BoundGraph runtime: content-addressed digests, work orders, context, condensates, evidence, and the ledger.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! What a reasoner charges — the input to every cost claim the system makes.
//!
//! # Why this is data and not a provider method
//!
//! The headline claim is that a flow's price can be bounded *before it runs*
//! (`ARCHITECTURE.md` §10). That is only possible if per-token pricing and the
//! context ceiling are knowable at build time, which means they cannot be
//! something you learn by calling a model. So a [`CostModel`] is a value the
//! compiler reads, and the provider that will eventually charge it is required
//! to declare one (US-0601).
//!
//! It lives here rather than beside the providers for the same reason
//! [`Budget`](crate::Budget) does: the compiler needs to reason about price
//! long before there is a provider to ask, and a type in `boundgraph-core` is one
//! both ends can see without either depending on the other.
//!
//! # Why pricing is loaded, not compiled in
//!
//! Model prices change on the vendor's schedule, not on ours. A constant in a
//! binary means every price change is a release; a [`Pricing`] catalogue read
//! from a file means it is a config edit. The catalogue is also what makes
//! staleness checkable — every entry carries the date it was correct on
//! ([`AsOf`]), so "this flow was priced against nine-month-old numbers" is a
//! question the compiler can answer instead of a thing nobody notices.
//!
//! # Cached reads are a different price, not a discount
//!
//! Prompt caching does not make input tokens cheaper — it makes *some* of them
//! a different line item. A cached read is roughly a tenth of the uncached
//! rate and a cache write is more than the uncached rate, so a model that
//! collapsed them into one number would misprice both directions. Hence four
//! rates rather than two.

use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

/// Tokens per pricing unit. Vendors quote per million; so do we.
const TOKENS_PER_UNIT: u64 = 1_000_000;

/// The date a price was correct on.
///
/// A plain calendar date with no timezone, because pricing changes on a
/// published date rather than at an instant. Ordering is chronological, which
/// is the only thing a staleness check needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct AsOf {
    /// Four-digit year.
    pub year: u16,
    /// Month, 1–12.
    pub month: u8,
    /// Day, 1–31.
    pub day: u8,
}

impl AsOf {
    /// A date, checked.
    ///
    /// # Errors
    ///
    /// [`AsOfParseError::OutOfRange`] if the month or day is not a calendar
    /// value. Day-of-month is checked against the month's real length,
    /// including February in leap years — a date that cannot exist is a typo,
    /// and a typo in a pricing date is how stale pricing goes unnoticed.
    pub fn new(year: u16, month: u8, day: u8) -> Result<Self, AsOfParseError> {
        let length = match month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 if is_leap(year) => 29,
            2 => 28,
            _ => return Err(AsOfParseError::OutOfRange),
        };
        if day == 0 || day > length {
            return Err(AsOfParseError::OutOfRange);
        }
        Ok(Self { year, month, day })
    }

    /// Whether this date is older than `horizon`.
    ///
    /// The horizon is supplied rather than computed from the clock: reading the
    /// wall clock here would make compilation nondeterministic, and a flow that
    /// compiles today and fails tomorrow with no change to its bytes is exactly
    /// what the determinism audit exists to prevent.
    pub fn is_older_than(self, horizon: Self) -> bool {
        self < horizon
    }
}

impl fmt::Display for AsOf {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
    }
}

const fn is_leap(year: u16) -> bool {
    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}

/// A pricing date could not be read.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AsOfParseError {
    /// Not `YYYY-MM-DD`.
    #[error("a pricing date must be YYYY-MM-DD")]
    Malformed,
    /// Parsed, but not a date that exists.
    #[error("that is not a calendar date")]
    OutOfRange,
}

impl FromStr for AsOf {
    type Err = AsOfParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.split('-');
        let (Some(y), Some(m), Some(d), None) =
            (parts.next(), parts.next(), parts.next(), parts.next())
        else {
            return Err(AsOfParseError::Malformed);
        };
        if (y.len(), m.len(), d.len()) != (4, 2, 2) {
            return Err(AsOfParseError::Malformed);
        }
        let year = y.parse().map_err(|_| AsOfParseError::Malformed)?;
        let part = |t: &str| t.parse::<u8>().map_err(|_| AsOfParseError::Malformed);
        Self::new(year, part(m)?, part(d)?)
    }
}

impl TryFrom<String> for AsOf {
    type Error = AsOfParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

impl From<AsOf> for String {
    fn from(date: AsOf) -> Self {
        date.to_string()
    }
}

/// What a call actually consumed, split by how each token was billed.
///
/// The four counts are disjoint: a prompt token is billed exactly once, as
/// uncached input, as a cache write, or as a cache read.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenUsage {
    /// Prompt tokens charged at the full input rate.
    pub input: u64,
    /// Completion tokens.
    pub output: u64,
    /// Prompt tokens written to the cache this call.
    pub cache_write: u64,
    /// Prompt tokens served from the cache this call.
    pub cache_read: u64,
}

impl TokenUsage {
    /// Nothing consumed.
    pub const NONE: Self = Self {
        input: 0,
        output: 0,
        cache_write: 0,
        cache_read: 0,
    };

    /// Every prompt token, however it was billed.
    pub fn prompt_tokens(&self) -> u64 {
        self.input
            .saturating_add(self.cache_write)
            .saturating_add(self.cache_read)
    }

    /// Prompt plus completion.
    pub fn total_tokens(&self) -> u64 {
        self.prompt_tokens().saturating_add(self.output)
    }

    /// What fraction of the prompt was served from cache, as a percentage.
    ///
    /// The number to watch when a cache is supposed to be working: a prefix
    /// that should be hitting and reads zero means something upstream is
    /// changing bytes that were meant to be stable.
    pub fn cache_hit_rate(&self) -> Option<Decimal> {
        let prompt = self.prompt_tokens();
        if prompt == 0 {
            return None;
        }
        Some(Decimal::from(self.cache_read) * Decimal::ONE_HUNDRED / Decimal::from(prompt))
    }

    /// Add another call's usage to this one.
    #[must_use]
    pub fn plus(self, other: Self) -> Self {
        Self {
            input: self.input.saturating_add(other.input),
            output: self.output.saturating_add(other.output),
            cache_write: self.cache_write.saturating_add(other.cache_write),
            cache_read: self.cache_read.saturating_add(other.cache_read),
        }
    }
}

/// What one reasoner charges, and how much it can be given.
///
/// # Example
///
/// ```
/// use boundgraph_core::{AsOf, CostModel, TokenUsage};
/// use rust_decimal::Decimal;
///
/// let usd = |s: &str| s.parse::<Decimal>().unwrap();
///
/// let model = CostModel::new(
///     usd("5.00"),   // input, per million tokens
///     usd("25.00"),  // output
///     AsOf::new(2026, 6, 24).unwrap(),
/// )
/// .with_context_window(1_000_000)
/// .with_cache_rates(usd("0.50"), usd("6.25"));
///
/// // A cached read is a tenth of the uncached rate, and the price says so.
/// let cold = model.price(&TokenUsage { input: 1_000_000, ..TokenUsage::NONE });
/// let warm = model.price(&TokenUsage { cache_read: 1_000_000, ..TokenUsage::NONE });
/// assert_eq!(cold, usd("5.00"));
/// assert_eq!(warm, usd("0.50"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CostModel {
    /// US dollars per million uncached prompt tokens.
    pub input: Decimal,
    /// US dollars per million completion tokens.
    pub output: Decimal,
    /// US dollars per million prompt tokens served from the cache.
    ///
    /// Substantially below [`input`](Self::input) — that difference is the
    /// whole point of caching, and collapsing the two would hide it.
    pub cache_read: Decimal,
    /// US dollars per million prompt tokens written to the cache.
    ///
    /// Above [`input`](Self::input): a write costs more than not caching at
    /// all, which is why a prefix has to be read back at least twice before
    /// caching it pays for itself.
    pub cache_write: Decimal,
    /// The same, for a provider's longer-lived cache tier, if it has one.
    pub cache_write_long: Option<Decimal>,
    /// The largest prompt this model will accept, in tokens.
    ///
    /// A ceiling the compiler checks a flow's declared context against, so
    /// "this step asks for more window than the model has" is a build error
    /// rather than a run-time refusal.
    pub context_window: u32,
    /// The largest completion it will produce, in tokens.
    pub max_output: u32,
    /// The date these figures were correct on.
    pub as_of: AsOf,
}

impl CostModel {
    /// A model priced per million tokens, with no cache tier.
    ///
    /// Cache rates default to the uncached input rate, which is the
    /// conservative reading: a provider that has not told us caching is
    /// cheaper is priced as though it is not.
    pub fn new(input: Decimal, output: Decimal, as_of: AsOf) -> Self {
        Self {
            input,
            output,
            cache_read: input,
            cache_write: input,
            cache_write_long: None,
            context_window: 0,
            max_output: 0,
            as_of,
        }
    }

    /// Declare the cache tier's rates.
    #[must_use]
    pub fn with_cache_rates(mut self, read: Decimal, write: Decimal) -> Self {
        self.cache_read = read;
        self.cache_write = write;
        self
    }

    /// Declare a longer-lived cache tier's write rate.
    #[must_use]
    pub fn with_long_cache_write(mut self, write: Decimal) -> Self {
        self.cache_write_long = Some(write);
        self
    }

    /// Declare the prompt ceiling.
    #[must_use]
    pub fn with_context_window(mut self, tokens: u32) -> Self {
        self.context_window = tokens;
        self
    }

    /// Declare the completion ceiling.
    #[must_use]
    pub fn with_max_output(mut self, tokens: u32) -> Self {
        self.max_output = tokens;
        self
    }

    /// What a call consuming `usage` costs, in US dollars.
    ///
    /// Exact decimal arithmetic throughout: this figure ends up in the ledger
    /// and gets summed across a run, and a rounding error that compounds is
    /// worse than no figure at all.
    pub fn price(&self, usage: &TokenUsage) -> Decimal {
        let per = |tokens: u64, rate: Decimal| Decimal::from(tokens) * rate;
        (per(usage.input, self.input)
            + per(usage.output, self.output)
            + per(usage.cache_read, self.cache_read)
            + per(usage.cache_write, self.cache_write))
            / Decimal::from(TOKENS_PER_UNIT)
    }

    /// Whether a prompt of this size fits.
    pub fn admits(&self, prompt_tokens: u32) -> bool {
        self.context_window == 0 || prompt_tokens <= self.context_window
    }

    /// Whether these figures are older than `horizon`.
    pub fn is_stale(&self, horizon: AsOf) -> bool {
        self.as_of.is_older_than(horizon)
    }

    /// Whether two models would price the same call identically.
    ///
    /// What a failover has to satisfy: a fallback that charges differently
    /// changes the ceiling the flow was compiled against, so the compiler
    /// refuses it (US-0604) rather than letting the proved bound quietly stop
    /// being true.
    pub fn prices_alike(&self, other: &Self) -> bool {
        self.input == other.input
            && self.output == other.output
            && self.cache_read == other.cache_read
            && self.cache_write == other.cache_write
    }

    /// Whichever of two models is more expensive on every rate.
    ///
    /// Used to bound a choice the compiler cannot resolve — a ladder or a
    /// failover list — by pricing it at its worst case rather than its
    /// expected one.
    pub fn costlier(&self, other: &Self) -> Self {
        Self {
            input: self.input.max(other.input),
            output: self.output.max(other.output),
            cache_read: self.cache_read.max(other.cache_read),
            cache_write: self.cache_write.max(other.cache_write),
            cache_write_long: match (self.cache_write_long, other.cache_write_long) {
                (Some(a), Some(b)) => Some(a.max(b)),
                (a, b) => a.or(b),
            },
            // The tighter ceiling binds: a chain can only accept what its most
            // limited member accepts.
            context_window: match (self.context_window, other.context_window) {
                (0, w) | (w, 0) => w,
                (a, b) => a.min(b),
            },
            max_output: match (self.max_output, other.max_output) {
                (0, w) | (w, 0) => w,
                (a, b) => a.min(b),
            },
            as_of: self.as_of.min(other.as_of),
        }
    }
}

/// Every model's pricing, keyed by model id.
///
/// Loaded rather than compiled in — see the module documentation.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Pricing {
    models: BTreeMap<String, CostModel>,
}

impl Pricing {
    /// An empty catalogue.
    pub fn new() -> Self {
        Self::default()
    }

    /// Read a catalogue from JSON.
    ///
    /// # Errors
    ///
    /// [`PricingError::Malformed`] if the document is not a map of model id to
    /// cost model.
    pub fn from_json(json: &str) -> Result<Self, PricingError> {
        serde_json::from_str(json).map_err(|e| PricingError::Malformed(e.to_string()))
    }

    /// Render the catalogue back to JSON.
    ///
    /// # Errors
    ///
    /// [`PricingError::Malformed`] if the catalogue cannot be encoded.
    pub fn to_json(&self) -> Result<String, PricingError> {
        serde_json::to_string_pretty(self).map_err(|e| PricingError::Malformed(e.to_string()))
    }

    /// Add or replace one model's pricing.
    #[must_use]
    pub fn with(mut self, model: impl Into<String>, cost: CostModel) -> Self {
        self.models.insert(model.into(), cost);
        self
    }

    /// What a model charges, if the catalogue knows it.
    pub fn get(&self, model: &str) -> Option<&CostModel> {
        self.models.get(model)
    }

    /// Every model priced, in id order.
    pub fn models(&self) -> impl Iterator<Item = (&str, &CostModel)> {
        self.models.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// How many models are priced.
    pub fn len(&self) -> usize {
        self.models.len()
    }

    /// Whether nothing is priced.
    pub fn is_empty(&self) -> bool {
        self.models.is_empty()
    }

    /// The models whose figures predate `horizon`, in id order.
    pub fn stale(&self, horizon: AsOf) -> Vec<&str> {
        self.models
            .iter()
            .filter(|(_, cost)| cost.is_stale(horizon))
            .map(|(id, _)| id.as_str())
            .collect()
    }
}

/// A pricing catalogue could not be read.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum PricingError {
    /// The document is not a pricing catalogue.
    #[error("the pricing catalogue is malformed: {0}")]
    Malformed(String),
}

#[cfg(test)]
mod tests {
    use super::*;

    fn usd(s: &str) -> Decimal {
        s.parse().unwrap()
    }

    fn opus() -> CostModel {
        CostModel::new(usd("5.00"), usd("25.00"), AsOf::new(2026, 6, 24).unwrap())
            .with_cache_rates(usd("0.50"), usd("6.25"))
            .with_long_cache_write(usd("10.00"))
            .with_context_window(1_000_000)
            .with_max_output(128_000)
    }

    // ── the four rates ──────────────────────────────────────────────────────

    #[test]
    fn a_cost_model_carries_input_output_and_the_context_ceiling() {
        let m = opus();
        assert_eq!(m.input, usd("5.00"));
        assert_eq!(m.output, usd("25.00"));
        assert_eq!(m.context_window, 1_000_000);
        assert_eq!(m.max_output, 128_000);
    }

    /// The distinction the story turns on: a cached read is its own rate, not a
    /// discount applied to the input rate.
    #[test]
    fn cached_reads_are_priced_separately_from_uncached_input() {
        let m = opus();
        assert_ne!(m.cache_read, m.input);
        assert!(
            m.cache_read < m.input,
            "a read should be cheaper than a miss"
        );
        assert!(
            m.cache_write > m.input,
            "a write should cost more than not caching"
        );

        let million = 1_000_000;
        assert_eq!(
            m.price(&TokenUsage {
                input: million,
                ..TokenUsage::NONE
            }),
            usd("5.00")
        );
        assert_eq!(
            m.price(&TokenUsage {
                cache_read: million,
                ..TokenUsage::NONE
            }),
            usd("0.50")
        );
        assert_eq!(
            m.price(&TokenUsage {
                cache_write: million,
                ..TokenUsage::NONE
            }),
            usd("6.25")
        );
    }

    /// A model that never told us caching is cheaper is priced as though it is
    /// not — conservative by default, like everything else that guesses.
    #[test]
    fn a_model_with_no_cache_tier_prices_reads_at_the_input_rate() {
        let m = CostModel::new(usd("3.00"), usd("15.00"), AsOf::new(2026, 6, 24).unwrap());
        assert_eq!(m.cache_read, m.input);
        assert_eq!(m.cache_write, m.input);
    }

    #[test]
    fn a_priced_call_sums_every_rate() {
        let m = opus();
        let usage = TokenUsage {
            input: 100_000,
            output: 20_000,
            cache_write: 40_000,
            cache_read: 800_000,
        };
        // 0.5 + 0.5 + 0.25 + 0.4
        assert_eq!(m.price(&usage), usd("1.65"));
    }

    #[test]
    fn money_is_exact() {
        let m = CostModel::new(usd("0.1"), usd("0.2"), AsOf::new(2026, 1, 1).unwrap());
        let a = m.price(&TokenUsage {
            input: 1_000_000,
            ..TokenUsage::NONE
        });
        let b = m.price(&TokenUsage {
            output: 1_000_000,
            ..TokenUsage::NONE
        });
        assert_eq!(a + b, usd("0.3"), "0.1 + 0.2 must be exactly 0.3");
    }

    // ── usage ───────────────────────────────────────────────────────────────

    #[test]
    fn the_four_counts_are_disjoint_halves_of_one_total() {
        let u = TokenUsage {
            input: 10,
            output: 5,
            cache_write: 3,
            cache_read: 90,
        };
        assert_eq!(u.prompt_tokens(), 103);
        assert_eq!(u.total_tokens(), 108);
    }

    #[test]
    fn the_cache_hit_rate_is_reported_over_the_whole_prompt() {
        let u = TokenUsage {
            input: 100,
            cache_read: 900,
            ..TokenUsage::NONE
        };
        assert_eq!(u.cache_hit_rate(), Some(usd("90")));
        assert_eq!(TokenUsage::NONE.cache_hit_rate(), None, "nothing to divide");
    }

    #[test]
    fn usage_accumulates_across_calls() {
        let a = TokenUsage {
            input: 1,
            output: 2,
            cache_write: 3,
            cache_read: 4,
        };
        assert_eq!(a.plus(a).total_tokens(), 20);
    }

    // ── staleness ───────────────────────────────────────────────────────────

    #[test]
    fn pricing_dates_order_chronologically() {
        let older = AsOf::new(2025, 12, 31).unwrap();
        let newer = AsOf::new(2026, 1, 1).unwrap();
        assert!(older < newer);
        assert!(older.is_older_than(newer));
        assert!(!newer.is_older_than(older));
        assert!(!newer.is_older_than(newer), "a horizon is not yet stale");
    }

    /// Compilation must not depend on the wall clock, so the horizon is passed
    /// in. A flow that compiles today and fails tomorrow with the same bytes is
    /// the exact nondeterminism the audit exists to catch.
    #[test]
    fn staleness_is_measured_against_a_supplied_horizon() {
        let m = opus();
        assert!(!m.is_stale(AsOf::new(2026, 1, 1).unwrap()));
        assert!(m.is_stale(AsOf::new(2027, 1, 1).unwrap()));
    }

    #[test]
    fn a_pricing_date_round_trips_through_its_iso_form() {
        let d = AsOf::new(2026, 6, 24).unwrap();
        assert_eq!(d.to_string(), "2026-06-24");
        assert_eq!("2026-06-24".parse::<AsOf>().unwrap(), d);
    }

    #[test]
    fn a_date_that_cannot_exist_is_refused() {
        for bad in ["2026-02-30", "2026-13-01", "2026-00-10", "2026-01-00"] {
            assert_eq!(
                bad.parse::<AsOf>(),
                Err(AsOfParseError::OutOfRange),
                "{bad} should not parse"
            );
        }
        for bad in ["2026-6-24", "26-06-24", "2026/06/24", "2026-06", ""] {
            assert_eq!(
                bad.parse::<AsOf>(),
                Err(AsOfParseError::Malformed),
                "{bad} should not parse"
            );
        }
    }

    #[test]
    fn february_29_exists_only_in_a_leap_year() {
        assert!("2024-02-29".parse::<AsOf>().is_ok());
        assert!("2000-02-29".parse::<AsOf>().is_ok(), "2000 is a leap year");
        assert!("1900-02-29".parse::<AsOf>().is_err(), "1900 is not");
        assert!("2026-02-29".parse::<AsOf>().is_err());
    }

    // ── the catalogue ───────────────────────────────────────────────────────

    #[test]
    fn a_catalogue_round_trips_through_json() {
        let catalogue = Pricing::new().with("claude-opus-5", opus()).with(
            "claude-haiku-4-5",
            CostModel::new(usd("1.00"), usd("5.00"), AsOf::new(2026, 6, 24).unwrap()),
        );

        let json = catalogue.to_json().unwrap();
        assert_eq!(Pricing::from_json(&json).unwrap(), catalogue);
        assert_eq!(catalogue.len(), 2);
        assert_eq!(catalogue.get("claude-opus-5").unwrap().input, usd("5.00"));
        assert!(catalogue.get("nothing-by-that-name").is_none());
    }

    #[test]
    fn a_malformed_catalogue_is_refused_rather_than_half_read() {
        assert!(matches!(
            Pricing::from_json("{\"a\": 3}"),
            Err(PricingError::Malformed(_))
        ));
        assert!(Pricing::from_json("not json at all").is_err());
    }

    #[test]
    fn the_catalogue_reports_which_models_have_gone_stale() {
        let catalogue = Pricing::new().with("fresh", opus()).with(
            "ancient",
            CostModel::new(usd("1"), usd("1"), AsOf::new(2024, 1, 1).unwrap()),
        );
        assert_eq!(catalogue.stale(AsOf::new(2026, 1, 1).unwrap()), ["ancient"]);
        assert!(catalogue.stale(AsOf::new(2020, 1, 1).unwrap()).is_empty());
    }

    // ── comparing models ────────────────────────────────────────────────────

    #[test]
    fn two_models_price_alike_only_when_every_rate_matches() {
        let a = opus();
        let mut b = opus();
        assert!(a.prices_alike(&b));

        b.output = usd("30.00");
        assert!(!a.prices_alike(&b), "a different output rate is a mismatch");

        let mut c = opus();
        c.cache_read = usd("0.60");
        assert!(!a.prices_alike(&c), "a different cache rate is a mismatch");

        // The date is metadata about the figures, not one of them.
        let mut d = opus();
        d.as_of = AsOf::new(2026, 1, 1).unwrap();
        assert!(a.prices_alike(&d));
    }

    /// Bounding a choice the compiler cannot resolve: the price is the dearest
    /// option's, and the ceiling is the most limited option's.
    #[test]
    fn the_costlier_of_two_models_takes_the_worst_of_each() {
        let cheap = CostModel::new(usd("1.00"), usd("5.00"), AsOf::new(2026, 6, 1).unwrap())
            .with_context_window(200_000);
        let dear = opus();

        let worst = cheap.costlier(&dear);
        assert_eq!(worst.input, usd("5.00"));
        assert_eq!(worst.output, usd("25.00"));
        assert_eq!(
            worst.context_window, 200_000,
            "the tighter window binds the chain"
        );
        assert_eq!(
            worst.as_of,
            AsOf::new(2026, 6, 1).unwrap(),
            "the older date"
        );
    }

    #[test]
    fn a_prompt_is_admitted_only_within_the_window() {
        let m = opus();
        assert!(m.admits(999_999));
        assert!(m.admits(1_000_000));
        assert!(!m.admits(1_000_001));

        // A model that never declared a window does not refuse anything.
        let unbounded = CostModel::new(usd("1"), usd("1"), AsOf::new(2026, 1, 1).unwrap());
        assert!(unbounded.admits(u32::MAX));
    }
}