rolling-cost-cap 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rolling_cost_cap-0.1.0/.github/workflows/ci.yml +20 -0
- rolling_cost_cap-0.1.0/.github/workflows/publish.yml +33 -0
- rolling_cost_cap-0.1.0/.gitignore +30 -0
- rolling_cost_cap-0.1.0/LICENSE +21 -0
- rolling_cost_cap-0.1.0/PKG-INFO +125 -0
- rolling_cost_cap-0.1.0/README.md +100 -0
- rolling_cost_cap-0.1.0/bench.py +28 -0
- rolling_cost_cap-0.1.0/pyproject.toml +47 -0
- rolling_cost_cap-0.1.0/src/rolling_cost_cap/__init__.py +166 -0
- rolling_cost_cap-0.1.0/src/rolling_cost_cap/py.typed +0 -0
- rolling_cost_cap-0.1.0/tests/test_cap.py +196 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
- run: pip install -e '.[dev]'
|
|
20
|
+
- run: pytest
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
build:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
steps:
|
|
11
|
+
- uses: actions/checkout@v4
|
|
12
|
+
- uses: actions/setup-python@v5
|
|
13
|
+
with:
|
|
14
|
+
python-version: "3.12"
|
|
15
|
+
- run: pip install build
|
|
16
|
+
- run: python -m build
|
|
17
|
+
- uses: actions/upload-artifact@v4
|
|
18
|
+
with:
|
|
19
|
+
name: dist
|
|
20
|
+
path: dist/
|
|
21
|
+
|
|
22
|
+
publish:
|
|
23
|
+
needs: build
|
|
24
|
+
runs-on: ubuntu-latest
|
|
25
|
+
environment: pypi
|
|
26
|
+
permissions:
|
|
27
|
+
id-token: write
|
|
28
|
+
steps:
|
|
29
|
+
- uses: actions/download-artifact@v4
|
|
30
|
+
with:
|
|
31
|
+
name: dist
|
|
32
|
+
path: dist/
|
|
33
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.so
|
|
5
|
+
.Python
|
|
6
|
+
.venv/
|
|
7
|
+
venv/
|
|
8
|
+
env/
|
|
9
|
+
*.egg-info/
|
|
10
|
+
dist/
|
|
11
|
+
build/
|
|
12
|
+
.pytest_cache/
|
|
13
|
+
.mypy_cache/
|
|
14
|
+
.ruff_cache/
|
|
15
|
+
*.whl
|
|
16
|
+
|
|
17
|
+
# Environment
|
|
18
|
+
.env
|
|
19
|
+
.env.*
|
|
20
|
+
!.env.example
|
|
21
|
+
|
|
22
|
+
# BMad artifacts
|
|
23
|
+
_bmad-output/
|
|
24
|
+
_bmad/
|
|
25
|
+
*_explained.md
|
|
26
|
+
CLAUDE.md
|
|
27
|
+
AGENTS.md
|
|
28
|
+
|
|
29
|
+
# OS
|
|
30
|
+
.DS_Store
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Corey Stevens
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rolling-cost-cap
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Runaway-cost circuit breaker for LLM and metered API calls: rolling-median anomaly detection, absolute per-call ceiling, monthly budget
|
|
5
|
+
Project-URL: Homepage, https://github.com/coreystevensdev/rolling-cost-cap
|
|
6
|
+
Project-URL: Issues, https://github.com/coreystevensdev/rolling-cost-cap/issues
|
|
7
|
+
Author: Corey Stevens
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: anthropic,budget,circuit-breaker,cost-control,llm,observability,openai
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# rolling-cost-cap
|
|
27
|
+
|
|
28
|
+
[](https://github.com/coreystevensdev/rolling-cost-cap/actions/workflows/ci.yml)
|
|
29
|
+
[](https://pypi.org/project/rolling-cost-cap/)
|
|
30
|
+
|
|
31
|
+
A runaway-cost circuit breaker for LLM and metered API calls. Judges every observed cost against three independent layers: a rolling-median anomaly cap, an absolute per-call ceiling, and a cumulative monthly budget. Zero dependencies, thread-safe, fully typed, 27 tests.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install rolling-cost-cap
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Problem
|
|
38
|
+
|
|
39
|
+
A single malformed request can make an LLM call cost 50x the usual amount: a prompt that triggers maximum-length output, a retry loop that compounds, a model misconfiguration that routes traffic to a tier 5x more expensive. Provider billing alerts fire hours later, and a fixed per-call dollar limit is either too loose to catch anomalies or too tight for legitimate heavy calls.
|
|
40
|
+
|
|
41
|
+
The core difficulty is that "expensive" is relative. $0.10 is an anomaly when your median call costs $0.02, and completely normal when it costs $0.08. A static threshold cannot express that.
|
|
42
|
+
|
|
43
|
+
## Solution
|
|
44
|
+
|
|
45
|
+
`CostCap` keeps a rolling window of recent call costs and trips when a new cost exceeds a multiple of the window's median. The median self-calibrates to your real traffic, so the same configuration works whether your calls cost fractions of a cent or dollars. Two fixed layers back it up: an absolute per-call ceiling that catches runaways before the median has warmed up, and a monthly budget that bounds total damage.
|
|
46
|
+
|
|
47
|
+
Decision precedence: absolute ceiling, then monthly budget, then rolling median. The median layer stays dormant until `min_samples` costs have been recorded, so one cheap first call cannot set a hair-trigger baseline. A median of zero (free calls) also keeps it dormant rather than tripping on the first nonzero cost.
|
|
48
|
+
|
|
49
|
+
This design was extracted from the cost-control layer of [InvoiceFlow](https://github.com/coreystevensdev/invoiceflow), where it runs in production as a post-call ceiling on Anthropic API spend.
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from rolling_cost_cap import CostCap
|
|
55
|
+
|
|
56
|
+
cap = CostCap(
|
|
57
|
+
multiplier=3.0, # trip when cost > 3x rolling median
|
|
58
|
+
window=50, # median over the last 50 calls
|
|
59
|
+
min_samples=5, # median layer dormant until 5 costs recorded
|
|
60
|
+
absolute_ceiling=1.00, # never allow a single call over $1
|
|
61
|
+
monthly_budget=25.00, # stop everything past $25/month
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
# After each API call, compute the observed cost and evaluate it
|
|
65
|
+
usage = response.usage
|
|
66
|
+
cost = (usage.input_tokens / 1e6) * 3.00 + (usage.output_tokens / 1e6) * 15.00
|
|
67
|
+
|
|
68
|
+
decision = cap.evaluate(cost)
|
|
69
|
+
if not decision.allowed:
|
|
70
|
+
match decision.trip:
|
|
71
|
+
case "absolute-ceiling":
|
|
72
|
+
alert(f"single call cost ${decision.observed:.2f}")
|
|
73
|
+
case "rolling-median":
|
|
74
|
+
alert(f"cost {decision.observed / decision.median:.0f}x the median")
|
|
75
|
+
case "monthly-budget":
|
|
76
|
+
disable_feature_until_next_month()
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`evaluate` judges the cost against the history that preceded it, then records it. Recording happens even when the decision trips, because the money is already spent and hiding real spend would make the monthly total under-count. For pre-call gating with an estimate, use `check`, which never records:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
if not cap.check(estimated_cost).allowed:
|
|
83
|
+
return err_budget_exceeded()
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The monthly window follows the wall clock (UTC by default) and resets on calendar-month rollover. Inject a `clock` callable to control time in tests:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
cap = CostCap(monthly_budget=25.0, clock=lambda: datetime(2026, 8, 1, tzinfo=timezone.utc))
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## API
|
|
93
|
+
|
|
94
|
+
| Member | Behavior |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `evaluate(cost) -> Decision` | Judge against prior history, then record. The common post-call path. |
|
|
97
|
+
| `check(cost) -> Decision` | Judge without recording. For pre-call estimates. |
|
|
98
|
+
| `record(cost) -> None` | Record without judging. For backfilling history. |
|
|
99
|
+
| `median` | Current rolling median, or `None` with empty history. |
|
|
100
|
+
| `monthly_spend` | Cumulative recorded spend this calendar month. |
|
|
101
|
+
| `reset()` | Clear window and monthly state. |
|
|
102
|
+
|
|
103
|
+
`Decision` is a frozen dataclass: `allowed`, `trip` (`"absolute-ceiling" | "monthly-budget" | "rolling-median" | None`), `observed`, `cap`, `median`, `monthly_spend`. All fields reflect state at decision time, before the cost is recorded.
|
|
104
|
+
|
|
105
|
+
Costs must be non-negative finite numbers; `NaN`, infinity, negatives, and non-numeric types raise instead of being silently ignored.
|
|
106
|
+
|
|
107
|
+
## Benchmarks
|
|
108
|
+
|
|
109
|
+
`evaluate` throughput on Apple Silicon (M-series), CPython 3.14, single thread, via `python bench.py`:
|
|
110
|
+
|
|
111
|
+
| Window | Throughput | Latency |
|
|
112
|
+
|---|---|---|
|
|
113
|
+
| 50 (default) | 72,800 ops/sec | 13.7 us |
|
|
114
|
+
| 200 | 45,400 ops/sec | 22.0 us |
|
|
115
|
+
| 1,000 | 10,700 ops/sec | 93.0 us |
|
|
116
|
+
|
|
117
|
+
The median is recomputed from a window snapshot on every decision, which is O(n log n). At realistic API-call rates (tens of calls per second) this is noise; the naive recompute was chosen over an incremental two-heap median because it is simpler to verify and the window is small.
|
|
118
|
+
|
|
119
|
+
## Known limitations
|
|
120
|
+
|
|
121
|
+
- **State is in-process.** Each worker, container, or serverless instance caps independently. A fleet of N workers can collectively spend up to N times the monthly budget. Acceptable as an anomaly detector and defense-in-depth; not a substitute for a provider-side billing cap.
|
|
122
|
+
- **The rolling median can drift under a slow ramp.** Costs that grow gradually (each within `multiplier` of the current median) raise the baseline without ever tripping. The absolute ceiling is the backstop for this case.
|
|
123
|
+
- **`evaluate` is post-call.** It detects that money was spent; it does not prevent the spend. Real prevention lives upstream: bounded retries, `max_tokens` limits, and `check` with estimates where estimation is feasible.
|
|
124
|
+
- **Monthly rollover is calendar-based and UTC by default.** There is no proration and no billing-cycle alignment beyond what a custom `clock` gives you.
|
|
125
|
+
- **No persistence.** A process restart forgets both the window and the month-to-date spend.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# rolling-cost-cap
|
|
2
|
+
|
|
3
|
+
[](https://github.com/coreystevensdev/rolling-cost-cap/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/rolling-cost-cap/)
|
|
5
|
+
|
|
6
|
+
A runaway-cost circuit breaker for LLM and metered API calls. Judges every observed cost against three independent layers: a rolling-median anomaly cap, an absolute per-call ceiling, and a cumulative monthly budget. Zero dependencies, thread-safe, fully typed, 27 tests.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install rolling-cost-cap
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Problem
|
|
13
|
+
|
|
14
|
+
A single malformed request can make an LLM call cost 50x the usual amount: a prompt that triggers maximum-length output, a retry loop that compounds, a model misconfiguration that routes traffic to a tier 5x more expensive. Provider billing alerts fire hours later, and a fixed per-call dollar limit is either too loose to catch anomalies or too tight for legitimate heavy calls.
|
|
15
|
+
|
|
16
|
+
The core difficulty is that "expensive" is relative. $0.10 is an anomaly when your median call costs $0.02, and completely normal when it costs $0.08. A static threshold cannot express that.
|
|
17
|
+
|
|
18
|
+
## Solution
|
|
19
|
+
|
|
20
|
+
`CostCap` keeps a rolling window of recent call costs and trips when a new cost exceeds a multiple of the window's median. The median self-calibrates to your real traffic, so the same configuration works whether your calls cost fractions of a cent or dollars. Two fixed layers back it up: an absolute per-call ceiling that catches runaways before the median has warmed up, and a monthly budget that bounds total damage.
|
|
21
|
+
|
|
22
|
+
Decision precedence: absolute ceiling, then monthly budget, then rolling median. The median layer stays dormant until `min_samples` costs have been recorded, so one cheap first call cannot set a hair-trigger baseline. A median of zero (free calls) also keeps it dormant rather than tripping on the first nonzero cost.
|
|
23
|
+
|
|
24
|
+
This design was extracted from the cost-control layer of [InvoiceFlow](https://github.com/coreystevensdev/invoiceflow), where it runs in production as a post-call ceiling on Anthropic API spend.
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from rolling_cost_cap import CostCap
|
|
30
|
+
|
|
31
|
+
cap = CostCap(
|
|
32
|
+
multiplier=3.0, # trip when cost > 3x rolling median
|
|
33
|
+
window=50, # median over the last 50 calls
|
|
34
|
+
min_samples=5, # median layer dormant until 5 costs recorded
|
|
35
|
+
absolute_ceiling=1.00, # never allow a single call over $1
|
|
36
|
+
monthly_budget=25.00, # stop everything past $25/month
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# After each API call, compute the observed cost and evaluate it
|
|
40
|
+
usage = response.usage
|
|
41
|
+
cost = (usage.input_tokens / 1e6) * 3.00 + (usage.output_tokens / 1e6) * 15.00
|
|
42
|
+
|
|
43
|
+
decision = cap.evaluate(cost)
|
|
44
|
+
if not decision.allowed:
|
|
45
|
+
match decision.trip:
|
|
46
|
+
case "absolute-ceiling":
|
|
47
|
+
alert(f"single call cost ${decision.observed:.2f}")
|
|
48
|
+
case "rolling-median":
|
|
49
|
+
alert(f"cost {decision.observed / decision.median:.0f}x the median")
|
|
50
|
+
case "monthly-budget":
|
|
51
|
+
disable_feature_until_next_month()
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`evaluate` judges the cost against the history that preceded it, then records it. Recording happens even when the decision trips, because the money is already spent and hiding real spend would make the monthly total under-count. For pre-call gating with an estimate, use `check`, which never records:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
if not cap.check(estimated_cost).allowed:
|
|
58
|
+
return err_budget_exceeded()
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The monthly window follows the wall clock (UTC by default) and resets on calendar-month rollover. Inject a `clock` callable to control time in tests:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
cap = CostCap(monthly_budget=25.0, clock=lambda: datetime(2026, 8, 1, tzinfo=timezone.utc))
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## API
|
|
68
|
+
|
|
69
|
+
| Member | Behavior |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `evaluate(cost) -> Decision` | Judge against prior history, then record. The common post-call path. |
|
|
72
|
+
| `check(cost) -> Decision` | Judge without recording. For pre-call estimates. |
|
|
73
|
+
| `record(cost) -> None` | Record without judging. For backfilling history. |
|
|
74
|
+
| `median` | Current rolling median, or `None` with empty history. |
|
|
75
|
+
| `monthly_spend` | Cumulative recorded spend this calendar month. |
|
|
76
|
+
| `reset()` | Clear window and monthly state. |
|
|
77
|
+
|
|
78
|
+
`Decision` is a frozen dataclass: `allowed`, `trip` (`"absolute-ceiling" | "monthly-budget" | "rolling-median" | None`), `observed`, `cap`, `median`, `monthly_spend`. All fields reflect state at decision time, before the cost is recorded.
|
|
79
|
+
|
|
80
|
+
Costs must be non-negative finite numbers; `NaN`, infinity, negatives, and non-numeric types raise instead of being silently ignored.
|
|
81
|
+
|
|
82
|
+
## Benchmarks
|
|
83
|
+
|
|
84
|
+
`evaluate` throughput on Apple Silicon (M-series), CPython 3.14, single thread, via `python bench.py`:
|
|
85
|
+
|
|
86
|
+
| Window | Throughput | Latency |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| 50 (default) | 72,800 ops/sec | 13.7 us |
|
|
89
|
+
| 200 | 45,400 ops/sec | 22.0 us |
|
|
90
|
+
| 1,000 | 10,700 ops/sec | 93.0 us |
|
|
91
|
+
|
|
92
|
+
The median is recomputed from a window snapshot on every decision, which is O(n log n). At realistic API-call rates (tens of calls per second) this is noise; the naive recompute was chosen over an incremental two-heap median because it is simpler to verify and the window is small.
|
|
93
|
+
|
|
94
|
+
## Known limitations
|
|
95
|
+
|
|
96
|
+
- **State is in-process.** Each worker, container, or serverless instance caps independently. A fleet of N workers can collectively spend up to N times the monthly budget. Acceptable as an anomaly detector and defense-in-depth; not a substitute for a provider-side billing cap.
|
|
97
|
+
- **The rolling median can drift under a slow ramp.** Costs that grow gradually (each within `multiplier` of the current median) raise the baseline without ever tripping. The absolute ceiling is the backstop for this case.
|
|
98
|
+
- **`evaluate` is post-call.** It detects that money was spent; it does not prevent the spend. Real prevention lives upstream: bounded retries, `max_tokens` limits, and `check` with estimates where estimation is feasible.
|
|
99
|
+
- **Monthly rollover is calendar-based and UTC by default.** There is no proration and no billing-cycle alignment beyond what a custom `clock` gives you.
|
|
100
|
+
- **No persistence.** A process restart forgets both the window and the month-to-date spend.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Throughput benchmark for CostCap.evaluate at several window sizes.
|
|
2
|
+
|
|
3
|
+
Run: python bench.py
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import random
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from rolling_cost_cap import CostCap
|
|
10
|
+
|
|
11
|
+
ITERATIONS = 200_000
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def bench(window: int) -> float:
|
|
15
|
+
cap = CostCap(window=window, absolute_ceiling=10.0, monthly_budget=1e9)
|
|
16
|
+
rng = random.Random(42)
|
|
17
|
+
costs = [rng.uniform(0.01, 0.05) for _ in range(ITERATIONS)]
|
|
18
|
+
start = time.perf_counter()
|
|
19
|
+
for cost in costs:
|
|
20
|
+
cap.evaluate(cost)
|
|
21
|
+
elapsed = time.perf_counter() - start
|
|
22
|
+
return ITERATIONS / elapsed
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
if __name__ == "__main__":
|
|
26
|
+
for window in (50, 200, 1000):
|
|
27
|
+
ops = bench(window)
|
|
28
|
+
print(f"window={window:>5} {ops:>12,.0f} evaluate/sec ({1e6 / ops:.1f} us/op)")
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rolling-cost-cap"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Runaway-cost circuit breaker for LLM and metered API calls: rolling-median anomaly detection, absolute per-call ceiling, monthly budget"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Corey Stevens" }]
|
|
14
|
+
keywords = [
|
|
15
|
+
"llm",
|
|
16
|
+
"cost-control",
|
|
17
|
+
"budget",
|
|
18
|
+
"circuit-breaker",
|
|
19
|
+
"anthropic",
|
|
20
|
+
"openai",
|
|
21
|
+
"observability",
|
|
22
|
+
]
|
|
23
|
+
classifiers = [
|
|
24
|
+
"Development Status :: 4 - Beta",
|
|
25
|
+
"Intended Audience :: Developers",
|
|
26
|
+
"Operating System :: OS Independent",
|
|
27
|
+
"Programming Language :: Python :: 3",
|
|
28
|
+
"Programming Language :: Python :: 3.10",
|
|
29
|
+
"Programming Language :: Python :: 3.11",
|
|
30
|
+
"Programming Language :: Python :: 3.12",
|
|
31
|
+
"Programming Language :: Python :: 3.13",
|
|
32
|
+
"Programming Language :: Python :: 3.14",
|
|
33
|
+
"Typing :: Typed",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://github.com/coreystevensdev/rolling-cost-cap"
|
|
38
|
+
Issues = "https://github.com/coreystevensdev/rolling-cost-cap/issues"
|
|
39
|
+
|
|
40
|
+
[project.optional-dependencies]
|
|
41
|
+
dev = ["pytest>=8"]
|
|
42
|
+
|
|
43
|
+
[tool.hatch.build.targets.wheel]
|
|
44
|
+
packages = ["src/rolling_cost_cap"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Runaway-cost circuit breaker for metered API calls.
|
|
2
|
+
|
|
3
|
+
Judges each observed cost against three independent layers: an optional
|
|
4
|
+
absolute per-call ceiling, an optional cumulative monthly budget, and a
|
|
5
|
+
rolling-median anomaly cap. State is in-process only; if you run
|
|
6
|
+
multiple workers, each worker caps independently (see README).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
import statistics
|
|
13
|
+
import threading
|
|
14
|
+
from collections import deque
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from typing import Callable, Literal
|
|
18
|
+
|
|
19
|
+
__all__ = ["CostCap", "Decision", "Trip"]
|
|
20
|
+
|
|
21
|
+
Trip = Literal["absolute-ceiling", "monthly-budget", "rolling-median"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Decision:
|
|
26
|
+
"""Outcome of judging one cost. Reflects state before the cost is recorded."""
|
|
27
|
+
|
|
28
|
+
allowed: bool
|
|
29
|
+
trip: Trip | None
|
|
30
|
+
observed: float
|
|
31
|
+
cap: float | None
|
|
32
|
+
median: float | None
|
|
33
|
+
monthly_spend: float
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _utc_now() -> datetime:
|
|
37
|
+
return datetime.now(timezone.utc)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class CostCap:
|
|
41
|
+
"""Three-layer cost circuit breaker.
|
|
42
|
+
|
|
43
|
+
The rolling-median layer trips when a cost exceeds ``multiplier`` times
|
|
44
|
+
the median of the last ``window`` recorded costs. It stays dormant until
|
|
45
|
+
``min_samples`` costs have been recorded, so one cheap first call cannot
|
|
46
|
+
set a hair-trigger baseline.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
*,
|
|
52
|
+
multiplier: float = 3.0,
|
|
53
|
+
window: int = 50,
|
|
54
|
+
min_samples: int = 5,
|
|
55
|
+
absolute_ceiling: float | None = None,
|
|
56
|
+
monthly_budget: float | None = None,
|
|
57
|
+
clock: Callable[[], datetime] | None = None,
|
|
58
|
+
) -> None:
|
|
59
|
+
if multiplier < 1.0:
|
|
60
|
+
raise ValueError("multiplier must be >= 1.0")
|
|
61
|
+
if window < 1:
|
|
62
|
+
raise ValueError("window must be >= 1")
|
|
63
|
+
if not 1 <= min_samples <= window:
|
|
64
|
+
raise ValueError("min_samples must be between 1 and window")
|
|
65
|
+
if absolute_ceiling is not None and absolute_ceiling <= 0:
|
|
66
|
+
raise ValueError("absolute_ceiling must be positive")
|
|
67
|
+
if monthly_budget is not None and monthly_budget <= 0:
|
|
68
|
+
raise ValueError("monthly_budget must be positive")
|
|
69
|
+
|
|
70
|
+
self._multiplier = multiplier
|
|
71
|
+
self._min_samples = min_samples
|
|
72
|
+
self._absolute_ceiling = absolute_ceiling
|
|
73
|
+
self._monthly_budget = monthly_budget
|
|
74
|
+
self._clock = clock or _utc_now
|
|
75
|
+
self._history: deque[float] = deque(maxlen=window)
|
|
76
|
+
self._month_key = self._current_month()
|
|
77
|
+
self._monthly_spend = 0.0
|
|
78
|
+
self._lock = threading.Lock()
|
|
79
|
+
|
|
80
|
+
def check(self, cost: float) -> Decision:
|
|
81
|
+
"""Judge a cost without recording it."""
|
|
82
|
+
self._validate(cost)
|
|
83
|
+
with self._lock:
|
|
84
|
+
self._roll_month()
|
|
85
|
+
return self._decide(cost)
|
|
86
|
+
|
|
87
|
+
def record(self, cost: float) -> None:
|
|
88
|
+
"""Record a cost into the rolling window and monthly total."""
|
|
89
|
+
self._validate(cost)
|
|
90
|
+
with self._lock:
|
|
91
|
+
self._roll_month()
|
|
92
|
+
self._append(cost)
|
|
93
|
+
|
|
94
|
+
def evaluate(self, cost: float) -> Decision:
|
|
95
|
+
"""Judge a cost, then record it.
|
|
96
|
+
|
|
97
|
+
Recording happens even when the decision trips: the money is already
|
|
98
|
+
spent, and hiding real spend from the monthly total would let the
|
|
99
|
+
budget layer under-count. The spike is judged against the history
|
|
100
|
+
that preceded it.
|
|
101
|
+
"""
|
|
102
|
+
self._validate(cost)
|
|
103
|
+
with self._lock:
|
|
104
|
+
self._roll_month()
|
|
105
|
+
decision = self._decide(cost)
|
|
106
|
+
self._append(cost)
|
|
107
|
+
return decision
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def median(self) -> float | None:
|
|
111
|
+
with self._lock:
|
|
112
|
+
return self._median()
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def monthly_spend(self) -> float:
|
|
116
|
+
with self._lock:
|
|
117
|
+
self._roll_month()
|
|
118
|
+
return self._monthly_spend
|
|
119
|
+
|
|
120
|
+
def reset(self) -> None:
|
|
121
|
+
with self._lock:
|
|
122
|
+
self._history.clear()
|
|
123
|
+
self._month_key = self._current_month()
|
|
124
|
+
self._monthly_spend = 0.0
|
|
125
|
+
|
|
126
|
+
def _validate(self, cost: float) -> None:
|
|
127
|
+
if not isinstance(cost, (int, float)) or isinstance(cost, bool):
|
|
128
|
+
raise TypeError(f"cost must be a number, got {type(cost).__name__}")
|
|
129
|
+
if not math.isfinite(cost) or cost < 0:
|
|
130
|
+
raise ValueError(f"cost must be a non-negative finite number, got {cost}")
|
|
131
|
+
|
|
132
|
+
def _decide(self, cost: float) -> Decision:
|
|
133
|
+
median = self._median()
|
|
134
|
+
spend = self._monthly_spend
|
|
135
|
+
|
|
136
|
+
if self._absolute_ceiling is not None and cost > self._absolute_ceiling:
|
|
137
|
+
return Decision(False, "absolute-ceiling", cost, self._absolute_ceiling, median, spend)
|
|
138
|
+
|
|
139
|
+
if self._monthly_budget is not None and spend + cost > self._monthly_budget:
|
|
140
|
+
return Decision(False, "monthly-budget", cost, self._monthly_budget, median, spend)
|
|
141
|
+
|
|
142
|
+
if median is not None and median > 0 and len(self._history) >= self._min_samples:
|
|
143
|
+
cap = median * self._multiplier
|
|
144
|
+
if cost > cap:
|
|
145
|
+
return Decision(False, "rolling-median", cost, cap, median, spend)
|
|
146
|
+
return Decision(True, None, cost, cap, median, spend)
|
|
147
|
+
|
|
148
|
+
return Decision(True, None, cost, None, median, spend)
|
|
149
|
+
|
|
150
|
+
def _median(self) -> float | None:
|
|
151
|
+
if not self._history:
|
|
152
|
+
return None
|
|
153
|
+
return statistics.median(self._history)
|
|
154
|
+
|
|
155
|
+
def _append(self, cost: float) -> None:
|
|
156
|
+
self._history.append(float(cost))
|
|
157
|
+
self._monthly_spend += cost
|
|
158
|
+
|
|
159
|
+
def _current_month(self) -> str:
|
|
160
|
+
return self._clock().strftime("%Y-%m")
|
|
161
|
+
|
|
162
|
+
def _roll_month(self) -> None:
|
|
163
|
+
now = self._current_month()
|
|
164
|
+
if now != self._month_key:
|
|
165
|
+
self._month_key = now
|
|
166
|
+
self._monthly_spend = 0.0
|
|
File without changes
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import threading
|
|
2
|
+
from datetime import datetime, timezone
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from rolling_cost_cap import CostCap
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def utc(year, month, day=1):
|
|
10
|
+
return datetime(year, month, day, tzinfo=timezone.utc)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FakeClock:
|
|
14
|
+
def __init__(self, now):
|
|
15
|
+
self.now = now
|
|
16
|
+
|
|
17
|
+
def __call__(self):
|
|
18
|
+
return self.now
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TestConstructorValidation:
|
|
22
|
+
def test_multiplier_below_one_rejected(self):
|
|
23
|
+
with pytest.raises(ValueError, match="multiplier"):
|
|
24
|
+
CostCap(multiplier=0.9)
|
|
25
|
+
|
|
26
|
+
def test_window_below_one_rejected(self):
|
|
27
|
+
with pytest.raises(ValueError, match="window"):
|
|
28
|
+
CostCap(window=0)
|
|
29
|
+
|
|
30
|
+
def test_min_samples_above_window_rejected(self):
|
|
31
|
+
with pytest.raises(ValueError, match="min_samples"):
|
|
32
|
+
CostCap(window=10, min_samples=11)
|
|
33
|
+
|
|
34
|
+
def test_zero_ceiling_rejected(self):
|
|
35
|
+
with pytest.raises(ValueError, match="absolute_ceiling"):
|
|
36
|
+
CostCap(absolute_ceiling=0)
|
|
37
|
+
|
|
38
|
+
def test_negative_budget_rejected(self):
|
|
39
|
+
with pytest.raises(ValueError, match="monthly_budget"):
|
|
40
|
+
CostCap(monthly_budget=-5)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class TestCostValidation:
|
|
44
|
+
def test_negative_cost_raises(self):
|
|
45
|
+
with pytest.raises(ValueError):
|
|
46
|
+
CostCap().evaluate(-0.01)
|
|
47
|
+
|
|
48
|
+
def test_nan_raises(self):
|
|
49
|
+
with pytest.raises(ValueError):
|
|
50
|
+
CostCap().evaluate(float("nan"))
|
|
51
|
+
|
|
52
|
+
def test_infinity_raises(self):
|
|
53
|
+
with pytest.raises(ValueError):
|
|
54
|
+
CostCap().evaluate(float("inf"))
|
|
55
|
+
|
|
56
|
+
def test_bool_raises_type_error(self):
|
|
57
|
+
with pytest.raises(TypeError):
|
|
58
|
+
CostCap().evaluate(True)
|
|
59
|
+
|
|
60
|
+
def test_string_raises_type_error(self):
|
|
61
|
+
with pytest.raises(TypeError):
|
|
62
|
+
CostCap().evaluate("0.02")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class TestAbsoluteCeiling:
|
|
66
|
+
def test_trips_above_ceiling(self):
|
|
67
|
+
cap = CostCap(absolute_ceiling=1.0)
|
|
68
|
+
decision = cap.evaluate(1.5)
|
|
69
|
+
assert not decision.allowed
|
|
70
|
+
assert decision.trip == "absolute-ceiling"
|
|
71
|
+
assert decision.cap == 1.0
|
|
72
|
+
|
|
73
|
+
def test_allows_at_ceiling(self):
|
|
74
|
+
cap = CostCap(absolute_ceiling=1.0)
|
|
75
|
+
assert cap.evaluate(1.0).allowed
|
|
76
|
+
|
|
77
|
+
def test_no_ceiling_never_trips_on_first_call(self):
|
|
78
|
+
assert CostCap().evaluate(500.0).allowed
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class TestRollingMedian:
|
|
82
|
+
def test_dormant_below_min_samples(self):
|
|
83
|
+
cap = CostCap(min_samples=5)
|
|
84
|
+
for _ in range(4):
|
|
85
|
+
cap.evaluate(0.02)
|
|
86
|
+
assert cap.evaluate(10.0).allowed
|
|
87
|
+
|
|
88
|
+
def test_trips_after_warmup(self):
|
|
89
|
+
cap = CostCap(multiplier=3.0, min_samples=5)
|
|
90
|
+
for _ in range(5):
|
|
91
|
+
cap.evaluate(0.02)
|
|
92
|
+
decision = cap.evaluate(0.10)
|
|
93
|
+
assert not decision.allowed
|
|
94
|
+
assert decision.trip == "rolling-median"
|
|
95
|
+
assert decision.median == pytest.approx(0.02)
|
|
96
|
+
assert decision.cap == pytest.approx(0.06)
|
|
97
|
+
|
|
98
|
+
def test_allows_within_multiplier(self):
|
|
99
|
+
cap = CostCap(multiplier=3.0, min_samples=5)
|
|
100
|
+
for _ in range(5):
|
|
101
|
+
cap.evaluate(0.02)
|
|
102
|
+
assert cap.evaluate(0.05).allowed
|
|
103
|
+
|
|
104
|
+
def test_zero_median_stays_dormant(self):
|
|
105
|
+
cap = CostCap(min_samples=1)
|
|
106
|
+
for _ in range(5):
|
|
107
|
+
cap.evaluate(0.0)
|
|
108
|
+
assert cap.evaluate(0.5).allowed
|
|
109
|
+
|
|
110
|
+
def test_spike_judged_against_prior_history(self):
|
|
111
|
+
cap = CostCap(multiplier=3.0, min_samples=5)
|
|
112
|
+
for _ in range(10):
|
|
113
|
+
cap.evaluate(0.02)
|
|
114
|
+
assert not cap.evaluate(0.10).allowed
|
|
115
|
+
# the spike entered the window but ten 0.02s still dominate the median
|
|
116
|
+
assert not cap.evaluate(0.10).allowed
|
|
117
|
+
|
|
118
|
+
def test_window_eviction_forgets_old_costs(self):
|
|
119
|
+
cap = CostCap(window=5, min_samples=5, multiplier=3.0)
|
|
120
|
+
for _ in range(5):
|
|
121
|
+
cap.evaluate(1.0)
|
|
122
|
+
for _ in range(5):
|
|
123
|
+
cap.evaluate(0.01)
|
|
124
|
+
# window now holds only 0.01s, so 1.0 is an anomaly again
|
|
125
|
+
assert not cap.evaluate(1.0).allowed
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class TestMonthlyBudget:
|
|
129
|
+
def test_trips_when_cost_would_exceed_budget(self):
|
|
130
|
+
cap = CostCap(monthly_budget=1.0)
|
|
131
|
+
cap.evaluate(0.6)
|
|
132
|
+
decision = cap.evaluate(0.5)
|
|
133
|
+
assert not decision.allowed
|
|
134
|
+
assert decision.trip == "monthly-budget"
|
|
135
|
+
assert decision.monthly_spend == pytest.approx(0.6)
|
|
136
|
+
|
|
137
|
+
def test_spend_recorded_even_when_tripped(self):
|
|
138
|
+
cap = CostCap(monthly_budget=1.0)
|
|
139
|
+
cap.evaluate(0.6)
|
|
140
|
+
cap.evaluate(0.5)
|
|
141
|
+
assert cap.monthly_spend == pytest.approx(1.1)
|
|
142
|
+
|
|
143
|
+
def test_resets_on_month_rollover(self):
|
|
144
|
+
clock = FakeClock(utc(2026, 7))
|
|
145
|
+
cap = CostCap(monthly_budget=1.0, clock=clock)
|
|
146
|
+
cap.evaluate(0.9)
|
|
147
|
+
assert not cap.check(0.2).allowed
|
|
148
|
+
clock.now = utc(2026, 8)
|
|
149
|
+
assert cap.check(0.2).allowed
|
|
150
|
+
assert cap.monthly_spend == 0.0
|
|
151
|
+
|
|
152
|
+
def test_rolling_window_survives_month_rollover(self):
|
|
153
|
+
clock = FakeClock(utc(2026, 7))
|
|
154
|
+
cap = CostCap(multiplier=3.0, min_samples=5, clock=clock)
|
|
155
|
+
for _ in range(5):
|
|
156
|
+
cap.evaluate(0.02)
|
|
157
|
+
clock.now = utc(2026, 8)
|
|
158
|
+
assert not cap.evaluate(0.10).allowed
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class TestCheckVersusEvaluate:
|
|
162
|
+
def test_check_does_not_record(self):
|
|
163
|
+
cap = CostCap()
|
|
164
|
+
cap.check(0.5)
|
|
165
|
+
assert cap.monthly_spend == 0.0
|
|
166
|
+
assert cap.median is None
|
|
167
|
+
|
|
168
|
+
def test_record_without_decision(self):
|
|
169
|
+
cap = CostCap()
|
|
170
|
+
cap.record(0.5)
|
|
171
|
+
assert cap.monthly_spend == pytest.approx(0.5)
|
|
172
|
+
assert cap.median == pytest.approx(0.5)
|
|
173
|
+
|
|
174
|
+
def test_reset_clears_all_state(self):
|
|
175
|
+
cap = CostCap()
|
|
176
|
+
cap.evaluate(0.5)
|
|
177
|
+
cap.reset()
|
|
178
|
+
assert cap.monthly_spend == 0.0
|
|
179
|
+
assert cap.median is None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class TestThreadSafety:
|
|
183
|
+
def test_concurrent_evaluate_counts_all_spend(self):
|
|
184
|
+
cap = CostCap()
|
|
185
|
+
per_thread, threads = 200, 8
|
|
186
|
+
|
|
187
|
+
def worker():
|
|
188
|
+
for _ in range(per_thread):
|
|
189
|
+
cap.evaluate(0.01)
|
|
190
|
+
|
|
191
|
+
pool = [threading.Thread(target=worker) for _ in range(threads)]
|
|
192
|
+
for t in pool:
|
|
193
|
+
t.start()
|
|
194
|
+
for t in pool:
|
|
195
|
+
t.join()
|
|
196
|
+
assert cap.monthly_spend == pytest.approx(per_thread * threads * 0.01)
|