Skip to content

Add UsdBudget: hard USD caps via llm-budget (feature-gated) - #3

Closed
Mattbusel wants to merge 1 commit into
joydle:mainfrom
tensorust-ai:usd-budget
Closed

Mattbusel wants to merge 1 commit into
joydle:mainfrom
tensorust-ai:usd-budget

Conversation

@Mattbusel

Copy link
Copy Markdown

Problem

InMemoryBudget counts tokens, but tokens are a leaky proxy for money:

  • 1M tokens on a haiku-class model and 1M on a frontier model differ by ~100x in cost
  • with_cache_read_percent approximates one provider's cache pricing; OpenAI (50%), Google (25%) and Anthropic (10%) all differ, and cache writes have their own rates

Teams running borg pipelines against real APIs need to say "this composition may not spend more than $0.25", not "…more than N tokens".

Change

New feature-gated module borg::usd_budget (feature usd-budget, optional dep llm-budget = "0.3"):

// Cap this composition tree at /usr/bin/bash.25 of claude-haiku-4-5 spend.
let budget = UsdBudget::new(0.25, claude-haiku-4-5)?;
let verdict = budget.record_usage(&TokenUsage::new(12_000, 400).with_cache(8_000, 0));

UsdBudget implements Budget over llm_budget::AgentBudget:

  • Real prices: record_usage prices the full usage split (fresh input, cache reads, cache writes, output) from a built-in table of 232 models; custom tables via with_price_table
  • Hard cap: enforced with compare-and-swap reservations inside AgentBudget; safe to share across parallel branches per the trait contract
  • Trait units: the token-denominated Budget trait reports micro-USD (1 USD = 1,000,000 units) — documented on the type
  • Worst-case fallback: record() (no usage split) prices every token at the model's output rate so an un-split charge can't silently underdraw
  • Fail fast: construction rejects unknown model ids instead of silently pricing $0
  • inner() exposes the wrapped AgentBudget for what the trait has no spelling for (audit log, kill switch, tier cascade)

Verification

  • 7 new unit tests (pricing math, cap exhaustion, overdraft verdict, parallel admission in micro-USD, unknown-model rejection, custom table)
  • cargo clippy -p borg --features usd-budget -- -D warnings clean
  • cargo test -p borg --features usd-budget,testing — all green. (The one doctest failure under --features usd-budget alone, ladder.rs needing the testing feature, fails identically on clean main.)

Disclosure: I'm the author of llm-budget. It's MIT-licensed, on crates.io, dependency-light, and its price table is maintained against provider pricing pages — happy to adjust the integration shape if you'd rather see e.g. a different unit denomination.

…get)

InMemoryBudget counts tokens, but tokens are a leaky proxy for money:
a million tokens differs by two orders of magnitude between haiku-class
and frontier models, and the flat cache-read percent only approximates
one provider's cache pricing.

UsdBudget implements Budget over llm_budget::AgentBudget: every call is
priced from a built-in table of 232 models (prompt-cache reads and
writes at their real rates) and booked against a hard USD cap enforced
with CAS reservations, with an audit log and a kill switch. The
token-denominated trait reports micro-USD.

- record_usage prices the full cache split at real rates
- record (no split) prices every token at the output rate, worst case
- construction rejects unknown models instead of silently pricing /usr/bin/bash
- 7 unit tests; clippy -D warnings clean; pre-existing ladder doctest
  failure (needs 'testing' feature) untouched

@batuhansk batuhansk left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, and for saying up front that you maintain llm-budget. Pricing by real cost instead of tokens is a fair point. We can't merge this version, though. Here's why:

CI

  • rustfmt fails: the cfg'd pub use in lib.rs sorts after terminal_guard, and two assert_eq!s in the tests need wrapping. Running cargo fmt --all fixes both.
  • The branch now conflicts with main in Cargo.lock, because #4 upgraded rmcp to 3.11 and cleaned up the workspace manifests. Rebase onto main and regenerate the lockfile. (cargo deny and cargo audit were failing on main before; #4 fixed both, so a rebased branch gets a clean run.)

