rolling-cost-cap 0.1.0__py3-none-any.whl

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.
@@ -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,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
+ [![CI](https://github.com/coreystevensdev/rolling-cost-cap/actions/workflows/ci.yml/badge.svg)](https://github.com/coreystevensdev/rolling-cost-cap/actions/workflows/ci.yml)
29
+ [![PyPI](https://img.shields.io/pypi/v/rolling-cost-cap)](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,6 @@
1
+ rolling_cost_cap/__init__.py,sha256=tGqTuv3JcmlSXOVFPZKJ4qbj0pzkaPhjmqMaCbIEdD8,5704
2
+ rolling_cost_cap/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ rolling_cost_cap-0.1.0.dist-info/METADATA,sha256=jmvI_HsahbT28bPT270Kd4zyygs_Wkvl4h1DDmj7Cgo,7254
4
+ rolling_cost_cap-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
5
+ rolling_cost_cap-0.1.0.dist-info/licenses/LICENSE,sha256=RFCqnnEfxKw_A3j2EQ41SkCC28NEirhvaglhKxbd0h4,1070
6
+ rolling_cost_cap-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.