troupekit-agent 0.4.0

Persona TOML agents for the Troupekit LLM agent framework: loader, checkpointable run state machine, typed output, evals and budgets.
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
use crate::persona::Budget;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
use troupekit_core::error::CoreError;
use troupekit_core::event::Usage;
use troupekit_core::tool::WEB_SEARCH;
use troupekit_providers::{CompletionRequest, Price, RESEND_NOTE_BYTES};
use troupekit_trace::{content, trace_span, Trace};

/// A spend limit for one period, such as a goal's or a user's month.
/// `key` names the ledger total (for example `goal:42`); the ledger decides
/// what the period is. Amounts are millionths of a US dollar.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PeriodLimit {
    pub key: String,
    pub max_usd_micros: u64,
}

/// The layered limits a run checks before every model call: one call,
/// the whole run, the scope's period and the user's period. `None` is no
/// limit. Amounts are millionths of a US dollar.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Limits {
    pub call: Option<u64>,
    pub run: Option<u64>,
    pub scope: Option<PeriodLimit>,
    pub user: Option<PeriodLimit>,
}

impl Limits {
    /// Applies a persona `budget` on top: each of `call` and `run` becomes
    /// the stricter of the two, so neither side can loosen the other.
    /// Returns the combined limits.
    pub fn with_budget(mut self, budget: &Budget) -> Self {
        let stricter = |a: Option<u64>, b: Option<u64>| match (a, b) {
            (Some(x), Some(y)) => Some(x.min(y)),
            (x, y) => x.or(y),
        };
        self.call = stricter(self.call, budget.call_usd_micros);
        self.run = stricter(self.run, budget.run_usd_micros);
        self
    }

    /// Combines two limit sets, each layer the stricter: the lower `call`
    /// and `run`, and per period the lower amount when both name the same
    /// key. A period whose key differs is replaced by `other`'s, the host's
    /// current ledger (for example a new day): a replacement, not a
    /// tightening. Input: the other set. Output: the combined limits.
    pub fn stricter(self, other: &Limits) -> Limits {
        let lower = |a: Option<u64>, b: Option<u64>| match (a, b) {
            (Some(x), Some(y)) => Some(x.min(y)),
            (x, y) => x.or(y),
        };
        let period = |a: Option<PeriodLimit>, b: &Option<PeriodLimit>| match (a, b) {
            (Some(x), Some(y)) if x.key == y.key => Some(PeriodLimit {
                key: x.key,
                max_usd_micros: x.max_usd_micros.min(y.max_usd_micros),
            }),
            (x, None) => x,
            (_, Some(y)) => Some(y.clone()),
        };
        Limits {
            call: lower(self.call, other.call),
            run: lower(self.run, other.run),
            scope: period(self.scope, &other.scope),
            user: period(self.user, &other.user),
        }
    }

    /// Reports whether no layer has a limit.
    /// An empty set skips every budget check, including the
    /// unverified price check.
    pub fn is_empty(&self) -> bool {
        self.call.is_none() && self.run.is_none() && self.scope.is_none() && self.user.is_none()
    }
}

pub use troupekit_core::store::UsageLedger;

/// In-memory `UsageLedger` for tests and examples.
/// It has one period that never ends; `usage` reads a key's totals.
/// Safe to share across threads.
#[derive(Debug, Default)]
pub struct InMemoryLedger(Mutex<HashMap<String, Usage>>);

impl InMemoryLedger {
    /// Returns the usage recorded under `key`.
    /// A key never recorded reads as zero usage.
    /// Tests use it to check what a run charged.
    pub fn usage(&self, key: &str) -> Usage {
        self.0
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .get(key)
            .copied()
            .unwrap_or_default()
    }
}

#[async_trait]
impl UsageLedger for InMemoryLedger {
    async fn period_total(&self, key: &str) -> Result<u64, CoreError> {
        Ok(self.usage(key).cost_usd_micros)
    }

    async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError> {
        *self
            .0
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .entry(key.to_string())
            .or_default() += usage;
        Ok(())
    }
}

/// Worst-case cost of sending `req` at `price`: input tokens counted as
/// a quarter of the JSON bytes of system text, messages and tool specs,
/// rounded up, plus `max_tokens` output tokens and every web search the
/// hosted tools allow. Never under-counts output.
pub fn estimate(req: &CompletionRequest, price: &Price) -> u64 {
    let bytes = req.system.as_ref().map_or(0, String::len)
        + serde_json::to_string(&req.messages)
            .expect("messages serialize")
            .len()
        + serde_json::to_string(&req.tools)
            .expect("tool specs serialize")
            .len();
    let input_tokens = u64::try_from(bytes.div_ceil(4)).expect("byte count fits in u64");
    let searches: u64 = req
        .tools
        .iter()
        .filter_map(|t| t.hosted)
        .filter(|h| h.name() == WEB_SEARCH)
        .map(|h| u64::from(h.max_uses()))
        .sum();
    price
        .cost_usd_micros(&Usage {
            input_tokens,
            output_tokens: u64::from(req.max_tokens),
            cost_usd_micros: 0,
        })
        .saturating_add(searches.saturating_mul(price.search_usd_micros))
}

/// Worst-case cost of one call with `req` at `price` that makes `extra`
/// more provider calls: `estimate` for the first, and for each extra one
/// `estimate` again plus the previous reply (`max_tokens`) and
/// `RESEND_NOTE_BYTES` as input. Equals `estimate` when `extra` is 0.
pub fn estimate_calls(req: &CompletionRequest, price: &Price, extra: u32) -> u64 {
    let first = estimate(req, price);
    if extra == 0 {
        return first;
    }
    let resent = price.cost_usd_micros(&Usage {
        input_tokens: u64::from(req.max_tokens)
            + u64::try_from(RESEND_NOTE_BYTES.div_ceil(4)).expect("note bytes fit in u64"),
        output_tokens: 0,
        cost_usd_micros: 0,
    });
    let each = first.saturating_add(resent);
    let total = first.saturating_add(each.saturating_mul(u64::from(extra)));
    assert!(total >= first);
    total
}

static TURNS: Mutex<BTreeMap<usize, Arc<tokio::sync::Mutex<()>>>> = Mutex::new(BTreeMap::new());

/// One admission's turn on one ledger: it waits for and then holds that
/// ledger's admission lock, so admissions on other ledgers never queue
/// behind it. Dropping it, also while still waiting, removes the lock
/// from the table once no other admission holds or waits for it.
struct Turn {
    id: usize,
    lock: Arc<tokio::sync::Mutex<()>>,
    guard: Option<tokio::sync::OwnedMutexGuard<()>>,
}

impl Turn {
    /// Waits for the admission lock of the ledger `id`. Output: the held turn.
    async fn take(id: usize) -> Turn {
        let lock = TURNS
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .entry(id)
            .or_default()
            .clone();
        let mut turn = Turn {
            id,
            lock,
            guard: None,
        };
        turn.guard = Some(Arc::clone(&turn.lock).lock_owned().await);
        turn
    }
}

impl Drop for Turn {
    /// Releases the lock and drops the table entry when this turn was its
    /// last user. Output: none.
    fn drop(&mut self) {
        drop(self.guard.take());
        let mut turns = TURNS.lock().unwrap_or_else(|p| p.into_inner());
        assert!(
            Arc::strong_count(&self.lock) >= 2,
            "the table and this turn hold the lock"
        );
        if Arc::strong_count(&self.lock) == 2 {
            turns.remove(&self.id);
        }
    }
}
static RESERVED: Mutex<BTreeMap<(usize, String), u64>> = Mutex::new(BTreeMap::new());

/// The cost estimate of one admitted call, held against the scope and
/// user totals of its ledger from admission until the call's cost is
/// recorded, so concurrent runs on one ledger see it. The hold is the
/// estimate, so a call that costs more than its estimate can still pass
/// the cap. Dropping it, after
/// `record` or when the call fails or is dropped, releases the amount.
/// It covers runs in this process that share one ledger value; two ledger
/// values over one store, or other processes, do not see it.
#[must_use = "dropping the reservation releases it before the call is recorded"]
#[derive(Debug)]
pub(crate) struct Reservation {
    slots: Vec<(usize, String)>,
    amount: u64,
}

impl Drop for Reservation {
    /// Subtracts the amount from every key it holds and removes a key
    /// whose reservations reach zero. Output: none.
    fn drop(&mut self) {
        let mut table = RESERVED.lock().unwrap_or_else(|p| p.into_inner());
        for slot in &self.slots {
            let held = table.get_mut(slot).expect("a held slot is in the table");
            assert!(
                *held >= self.amount,
                "a release never exceeds the reservations"
            );
            *held -= self.amount;
            if *held == 0 {
                table.remove(slot);
            }
        }
    }
}

/// The table identity of `ledger`: its address, stable while any run
/// holds it. Input: the ledger. Output: the address.
fn ledger_id(ledger: &dyn UsageLedger) -> usize {
    std::ptr::from_ref(ledger).cast::<()>() as usize
}

/// The in-flight reservations on `key` of the ledger `id`. Output: the sum.
fn reserved(id: usize, key: &str) -> u64 {
    RESERVED
        .lock()
        .unwrap_or_else(|p| p.into_inner())
        .get(&(id, key.to_string()))
        .copied()
        .unwrap_or(0)
}

/// Checks a call costing up to `estimate` against every layer of `limits`,
/// given `run_spent` so far and the ledger's period totals plus in-flight
/// reservations, and reserves nothing. Returns the first crossed layer:
/// `unverified_price`, `call`, `run`, `scope`, `user`.
pub async fn check(
    limits: &Limits,
    price: &Price,
    run_spent: u64,
    estimate: u64,
    ledger: &dyn UsageLedger,
) -> Result<Option<&'static str>, CoreError> {
    Ok(admit(limits, price, run_spent, estimate, ledger)
        .await?
        .err())
}

/// Checks a call like `check` and, when it fits, reserves `estimate`
/// under the scope and user keys in the same step: admissions on one
/// ledger run one at a time, so two runs can never both take the last
/// room under a cap, and admissions on other ledgers do not wait. Keep the reservation until the call's cost is
/// recorded. Output: the reservation, or the first crossed layer.
pub(crate) async fn admit(
    limits: &Limits,
    price: &Price,
    run_spent: u64,
    estimate: u64,
    ledger: &dyn UsageLedger,
) -> Result<Result<Reservation, &'static str>, CoreError> {
    let mut span = trace_span!(
        Trace::Budget,
        "budget.check",
        estimate = estimate,
        run_spent = run_spent,
    );
    let periodic = limits.scope.is_some() || limits.user.is_some();
    let id = ledger_id(ledger);
    let _turn = if periodic {
        Some(Turn::take(id).await)
    } else {
        None
    };
    let result = span
        .instrument(crossed(limits, price, run_spent, estimate, ledger, id))
        .await;
    match &result {
        Ok(layer) => span.record("crossed", layer.unwrap_or("none")),
        Err(e) => {
            span.fail("usage ledger failed");
            span.record("error", content(e.to_string()));
        }
    }
    Ok(match result? {
        Some(layer) => Err(layer),
        None => Ok(reserve(limits, id, estimate)),
    })
}