Micro-USD units don't fit how borg uses Budget
Everything else that touches the trait still counts in tokens:

  • executor.rs:1298 admits parallel branches with admit_parallel(n, 1_000), which is 1k tokens. With this budget that turns into $0.001 per branch, so admission no longer means anything.
  • BudgetExhausted { needed, remaining } (agent.rs:191, executor.rs:1326) would show needed in tokens next to remaining in micro-USD.
  • SubBudget over a UsdBudget parent gives you remaining() = min(child tokens, parent micro-USD). That's also the split the docs suggest for compositions that mix models, so the suggested workaround doesn't work.

One price per budget
Every charge is priced at the single model you pass to the constructor. But borg compositions mix models (each agent has its own model(), and the ladder moves between tiers), and TokenUsage doesn't record which model a call used. So a tree that mixes haiku and a frontier model gets mispriced by the same ~100x this PR is trying to fix. Getting this right means changing the trait so the charge path carries the model. That's a bigger design question than one feature flag.

Dependency / API surface

  • This pins llm-budget = "0.3", but crates.io is already at 0.8.1. It also brings in thiserror 1.x, dashmap 5 and a second hashbrown.
  • borg's public API would expose llm_budget types: inner(), with_price_table(Arc<llm_budget::PriceTable>) and UsdBudgetError::Config(llm_budget::BudgetError). Every 0.x bump of llm-budget would then be a breaking change for borg.
  • borg's spend caps would depend on a price table maintained outside this repo.

Suggested path
Budget is a public trait, and nothing here needs borg internals. We'd prefer this live on your side, either behind a borg feature in llm-budget or as a small llm-budget-borg crate. We're glad to link it from our docs. If we end up making the budget path model-aware in borg itself (charging per model), we'll open an issue and would welcome your input there.

Minor, if you keep a version of this: PriceTable::builtin().clone() copies the whole table for every budget (an Arc would avoid that). Also, the code sample in the PR description lost its quoting (/usr/bin/bash.25, model name unquoted).

@Mattbusel

Copy link
Copy Markdown
Author

Thanks for the detailed read, that all makes sense. The unit mismatch with admit_parallel and SubBudget is a real problem I missed, and you're right that pricing per charge needs the model on the charge path, which is your call to make in the trait.

I'll move this to my side as a borg feature in llm-budget (on the current version, with the price table behind an Arc) and close this one. I'll ping you here when it's published so you can link it. If you open the model-aware budget issue, happy to help there.

@Mattbusel Mattbusel closed this Nov 18, 2026
@Mattbusel

Copy link
Copy Markdown
Author

Published as the borg feature in llm-budget 0.9.0: https://docs.rs/llm-budget/0.9.0/llm_budget/borg/index.html (guide: https://github.com/Mattbusel/llm-budget/blob/main/docs/borg.md)

It keeps borg's units as tokens. You pick a reference model, and each call is charged the reference-model tokens that cost the same as that call did on its own model. So admit_parallel(n, 1_000), BudgetExhausted and SubBudget keep their meaning, and a tree that mixes haiku and a frontier model is priced per call. borg isn't on crates.io, so a macro writes the two adapter types into the user's crate against their own borg, and no llm-budget types end up in borg's API. The price table sits behind an Arc.

Usage: llm_budget::borg_adapter!(); then ExecCtx::new(PricedLlm::shared(&pricing, llm), PricedBudget::in_memory(&pricing, 200_000), emitter, cancel, "session") with let pricing = Arc::new(BorgPricing::new("claude-sonnet-4-6")?);

The tests run it inside real borg v1.0.0 compositions: mixed-model trees, 64 parallel branches across threads, parallel admission, and sub-budget exhaustion.

If you open the model-aware budget issue, I'm happy to help there. Putting the model on the charge path would also let this drop the per-thread note it uses to match each charge to its call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants