API spend guard
Can a rules engine price unknown model usage honestly and stop a retry storm?
The question, and who it is for
A scheduled job can keep costing money even when no one is watching. The meaningful records are completed model usage, known prices and the point at which a budget stops additional work.
recohut_kit.spend_guard is the owner that stops scheduled jobs from silently burning model-API credits. The notebooks price each receipt from a caller-supplied table, leave missing usage unknown, catch a retry loop and open a breaker, flag spikes while staying quiet on ordinary weekday variation, project the day's burn against a budget, reset the breaker only for a named person, and write alerts plus a daily digest record.
The setting is the fictional twin-brand group (Den & Ember, Saddle & Grain). call-summary-writer summarises each inbound sales call. pulse-daily-digest writes the daily KPI digest. On Wednesday 2026-10-14 a webhook retry storm makes call-summary-writer re-summarise the same call every 30 seconds. The digest prompt has been growing slowly for weeks.
Notebooks 1 to 5 use synthetic receipts and make no model call. Notebook 6 is the only Codex live lane. The guard is a rules engine: no notebook in this set contains an agent, because no model chooses an action. Notebook 6's model only writes a summary.
The order table names a group finance lead, an on-call engineer, a reliability lead, a head of operations, a finance controller, and the job owner. Notebooks 1 to 5 are scripted, with 0 model calls. Notebook 6 is Codex live, with no call quota, usage recorded per call, and at most 5 calls this run. No browser checkpoint is declared.
How to run it
From the kit root (recohut-kit). The owner needs only the standard library. The codex extra is for notebook 6's CodexTextClient. ruff is for the set checker. Exact installed versions are in docs/api-spend-guard/versions.json. No dependency pin, pyproject.toml or project.yaml value is changed.
uv venv .venv-api-spend-guard
uv pip install --python .venv-api-spend-guard/bin/python -e '.[codex]' nbconvert ipykernel ruff
.venv-api-spend-guard/bin/python -m ipykernel install --user --name api-spend-guardThe kernel name is api-spend-guard. Run in README order with the agentcore-set-run skill, which retains every attempt, then run the checker plain and with --executed. The checker loads the shared tests/check_notebooks.py unchanged for the per-cell rules.
python3 ../recohut-skills/skills/agentcore-set-run/scripts/run_set.py --kit . --set api-spend-guard
.venv-api-spend-guard/bin/python scripts/check_api_spend_guard_notebooks.py
.venv-api-spend-guard/bin/python scripts/check_api_spend_guard_notebooks.py --executedspend_fixtures.py builds deterministic synthetic receipts shaped like recohut_kit.usage.UsageReceipt from catalogue.rng(...) (seed 20261020): weekday variation, about 2% failed-then-retried calls, planted 1.8%-a-day digest prompt growth, and the retry storm. It holds the illustrative price table and three fictional transcripts for notebook 6. No receipt in notebooks 1 to 5 came from a provider. Codex-credit calls in notebook 6 have no per-token price; their cost is reported as unknown.
Notebook 6 reads agents/travel-marketplace-agent/data/local/codex-auth in place and never copies or prints it. The only limit stated for that lane is the loop threshold being demonstrated. One metadata-only receipt per call is appended to docs/api-spend-guard/receipts/codex-usage-guarded.jsonl. No API-key provider and no AWS service is called anywhere in the set. Notebook 5 writes docs/api-spend-guard/daily-digest-2026-10-14.json (synthetic). Nothing else is written outside .runtime/ (ignored). No cloud resource is created, so no ledger cleanup applies.
Notebooks in order
| Notebook | What it does | Recorded output |
|---|---|---|
01-priced-receipts-and-unknown-usage.ipynb | Prices one day from a caller AUD table. Unknown usage stays unknown. A total that includes an unknown has no total. Rounding is once per line. | yes |
02-loop-detection-identical-requests.ipynb | Replays 2026-10-14. Five identical requests in 10 minutes fire at 10:02:00 local. Four repeats and ordinary retries stay quiet. | yes |
03-spend-baselines-and-spikes.ipynb | Fits hourly weekday and weekend baselines for call count and known spend. Ordinary hours stay quiet. | yes |
04-circuit-breaker-and-daily-burn.ipynb | Opens the breaker on the fifth identical request, refuses that job, and refuses automation resets. Projects burn against 15.00 AUD. | yes |
05-alerts-and-daily-digest-record.ipynb | Alerts carry receipt ids. A monitor-only guard sits beside the guarded day. The digest is a JSON record per job. | yes |
06-guarded-codex-calls.ipynb | Codex calls through the guard. Loop threshold 3 identical requests in 10 minutes. At most 5 calls, usage recorded per call. | yes |
Each digest header counts recorded outputs: 10, 6, 7, 10, 9 and 12.
What the recorded outputs show
Notebook 1 prints currency AUD; as of 2026-10-20, source illustrative prices, check the provider's pricing page, and the label illustrative prices; not a vendor quote and not reconciled billing. Rates: api_key/summary-large-v1 input 450 c/M, output 1800 c/M, cache read 45 c/M; api_key/digest-small-v1 input 60 c/M, output 240 c/M, cache read None. Totals: call-summary-writer 120 receipts, known cost 5.82 AUD, 2 unknown receipts (tokens_not_reported:input_tokens,output_tokens), complete=False, cost_minor=None. pulse-daily-digest 1 receipt, known cost 0.01 AUD, complete=True, cost_minor=1.
Notebook 2 prints 4523 ordinary receipts, 4448 distinct requests, 75 requests sent more than once, largest group 2, and on 150 repeated-request receipts fired 0; most seen in one window 2. The storm prints fired at 2026-10-14 10:02:00 AEDT local: 5 identical requests in 600s (threshold 5), rule loop.identical_request, observed 5, with five evidence ids. At 10:01:30 the same request prints fired=False; 4 identical requests in 600s (threshold 5).
Notebook 3 prints 10:00 medians: Monday 17.0 calls over 6 days; Tuesday 14, Wednesday 13, Thursday 17, Friday 11, Saturday 5 and Sunday 3, each over 7 days. Weekday 10:00 known spend is median 70.09 cents, threshold 163.12 cents. Ordinary history prints ordinary hours checked: 1128 over 47 days (6 Mondays) and hours flagged: 0.
Notebook 4 prints until 10:40: 21 calls admitted, 94 refused, with pulse-daily-digest closed and call-summary-writer open. The transition is closed -> open at 10:02:00 local, cause tripped: 5 identical requests in 600s (threshold 5), 94 refusals from call-summary-writer and 0 from other jobs. A further admit prints BreakerOpen for call-summary-writer, open since 2026-10-13T23:02:00+00:00 by loop.identical_request, with 5 evidence receipts and refusals counted on the breaker: 95.
Notebook 5 prints 4138 history receipts; baselines over 2026-09-21..2026-10-12. Drift windows are pinned 2026-09-01 to 2026-09-08 00:00 local and recent 2026-10-08 to 2026-10-14 23:59 local.
Notebook 6 prints Codex live available; access token valid for another 28 minutes and receipts recorded before this run: 10. The guard prints loop threshold 3 identical requests in 0:10:00 and price table: no Codex-credit price in this set; entries 0.
What is not shown
Each saved notebook has recorded outputs. The digest text stops mid-cell, so the later prints are absent here.
| Notebook | Outputs in the file | Blocks in the digest | Absent from the digest |
|---|---|---|---|
| 01 | 10 | 3 | The digest already names the six planted states, and the day total records tokens_not_reported:input_tokens,output_tokens; only the planted-state result table is missing from the excerpt. |
| 02 | 6 | 3 | The digest already names call AC-20261014-0007, every 30 seconds from 10:00 local, and a prior answer at 09:28:54; it does not print the unguarded storm cost. |
| 03 | 7 | 3 | The digest proof already states the storm-hour flags from 10:00 local and digest drift against a pinned week; those later prints are not in the excerpt. |
| 04 | 10 | 3 | The digest already includes the 1500-minor budget, the refused-reset attempts, the 10:40 Priya Natarajan reset in the proof, and the project_daily_burn import; it does not include the later result prints. |
| 05 | 9 | 2 | The digest already sets budget_minor=100 for pulse-daily-digest and the proof already describes the loop alert, drift warning, monitor-only comparison, digest fields, and rebuilt id; those result prints are not in the excerpt. |
| 06 | 12 | 2 | The digest already sets model gpt-6-luna and the proof already states that calls 1 to 3 reach Codex, the third trips the breaker, and attempts 4 and 5 are refused before sending; those call prints are not recorded in the excerpt. |
The README says notebooks 1 to 5 prove the planted cases, and leaves unverified real-history baselines, the thresholds as recommendations, cross-process persistence, host-side replay, and provider billing. Notebooks 1 to 5 prove the rules on the planted cases. Real baselines need the job's own history. The thresholds (5 identical requests in 10 minutes, 6 scaled MADs with floors of 15 calls and 50 cents, drift limit 1.25, a 15.00 AUD budget) are illustrative choices for this data. Breaker state, alerts and the digest stay in process; the owner does not persist them across processes. Refused calls stay refused, and the host must queue and replay work it still needs. The Codex lane is one client on one route. It does not show provider billing, and Codex-credit spend is not priced in money here.
Where it fits in the kit
The notebooks import the spend-guard owner. Notebook 6 also imports the Codex provider. Notebook 1 prices with price_receipt. The kit contains no price of its own. Receipt rows are UsageReceipt values. spend_fixtures reads examples/twin-brand-common/catalogue.py read-only.
| Notebook | Modules imported |
|---|---|
| 01 | recohut_kit.spend_guard, recohut_kit.usage, spend_fixtures |
| 02 | recohut_kit.spend_guard, spend_fixtures |
| 03 | recohut_kit.spend_guard, spend_fixtures |
| 04 | recohut_kit.spend_guard, spend_fixtures |
| 05 | recohut_kit.spend_guard, spend_fixtures |
| 06 | recohut_kit.spend_guard, recohut_kit.usage, recohut_kit.providers.codex, recohut_kit.providers.codex_auth, spend_fixtures |
How is this page?
Last updated on