/// Adds `estimate` under each distinct period key of `limits` for the
/// ledger `id`. A zero estimate holds nothing and takes no slot, so its
/// release never looks for a key another release already removed.
/// Output: the reservation that gives it back.
fn reserve(limits: &Limits, id: usize, estimate: u64) -> Reservation {
    if estimate == 0 {
        return Reservation {
            slots: Vec::new(),
            amount: 0,
        };
    }
    let mut slots: Vec<(usize, String)> = [&limits.scope, &limits.user]
        .into_iter()
        .flatten()
        .map(|l| (id, l.key.clone()))
        .collect();
    slots.dedup();
    let mut table = RESERVED.lock().unwrap_or_else(|p| p.into_inner());
    for slot in &slots {
        let held = table.entry(slot.clone()).or_insert(0);
        *held = held.saturating_add(estimate);
    }
    Reservation {
        slots,
        amount: estimate,
    }
}

/// The first crossed layer for a call costing up to `estimate`. Each
/// period key's reservations are read before its ledger total, so a call
/// recorded and released between the two reads counts twice, never zero
/// times. A key whose reservations plus `estimate` would overflow is
/// crossed. Output: the layer, or None when the call fits.
async fn crossed(
    limits: &Limits,
    price: &Price,
    run_spent: u64,
    estimate: u64,
    ledger: &dyn UsageLedger,
    id: usize,
) -> Result<Option<&'static str>, CoreError> {
    if limits.is_empty() {
        return Ok(None);
    }
    if !price.verified {
        return Ok(Some("unverified_price"));
    }
    if limits.call.is_some_and(|max| estimate > max) {
        return Ok(Some("call"));
    }
    if limits
        .run
        .is_some_and(|max| run_spent.saturating_add(estimate) > max)
    {
        return Ok(Some("run"));
    }
    for (name, limit) in [("scope", &limits.scope), ("user", &limits.user)] {
        if let Some(l) = limit {
            let held = reserved(id, &l.key);
            let Some(holding) = held.checked_add(estimate) else {
                return Ok(Some(name));
            };
            let total = ledger.period_total(&l.key).await?.saturating_add(holding);
            if total > l.max_usd_micros {
                return Ok(Some(name));
            }
        }
    }
    Ok(None)
}

