Skip to main content

base/interface/
budget_policy.rs

1//! What a turn is allowed to spend, and how much context it may carry: the
2//! engine's ceilings ([`SpendNode`]) and the deployment's own judgement
3//! ([`BudgetPolicy`]).
4//!
5//! # Two ceilings that look alike and are not
6//!
7//! `Spending` is about the bill, accumulated and checked against what the
8//! provider actually reported. `OutputTarget` is about the opposite problem —
9//! the model stopping short of the volume of work that was asked for. One ends
10//! a turn that has spent too much, the other prolongs a turn that has produced
11//! too little. They stay separate methods because merging them would let
12//! "write more" and "you have spent enough" argue with each other inside one
13//! verdict.
14//!
15//! # One count, one chain
16//!
17//! Every call is counted once, where it is routed: the router (or the meter
18//! that stands in for one) adds its usage to the [`SpendNode`] the call's
19//! [`UsageTap`](crate::interface::model::UsageTap) is charged to. That node is
20//! the turn the call belongs to; above it is the turn that delegated it, and
21//! above a root turn its goal (for a goal round) and its session; above a
22//! budgeted host sub-agent's turn, its task and then its session. A call
23//! spends into every node up the chain, and the engine's ceilings — a turn's,
24//! a goal's, a task's, a session's — are judged together: the next call may
25//! ask for no more than the tightest of them leaves ([`SpendNode::remaining`]).
26//!
27//! The engine counts [`Spend::counted_tokens`] — input not read from the cache,
28//! cache writes and output — against every ceiling and provider quota alike. A
29//! cache read is billed at a fraction of ordinary input, and leaving it out is
30//! what keeps a ceiling from moving with the cache hit rate. [`Spend`] keeps
31//! the four figures apart, so a [`BudgetPolicy`] that wants another reading
32//! has the parts; it is judged in addition to the engine's ceilings, never in
33//! their place.
34//!
35//! `ContextBudget` is neither: it is about the size of a single request, not
36//! the cost of the turn.
37
38use std::sync::atomic::{AtomicU64, Ordering};
39use std::sync::Arc;
40
41use crate::interface::scene::TokenBudget;
42
43/// What has been spent so far, as the provider reported it, kept apart by
44/// kind because each kind is priced differently.
45#[derive(
46    Debug,
47    Clone,
48    Copy,
49    PartialEq,
50    Eq,
51    Default,
52    serde::Serialize,
53    serde::Deserialize,
54    schemars::JsonSchema,
55)]
56pub struct Spend {
57    pub input_tokens: u64,
58    pub output_tokens: u64,
59    /// Tokens written into the prompt cache, and tokens read back from it.
60    #[serde(rename = "cache_creation_input_tokens")]
61    pub cache_creation_tokens: u64,
62    #[serde(rename = "cache_read_input_tokens")]
63    pub cache_read_tokens: u64,
64}
65
66impl Spend {
67    /// Input, cache writes and output: what every ceiling and quota of the
68    /// engine counts. Cache reads are left out.
69    pub fn counted_tokens(&self) -> u64 {
70        self.input_tokens
71            .saturating_add(self.cache_creation_tokens)
72            .saturating_add(self.output_tokens)
73    }
74
75    /// Every token the provider reported, cache reads included.
76    pub fn all_tokens(&self) -> u64 {
77        self.counted_tokens().saturating_add(self.cache_read_tokens)
78    }
79
80    /// As the four-field usage a turn reports, each figure held at
81    /// `u32::MAX`.
82    pub fn as_usage(&self) -> crate::interface::model::Usage {
83        let narrow = |n: u64| u32::try_from(n).unwrap_or(u32::MAX);
84        crate::interface::model::Usage {
85            input_tokens: narrow(self.input_tokens),
86            output_tokens: narrow(self.output_tokens),
87            cache_creation_input_tokens: narrow(self.cache_creation_tokens),
88            cache_read_input_tokens: narrow(self.cache_read_tokens),
89        }
90    }
91
92    /// Figure by figure, the larger of the two.
93    pub fn max(self, other: Self) -> Self {
94        Self {
95            input_tokens: self.input_tokens.max(other.input_tokens),
96            output_tokens: self.output_tokens.max(other.output_tokens),
97            cache_creation_tokens: self.cache_creation_tokens.max(other.cache_creation_tokens),
98            cache_read_tokens: self.cache_read_tokens.max(other.cache_read_tokens),
99        }
100    }
101}
102
103impl From<crate::interface::model::Usage> for Spend {
104    fn from(u: crate::interface::model::Usage) -> Self {
105        Self {
106            input_tokens: u.input_tokens as u64,
107            output_tokens: u.output_tokens as u64,
108            cache_creation_tokens: u.cache_creation_input_tokens as u64,
109            cache_read_tokens: u.cache_read_input_tokens as u64,
110        }
111    }
112}
113
114/// Whose ceiling a [`SpendNode`] holds.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)]
116#[serde(rename_all = "snake_case")]
117pub enum Scope {
118    Turn,
119    Goal,
120    Task,
121    Session,
122}
123
124impl Scope {
125    pub fn whose(self) -> &'static str {
126        match self {
127            Self::Turn => "this turn's",
128            Self::Goal => "the goal's",
129            Self::Task => "the task's",
130            Self::Session => "this session's",
131        }
132    }
133}
134
135/// What one turn, goal, task or session has spent and the engine's ceiling on
136/// it, with the node above it that it spends into as well.
137///
138/// A turn's own calls, those made on its side (compaction, memory, web
139/// extraction) and those of the delegates it started all spend into its node:
140/// a delegate's turn sits under the turn that started it, and keeps spending
141/// into it after that turn has ended. A root turn sits under its goal, for a
142/// goal round, and its session.
143#[derive(Debug)]
144pub struct SpendNode {
145    scope: Scope,
146    /// `0` is no ceiling.
147    limit: AtomicU64,
148    all: Tally,
149    delegated: Tally,
150    above: Option<Arc<SpendNode>>,
151    /// A delegate turn's own session, which it counts into without being
152    /// judged by: the chain it is judged by runs through the turn above it.
153    own_session: Option<Arc<SpendNode>>,
154}
155
156impl Default for SpendNode {
157    fn default() -> Self {
158        Self::turn(None, None)
159    }
160}
161
162impl SpendNode {
163    pub fn session(limit: Option<u64>) -> Self {
164        Self::node(Scope::Session, limit, None)
165    }
166
167    pub fn goal(limit: Option<u64>, session: Arc<SpendNode>) -> Self {
168        Self::node(Scope::Goal, limit, Some(session))
169    }
170
171    /// A host sub-agent's own ceiling. Never under a turn: a turn's
172    /// `delegated` counts only through the turns directly under it.
173    pub fn task(limit: Option<u64>, session: Arc<SpendNode>) -> Self {
174        Self::node(Scope::Task, limit, Some(session))
175    }
176
177    /// A root turn under its goal or session, or a delegate's under the
178    /// turn that started it.
179    pub fn turn(limit: Option<u64>, above: Option<Arc<SpendNode>>) -> Self {
180        Self::node(Scope::Turn, limit, above)
181    }
182
183    fn node(scope: Scope, limit: Option<u64>, above: Option<Arc<SpendNode>>) -> Self {
184        Self {
185            scope,
186            limit: AtomicU64::new(limit.unwrap_or(0)),
187            all: Tally::default(),
188            delegated: Tally::default(),
189            above,
190            own_session: None,
191        }
192    }
193
194    /// A delegate turn that also counts into `session`, its own.
195    pub fn counting_into(mut self, session: Arc<SpendNode>) -> Self {
196        self.own_session = Some(session);
197        self
198    }
199
200    pub fn scope(&self) -> Scope {
201        self.scope
202    }
203
204    pub fn limit(&self) -> Option<u64> {
205        Some(self.limit.load(Ordering::Relaxed)).filter(|&l| l > 0)
206    }
207
208    pub fn set_limit(&self, limit: Option<u64>) {
209        self.limit.store(limit.unwrap_or(0), Ordering::Relaxed);
210    }
211
212    /// One call, made by this node's agent or on its side.
213    pub fn add(&self, call: crate::interface::model::Usage) {
214        let call = Spend::from(call);
215        self.all.add(call);
216        if let Some(own) = &self.own_session {
217            own.all.add(call);
218        }
219        let mut delegated = self.scope == Scope::Turn;
220        let mut above = self.above.as_deref();
221        while let Some(node) = above {
222            node.all.add(call);
223            if delegated && node.scope == Scope::Turn {
224                node.delegated.add(call);
225            }
226            delegated &= node.scope == Scope::Turn;
227            above = node.above.as_deref();
228        }
229    }
230
231    /// This node, everything under it included.
232    pub fn read(&self) -> Spend {
233        self.all.read()
234    }
235
236    /// The part of a turn's [`Self::read`] its delegates spent.
237    pub fn delegated(&self) -> Spend {
238        self.delegated.read()
239    }
240
241    /// Start from what the session log recorded, before anything spends.
242    pub fn restore(&self, spent: Spend) {
243        self.all.set(spent);
244    }
245
246    /// The root turn and every delegate under it; for a node that is not a
247    /// turn, its own reading.
248    pub fn whole_turn(&self) -> Spend {
249        let mut turn = self;
250        while let Some(above) = turn.above.as_deref().filter(|a| a.scope == Scope::Turn) {
251            turn = above;
252        }
253        turn.read()
254    }
255
256    /// The nearest node up the chain, this one included, that is `scope`'s.
257    pub fn find(&self, scope: Scope) -> Option<&SpendNode> {
258        self.chain().find(|node| node.scope == scope)
259    }
260
261    fn chain(&self) -> impl Iterator<Item = &SpendNode> {
262        std::iter::successors(Some(self), |node| node.above.as_deref())
263    }
264
265    fn ceilings(&self) -> impl Iterator<Item = (Scope, u64, u64)> + '_ {
266        self.chain().filter_map(|node| {
267            let limit = node.limit()?;
268            Some((node.scope, limit, node.read().counted_tokens()))
269        })
270    }
271
272    /// What is left under the tightest ceiling up the chain, and whose it
273    /// is; `None` with no ceiling.
274    pub fn remaining(&self) -> Option<(Scope, Remaining)> {
275        self.ceilings()
276            .map(|(scope, limit, spent)| {
277                let tokens = limit.saturating_sub(spent);
278                (scope, Remaining { tokens, limit })
279            })
280            .min_by_key(|(_, left)| left.tokens)
281    }
282
283    /// Whether to keep spending under the ceilings up the chain: the first
284    /// one reached ends the turn, and the nearest one past 90% has the model
285    /// told to wrap up.
286    pub fn judge(&self) -> (Scope, Spending) {
287        let mut warned = None;
288        for (scope, limit, spent) in self.ceilings() {
289            if spent >= limit {
290                return (scope, Spending::Exhausted { limit });
291            }
292            if warned.is_none() && spent >= limit.saturating_mul(9) / 10 {
293                warned = Some((scope, limit));
294            }
295        }
296        match warned {
297            Some((scope, limit)) => (
298                scope,
299                Spending::Warn {
300                    reminder: format!(
301                        "<system-reminder>\n{} token budget is nearly exhausted. Keep your \
302                         response concise and wrap up.\n</system-reminder>",
303                        capitalized(scope.whose())
304                    ),
305                    limit,
306                },
307            ),
308            None => (Scope::Turn, Spending::WithinBudget),
309        }
310    }
311}
312
313fn capitalized(text: &str) -> String {
314    let mut chars = text.chars();
315    match chars.next() {
316        Some(first) => first.to_uppercase().chain(chars).collect(),
317        None => String::new(),
318    }
319}
320
321/// Why a turn ended `budget_exceeded`: whose ceiling was reached, for the
322/// turn's `message`.
323pub fn exhausted_message(scope: Scope, limit: u64) -> String {
324    format!("{} token budget of {limit} is used up", scope.whose())
325}
326
327#[derive(Debug, Default)]
328struct Tally {
329    input_tokens: AtomicU64,
330    output_tokens: AtomicU64,
331    cache_creation_tokens: AtomicU64,
332    cache_read_tokens: AtomicU64,
333}
334
335impl Tally {
336    fn add(&self, call: Spend) {
337        for (total, part) in [
338            (&self.input_tokens, call.input_tokens),
339            (&self.output_tokens, call.output_tokens),
340            (&self.cache_creation_tokens, call.cache_creation_tokens),
341            (&self.cache_read_tokens, call.cache_read_tokens),
342        ] {
343            total.fetch_add(part, Ordering::Relaxed);
344        }
345    }
346
347    fn set(&self, to: Spend) {
348        self.input_tokens.store(to.input_tokens, Ordering::Relaxed);
349        self.output_tokens
350            .store(to.output_tokens, Ordering::Relaxed);
351        self.cache_creation_tokens
352            .store(to.cache_creation_tokens, Ordering::Relaxed);
353        self.cache_read_tokens
354            .store(to.cache_read_tokens, Ordering::Relaxed);
355    }
356
357    fn read(&self) -> Spend {
358        Spend {
359            input_tokens: self.input_tokens.load(Ordering::Relaxed),
360            output_tokens: self.output_tokens.load(Ordering::Relaxed),
361            cache_creation_tokens: self.cache_creation_tokens.load(Ordering::Relaxed),
362            cache_read_tokens: self.cache_read_tokens.load(Ordering::Relaxed),
363        }
364    }
365}
366
367/// What is left under a ceiling before the next model call.
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
369pub struct Remaining {
370    pub tokens: u64,
371    pub limit: u64,
372}
373
374/// Whether the turn may keep spending.
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub enum Spending {
377    WithinBudget,
378    /// Close enough to say so. The turn continues.
379    Warn {
380        reminder: String,
381        /// The ceiling this was measured against, for the record the engine
382        /// keeps of budget enforcement.
383        limit: u64,
384    },
385    /// The turn ends, reporting `budget_exceeded`.
386    Exhausted {
387        limit: u64,
388    },
389}
390
391/// Progress toward an output-volume target.
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
393pub struct OutputProgress {
394    /// Output tokens accumulated across the turn.
395    pub accumulated: u64,
396    pub target: u64,
397    /// How many times the model has already been asked to keep going.
398    pub continuations: u32,
399    /// Output tokens from the call that just returned.
400    pub this_delta: u64,
401    /// Output tokens from the call before it.
402    pub last_delta: u64,
403}
404
405#[derive(Debug, Clone, PartialEq, Eq)]
406pub enum OutputTarget {
407    /// Enough, or not worth asking again. The turn ends normally.
408    Reached,
409    /// Say this and go around again.
410    KeepGoing { nudge: String },
411}
412
413/// How large a single request's context may get.
414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415pub struct ContextBudget {
416    /// Compact once the context passes this. `0` disables compaction.
417    pub compact_threshold: usize,
418    /// Rounds compaction keeps.
419    pub compact_keep_recent: usize,
420    /// A ceiling compaction is not allowed to leave the context above. `None`
421    /// is what the engine has always done — the threshold said when to start
422    /// compacting and nothing said when to stop trying.
423    pub hard_cap: Option<usize>,
424}
425
426/// A deployment's judgement of what a turn may spend and how much it may
427/// carry, on top of the engine's own ceilings.
428pub trait BudgetPolicy: Send + Sync {
429    /// After a model call, against the root turn's reading
430    /// ([`SpendNode::whole_turn`]) then. A turn the engine's ceilings
431    /// already ended does not ask.
432    fn on_usage(&self, _spend: &Spend) -> Spending {
433        Spending::WithinBudget
434    }
435
436    /// Before a model call, against the root turn's reading. The call is not
437    /// sent when less than [`MIN_CALL_TOKENS`] remain under this or any of
438    /// the engine's ceilings, and otherwise asks for no more output than the
439    /// tightest leaves. `None`: no ceiling of the policy's own.
440    fn remaining(&self, _spend: &Spend) -> Option<Remaining> {
441        None
442    }
443
444    /// When the model has stopped and a volume of output was asked for.
445    ///
446    /// Last of the three that can act on a reply cut off at `max_tokens`:
447    /// [`TurnPolicy::after_model_call`] can end the turn first,
448    /// [`RecoveryPolicy::on_early_stop`] can retry it with a higher limit
449    /// first, and a `Stop` hook that ends or sends back the turn comes first
450    /// too.
451    ///
452    /// [`TurnPolicy::after_model_call`]: crate::interface::turn_policy::TurnPolicy::after_model_call
453    /// [`RecoveryPolicy::on_early_stop`]: crate::interface::recovery_policy::RecoveryPolicy::on_early_stop
454    fn on_output_target(&self, _progress: &OutputProgress) -> OutputTarget {
455        OutputTarget::Reached
456    }
457
458    /// What the scene asked for, and what the deployment will actually allow.
459    fn context_budget(&self, scene: &TokenBudget) -> ContextBudget {
460        ContextBudget {
461            compact_threshold: scene.compact_threshold,
462            compact_keep_recent: scene.compact_keep_recent,
463            hard_cap: None,
464        }
465    }
466}
467
468/// Below this much remaining budget a model call is not sent.
469pub const MIN_CALL_TOKENS: u64 = 1024;
470
471/// The engine's own numbers for what a policy judges: the output target and
472/// the compaction settings. Its token ceilings are on the [`SpendNode`]s.
473#[derive(Default)]
474pub struct EngineBudget {
475    /// `settings.compaction`: over the scene's threshold and kept rounds when
476    /// set.
477    pub compact_threshold: Option<usize>,
478    pub compact_keep_recent: Option<usize>,
479}
480
481impl BudgetPolicy for EngineBudget {
482    fn on_output_target(&self, p: &OutputProgress) -> OutputTarget {
483        // 90% of the target counts as met, and three consecutive
484        // sub-500-token calls count as the model having run out of things to
485        // say rather than needing another nudge.
486        let met = (p.target as f64 * 0.9) as u64;
487        let diminishing = p.continuations >= 3 && p.this_delta < 500 && p.last_delta < 500;
488        if diminishing || p.accumulated >= met {
489            return OutputTarget::Reached;
490        }
491        let remaining = p.target.saturating_sub(p.accumulated);
492        OutputTarget::KeepGoing {
493            nudge: format!(
494                "\
495<system-reminder>
496Continue working. Used {}/{} output tokens ({} remaining).
497</system-reminder>",
498                p.accumulated, p.target, remaining
499            ),
500        }
501    }
502
503    fn context_budget(&self, scene: &TokenBudget) -> ContextBudget {
504        ContextBudget {
505            compact_threshold: self.compact_threshold.unwrap_or(scene.compact_threshold),
506            compact_keep_recent: self
507                .compact_keep_recent
508                .unwrap_or(scene.compact_keep_recent),
509            hard_cap: None,
510        }
511    }
512}
513
514/// A ceiling on request size, on top of whatever else a policy decides.
515///
516/// The second implementation, and the one the missing capability calls for: a
517/// deployment that has to guarantee it never sends a request past some size —
518/// a provider hard limit, a cost ceiling, a compliance rule — wraps its policy
519/// in this. A turn whose context is still above the cap after compaction ends
520/// rather than sending the request anyway.
521pub struct Capped<P> {
522    pub inner: P,
523    pub context_hard_cap: usize,
524}
525
526impl<P: BudgetPolicy> BudgetPolicy for Capped<P> {
527    fn on_usage(&self, spend: &Spend) -> Spending {
528        self.inner.on_usage(spend)
529    }
530
531    fn remaining(&self, spend: &Spend) -> Option<Remaining> {
532        self.inner.remaining(spend)
533    }
534
535    fn on_output_target(&self, progress: &OutputProgress) -> OutputTarget {
536        self.inner.on_output_target(progress)
537    }
538
539    fn context_budget(&self, scene: &TokenBudget) -> ContextBudget {
540        ContextBudget {
541            hard_cap: Some(self.context_hard_cap),
542            ..self.inner.context_budget(scene)
543        }
544    }
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550
551    fn engine() -> EngineBudget {
552        EngineBudget::default()
553    }
554
555    fn call(input: u32, output: u32) -> crate::interface::model::Usage {
556        crate::interface::model::Usage {
557            input_tokens: input,
558            output_tokens: output,
559            ..Default::default()
560        }
561    }
562
563    fn turn_capped(limit: u64) -> SpendNode {
564        SpendNode::turn(Some(limit), None)
565    }
566
567    #[test]
568    fn the_bill_warns_at_ninety_percent_and_stops_at_the_cap() {
569        let turn = turn_capped(1_000);
570        turn.add(call(800, 99));
571        assert_eq!(turn.judge(), (Scope::Turn, Spending::WithinBudget));
572        turn.add(call(0, 1));
573        assert!(matches!(turn.judge(), (Scope::Turn, Spending::Warn { .. })));
574        turn.add(call(0, 100));
575        assert_eq!(
576            turn.judge(),
577            (Scope::Turn, Spending::Exhausted { limit: 1_000 }),
578            "the check is `>=`; at the cap the turn is over, not one call later"
579        );
580    }
581
582    #[test]
583    fn what_remains_is_the_tightest_ceiling_up_the_chain() {
584        let session = Arc::new(SpendNode::session(Some(10_000)));
585        session.restore(Spend {
586            input_tokens: 7_000,
587            ..Default::default()
588        });
589        let goal = Arc::new(SpendNode::goal(Some(5_000), session.clone()));
590        let turn = Arc::new(SpendNode::turn(Some(4_000), Some(goal.clone())));
591        let delegate = SpendNode::turn(None, Some(turn.clone()));
592        delegate.add(call(1_000, 500));
593        assert_eq!(
594            delegate.remaining(),
595            Some((
596                Scope::Session,
597                Remaining {
598                    tokens: 1_500,
599                    limit: 10_000
600                }
601            ))
602        );
603        assert_eq!(goal.read().counted_tokens(), 1_500);
604        assert_eq!(turn.remaining().unwrap().1.tokens, 1_500);
605        session.set_limit(None);
606        assert_eq!(
607            delegate.remaining(),
608            Some((
609                Scope::Turn,
610                Remaining {
611                    tokens: 2_500,
612                    limit: 4_000
613                }
614            ))
615        );
616        assert_eq!(SpendNode::default().remaining(), None);
617    }
618
619    #[test]
620    fn a_ceiling_reached_anywhere_up_the_chain_ends_the_turn() {
621        let session = Arc::new(SpendNode::session(Some(1_000)));
622        let turn = SpendNode::turn(Some(1_000_000), Some(session.clone()));
623        turn.add(call(1_000, 0));
624        assert_eq!(
625            turn.judge(),
626            (Scope::Session, Spending::Exhausted { limit: 1_000 })
627        );
628        let next = SpendNode::turn(None, Some(session));
629        assert_eq!(next.remaining().unwrap().1.tokens, 0);
630    }
631
632    #[test]
633    fn delegates_spending_at_once_lose_nothing() {
634        let shared = Arc::new(turn_capped(40_000));
635        let usage = crate::interface::model::Usage {
636            input_tokens: 3,
637            output_tokens: 2,
638            cache_creation_input_tokens: 1,
639            cache_read_input_tokens: 7,
640        };
641        let spenders: Vec<_> = (0..8)
642            .map(|_| {
643                let shared = shared.clone();
644                std::thread::spawn(move || {
645                    for _ in 0..1_000 {
646                        shared.add(usage);
647                    }
648                })
649            })
650            .collect();
651        for spender in spenders {
652            spender.join().unwrap();
653        }
654        assert_eq!(
655            shared.read(),
656            Spend {
657                input_tokens: 24_000,
658                output_tokens: 16_000,
659                cache_creation_tokens: 8_000,
660                cache_read_tokens: 56_000,
661            }
662        );
663        assert_eq!(shared.judge().1, Spending::Exhausted { limit: 40_000 });
664    }
665
666    #[test]
667    fn a_delegates_call_is_spent_by_every_node_above_it_once() {
668        let session = Arc::new(SpendNode::session(None));
669        let root = Arc::new(SpendNode::turn(None, Some(session.clone())));
670        let child_session = Arc::new(SpendNode::session(None));
671        let child = Arc::new(
672            SpendNode::turn(None, Some(root.clone())).counting_into(child_session.clone()),
673        );
674        let grandchild = SpendNode::turn(None, Some(child.clone()));
675        root.add(call(1, 0));
676        child.add(call(10, 0));
677        grandchild.add(call(100, 0));
678        assert_eq!(root.read().input_tokens, 111);
679        assert_eq!(root.delegated().input_tokens, 110);
680        assert_eq!(child.read().input_tokens, 110);
681        assert_eq!(child.delegated().input_tokens, 100);
682        assert_eq!(grandchild.whole_turn().input_tokens, 111);
683        assert_eq!(session.read().input_tokens, 111);
684        assert_eq!(session.delegated().input_tokens, 0);
685        assert_eq!(child_session.read().input_tokens, 10);
686        assert_eq!(
687            grandchild.find(Scope::Session).unwrap().read().input_tokens,
688            111
689        );
690    }
691
692    #[test]
693    fn a_tasks_ceiling_is_its_own_and_its_calls_are_the_sessions() {
694        let session = Arc::new(SpendNode::session(Some(10_000)));
695        let budgeted = Arc::new(SpendNode::task(Some(3_000), session.clone()));
696        let sibling = SpendNode::turn(None, Some(session.clone()));
697        let child_session = Arc::new(SpendNode::session(None));
698        let turn =
699            SpendNode::turn(None, Some(budgeted.clone())).counting_into(child_session.clone());
700        turn.add(call(2_000, 500));
701        sibling.add(call(4_000, 0));
702        assert_eq!(budgeted.read().counted_tokens(), 2_500);
703        assert_eq!(session.read().counted_tokens(), 6_500);
704        assert_eq!(child_session.read().counted_tokens(), 2_500);
705        assert_eq!(budgeted.delegated(), Spend::default());
706        assert_eq!(session.delegated(), Spend::default());
707        assert_eq!(turn.whole_turn(), turn.read());
708        assert_eq!(
709            turn.remaining(),
710            Some((
711                Scope::Task,
712                Remaining {
713                    tokens: 500,
714                    limit: 3_000
715                }
716            ))
717        );
718        assert_eq!(
719            sibling.remaining().map(|(scope, _)| scope),
720            Some(Scope::Session)
721        );
722        turn.add(call(500, 0));
723        assert_eq!(
724            turn.judge(),
725            (Scope::Task, Spending::Exhausted { limit: 3_000 })
726        );
727        assert_eq!(sibling.judge().1, Spending::WithinBudget);
728        session.restore(Spend {
729            input_tokens: 9_900,
730            ..Default::default()
731        });
732        let fresh = SpendNode::task(Some(3_000), session);
733        assert_eq!(
734            fresh.remaining(),
735            Some((
736                Scope::Session,
737                Remaining {
738                    tokens: 100,
739                    limit: 10_000
740                }
741            )),
742            "a task's ceiling loosened its session's"
743        );
744    }
745
746    #[test]
747    fn no_ceiling_configured_means_none() {
748        let turn = SpendNode::default();
749        turn.add(call(u32::MAX, 0));
750        assert_eq!(turn.judge().1, Spending::WithinBudget);
751        assert_eq!(turn.remaining(), None);
752    }
753
754    /// The reading every ceiling and quota counts, and what it leaves out.
755    #[test]
756    fn a_cache_read_is_not_counted_and_a_cache_write_is() {
757        let spend = Spend {
758            input_tokens: 400,
759            output_tokens: 600,
760            cache_creation_tokens: 2_000,
761            cache_read_tokens: 30_000,
762        };
763        assert_eq!(spend.counted_tokens(), 3_000);
764        assert_eq!(spend.all_tokens(), 33_000);
765    }
766
767    /// A ceiling an operator set does not move with the cache hit rate, and a
768    /// policy that wants the cache counted has the parts.
769    #[test]
770    fn the_engines_ceiling_does_not_move_when_the_cache_fills() {
771        let turn = turn_capped(1_000);
772        turn.add(crate::interface::model::Usage {
773            input_tokens: 400,
774            output_tokens: 300,
775            cache_creation_input_tokens: 100,
776            cache_read_input_tokens: 90_000,
777        });
778        assert!(
779            matches!(turn.judge().1, Spending::WithinBudget),
780            "the cache moved a 1000-token ceiling that nobody asked to move"
781        );
782
783        struct CountsTheCache;
784        impl BudgetPolicy for CountsTheCache {
785            fn on_usage(&self, spend: &Spend) -> Spending {
786                if spend.all_tokens() >= 1_000 {
787                    Spending::Exhausted { limit: 1_000 }
788                } else {
789                    Spending::WithinBudget
790                }
791            }
792        }
793        assert_eq!(
794            CountsTheCache.on_usage(&turn.whole_turn()),
795            Spending::Exhausted { limit: 1_000 },
796            "the parts a policy needs to reach the other answer are not reachable"
797        );
798    }
799
800    #[test]
801    fn a_spend_is_written_with_the_wire_names_of_a_usage() {
802        let spend = Spend::from(crate::interface::model::Usage {
803            input_tokens: 11,
804            output_tokens: 7,
805            cache_creation_input_tokens: 5,
806            cache_read_input_tokens: 23,
807        });
808        assert_eq!(
809            serde_json::to_value(spend).unwrap(),
810            serde_json::to_value(spend.as_usage()).unwrap()
811        );
812    }
813
814    fn progress(accumulated: u64, continuations: u32, this: u64, last: u64) -> OutputProgress {
815        OutputProgress {
816            accumulated,
817            target: 100_000,
818            continuations,
819            this_delta: this,
820            last_delta: last,
821        }
822    }
823
824    #[test]
825    fn ninety_percent_of_the_output_target_counts_as_reached() {
826        let p = engine();
827        assert!(matches!(
828            p.on_output_target(&progress(89_000, 0, 1_000, 0)),
829            OutputTarget::KeepGoing { .. }
830        ));
831        assert_eq!(
832            p.on_output_target(&progress(90_000, 0, 1_000, 0)),
833            OutputTarget::Reached
834        );
835    }
836
837    /// The rule that stops the engine nagging a model that has nothing left
838    /// to add: three continuations *and* two consecutive small answers.
839    #[test]
840    fn diminishing_returns_take_all_three_conditions() {
841        let p = engine();
842        assert_eq!(
843            p.on_output_target(&progress(10_000, 3, 400, 400)),
844            OutputTarget::Reached
845        );
846        assert!(matches!(
847            p.on_output_target(&progress(10_000, 2, 400, 400)),
848            OutputTarget::KeepGoing { .. },
849        ),);
850        assert!(matches!(
851            p.on_output_target(&progress(10_000, 3, 600, 400)),
852            OutputTarget::KeepGoing { .. }
853        ));
854    }
855
856    /// There is no cap on how many times the model can be asked to continue.
857    /// A count alone never ends it — only the count together with two small
858    /// answers does.
859    #[test]
860    fn a_long_run_of_substantial_answers_keeps_going() {
861        assert!(matches!(
862            engine().on_output_target(&progress(10_000, 20, 1_000, 1_000)),
863            OutputTarget::KeepGoing { .. }
864        ));
865    }
866
867    #[test]
868    fn the_scene_decides_the_threshold_until_a_deployment_caps_it() {
869        let scene = TokenBudget {
870            compact_threshold: 150_000,
871            compact_keep_recent: 4,
872        };
873        let engine_only = EngineBudget::default().context_budget(&scene);
874        assert_eq!(engine_only.compact_threshold, 150_000);
875        assert_eq!(
876            engine_only.hard_cap, None,
877            "the shape of the gap this fills"
878        );
879
880        let capped = Capped {
881            inner: EngineBudget::default(),
882            context_hard_cap: 120_000,
883        }
884        .context_budget(&scene);
885        assert_eq!(capped.hard_cap, Some(120_000));
886        assert_eq!(
887            capped.compact_threshold, 150_000,
888            "a ceiling is not a trigger — the scene still says when to compact"
889        );
890    }
891
892    #[test]
893    fn the_settings_compaction_numbers_override_the_scenes_when_set() {
894        let scene = TokenBudget {
895            compact_threshold: 150_000,
896            compact_keep_recent: 20,
897        };
898        let configured = EngineBudget {
899            compact_threshold: Some(60_000),
900            compact_keep_recent: Some(4),
901        }
902        .context_budget(&scene);
903        assert_eq!(
904            (configured.compact_threshold, configured.compact_keep_recent),
905            (60_000, 4)
906        );
907
908        let half = EngineBudget {
909            compact_keep_recent: Some(4),
910            ..EngineBudget::default()
911        }
912        .context_budget(&scene);
913        assert_eq!(
914            (half.compact_threshold, half.compact_keep_recent),
915            (150_000, 4)
916        );
917    }
918}