submilli_engine/runtime/llm.rs
1//! The embedder-supplied seam for `submilli:llm` — gated model calls from inside
2//! a Submilli program.
3//!
4//! `call`, `batch`, and `models()` all dispatch through the single
5//! embedder-provided [`LlmProvider`]: the actual HTTP, key resolution, retry, and
6//! provider-SDK dependencies live in the embedder (submilli-server), keeping this
7//! crate free of them — the same split [`crate::runtime::mcp::McpTransport`] makes.
8//!
9//! **Two taxonomies, answering different questions.** [`LlmCallError`] is the
10//! *dispatch-level* `Err`: the request never reached the model at all, or the
11//! transport died before any element ran. [`FailureReason`] is *per-element*: the
12//! request reached the model and that one element came back unusable or
13//! incomplete. Neither is a subset of the other, and a per-element failure must
14//! never be raised as an `Err` — a whole-batch `Err` would discard every element
15//! outcome including successes that were already billed, and would leave
16//! per-element budget reconciliation with nothing to reconcile against.
17//!
18//! **No prompt or completion text appears here.** Not in an error `Display`, not
19//! in a log line, not in a permission-check context, and not in an
20//! [`LlmFailure::message`]. The taxonomies carry the model name, the numbers, a
21//! status code, and a fixed classification string — never the payload. Provider
22//! response bodies are dropped at this boundary specifically: they carry
23//! completion fragments, request echoes, and account identifiers, so unlike
24//! [`McpCallError::Upstream`](crate::runtime::mcp::McpCallError::Upstream) no
25//! variant here interpolates one.
26
27use std::future::Future;
28use std::pin::Pin;
29
30pub use super::token_ledger::SharedTokenBudget;
31use super::token_ledger::{LedgerLimits, LedgerRefusal, TokenLedger};
32
33/// The single internal host module every `submilli:llm` call dispatches through.
34pub const LLM_MODULE_NAME: &str = "submilli:llm";
35
36/// Tokens one execution may spend across every model call it makes.
37pub const DEFAULT_MAX_EXECUTION_TOKENS: u64 = 1_000_000;
38/// Tokens every live execution may spend between them.
39pub const DEFAULT_MAX_ALL_EXECUTIONS_TOKENS: u64 = 20_000_000;
40/// Tokens one execution may hold as indeterminate (null-usage) reserve before
41/// further dispatch is refused. See [`LlmLimitKind::IndeterminateSpend`].
42pub const DEFAULT_MAX_HELD_TOKENS: u64 = 200_000;
43/// Output tokens reserved per prompt when the model declares no `outputReserve`.
44pub const DEFAULT_OUTPUT_CAP: u64 = 64_000;
45/// Elements in one `batch` slice.
46pub const DEFAULT_MAX_PROMPT_COUNT: u64 = 128;
47/// UTF-8 bytes in a single prompt element.
48pub const DEFAULT_MAX_PROMPT_BYTES: u64 = 256 * 1024;
49
50/// The ceilings a dispatch is checked against.
51///
52/// Token ceilings and prompt bounds live in one struct deliberately: an operator
53/// raising how much a program may spend almost always means to raise how much it
54/// may send, and splitting them across two config surfaces makes that two edits
55/// with a silent failure between them.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct LlmLimits {
58 /// Tokens one execution may spend in total.
59 pub per_execution_tokens: u64,
60 /// Tokens one execution may hold as indeterminate reserve before further
61 /// dispatch is refused.
62 pub max_held_tokens: u64,
63 /// Output tokens reserved per prompt when the model declares no
64 /// `outputReserve` of its own.
65 pub default_output_cap: u64,
66 /// Elements in one `batch` slice. Enforced at the stdlib boundary.
67 pub max_prompt_count: u64,
68 /// UTF-8 bytes in a single prompt element. Enforced at the stdlib boundary.
69 pub max_prompt_bytes: u64,
70}
71
72impl Default for LlmLimits {
73 fn default() -> Self {
74 Self {
75 per_execution_tokens: DEFAULT_MAX_EXECUTION_TOKENS,
76 max_held_tokens: DEFAULT_MAX_HELD_TOKENS,
77 default_output_cap: DEFAULT_OUTPUT_CAP,
78 max_prompt_count: DEFAULT_MAX_PROMPT_COUNT,
79 max_prompt_bytes: DEFAULT_MAX_PROMPT_BYTES,
80 }
81 }
82}
83
84/// Which token ceiling a refused dispatch ran into. Carries the numbers, never
85/// the prompts — the same rule
86/// [`SessionKvLimitKind`](crate::runtime::session_kv::SessionKvLimitKind)
87/// follows for values.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum LlmLimitKind {
90 /// This execution's own token ceiling.
91 PerExecutionTokens { requested: u64, limit: u64 },
92 /// The server-wide budget summed across every live execution. Distinct from
93 /// [`Self::PerExecutionTokens`] because it wants the opposite response: the
94 /// tokens in the way belong to other executions, so this execution making
95 /// fewer or shorter calls need not help.
96 AllExecutionsTokens { requested: u64, limit: u64 },
97 /// Cumulative reserve held for elements whose usage the provider never
98 /// reported. Token spend is monotonic — unlike session-KV bytes, a held
99 /// estimate is never superseded by a real number — so without this bound a
100 /// long-lived execution ratchets toward zero with no recovery. Distinct from
101 /// a genuine overspend so an operator can tell a null-usage storm from real
102 /// consumption.
103 IndeterminateSpend { held: u64, limit: u64 },
104}
105
106impl std::fmt::Display for LlmLimitKind {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 match self {
109 Self::PerExecutionTokens { requested, limit } => write!(
110 f,
111 "execution token budget: {requested} tokens exceeds the {limit} this execution \
112 may spend — use fewer or shorter calls, or split the work across executions"
113 ),
114 Self::AllExecutionsTokens { requested, limit } => write!(
115 f,
116 "server token budget: {requested} tokens exceeds the {limit} allowed across all \
117 live executions — this execution's own spend is not what is in the way, so \
118 using fewer or shorter calls need not help; the operator raises the budget \
119 with `--max-llm-tokens`"
120 ),
121 // No CLI rung names this ceiling: `max_held_tokens` is set by the
122 // embedder, unlike the two above. Saying otherwise would send an
123 // operator looking for a flag that does not exist, so the advice is
124 // the action they can actually take.
125 Self::IndeterminateSpend { held, limit } => write!(
126 f,
127 "indeterminate spend ceiling reached: {held} tokens are held for calls the \
128 provider never reported usage for, exceeding the {limit} allowed — this is \
129 unreported spend, not measured consumption; start a new execution, and if it \
130 recurs the provider is not reporting usage and the operator should raise the \
131 held-token ceiling in the server configuration"
132 ),
133 }
134 }
135}
136
137/// Why a model *dispatch* failed — the request never reached the model, or the
138/// transport died before any element ran.
139///
140/// Reserved for dispatch-level failure only. A model that answered and produced
141/// an unusable or incomplete element reports that in [`LlmOutcome`]'s failure
142/// arm, never here: returning `Err` for one bad element would throw away the
143/// sibling elements that did succeed.
144///
145/// Every variant names the model it was dispatched at and the fix the caller can
146/// act on. None carries prompt or completion text.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum LlmCallError {
149 /// No [`LlmProvider`] is wired into the runtime, so nothing can dispatch.
150 /// The pure-interpreter path leaves the provider `None`, and this is the
151 /// catchable configuration error a script sees there.
152 NotConfigured { model: String },
153 /// The model name is not one the provider serves. `available` lists what it
154 /// does serve, so the message can name the alternatives rather than only the
155 /// rejection.
156 UnknownModel {
157 model: String,
158 available: Vec<String>,
159 },
160 /// A token ceiling cannot cover this dispatch. Charged before any element
161 /// ran, so nothing was billed.
162 ///
163 /// `limit_kind` carries which ceiling refused, because the three want
164 /// different responses and a message that reads the same for all of them
165 /// sends a caller to shrink work that was never what filled the budget.
166 BudgetExceeded {
167 model: String,
168 limit_kind: LlmLimitKind,
169 },
170 /// The prompt slice is outside the bounds the host accepts — too many
171 /// elements, or one element too large. Counted in elements and bytes, never
172 /// quoted.
173 PromptBoundsExceeded {
174 model: String,
175 limit_kind: PromptBoundKind,
176 actual: u64,
177 limit: u64,
178 },
179 /// The provider rejected the credential, or none was resolvable when the
180 /// provider was constructed. One variant covers both because the fix is the
181 /// same key — this is the `LoadAPIKeyError`-vs-`401` split collapsed at the
182 /// point where the caller can act on it.
183 Unauthorized { model: String },
184 /// The request never completed, and died before any element ran. A transport
185 /// failure *after* elements started belongs in [`FailureReason::Transport`]
186 /// on the affected elements instead.
187 ///
188 /// `detail` is a **fixed classification string** — "connection reset",
189 /// "dns lookup failed", "tls handshake failed". It is the one free-form field
190 /// in this taxonomy, and the no-payload rule binds it: never a provider response body, and
191 /// never a request echo. The precedent this trait otherwise mirrors does
192 /// interpolate a body
193 /// ([`McpCallError::Upstream`](crate::runtime::mcp::McpCallError::Upstream)
194 /// renders `HTTP {status}: {body}`); this one deliberately does not, because a
195 /// model provider's body carries completion fragments.
196 Transport { model: String, detail: String },
197}
198
199/// Which prompt bound a dispatch ran into. Carries the numbers, never the
200/// prompts — the same rule
201/// [`SessionKvLimitKind`](crate::runtime::session_kv::SessionKvLimitKind) follows
202/// for values.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub enum PromptBoundKind {
205 /// Elements in one `call` / `batch` slice.
206 PromptCount,
207 /// UTF-8 bytes of a single prompt element.
208 PromptBytes,
209}
210
211impl std::fmt::Display for PromptBoundKind {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 match self {
214 Self::PromptCount => write!(f, "prompts in one batch"),
215 Self::PromptBytes => write!(f, "bytes in a single prompt"),
216 }
217 }
218}
219
220impl std::fmt::Display for LlmCallError {
221 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222 match self {
223 Self::NotConfigured { model } => write!(
224 f,
225 "llm.call(\"{model}\"): no model provider is configured for this runtime — the \
226 operator wires one before model calls can dispatch"
227 ),
228 Self::UnknownModel { model, available } => {
229 write!(
230 f,
231 "llm.call(\"{model}\"): the provider does not serve that model — "
232 )?;
233 if available.is_empty() {
234 write!(
235 f,
236 "it serves none, so declare a model in the blueprint before calling"
237 )
238 } else {
239 write!(
240 f,
241 "call llm.models() and use one of: {}",
242 available.join(", ")
243 )
244 }
245 }
246 Self::BudgetExceeded { model, limit_kind } => {
247 write!(f, "llm.call(\"{model}\") exceeded the {limit_kind}")
248 }
249 Self::PromptBoundsExceeded {
250 model,
251 limit_kind,
252 actual,
253 limit,
254 } => write!(
255 f,
256 "llm.call(\"{model}\"): prompt bound exceeded: {actual} {limit_kind} exceeds the \
257 {limit} allowed — send fewer prompts per call, or shorten each one"
258 ),
259 Self::Unauthorized { model } => write!(
260 f,
261 "llm.call(\"{model}\"): the provider rejected the API credential, or none was \
262 available — the operator sets a valid key for this provider"
263 ),
264 Self::Transport { model, detail } => write!(
265 f,
266 "llm.call(\"{model}\"): transport error before any prompt ran: {detail} — no \
267 tokens were billed; retry the call"
268 ),
269 }
270 }
271}
272
273impl std::error::Error for LlmCallError {}
274
275impl LlmCallError {
276 /// The model this dispatch was aimed at. Every variant names one, so a caller
277 /// need not match to attribute the failure.
278 pub fn model(&self) -> &str {
279 match self {
280 Self::NotConfigured { model }
281 | Self::UnknownModel { model, .. }
282 | Self::BudgetExceeded { model, .. }
283 | Self::PromptBoundsExceeded { model, .. }
284 | Self::Unauthorized { model }
285 | Self::Transport { model, .. } => model,
286 }
287 }
288
289 /// Token-budget refusals become catchable `QuotaExceededError`s at the
290 /// stdlib boundary. Prompt size/count bounds remain `RangeError`s.
291 pub fn is_budget_exceeded(&self) -> bool {
292 matches!(self, Self::BudgetExceeded { .. })
293 }
294}
295
296/// Why one *element* of a dispatch is not a clean completion.
297///
298/// Per-element, and orthogonal to [`LlmCallError`]: the request did reach the
299/// model. Several of these still carry usable text on the [`LlmOutcome`] — a
300/// truncated or content-filtered completion is `ok: false` and has a partial
301/// answer worth reading.
302///
303/// A closed set of nine. It is what a guest branches on, so a provider that
304/// meets something it cannot place reports [`Self::Incomplete`] and puts the raw
305/// provider spelling in [`LlmFailure::finish_reason`] rather than widening this.
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
307pub enum FailureReason {
308 /// Hit the output-token ceiling mid-answer (`finishReason` of `length`). The
309 /// partial text is retained — that is the whole reason the failure arm has a
310 /// `text` field.
311 Truncated,
312 /// The provider's safety filter stopped or redacted the completion. Reached
313 /// from both directions: `generateText` resolves with a filtered result while
314 /// `generateObject` throws on the same input, and both normalize to here.
315 ContentFiltered,
316 /// The provider answered, but not with something usable: malformed output,
317 /// or output that ignored the requested schema. Distinct from
318 /// [`Self::Truncated`] — nothing was cut off, what arrived was wrong.
319 InvalidOutput,
320 /// The provider throttled this element (structurally, a 429). Honor any
321 /// reported retry-after before re-dispatching.
322 RateLimited,
323 /// The provider refused the request itself rather than failing to answer it:
324 /// a rejected credential, a malformed or oversized request, or a prompt that
325 /// does not fit the model's context window. These share an arm because they
326 /// share a shape — the request as sent will never succeed, so retrying it
327 /// unchanged cannot help.
328 RequestRejected,
329 /// The provider was reachable but could not serve the request (structurally,
330 /// a 5xx). Unlike [`Self::RequestRejected`] the request itself may be fine,
331 /// so the same bytes may succeed later.
332 ProviderUnavailable,
333 /// The connection failed for this element after dispatch had begun — no HTTP
334 /// status was ever observed. Sibling elements may still have succeeded.
335 Transport,
336 /// The element was abandoned before the model finished — deadline, shutdown,
337 /// or an aborted request. Classified separately from [`Self::Transport`]
338 /// because the cause is on this side, not the wire.
339 Cancelled,
340 /// The provider stopped for a reason this runtime does not classify. The raw
341 /// provider spelling travels in [`LlmFailure::finish_reason`] for diagnosis.
342 Incomplete,
343}
344
345impl FailureReason {
346 /// The stable kebab-case spelling. This is the wire form: it is what any
347 /// guest-facing rendering uses, so it must not drift.
348 pub fn as_str(&self) -> &'static str {
349 match self {
350 Self::Truncated => "truncated",
351 Self::ContentFiltered => "content-filtered",
352 Self::InvalidOutput => "invalid-output",
353 Self::RateLimited => "rate-limited",
354 Self::RequestRejected => "request-rejected",
355 Self::ProviderUnavailable => "provider-unavailable",
356 Self::Transport => "transport",
357 Self::Cancelled => "cancelled",
358 Self::Incomplete => "incomplete",
359 }
360 }
361
362 /// A fixed classification string for this reason, suitable as an
363 /// [`LlmFailure::message`] when a provider has nothing more specific that is
364 /// safe to say. Drawn from a closed vocabulary precisely so it cannot carry a
365 /// response body or completion fragment.
366 pub fn default_message(&self) -> &'static str {
367 match self {
368 Self::Truncated => "the model stopped at the output token cap",
369 Self::ContentFiltered => "the provider's safety filter stopped the completion",
370 Self::InvalidOutput => "the model returned output that did not match the request",
371 Self::RateLimited => "the provider throttled this request",
372 Self::RequestRejected => "the provider refused the request as sent",
373 Self::ProviderUnavailable => "the provider could not serve this request",
374 Self::Transport => "the connection failed before a response arrived",
375 Self::Cancelled => "the request was abandoned before the model finished",
376 Self::Incomplete => "the model stopped for an unclassified reason",
377 }
378 }
379
380 /// Whether re-dispatching the identical request could plausibly succeed.
381 ///
382 /// The default a provider starts from, not the last word: it may override
383 /// per element (see [`LlmFailure::retryable`]) when it knows better — a 429
384 /// carrying a retry-after is retryable, while one on an exhausted quota is
385 /// not.
386 pub fn retryable_by_default(&self) -> bool {
387 match self {
388 Self::RateLimited | Self::ProviderUnavailable | Self::Transport => true,
389 // The request as sent will not start succeeding, and a cancellation
390 // was someone's decision — retrying either is a guess, so the guest
391 // opts in rather than the runtime assuming.
392 Self::Truncated
393 | Self::ContentFiltered
394 | Self::InvalidOutput
395 | Self::RequestRejected
396 | Self::Cancelled
397 | Self::Incomplete => false,
398 }
399 }
400
401 /// Every reason, in the plan's declaration order. Kept so a mapper or a
402 /// guest-facing enumeration cannot silently omit one.
403 pub const ALL: [FailureReason; 9] = [
404 Self::Truncated,
405 Self::ContentFiltered,
406 Self::InvalidOutput,
407 Self::RateLimited,
408 Self::RequestRejected,
409 Self::ProviderUnavailable,
410 Self::Transport,
411 Self::Cancelled,
412 Self::Incomplete,
413 ];
414}
415
416impl std::fmt::Display for FailureReason {
417 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418 f.write_str(self.as_str())
419 }
420}
421
422/// The failure-arm payload of an [`LlmOutcome`]: everything that exists only
423/// when `ok` is false.
424///
425/// Held in an `Option` on the outcome rather than flattened into it, so the
426/// success arm *cannot* carry a `message`, a `retryable`, or a `status` — those
427/// fields are meaningless on a clean completion, and a flattened struct would
428/// have to invent values for them.
429#[derive(Debug, Clone, PartialEq, Eq)]
430pub struct LlmFailure {
431 /// The closed-set classification a guest branches on.
432 pub reason: FailureReason,
433 /// The degraded error string.
434 ///
435 /// This is the AI SDK's rule that an `error: unknown` becomes an
436 /// `errorText: string` at any serialization boundary — a guest cannot receive
437 /// a Rust error object, so it receives this. **The no-payload rule binds it absolutely: it is
438 /// a classification, never an echo.** No prompt, no completion fragment, and
439 /// no provider response body may reach it; provider bodies carry request
440 /// echoes and account identifiers, so they are dropped at this boundary.
441 /// [`FailureReason::default_message`] supplies a safe one.
442 pub message: String,
443 /// Whether re-dispatching the identical request could plausibly succeed.
444 /// Defaulted from [`FailureReason::retryable_by_default`] and overridable per
445 /// element, because a provider sometimes knows more than the class does.
446 pub retryable: bool,
447 /// The HTTP status, when one was observed. `None` is meaningful rather than
448 /// missing: a transport death never got a status, which is exactly what
449 /// distinguishes it from a provider that answered with an error.
450 pub status: Option<u16>,
451 /// The provider's own raw stop reason, verbatim, for diagnosis only.
452 ///
453 /// **Deliberately separate from [`Self::reason`].** `reason` is the closed
454 /// set a guest branches on; this is an open string that varies per provider
455 /// and per SDK version. Folding them together would either force the closed
456 /// set to grow with every provider quirk or silently discard the detail that
457 /// makes an unclassified stop diagnosable.
458 pub finish_reason: Option<String>,
459 /// Refused by this host's own configuration or network policy before the provider
460 /// was reached, rather than answered by it. Not part of what a guest sees: the call
461 /// log records such a failure as kind `local`, so a replay does not serve it.
462 pub local: bool,
463}
464
465impl LlmFailure {
466 /// A failure of this class carrying this classification message. `retryable`
467 /// starts from the reason's default; `status` and `finish_reason` start
468 /// absent.
469 pub fn new(reason: FailureReason, message: impl Into<String>) -> Self {
470 Self {
471 reason,
472 message: message.into(),
473 retryable: reason.retryable_by_default(),
474 status: None,
475 finish_reason: None,
476 local: false,
477 }
478 }
479
480 /// Override the class default when the provider knows better.
481 pub fn retryable(mut self, retryable: bool) -> Self {
482 self.retryable = retryable;
483 self
484 }
485
486 /// Record the observed HTTP status. Left absent when none was seen.
487 pub fn with_status(mut self, status: u16) -> Self {
488 self.status = Some(status);
489 self
490 }
491
492 /// Mark the failure as this host's own refusal; see [`Self::local`].
493 pub fn refused_locally(mut self) -> Self {
494 self.local = true;
495 self
496 }
497
498 /// Record the provider's raw stop reason for diagnosis.
499 pub fn with_finish_reason(mut self, finish_reason: impl Into<String>) -> Self {
500 self.finish_reason = Some(finish_reason.into());
501 self
502 }
503}
504
505/// One element's result, positionally matched to the prompt that produced it.
506///
507/// A struct rather than an enum because success and failure are not disjoint
508/// here: a truncated or content-filtered completion is `ok: false` and *still
509/// carries usable text*, and a caller that wants the partial answer should not
510/// have to reach through an error arm to get it.
511///
512/// `ok: true` means the provider reported a **natural stop** — not merely that no
513/// error was raised. A completion that returned cleanly but stopped on `length`
514/// is `ok: false` with [`FailureReason::Truncated`]. That choice trades a class
515/// of silent wrong-answer bugs for one honest data-loss risk, which is why the
516/// failure arm keeps its text rather than discarding it.
517///
518/// The arms differ in more than a flag: `text` is always present on success and
519/// nullable on failure, and the [`LlmFailure`] payload exists only on failure.
520#[derive(Debug, Clone, PartialEq, Eq)]
521pub struct LlmOutcome {
522 /// The provider reported a natural stop for this element.
523 pub ok: bool,
524 /// The completion text.
525 ///
526 /// Always `Some` on the success arm. On the failure arm it is `string | null`:
527 /// `Some` — including `Some("")` — when the model produced text, and `None`
528 /// when it produced none at all. The two must not collapse, since telling
529 /// "empty because filtered" from "empty because the model said nothing" is
530 /// the distinction the `ok` rule exists to preserve.
531 pub text: Option<String>,
532 /// The failure payload. `Some` exactly when `!ok`.
533 pub failure: Option<LlmFailure>,
534 /// Tokens the provider reported for the prompt. `None` means
535 /// **indeterminate, not free** — the provider reported nothing, or reported
536 /// something non-finite. Never `Some(0)` as a stand-in for "unknown": a
537 /// throttled call may still have been billed, so a reconciler holds a
538 /// conservative reserve for `None` rather than releasing it.
539 ///
540 /// Nullable on *both* arms: a provider can resolve successfully with no usage
541 /// reported, so this cannot be confined to the failure arm.
542 pub input_tokens: Option<u64>,
543 /// Tokens the provider reported for the completion. Same
544 /// `None`-means-indeterminate rule as [`Self::input_tokens`].
545 pub output_tokens: Option<u64>,
546}
547
548impl LlmOutcome {
549 /// A natural stop with the given text. Usage is left indeterminate; a
550 /// provider that reports counts sets them explicitly.
551 pub fn success(text: impl Into<String>) -> Self {
552 Self {
553 ok: true,
554 text: Some(text.into()),
555 failure: None,
556 input_tokens: None,
557 output_tokens: None,
558 }
559 }
560
561 /// A non-clean element. `text` is whatever the model did produce: `Some` when
562 /// it produced any, `None` when it produced none — retained rather than
563 /// discarded, so a partial answer survives.
564 pub fn failed(failure: LlmFailure, text: Option<impl Into<String>>) -> Self {
565 Self {
566 ok: false,
567 text: text.map(Into::into),
568 failure: Some(failure),
569 input_tokens: None,
570 output_tokens: None,
571 }
572 }
573
574 /// Attach reported usage. A non-finite or unreported count stays `None`.
575 pub fn with_usage(mut self, input_tokens: Option<u64>, output_tokens: Option<u64>) -> Self {
576 self.input_tokens = input_tokens;
577 self.output_tokens = output_tokens;
578 self
579 }
580}
581
582/// A model the provider serves.
583///
584/// Every optional may legitimately be `None`: models are blueprint-declared, and
585/// an operator may declare a name without a description, a context window, or an
586/// output reserve. Absent means unknown, not zero.
587#[derive(Debug, Clone, PartialEq, Eq)]
588pub struct LlmModel {
589 pub name: String,
590 pub description: Option<String>,
591 pub context_window: Option<u64>,
592}
593
594impl LlmModel {
595 pub fn new(name: impl Into<String>) -> Self {
596 Self {
597 name: name.into(),
598 description: None,
599 context_window: None,
600 }
601 }
602}
603
604/// The embedder-provided model provider: resolves the credential, performs the
605/// completions, and reports what each one cost.
606///
607/// Object-safe boxed-future trait (rather than `async fn`) so the interpreter
608/// stays free of the embedder's async stack while still `await`-ing the call from
609/// within the async host function — the shape
610/// [`McpTransport`](crate::runtime::mcp::McpTransport) uses.
611///
612/// # Obligations on every implementor
613///
614/// These are *contractual*, not enforced by the interpreter. A second
615/// implementor inherits them:
616///
617/// 1. **Positional ordering.** The returned `Vec<LlmOutcome>` has exactly one
618/// element per input prompt, in input order. Element `i` is the outcome of
619/// `prompts[i]`, including when it failed.
620/// 2. **Bounded concurrency.** `call` takes a *slice* rather than a single
621/// prompt because the guest is single-threaded Wasm holding one host call at a
622/// time: fan-out cannot live above this boundary, so it lives below it. The
623/// implementor is responsible for bounding that concurrency — the interpreter
624/// does not limit it.
625/// 3. **Per-element failure never becomes `Err`.** One bad element is an
626/// `LlmOutcome` with `ok: false`. `Err(LlmCallError)` is only for dispatch
627/// that never ran, or a transport that died before any element started; an
628/// `Err` discards the siblings that did succeed and were billed.
629/// 4. **No prompt or completion text in errors.** Nothing an implementor puts in
630/// an [`LlmCallError`] may quote the payload.
631pub trait LlmProvider: Send + Sync {
632 fn call<'a>(
633 &'a self,
634 model: &'a str,
635 prompts: &'a [String],
636 schema_json: Option<&'a str>,
637 ) -> Pin<Box<dyn Future<Output = Result<Vec<LlmOutcome>, LlmCallError>> + Send + 'a>>;
638
639 /// Returns the locally declared model catalog without network I/O or other
640 /// side effects. The caller must inspect these names before it can check
641 /// policy for each model, so this runs before per-model authorization.
642 fn models<'a>(
643 &'a self,
644 ) -> Pin<Box<dyn Future<Output = Result<Vec<LlmModel>, LlmCallError>> + Send + 'a>>;
645
646 /// The output cap declared for one model, consulted *before* dispatch.
647 ///
648 /// Separate from [`Self::models`] because the reservation needs one model's
649 /// reserve on the hot path of every `call`; using the whole catalog here
650 /// would add unnecessary work to each dispatch. An implementor that already
651 /// holds its declarations (the blueprint case) answers from memory, and one
652 /// that does not should return `None` rather than block.
653 ///
654 /// `None` means the model declared no reserve, or the implementor cannot
655 /// answer cheaply; the caller then applies
656 /// [`LlmLimits::default_output_cap`]. Returning `None` is always safe, which
657 /// is why this defaults rather than being required of every implementor.
658 fn output_reserve(&self, _model: &str) -> Option<u64> {
659 None
660 }
661}
662
663/// One execution's token budget, reserving against its own ceiling and the
664/// server-wide one together.
665///
666/// Both reservations are taken together and both unwound if either fails, so a
667/// refused dispatch leaves neither counter charged.
668pub struct ExecutionTokenBudget {
669 limits: LlmLimits,
670 ledger: TokenLedger,
671}
672
673impl ExecutionTokenBudget {
674 pub fn new(limits: LlmLimits, aggregate: SharedTokenBudget) -> Self {
675 let ledger = TokenLedger::new(
676 LedgerLimits {
677 per_execution_tokens: limits.per_execution_tokens,
678 max_held_tokens: limits.max_held_tokens,
679 },
680 aggregate,
681 );
682 Self { limits, ledger }
683 }
684
685 pub fn limits(&self) -> LlmLimits {
686 self.limits
687 }
688
689 /// Tokens this execution currently holds against its ceiling.
690 pub fn used(&self) -> u64 {
691 self.ledger.used()
692 }
693
694 /// The part of [`Self::used`] held for unreported usage.
695 pub fn held(&self) -> u64 {
696 self.ledger.held()
697 }
698
699 /// Reserve `tokens` against this execution and the aggregate, before
700 /// dispatch.
701 ///
702 /// The caller passes the full reservation — `estimated_input_tokens +
703 /// (output_cap × prompt_count)`, via [`Self::reservation_for`] — because
704 /// reserving only input enforces the ceiling retroactively: output tokens
705 /// are typically the expensive half, and a small prompt can legitimately
706 /// produce a very large completion with nothing standing in the way.
707 pub fn reserve(&self, model: &str, tokens: u64) -> Result<(), LlmCallError> {
708 self.ledger.reserve(tokens).map_err(|refusal| {
709 let limit_kind = match refusal {
710 LedgerRefusal::HeldReserve { held, limit } => {
711 LlmLimitKind::IndeterminateSpend { held, limit }
712 }
713 LedgerRefusal::PerExecution { requested, limit } => {
714 LlmLimitKind::PerExecutionTokens { requested, limit }
715 }
716 LedgerRefusal::AllExecutions { requested, limit } => {
717 LlmLimitKind::AllExecutionsTokens { requested, limit }
718 }
719 };
720 LlmCallError::BudgetExceeded {
721 model: model.to_string(),
722 limit_kind,
723 }
724 })
725 }
726
727 /// The reservation a dispatch of `prompt_count` prompts needs:
728 /// `estimated_input_tokens + (output_cap × prompt_count)`.
729 ///
730 /// `output_cap` is the resolved per-model `outputReserve` when the model
731 /// declares one, and [`LlmLimits::default_output_cap`] otherwise. The same
732 /// cap is passed to the provider as the request's `maxOutputTokens`, which
733 /// makes the reservation an actual upper bound rather than an estimate.
734 pub fn reservation_for(
735 &self,
736 estimated_input_tokens: u64,
737 prompt_count: u64,
738 output_cap: Option<u64>,
739 ) -> u64 {
740 let cap = output_cap.unwrap_or(self.limits.default_output_cap);
741 estimated_input_tokens.saturating_add(cap.saturating_mul(prompt_count))
742 }
743
744 /// Reconcile a completed dispatch down from its `reserved` estimate to what
745 /// the provider actually reported.
746 ///
747 /// `reported` is the summed usage of the elements the provider gave counts
748 /// for; `indeterminate` is the reserve belonging to elements it reported
749 /// nothing for. The indeterminate part is **not** released — `None` means
750 /// indeterminate, not free, since a throttled call may still have been
751 /// billed — and is instead carried as held reserve, bounded by
752 /// [`LlmLimits::max_held_tokens`].
753 pub fn reconcile(&self, reserved: u64, reported: u64, indeterminate: u64) {
754 self.ledger.reconcile(reserved, reported, indeterminate);
755 }
756
757 /// Release a reservation for prompts that never dispatched — the remainder
758 /// of a batch abandoned partway.
759 pub fn release(&self, tokens: u64) {
760 self.reconcile(tokens, 0, 0);
761 }
762}
763
764#[cfg(test)]
765mod tests {
766 use std::sync::Arc;
767 use std::sync::atomic::{AtomicU64, Ordering};
768
769 use super::{
770 ExecutionTokenBudget, FailureReason, LlmCallError, LlmFailure, LlmLimitKind, LlmLimits,
771 LlmModel, LlmOutcome, LlmProvider, PromptBoundKind, SharedTokenBudget,
772 };
773
774 const MODEL: &str = "claude-sonnet-4";
775
776 /// An execution ends by having its budget holder dropped, not by reconciling
777 /// every reservation first. Without the release on drop the reservation of
778 /// every ended execution would be held forever and the server-wide budget
779 /// would ratchet to its cap, refusing every later execution.
780 #[test]
781 fn dropping_an_execution_budget_returns_its_tokens_to_the_aggregate() {
782 let aggregate = SharedTokenBudget::new(1_000);
783 {
784 let held = ExecutionTokenBudget::new(limits_with_cap(1_000), aggregate.clone());
785 held.reserve(MODEL, 1_000)
786 .expect("the first execution fits");
787 assert_eq!(aggregate.used(), 1_000);
788 }
789 assert_eq!(
790 aggregate.used(),
791 0,
792 "the ended execution released its tokens"
793 );
794
795 let next = ExecutionTokenBudget::new(limits_with_cap(1_000), aggregate);
796 next.reserve(MODEL, 1_000)
797 .expect("a later execution reuses the capacity");
798 }
799
800 fn limits_with_cap(per_execution_tokens: u64) -> LlmLimits {
801 LlmLimits {
802 per_execution_tokens,
803 ..LlmLimits::default()
804 }
805 }
806
807 /// A panicking execution must still return its tokens: an unrelated panic
808 /// while the lock was held would otherwise strand the whole reservation, and
809 /// the aggregate would ratchet exactly as it does without any release.
810 #[test]
811 fn a_poisoned_lock_still_releases_on_drop() {
812 let aggregate = SharedTokenBudget::new(1_000);
813 {
814 let held = ExecutionTokenBudget::new(limits_with_cap(1_000), aggregate.clone());
815 held.reserve(MODEL, 600).expect("reservation fits");
816
817 let poisoner = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
818 let _guard = held.ledger.lock_state().expect("lock");
819 panic!("poison the budget's lock");
820 }));
821 assert!(poisoner.is_err(), "the panic must have unwound");
822 assert!(held.ledger.state_is_poisoned(), "the lock must be poisoned");
823 }
824 assert_eq!(
825 aggregate.used(),
826 0,
827 "a poisoned execution still returns its tokens"
828 );
829 }
830
831 /// Two executions reserving at once must not both observe the same headroom.
832 /// With `fetch_add`-and-compensate both can read the pre-add value and both
833 /// conclude they fit; the CAS loop makes exactly one win.
834 #[test]
835 fn concurrent_reservations_cannot_both_claim_the_same_headroom() {
836 // Many rounds with many threads: a race that resolves correctly once may
837 // only have been serialized by luck, and two threads rarely collide
838 // inside the few instructions between the load and the store.
839 const THREADS: u64 = 16;
840 const ROUNDS: usize = 500;
841
842 let mut overspends = 0;
843 for _ in 0..ROUNDS {
844 // Headroom for exactly one of the racing reservations.
845 let aggregate = SharedTokenBudget::new(1_000);
846 let start = Arc::new(std::sync::Barrier::new(THREADS as usize));
847 let winners = Arc::new(AtomicU64::new(0));
848
849 let threads: Vec<_> = (0..THREADS)
850 .map(|_| {
851 let aggregate = aggregate.clone();
852 let start = Arc::clone(&start);
853 let winners = Arc::clone(&winners);
854 std::thread::spawn(move || {
855 let budget =
856 ExecutionTokenBudget::new(limits_with_cap(1_000), aggregate.clone());
857 // Release every thread into the reservation together.
858 start.wait();
859 if budget.reserve(MODEL, 1_000).is_ok() {
860 winners.fetch_add(1, Ordering::Relaxed);
861 }
862 // Hold every reservation until the round is over, so a
863 // win is never handed back before it is contested.
864 std::mem::forget(budget);
865 })
866 })
867 .collect();
868 for t in threads {
869 t.join().expect("reserving thread");
870 }
871
872 let winners = winners.load(Ordering::Relaxed);
873 assert_eq!(
874 winners, 1,
875 "exactly one of {THREADS} racing reservations may claim the only headroom"
876 );
877 if aggregate.used() > aggregate.cap() {
878 overspends += 1;
879 }
880 }
881 assert_eq!(
882 overspends, 0,
883 "the aggregate was overdrawn in {overspends}/{ROUNDS} rounds"
884 );
885 }
886
887 /// The two token ceilings refuse for opposite reasons and want opposite
888 /// responses: make fewer or shorter calls, versus wait or ask an operator. A
889 /// message that reads the same for both sends a program — or the model
890 /// writing it — to shrink work that was never what filled the budget.
891 #[test]
892 fn the_per_execution_and_server_wide_token_limits_name_different_fixes() {
893 let roomy = SharedTokenBudget::new(u64::MAX);
894 let own = ExecutionTokenBudget::new(limits_with_cap(100), roomy)
895 .reserve(MODEL, 500)
896 .expect_err("over this execution's own ceiling")
897 .to_string();
898
899 // An aggregate with no headroom left by another execution, so this one is
900 // refused without ever approaching its own per-execution ceiling.
901 let aggregate = SharedTokenBudget::new(100);
902 let neighbour = ExecutionTokenBudget::new(limits_with_cap(u64::MAX), aggregate.clone());
903 neighbour.reserve(MODEL, 100).expect("neighbour fits");
904 let shared = ExecutionTokenBudget::new(limits_with_cap(u64::MAX), aggregate);
905 let server_wide = shared
906 .reserve(MODEL, 100)
907 .expect_err("over the server-wide budget")
908 .to_string();
909
910 assert_ne!(own, server_wide);
911 assert!(own.contains("this execution may spend"), "{own}");
912 assert!(own.contains("use fewer or shorter calls"), "{own}");
913 assert!(
914 !own.contains("--max-llm-tokens"),
915 "the per-execution ceiling is not the operator's flag: {own}"
916 );
917 assert!(
918 server_wide.contains("across all live executions"),
919 "{server_wide}"
920 );
921 assert!(
922 server_wide.contains("is not what is in the way"),
923 "{server_wide}"
924 );
925 assert!(
926 server_wide.contains("--max-llm-tokens"),
927 "the aggregate refusal must name the flag that raises it: {server_wide}"
928 );
929 }
930
931 /// Each refusal must name the limit it hit and the ceiling, so an operator
932 /// reading a log knows which knob is in play.
933 #[test]
934 fn exceeding_either_ceiling_names_the_limit_and_the_ceiling_hit() {
935 let aggregate = SharedTokenBudget::new(u64::MAX);
936 let budget = ExecutionTokenBudget::new(limits_with_cap(64), aggregate);
937 let err = budget.reserve(MODEL, 4_096).expect_err("over the ceiling");
938 assert!(
939 matches!(
940 err,
941 LlmCallError::BudgetExceeded {
942 limit_kind: LlmLimitKind::PerExecutionTokens { .. },
943 ..
944 }
945 ),
946 "{err:?}"
947 );
948 let rendered = err.to_string();
949 assert!(rendered.contains(MODEL), "{rendered}");
950 assert!(rendered.contains("4096"), "the request: {rendered}");
951 assert!(rendered.contains("64"), "the ceiling: {rendered}");
952 }
953
954 /// a budget refusal carries the numbers, never the payload.
955 #[test]
956 fn no_budget_error_display_leaks_prompt_text() {
957 const SECRET: &str = "the patient's diagnosis is";
958 let aggregate = SharedTokenBudget::new(10);
959 let neighbour = ExecutionTokenBudget::new(limits_with_cap(u64::MAX), aggregate.clone());
960 neighbour.reserve(MODEL, 10).expect("neighbour fits");
961
962 let rendered: Vec<String> = [
963 ExecutionTokenBudget::new(limits_with_cap(1), SharedTokenBudget::new(u64::MAX))
964 .reserve(MODEL, 900)
965 .expect_err("per-execution"),
966 ExecutionTokenBudget::new(limits_with_cap(u64::MAX), aggregate)
967 .reserve(MODEL, 900)
968 .expect_err("server-wide"),
969 held_budget_at_its_ceiling()
970 .reserve(MODEL, 1)
971 .expect_err("indeterminate"),
972 ]
973 .iter()
974 .map(ToString::to_string)
975 .collect();
976
977 for message in &rendered {
978 assert!(!message.contains(SECRET), "{message}");
979 assert!(!message.contains("patient"), "{message}");
980 }
981 }
982
983 /// An execution whose held reserve is already over the bound.
984 fn held_budget_at_its_ceiling() -> ExecutionTokenBudget {
985 let budget = ExecutionTokenBudget::new(
986 LlmLimits {
987 per_execution_tokens: u64::MAX,
988 max_held_tokens: 100,
989 ..LlmLimits::default()
990 },
991 SharedTokenBudget::new(u64::MAX),
992 );
993 budget.reserve(MODEL, 500).expect("the dispatch fits");
994 // Every element came back with no usage reported, so the whole
995 // reservation is carried as held rather than released.
996 budget.reconcile(500, 0, 500);
997 budget
998 }
999
1000 /// A batch abandoned partway must not keep charging for the prompts that
1001 /// never dispatched.
1002 #[test]
1003 fn an_undispatched_remainder_is_released_after_a_partial_batch() {
1004 let aggregate = SharedTokenBudget::new(1_000);
1005 let budget = ExecutionTokenBudget::new(limits_with_cap(1_000), aggregate.clone());
1006 budget.reserve(MODEL, 900).expect("the whole batch fits");
1007
1008 // Four of ten prompts ran and reported 120 tokens; the rest never
1009 // dispatched, so their share of the reservation is released.
1010 budget.reconcile(900, 120, 0);
1011
1012 assert_eq!(budget.used(), 120);
1013 assert_eq!(aggregate.used(), 120, "the remainder returned");
1014 budget
1015 .reserve(MODEL, 800)
1016 .expect("the released capacity is reusable");
1017 }
1018
1019 /// reserving only input enforces the ceiling retroactively. A
1020 /// 100-token prompt can legitimately produce 100k output tokens, so the
1021 /// output cap must be part of the reservation and the refusal must land
1022 /// before dispatch, not after the provider has billed.
1023 #[test]
1024 fn the_reservation_covers_output_tokens_and_refuses_before_dispatch() {
1025 let aggregate = SharedTokenBudget::new(u64::MAX);
1026 let budget = ExecutionTokenBudget::new(
1027 LlmLimits {
1028 per_execution_tokens: 10_000,
1029 default_output_cap: 64_000,
1030 ..LlmLimits::default()
1031 },
1032 aggregate.clone(),
1033 );
1034
1035 // Input alone is trivially under the ceiling.
1036 let input_only = 100;
1037 assert!(input_only < budget.limits().per_execution_tokens);
1038
1039 let reservation = budget.reservation_for(input_only, 1, None);
1040 assert_eq!(
1041 reservation,
1042 100 + 64_000,
1043 "output cap is in the reservation"
1044 );
1045
1046 let err = budget
1047 .reserve(MODEL, reservation)
1048 .expect_err("refused before dispatch, not after the provider billed");
1049 assert!(
1050 matches!(
1051 err,
1052 LlmCallError::BudgetExceeded {
1053 limit_kind: LlmLimitKind::PerExecutionTokens { .. },
1054 ..
1055 }
1056 ),
1057 "{err:?}"
1058 );
1059 assert_eq!(budget.used(), 0, "a refused dispatch charges nothing");
1060 assert_eq!(aggregate.used(), 0);
1061
1062 // The cap scales with the prompt count, and a model's own reserve wins
1063 // over the default.
1064 assert_eq!(budget.reservation_for(100, 4, None), 100 + 64_000 * 4);
1065 assert_eq!(budget.reservation_for(100, 4, Some(1_000)), 100 + 4_000);
1066 }
1067
1068 /// held reserve releases from the per-execution budget on teardown —
1069 /// that execution is over — but stays charged against the aggregate.
1070 /// Releasing it from the aggregate would let indeterminate spend escape the
1071 /// server-wide ceiling: N executions each under the per-execution ceiling
1072 /// could exceed the server-wide one without ever tripping it.
1073 #[test]
1074 fn a_held_reserve_commits_against_the_aggregate_and_releases_only_per_execution() {
1075 let aggregate = SharedTokenBudget::new(1_500);
1076 let limits = LlmLimits {
1077 per_execution_tokens: 400,
1078 max_held_tokens: 10_000,
1079 ..LlmLimits::default()
1080 };
1081
1082 // Three executions that each spend 400 tokens the provider never reports.
1083 for _ in 0..3 {
1084 let budget = ExecutionTokenBudget::new(limits, aggregate.clone());
1085 budget.reserve(MODEL, 400).expect("within its own ceiling");
1086 budget.reconcile(400, 0, 400);
1087 assert_eq!(budget.held(), 400);
1088 }
1089
1090 assert_eq!(
1091 aggregate.used(),
1092 1_200,
1093 "indeterminate spend stays charged against the aggregate after teardown"
1094 );
1095
1096 // A fourth execution, itself well under the per-execution ceiling, is
1097 // now refused by the server-wide ceiling it would otherwise have walked
1098 // straight past.
1099 let next = ExecutionTokenBudget::new(limits, aggregate);
1100 let err = next.reserve(MODEL, 400).expect_err("the aggregate refuses");
1101 assert!(
1102 matches!(
1103 err,
1104 LlmCallError::BudgetExceeded {
1105 limit_kind: LlmLimitKind::AllExecutionsTokens { .. },
1106 ..
1107 }
1108 ),
1109 "{err:?}"
1110 );
1111 }
1112
1113 /// Token spend is monotonic, so a held estimate is never superseded by a real
1114 /// number and a long-lived execution accumulating null usage would ratchet to
1115 /// zero with no recovery. The bound names *indeterminate spend*, distinctly
1116 /// from a genuine overspend, so an operator can tell a null-usage storm from
1117 /// real consumption.
1118 #[test]
1119 fn crossing_the_held_reserve_bound_is_distinguishable_from_a_genuine_overspend() {
1120 let held = held_budget_at_its_ceiling();
1121 let indeterminate = held
1122 .reserve(MODEL, 1)
1123 .expect_err("the held bound is crossed");
1124 assert!(
1125 matches!(
1126 indeterminate,
1127 LlmCallError::BudgetExceeded {
1128 limit_kind: LlmLimitKind::IndeterminateSpend { .. },
1129 ..
1130 }
1131 ),
1132 "{indeterminate:?}"
1133 );
1134
1135 let overspend =
1136 ExecutionTokenBudget::new(limits_with_cap(10), SharedTokenBudget::new(1_000))
1137 .reserve(MODEL, 900)
1138 .expect_err("a genuine overspend");
1139
1140 let indeterminate = indeterminate.to_string();
1141 let overspend = overspend.to_string();
1142 assert_ne!(indeterminate, overspend);
1143 assert!(
1144 indeterminate.contains("indeterminate spend ceiling reached"),
1145 "{indeterminate}"
1146 );
1147 assert!(
1148 indeterminate.contains("never reported usage"),
1149 "the operator must be able to tell unreported spend from measured: {indeterminate}"
1150 );
1151 assert!(
1152 !overspend.contains("indeterminate"),
1153 "a real overspend must not read as a null-usage storm: {overspend}"
1154 );
1155 }
1156
1157 /// A ceiling is something a program can catch and adapt to, so it reaches the
1158 /// guest as a catchable `QuotaExceededError`. A dispatch that failed for
1159 /// a reason retrying smaller cannot fix
1160 /// must not masquerade as one.
1161 #[test]
1162 fn only_quota_refusals_are_classified_as_quota_exceeded_errors() {
1163 for error in every_variant() {
1164 let expected = matches!(error, LlmCallError::BudgetExceeded { .. });
1165 assert_eq!(
1166 error.is_budget_exceeded(),
1167 expected,
1168 "{error:?} is misclassified for the guest boundary"
1169 );
1170 }
1171
1172 // Every token ceiling, not just the one in `every_variant`.
1173 for limit_kind in [
1174 LlmLimitKind::PerExecutionTokens {
1175 requested: 2,
1176 limit: 1,
1177 },
1178 LlmLimitKind::AllExecutionsTokens {
1179 requested: 2,
1180 limit: 1,
1181 },
1182 LlmLimitKind::IndeterminateSpend { held: 2, limit: 1 },
1183 ] {
1184 let error = LlmCallError::BudgetExceeded {
1185 model: MODEL.to_string(),
1186 limit_kind,
1187 };
1188 assert!(error.is_budget_exceeded(), "{error:?}");
1189 }
1190 }
1191
1192 /// The prompt bounds U4 enforces live alongside the token ceilings so an
1193 /// operator raising one raises the other in one place.
1194 #[test]
1195 fn default_limits_carry_both_token_ceilings_and_prompt_bounds() {
1196 let limits = LlmLimits::default();
1197 assert_eq!(limits.max_prompt_count, 128);
1198 assert_eq!(limits.max_prompt_bytes, 256 * 1024);
1199 assert_eq!(
1200 limits.per_execution_tokens,
1201 super::DEFAULT_MAX_EXECUTION_TOKENS
1202 );
1203 assert_eq!(limits.default_output_cap, super::DEFAULT_OUTPUT_CAP);
1204 }
1205
1206 /// One of every dispatch-level variant, so a new variant fails to compile
1207 /// here until it is added.
1208 fn every_variant() -> Vec<LlmCallError> {
1209 vec![
1210 LlmCallError::NotConfigured {
1211 model: MODEL.to_string(),
1212 },
1213 LlmCallError::UnknownModel {
1214 model: MODEL.to_string(),
1215 available: vec!["claude-haiku-4".to_string()],
1216 },
1217 LlmCallError::BudgetExceeded {
1218 model: MODEL.to_string(),
1219 limit_kind: LlmLimitKind::PerExecutionTokens {
1220 requested: 4_000,
1221 limit: 120,
1222 },
1223 },
1224 LlmCallError::PromptBoundsExceeded {
1225 model: MODEL.to_string(),
1226 limit_kind: PromptBoundKind::PromptCount,
1227 actual: 64,
1228 limit: 32,
1229 },
1230 LlmCallError::Unauthorized {
1231 model: MODEL.to_string(),
1232 },
1233 LlmCallError::Transport {
1234 model: MODEL.to_string(),
1235 detail: "connection reset".to_string(),
1236 },
1237 ]
1238 }
1239
1240 #[test]
1241 fn six_dispatch_variants_each_name_the_model_and_a_distinct_fix() {
1242 let variants = every_variant();
1243 assert_eq!(variants.len(), 6, "LlmCallError has six dispatch variants");
1244
1245 let mut fixes: Vec<String> = Vec::new();
1246 for err in &variants {
1247 let rendered = err.to_string();
1248 assert!(
1249 rendered.contains(MODEL),
1250 "variant must name the model: {rendered}"
1251 );
1252 assert_eq!(err.model(), MODEL);
1253 let (_, fix) = rendered.split_once(" — ").unwrap_or_else(|| {
1254 panic!("variant must suggest a fix after an em dash: {rendered}")
1255 });
1256 assert!(!fix.trim().is_empty(), "empty fix: {rendered}");
1257 fixes.push(fix.to_string());
1258 }
1259
1260 // Distinct fixes: a shared message would tell the caller nothing about
1261 // which of the six they hit.
1262 let mut sorted = fixes.clone();
1263 sorted.sort();
1264 sorted.dedup();
1265 assert_eq!(
1266 sorted.len(),
1267 fixes.len(),
1268 "each variant needs its own fix: {fixes:?}"
1269 );
1270 }
1271
1272 /// no prompt or completion text may reach an error `Display`.
1273 #[test]
1274 fn no_dispatch_error_display_leaks_prompt_text() {
1275 const SECRET_PROMPT: &str = "patient SSN is 000-00-0000";
1276 const SECRET_COMPLETION: &str = "the diagnosis is confidential";
1277
1278 for err in every_variant() {
1279 let rendered = err.to_string();
1280 assert!(
1281 !rendered.contains(SECRET_PROMPT),
1282 "prompt text leaked into Display: {rendered}"
1283 );
1284 assert!(
1285 !rendered.contains(SECRET_COMPLETION),
1286 "completion text leaked into Display: {rendered}"
1287 );
1288 }
1289
1290 // The only free-form field any variant carries is `Transport { detail }`,
1291 // which is a transport diagnostic and never built from a payload. Prove
1292 // no *other* variant has a construction path that could carry one by
1293 // showing the rendered set is otherwise fully determined by model name
1294 // and numbers.
1295 let bounded = LlmCallError::PromptBoundsExceeded {
1296 model: MODEL.to_string(),
1297 limit_kind: PromptBoundKind::PromptBytes,
1298 actual: 900_000,
1299 limit: 65_536,
1300 };
1301 let rendered = bounded.to_string();
1302 assert!(rendered.contains("900000") && rendered.contains("65536"));
1303 assert!(
1304 rendered.contains("bytes in a single prompt"),
1305 "bound kind must be named: {rendered}"
1306 );
1307 }
1308
1309 /// nine, in the plan's declaration order. The spellings are the wire
1310 /// form a guest branches on, so drift here is a guest-visible break.
1311 #[test]
1312 fn nine_failure_reasons_have_stable_kebab_case_spellings() {
1313 let spellings: Vec<&str> = FailureReason::ALL
1314 .iter()
1315 .map(FailureReason::as_str)
1316 .collect();
1317 assert_eq!(
1318 spellings,
1319 [
1320 "truncated",
1321 "content-filtered",
1322 "invalid-output",
1323 "rate-limited",
1324 "request-rejected",
1325 "provider-unavailable",
1326 "transport",
1327 "cancelled",
1328 "incomplete",
1329 ]
1330 );
1331 for reason in FailureReason::ALL {
1332 assert_eq!(reason.to_string(), reason.as_str());
1333 }
1334 }
1335
1336 /// `ok` keys off a natural stop, not off "didn't throw"; absent usage is
1337 /// `None`, never `Some(0)`; and the failure arm keeps partial text.
1338 #[test]
1339 fn truncated_outcome_is_not_ok_but_keeps_its_text_and_indeterminate_usage() {
1340 let partial = LlmOutcome::failed(
1341 LlmFailure::new(FailureReason::Truncated, "output token ceiling reached"),
1342 Some("the answer begins"),
1343 );
1344 assert!(!partial.ok, "a length stop is not a natural stop");
1345 assert_eq!(
1346 partial.text.as_deref(),
1347 Some("the answer begins"),
1348 "partial text is retained"
1349 );
1350 let failure = partial.failure.as_ref().expect("failure arm present");
1351 assert_eq!(failure.reason, FailureReason::Truncated);
1352 assert_eq!(
1353 partial.input_tokens, None,
1354 "unreported usage is indeterminate"
1355 );
1356 assert_eq!(partial.output_tokens, None);
1357
1358 let clean = LlmOutcome::success("done").with_usage(Some(12), Some(0));
1359 assert!(clean.ok);
1360 assert!(clean.failure.is_none(), "a natural stop carries no reason");
1361 assert_eq!(
1362 clean.output_tokens,
1363 Some(0),
1364 "a real zero is Some(0); only absence is None"
1365 );
1366 }
1367
1368 /// `text` is `string | null` on the failure arm specifically — a model
1369 /// that produced nothing is distinguishable from one that produced "".
1370 #[test]
1371 fn failure_text_is_nullable_and_distinct_from_empty() {
1372 let nothing = LlmOutcome::failed(
1373 LlmFailure::new(FailureReason::ContentFiltered, "filtered before any output"),
1374 None::<String>,
1375 );
1376 assert_eq!(nothing.text, None, "produced nothing at all");
1377
1378 let empty = LlmOutcome::failed(
1379 LlmFailure::new(
1380 FailureReason::ContentFiltered,
1381 "filtered after an empty turn",
1382 ),
1383 Some(""),
1384 );
1385 assert_eq!(empty.text.as_deref(), Some(""), "produced an empty string");
1386 assert_ne!(
1387 nothing.text, empty.text,
1388 "null and empty must not collapse — the whole point is telling \
1389 'empty because filtered' from 'empty because it said nothing'"
1390 );
1391 }
1392
1393 /// the failure arm carries `message`, `retryable`, and `status`, and the
1394 /// success arm structurally cannot.
1395 #[test]
1396 fn failure_arm_carries_message_retryable_and_nullable_status() {
1397 let throttled =
1398 LlmFailure::new(FailureReason::RateLimited, "provider throttled the request")
1399 .retryable(true)
1400 .with_status(429);
1401 assert_eq!(throttled.message, "provider throttled the request");
1402 assert!(throttled.retryable);
1403 assert_eq!(throttled.status, Some(429));
1404
1405 // `status: number | null` — a transport death has no HTTP status at all.
1406 // That absence is the classification: it is exactly what distinguishes a
1407 // dead connection from a provider that answered with an error.
1408 let dead = LlmFailure::new(
1409 FailureReason::Transport,
1410 "connection closed before response",
1411 );
1412 assert_eq!(dead.status, None);
1413
1414 // `retryable` defaults per class rather than uniformly: a dead connection
1415 // may succeed on the same bytes, while a refused request will not.
1416 assert!(dead.retryable, "transport is retryable by class");
1417 let refused = LlmFailure::new(FailureReason::RequestRejected, "request refused as sent");
1418 assert!(
1419 !refused.retryable,
1420 "a request the provider refused will not start succeeding unchanged"
1421 );
1422 // ...and the class default is a starting point, not the last word.
1423 assert!(
1424 !LlmFailure::new(FailureReason::RateLimited, "quota exhausted")
1425 .retryable(false)
1426 .retryable,
1427 "a provider that knows better overrides the class default"
1428 );
1429
1430 // Raw `finishReason` is a *diagnostic* field, separate from `reason`,
1431 // which is what guests branch on. They must not fold together.
1432 let truncated = LlmFailure::new(FailureReason::Truncated, "stopped at the output cap")
1433 .with_finish_reason("length");
1434 assert_eq!(truncated.reason, FailureReason::Truncated);
1435 assert_eq!(truncated.finish_reason.as_deref(), Some("length"));
1436
1437 // A provider reporting a stop reason we do not classify still surfaces the
1438 // raw string for diagnosis while `reason` stays in the closed set.
1439 let odd = LlmFailure::new(FailureReason::Incomplete, "unclassified stop")
1440 .with_finish_reason("surprise-reason");
1441 assert_eq!(odd.reason, FailureReason::Incomplete);
1442 assert_eq!(odd.finish_reason.as_deref(), Some("surprise-reason"));
1443 }
1444
1445 /// The retryable split follows the spike's structural classification: 429 and
1446 /// 5xx and a dead connection may succeed on the same bytes; everything else
1447 /// describes a request that will not start succeeding unchanged.
1448 #[test]
1449 fn retryable_defaults_split_transient_classes_from_terminal_ones() {
1450 let retryable: Vec<&str> = FailureReason::ALL
1451 .iter()
1452 .filter(|r| r.retryable_by_default())
1453 .map(FailureReason::as_str)
1454 .collect();
1455 assert_eq!(
1456 retryable,
1457 ["rate-limited", "provider-unavailable", "transport"]
1458 );
1459 }
1460
1461 /// unlike `McpCallError::Upstream`, which renders `HTTP {status}:
1462 /// {body}`, no variant here interpolates a provider response body — those
1463 /// carry completion fragments and request echoes.
1464 #[test]
1465 fn no_dispatch_error_display_leaks_a_provider_response_body() {
1466 const BODY: &str = r#"{"error":{"message":"your prompt was: summarize the memo"}}"#;
1467 // The only free-form field in the taxonomy. A provider impl is
1468 // contracted to pass a fixed classification string; prove that when it
1469 // does, nothing body-shaped can reach the rendered message.
1470 let classified = LlmCallError::Transport {
1471 model: MODEL.to_string(),
1472 detail: "connection reset".to_string(),
1473 };
1474 let rendered = classified.to_string();
1475 assert!(!rendered.contains(BODY));
1476 assert!(!rendered.contains("summarize the memo"));
1477 assert!(!rendered.contains('{'), "no JSON body shape: {rendered}");
1478 }
1479
1480 /// The degraded-error string: `message` follows the AI SDK's
1481 /// `error: unknown` → `errorText: string` rule, and carries no payload.
1482 #[test]
1483 fn failure_message_is_a_classification_not_a_payload_echo() {
1484 // Every message a provider impl is expected to produce is drawn from a
1485 // fixed classification vocabulary, so none can carry a response body.
1486 for reason in FailureReason::ALL {
1487 let failure = LlmFailure::new(reason, reason.default_message());
1488 assert!(
1489 !failure.message.is_empty(),
1490 "{reason} needs a message: it is the degraded error string"
1491 );
1492 assert!(
1493 !failure.message.contains("patient SSN"),
1494 "classification must not echo a payload: {}",
1495 failure.message
1496 );
1497 }
1498 }
1499
1500 #[test]
1501 fn llm_model_optionals_may_both_be_absent() {
1502 let declared = LlmModel::new("operator-declared");
1503 assert_eq!(declared.description, None);
1504 assert_eq!(declared.context_window, None);
1505 }
1506
1507 struct NoopProvider;
1508
1509 impl LlmProvider for NoopProvider {
1510 fn call<'a>(
1511 &'a self,
1512 model: &'a str,
1513 prompts: &'a [String],
1514 _schema_json: Option<&'a str>,
1515 ) -> std::pin::Pin<
1516 Box<
1517 dyn std::future::Future<Output = Result<Vec<LlmOutcome>, LlmCallError>> + Send + 'a,
1518 >,
1519 > {
1520 let n = prompts.len();
1521 let model = model.to_string();
1522 Box::pin(async move {
1523 if model.is_empty() {
1524 return Err(LlmCallError::NotConfigured { model });
1525 }
1526 // Obligation 1: one outcome per prompt, in order.
1527 Ok((0..n).map(|i| LlmOutcome::success(i.to_string())).collect())
1528 })
1529 }
1530
1531 fn models<'a>(
1532 &'a self,
1533 ) -> std::pin::Pin<
1534 Box<dyn std::future::Future<Output = Result<Vec<LlmModel>, LlmCallError>> + Send + 'a>,
1535 > {
1536 Box::pin(async { Ok(vec![LlmModel::new("noop")]) })
1537 }
1538 }
1539
1540 /// The trait must stay object-safe: the store holds it as `Arc<dyn ...>`.
1541 #[tokio::test]
1542 async fn provider_trait_is_object_safe_behind_arc() {
1543 let provider: Arc<dyn LlmProvider> = Arc::new(NoopProvider);
1544 let prompts = vec!["a".to_string(), "b".to_string()];
1545 let outcomes = provider
1546 .call(MODEL, &prompts, None)
1547 .await
1548 .expect("dispatch succeeds");
1549 assert_eq!(outcomes.len(), prompts.len(), "positional: one per prompt");
1550 assert_eq!(outcomes[1].text.as_deref(), Some("1"));
1551 assert_eq!(provider.models().await.unwrap()[0].name, "noop");
1552 }
1553
1554 #[tokio::test]
1555 async fn unconfigured_store_data_has_no_provider() {
1556 // The default runtime leaves the provider absent so an unconfigured
1557 // call reports a catchable configuration error rather than silently
1558 // succeeding — the `session_kv` rule.
1559 let data = crate::runtime::StoreData::with_tempdir().unwrap();
1560 assert!(data.llm_provider.is_none());
1561 }
1562}