/// Adds one call's `usage` to the ledger under the scope and user keys of
/// `limits`, when they are set, once per distinct key, so scope and user
/// caps on one key charge it once. Returns the first ledger failure.
pub async fn record(
    limits: &Limits,
    ledger: &dyn UsageLedger,
    usage: Usage,
) -> Result<(), CoreError> {
    let mut keys: Vec<&str> = [&limits.scope, &limits.user]
        .into_iter()
        .flatten()
        .map(|l| l.key.as_str())
        .collect();
    keys.dedup();
    for key in keys {
        ledger.record(key, usage).await?;
    }
    Ok(())
}

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

    /// A ledger whose `period_total` reads its total, signals `read` and
    /// then yields once before returning, like a store whose read is a
    /// snapshot taken before an await.
    #[derive(Default)]
    struct YieldingLedger {
        inner: InMemoryLedger,
        read: tokio::sync::Notify,
    }

    #[async_trait]
    impl UsageLedger for YieldingLedger {
        async fn period_total(&self, key: &str) -> Result<u64, CoreError> {
            let total = self.inner.period_total(key).await?;
            self.read.notify_one();
            tokio::task::yield_now().await;
            Ok(total)
        }

        async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError> {
            self.inner.record(key, usage).await
        }
    }

    fn capped(key: &str, max_usd_micros: u64) -> Limits {
        Limits {
            scope: Some(PeriodLimit {
                key: key.into(),
                max_usd_micros,
            }),
            ..Limits::default()
        }
    }

    #[tokio::test]
    async fn a_release_during_a_pending_read_still_counts() {
        let ledger = YieldingLedger::default();
        let limits = capped("goal:race", 150);
        let first = admit(&limits, &PRICE, 0, 100, &ledger)
            .await
            .unwrap()
            .unwrap();
        let settle = async {
            ledger.read.notified().await;
            record(
                &limits,
                &ledger,
                Usage {
                    cost_usd_micros: 100,
                    ..Usage::default()
                },
            )
            .await
            .unwrap();
            drop(first);
        };
        let (second, ()) = tokio::join!(admit(&limits, &PRICE, 0, 100, &ledger), settle);
        assert_eq!(
            second.unwrap().err(),
            Some("scope"),
            "a call recorded and released during the read was counted zero times"
        );
        assert_eq!(ledger.inner.usage("goal:race").cost_usd_micros, 100);
    }

    #[tokio::test]
    async fn a_busy_ledger_never_holds_up_another() {
        let busy = InMemoryLedger::default();
        let other = InMemoryLedger::default();
        let held = Turn::take(ledger_id(&busy)).await;
        let admitted = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            admit(&capped("goal:other", 150), &PRICE, 0, 100, &other),
        )
        .await
        .expect("an admission on another ledger waited for the busy one");
        assert!(admitted.unwrap().is_ok());
        let id = ledger_id(&busy);
        drop(held);
        assert!(
            !TURNS.lock().unwrap().contains_key(&id),
            "an unused lock stayed in the table"
        );
    }

    #[tokio::test]
    async fn reservations_near_u64_max_refuse_instead_of_overflowing() {
        let ledger = InMemoryLedger::default();
        let limits = capped("goal:max", u64::MAX);
        let first = admit(&limits, &PRICE, 0, u64::MAX - 1, &ledger)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            check(&limits, &PRICE, 0, 2, &ledger).await.unwrap(),
            Some("scope")
        );
        drop(first);
        assert_eq!(reserved(ledger_id(&ledger), "goal:max"), 0);
    }

    #[tokio::test]
    async fn admissions_on_a_yielding_ledger_take_turns() {
        let ledger = YieldingLedger::default();
        let limits = capped("goal:turns", 150);
        let (a, b) = tokio::join!(
            admit(&limits, &PRICE, 0, 100, &ledger),
            admit(&limits, &PRICE, 0, 100, &ledger)
        );
        let (a, b) = (a.unwrap(), b.unwrap());
        assert_eq!(
            usize::from(a.is_ok()) + usize::from(b.is_ok()),
            1,
            "two admissions read the same total and both took the last room"
        );
    }

    const PRICE: Price = Price {
        input_usd_micros_per_mtok: 1_000_000,
        output_usd_micros_per_mtok: 2_000_000,
        verified: true,
        long_context: None,
        search_usd_micros: 0,
    };

    fn req() -> CompletionRequest {
        CompletionRequest::user("x".repeat(400), 1000)
    }

    #[test]
    fn estimate_calls_adds_each_resend() {
        let r = req();
        let one = estimate(&r, &PRICE);
        assert_eq!(estimate_calls(&r, &PRICE, 0), one);
        let resend = (1000 + RESEND_NOTE_BYTES.div_ceil(4)) as u64;
        assert_eq!(estimate_calls(&r, &PRICE, 1), one + one + resend);
        assert_eq!(estimate_calls(&r, &PRICE, 2), one + 2 * (one + resend));
        assert_eq!(estimate_calls(&r, &Price::FREE, 3), 0);
    }

    #[test]
    fn estimate_is_worst_case() {
        let r = req();
        let bytes = serde_json::to_string(&r.messages).unwrap().len() + 2;
        let input = bytes.div_ceil(4) as u64;
        assert_eq!(
            estimate(&r, &PRICE),
            PRICE.cost_usd_micros(&Usage {
                input_tokens: input,
                output_tokens: 1000,
                cost_usd_micros: 0
            })
        );
        assert!(estimate(&r, &PRICE) >= 2000 + 100);
        assert_eq!(estimate(&r, &Price::FREE), 0);
    }

    #[test]
    fn estimate_adds_every_allowed_search() {
        use troupekit_core::tool::{HostedTool, ToolSpec};
        let mut r = req();
        let priced = Price {
            search_usd_micros: 10_000,
            ..PRICE
        };
        let base = estimate(&r, &priced);
        r.tools.push(ToolSpec {
            name: "web_search".into(),
            description: String::new(),
            schema: serde_json::json!({}),
            hosted: Some(HostedTool::WebSearch { max_uses: 3 }),
        });
        let tools = serde_json::to_string(&r.tools).unwrap().len() as u64;
        assert!(estimate(&r, &priced) >= base + 30_000);
        assert!(estimate(&r, &priced) <= base + 30_000 + tools.div_ceil(4) + 1);
    }

    #[tokio::test]
    async fn each_layer_pauses_by_name() {
        let ledger = InMemoryLedger::default();
        ledger
            .record(
                "goal:1",
                Usage {
                    cost_usd_micros: 900,
                    ..Usage::default()
                },
            )
            .await
            .unwrap();
        ledger
            .record(
                "user:1",
                Usage {
                    cost_usd_micros: 5_000,
                    ..Usage::default()
                },
            )
            .await
            .unwrap();
        let scope = Some(PeriodLimit {
            key: "goal:1".into(),
            max_usd_micros: 1_000,
        });
        let user = Some(PeriodLimit {
            key: "user:1".into(),
            max_usd_micros: 5_050,
        });
        let cases = [
            (
                Limits {
                    call: Some(99),
                    ..Limits::default()
                },
                0,
                Some("call"),
            ),
            (
                Limits {
                    call: Some(100),
                    ..Limits::default()
                },
                0,
                None,
            ),
            (
                Limits {
                    run: Some(150),
                    ..Limits::default()
                },
                60,
                Some("run"),
            ),
            (
                Limits {
                    run: Some(150),
                    ..Limits::default()
                },
                50,
                None,
            ),
            (
                Limits {
                    scope: scope.clone(),
                    ..Limits::default()
                },
                0,
                None,
            ),
            (
                Limits {
                    scope: Some(PeriodLimit {
                        key: "goal:1".into(),
                        max_usd_micros: 999,
                    }),
                    ..Limits::default()
                },
                0,
                Some("scope"),
            ),
            (
                Limits {
                    scope,
                    user,
                    ..Limits::default()
                },
                0,
                Some("user"),
            ),
        ];
        for (limits, spent, want) in cases {
            assert_eq!(
                check(&limits, &PRICE, spent, 100, &ledger).await.unwrap(),
                want,
                "{limits:?}"
            );
        }
    }

    #[tokio::test]
    async fn concurrent_checks_never_share_the_last_room() {
        let ledger = InMemoryLedger::default();
        let limits = Limits {
            scope: Some(PeriodLimit {
                key: "goal:cap".into(),
                max_usd_micros: 150,
            }),
            user: Some(PeriodLimit {
                key: "goal:cap".into(),
                max_usd_micros: 150,
            }),
            ..Limits::default()
        };
        let (a, b) = tokio::join!(
            admit(&limits, &PRICE, 0, 100, &ledger),
            admit(&limits, &PRICE, 0, 100, &ledger)
        );
        let (a, b) = (a.unwrap(), b.unwrap());
        assert_eq!(
            usize::from(a.is_ok()) + usize::from(b.is_ok()),
            1,
            "both runs took the last room: {a:?} {b:?}"
        );
        let held = if a.is_ok() { a } else { b }.unwrap();
        assert_eq!(
            check(&limits, &PRICE, 0, 100, &ledger).await.unwrap(),
            Some("scope"),
            "a third check passed while the first call was in flight"
        );
        record(
            &limits,
            &ledger,
            Usage {
                cost_usd_micros: 40,
                ..Usage::default()
            },
        )
        .await
        .unwrap();
        drop(held);
        assert_eq!(reserved(ledger_id(&ledger), "goal:cap"), 0);
        let next = admit(&limits, &PRICE, 0, 100, &ledger).await.unwrap();
        assert!(next.is_ok(), "the recorded cost left room: {next:?}");
    }

    #[tokio::test]
    async fn a_zero_estimate_releases_in_any_order() {
        let ledger = InMemoryLedger::default();
        let limits = Limits {
            scope: Some(PeriodLimit {
                key: "goal:free".into(),
                max_usd_micros: 1_000,
            }),
            ..Limits::default()
        };
        let id = ledger_id(&ledger);
        let free = admit(&limits, &Price::FREE, 0, 0, &ledger)
            .await
            .unwrap()
            .unwrap();
        let paid = admit(&limits, &PRICE, 0, 100, &ledger)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(reserved(id, "goal:free"), 100);
        drop(paid);
        drop(free);
        assert_eq!(reserved(id, "goal:free"), 0);
        for first_out in [true, false] {
            let a = admit(&limits, &Price::FREE, 0, 0, &ledger)
                .await
                .unwrap()
                .unwrap();
            let b = admit(&limits, &Price::FREE, 0, 0, &ledger)
                .await
                .unwrap()
                .unwrap();
            if first_out {
                drop(a);
                drop(b);
            } else {
                drop(b);
                drop(a);
            }
            assert_eq!(reserved(id, "goal:free"), 0);
        }
    }

    #[tokio::test]
    async fn one_key_for_both_caps_is_charged_once() {
        let ledger = InMemoryLedger::default();
        let cap = Some(PeriodLimit {
            key: "goal:shared".into(),
            max_usd_micros: 1_000,
        });
        let limits = Limits {
            scope: cap.clone(),
            user: cap,
            ..Limits::default()
        };
        record(
            &limits,
            &ledger,
            Usage {
                cost_usd_micros: 40,
                ..Usage::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(ledger.usage("goal:shared").cost_usd_micros, 40);
    }

    #[test]
    fn persona_budget_only_tightens() {
        let b = Budget {
            call_usd_micros: Some(10),
            run_usd_micros: None,
        };
        let host = Limits {
            call: Some(20),
            run: Some(30),
            ..Limits::default()
        };
        assert_eq!(
            host.clone().with_budget(&b),
            Limits {
                call: Some(10),
                run: Some(30),
                ..Limits::default()
            }
        );
        let tight = Limits {
            call: Some(5),
            ..Limits::default()
        };
        assert_eq!(tight.with_budget(&b).call, Some(5));
        assert_eq!(Limits::default().with_budget(&b).call, Some(10));
    }

    #[tokio::test]
    async fn unverified_price_pauses_only_with_limits() {
        let ledger = InMemoryLedger::default();
        let unverified = Price {
            verified: false,
            ..Price::FREE
        };
        assert_eq!(
            check(&Limits::default(), &unverified, 0, 0, &ledger)
                .await
                .unwrap(),
            None
        );
        let limits = Limits {
            run: Some(1),
            ..Limits::default()
        };
        assert_eq!(
            check(&limits, &unverified, 0, 0, &ledger).await.unwrap(),
            Some("unverified_price")
        );
        assert_eq!(
            check(&limits, &Price::FREE, 0, 0, &ledger).await.unwrap(),
            None
        );
    }

    #[tokio::test]
    async fn ledger_sums_per_key() {
        let ledger = InMemoryLedger::default();
        let limits = Limits {
            scope: Some(PeriodLimit {
                key: "goal:1".into(),
                max_usd_micros: 10,
            }),
            user: Some(PeriodLimit {
                key: "user:1".into(),
                max_usd_micros: 10,
            }),
            ..Limits::default()
        };
        let u = Usage {
            input_tokens: 3,
            output_tokens: 4,
            cost_usd_micros: 7,
        };
        record(&limits, &ledger, u).await.unwrap();
        record(&limits, &ledger, u).await.unwrap();
        record(&Limits::default(), &ledger, u).await.unwrap();
        assert_eq!(ledger.usage("goal:1"), u + u);
        assert_eq!(ledger.period_total("user:1").await.unwrap(), 14);
        assert_eq!(ledger.usage("other"), Usage::default());
    }
}