Skip to content

Commit bb43abb

Browse files
committed
fix: circuit breaker ignores straggler outcomes, unwraps budget exhaustion, rate-limits circuit.rejected
Outcomes now carry an epoch ticket from admission, so a request that finishes after its circuit changed state no longer reopens, closes or frees the probe slot. A RetryBudgetExhaustedError is classified by its last_exception. circuit.rejected is emitted outside the sync lock, at most once per second per circuit, with a suppressed count.
1 parent 4073099 commit bb43abb

9 files changed

Lines changed: 803 additions & 106 deletions

‎CONTEXT.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,9 @@ _Avoid_: adapter, which names the third-party object a decoder builds and memoiz
4646
**Counted failure**:
4747
The circuit breaker's unit of account: a `NetworkError`, an httpware `TimeoutError`, or a
4848
`StatusError` whose status is in the effective failure set (default: all 5xx). Every other 4xx —
49-
429 included — counts as a *success*, and any other exception type propagates without touching
50-
circuit state. "Failure" alone is ambiguous here: a failed request is very often not a counted
51-
failure.
49+
429 included — counts as a *success*. A `RetryBudgetExhaustedError` is classified by its
50+
`last_exception`, and any other exception type propagates without touching circuit state. "Failure"
51+
alone is ambiguous here: a failed request is very often not a counted failure.
5252

5353
**Circuit key**:
5454
The value a keyed circuit breaker computes from a request to pick its circuit; requests with equal

‎docs/observability.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ The logger and event names below are a stable public contract:
1111
| `httpware.circuit_breaker` | `circuit.opened` (WARNING), `circuit.rejected` (WARNING), `circuit.half_open` (INFO), `circuit.closed` (INFO) |
1212
| `httpware.timeout` | `timeout.exceeded` (WARNING) |
1313

14-
Each log record has an `event` field holding the event name, such as `event="circuit.opened"`, which you can filter on in your log aggregator. Events from `AsyncKeyedCircuitBreaker` and `KeyedCircuitBreaker` also carry `circuit_key`, the circuit they belong to. [Resilience](resilience.md) describes when each event fires.
14+
Each log record has an `event` field holding the event name, such as `event="circuit.opened"`, which you can filter on in your log aggregator. `circuit.rejected` is emitted at most once per second per circuit, so an open circuit under heavy traffic does not flood your logs; its `suppressed` attribute counts the rejections that were left out since the previous one. Events from `AsyncKeyedCircuitBreaker` and `KeyedCircuitBreaker` also carry `circuit_key`, the circuit they belong to. [Resilience](resilience.md) describes when each event fires.
1515

1616
```python
1717
import logging

‎docs/resilience.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ A circuit breaker counts consecutive failures and, past a threshold, stops sendi
160160
- OPEN: until `reset_timeout` has passed, every request fails at once with `CircuitOpenError`, whose `retry_after` says how many seconds remain. The first request after that moves the circuit to HALF_OPEN and becomes the probe.
161161
- HALF_OPEN: one probe at a time is let through. After `success_threshold` successful probes in a row the circuit closes; one failed probe opens it again.
162162

163+
An outcome only counts against the state its request was admitted under. A request that is still in flight when the circuit changes state, such as a slow call sent before the circuit opened, finishes without touching the circuit. It cannot reopen a HALF_OPEN circuit, count toward `success_threshold`, or free the probe slot.
164+
163165
### Constructor
164166

165167
| Parameter | Default | Effect |
@@ -176,6 +178,8 @@ A circuit breaker counts consecutive failures and, past a threshold, stops sendi
176178

177179
A counted failure is a `NetworkError`, an httpware `TimeoutError`, or a `StatusError` whose status is in `failure_status_codes`. Other exceptions pass through without changing the circuit.
178180

181+
A `RetryBudgetExhaustedError` from a retry placed after the breaker is classified by its `last_exception`. If the last attempt failed with a counted failure, the breaker counts one; if it failed with a 4xx, that is a success.
182+
179183
4xx responses, 429 included, count as successes. A 429 means the service is up and throttling you; opening the circuit on it would add circuit-open rejections on top of the throttling.
180184

181185
### `CircuitOpenError`
@@ -189,7 +193,7 @@ Emitted on logger `httpware.circuit_breaker`:
189193
| Event | When |
190194
|---|---|
191195
| `circuit.opened` | The failure threshold was reached and the circuit went from CLOSED to OPEN. |
192-
| `circuit.rejected` | A request failed fast because the circuit was OPEN or a HALF_OPEN probe was already running. |
196+
| `circuit.rejected` | A request failed fast because the circuit was OPEN or a HALF_OPEN probe was already running. Emitted at most once per second per circuit; its `suppressed` attribute counts the rejections since the previous `circuit.rejected` that were not emitted. |
193197
| `circuit.half_open` | The reset timeout passed and the circuit went from OPEN to HALF_OPEN. |
194198
| `circuit.closed` | The success threshold was reached and the circuit went from HALF_OPEN to CLOSED. |
195199

‎src/httpware/middleware/resilience/circuit_breaker.py‎

Lines changed: 128 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
A counted failure is a NetworkError, an httpware TimeoutError, or a StatusError whose
77
status_code is in the effective failure set (default: all 5xx). 4xx — including 429 —
88
count as successes: 429 means healthy-but-throttling, and tripping on it amplifies
9-
incidents. Any other exception propagates without affecting circuit state. In
9+
incidents. A RetryBudgetExhaustedError is classified by its last_exception. Any other
10+
exception propagates without affecting circuit state. In
1011
particular, non-NetworkError transport problems — e.g. httpx2.InvalidURL from a
1112
malformed URL — are foreign: they propagate unchanged and do not increment the
1213
failure counter, so programming errors cannot trip the breaker.
@@ -18,6 +19,12 @@
1819
HALF_OPEN — admit exactly one probe at a time; success_threshold consecutive probe
1920
successes close the circuit; one probe failure re-opens it.
2021
22+
An outcome applies only to the state its request was admitted under: a request still in
23+
flight when the circuit changes state finishes without touching the circuit.
24+
25+
circuit.rejected is emitted at most once per second per circuit; its `suppressed`
26+
attribute counts the rejections not emitted since the previous one.
27+
2128
Trip modes:
2229
Classic (default) — opens when consecutive counted-failures reach failure_threshold.
2330
Set failure_threshold to use this mode; leave failure_rate_threshold unset.
@@ -38,6 +45,7 @@
3845
import enum
3946
import functools
4047
import logging
48+
import math
4149
import threading
4250
import time
4351
import typing
@@ -46,7 +54,13 @@
4654
import httpx2
4755

4856
from httpware._internal.observability import _emit_event
49-
from httpware.errors import CircuitOpenError, NetworkError, StatusError, TimeoutError # noqa: A004
57+
from httpware.errors import (
58+
CircuitOpenError,
59+
NetworkError,
60+
RetryBudgetExhaustedError,
61+
StatusError,
62+
TimeoutError, # noqa: A004
63+
)
5064
from httpware.middleware import AsyncNext, Next
5165
from httpware.middleware.resilience._event_loop_guard import check_event_loop
5266

@@ -72,8 +86,14 @@
7286

7387
_BUCKET_COUNT = 10
7488

75-
_ROLE_CLOSED = "closed"
76-
_ROLE_PROBE = "probe"
89+
_SUCCESS = 0
90+
_FAILURE = 1
91+
_FOREIGN = 2
92+
93+
_PROBE = 1
94+
_EPOCH_STEP = 2
95+
96+
_REJECTED_EVENT_INTERVAL = 1.0
7797

7898
_LOGGER = logging.getLogger("httpware.circuit_breaker")
7999

@@ -136,12 +156,23 @@ def clear(self) -> None:
136156
self._failure = [0] * _BUCKET_COUNT
137157

138158

159+
class _RejectionError(Exception):
160+
"""Raised by `admit` to refuse a request; `message` is None when the event is suppressed."""
161+
162+
def __init__(self, retry_after: float | None, message: str | None, suppressed: int) -> None:
163+
self.retry_after = retry_after
164+
self.message = message
165+
self.suppressed = suppressed
166+
167+
139168
class _CircuitBreakerState:
140169
"""Lock-free circuit-breaker state machine shared by the sync + async wrappers.
141170
142171
Every method is synchronous and performs no I/O beyond logging. The async wrapper
143172
calls these directly (atomic under a single event loop because no await occurs
144-
inside a transition); the sync wrapper wraps each call in a threading.Lock.
173+
inside a transition); the sync wrapper wraps `admit` and `record` in a threading.Lock.
174+
`admit` hands out a ticket: the epoch, which every transition advances by two, plus one
175+
for the probe. `record` ignores a ticket from an earlier epoch.
145176
"""
146177

147178
def __init__( # noqa: PLR0913 — breaker state has many orthogonal knobs; a dataclass would be worse
@@ -189,86 +220,99 @@ def __init__( # noqa: PLR0913 — breaker state has many orthogonal knobs; a da
189220
self._consecutive_successes = 0
190221
self._opened_at = 0.0
191222
self._probe_in_flight = False
192-
193-
def is_failure_status(self, status_code: int) -> bool:
194-
return status_code in self._failure_status_codes
223+
self._epoch = 0
224+
self._rejected_emitted_at = -math.inf
225+
self._rejections_suppressed = 0
195226

196227
@property
197228
def state(self) -> CircuitState:
198229
"""The circuit's current stored state (raw read; no lazy OPEN→HALF_OPEN transition)."""
199230
return self._state
200231

201-
def admit(self, request: httpx2.Request) -> str:
202-
"""Decide the request's role, or raise CircuitOpenError. No await inside."""
232+
def admit(self, request: httpx2.Request) -> int:
233+
"""Return the request's ticket, or raise _RejectionError. No await inside."""
203234
if self._state is CircuitState.CLOSED:
204-
return _ROLE_CLOSED
235+
return self._epoch
236+
now = self._now()
205237
if self._state is CircuitState.OPEN:
206-
elapsed = self._now() - self._opened_at
207-
if elapsed >= self._reset_timeout:
208-
self._state = CircuitState.HALF_OPEN
209-
self._probe_in_flight = True
210-
self._emit(request, "circuit.half_open", logging.INFO, "circuit half-open — admitting probe", {})
211-
return _ROLE_PROBE
212-
retry_after = max(0.0, self._reset_timeout - elapsed)
213-
self._emit(
214-
request,
215-
"circuit.rejected",
216-
logging.WARNING,
217-
"circuit open — rejecting request",
218-
{"retry_after": retry_after},
219-
)
220-
raise CircuitOpenError(retry_after=retry_after)
221-
# HALF_OPEN
222-
if self._probe_in_flight:
238+
elapsed = now - self._opened_at
239+
if elapsed < self._reset_timeout:
240+
self._reject(now, max(0.0, self._reset_timeout - elapsed), "circuit open — rejecting request")
241+
self._move_to(CircuitState.HALF_OPEN)
242+
self._emit(request, "circuit.half_open", logging.INFO, "circuit half-open — admitting probe", {})
243+
elif self._probe_in_flight:
244+
self._reject(now, None, "circuit half-open — rejecting request (probe in flight)")
245+
self._probe_in_flight = True
246+
return self._epoch + _PROBE
247+
248+
def classify(self, exc: BaseException | None) -> int:
249+
"""Map an exception raised past the breaker to _SUCCESS, _FAILURE or _FOREIGN."""
250+
if isinstance(exc, RetryBudgetExhaustedError):
251+
exc = exc.last_exception
252+
if isinstance(exc, StatusError):
253+
return _FAILURE if exc.response.status_code in self._failure_status_codes else _SUCCESS
254+
if isinstance(exc, (NetworkError, TimeoutError)):
255+
return _FAILURE
256+
return _FOREIGN
257+
258+
def record(self, ticket: int, outcome: int, request: httpx2.Request) -> None:
259+
"""Apply an admitted request's outcome; a no-op if the circuit has transitioned since."""
260+
if ticket == self._epoch:
261+
if outcome == _SUCCESS and not self._rate_mode:
262+
self._consecutive_failures = 0
263+
elif outcome != _FOREIGN:
264+
self._record_closed(request, failed=outcome == _FAILURE)
265+
elif ticket == self._epoch + _PROBE:
266+
self._probe_in_flight = False
267+
if outcome == _SUCCESS:
268+
self._record_probe_success(request)
269+
elif outcome == _FAILURE:
270+
self._open(request, failures=1) # 1 = the single probe failure that re-opened the circuit
271+
272+
def rejected(self, request: httpx2.Request, rejection: _RejectionError) -> CircuitOpenError:
273+
"""Emit the rejection's event unless `admit` suppressed it; return the error to raise."""
274+
if rejection.message is not None:
223275
self._emit(
224276
request,
225277
"circuit.rejected",
226278
logging.WARNING,
227-
"circuit half-open — rejecting request (probe in flight)",
228-
{"retry_after": None},
279+
rejection.message,
280+
{"retry_after": rejection.retry_after, "suppressed": rejection.suppressed},
229281
)
230-
raise CircuitOpenError(retry_after=None)
231-
self._probe_in_flight = True
232-
return _ROLE_PROBE
233-
234-
def on_success(self, role: str, request: httpx2.Request) -> None:
235-
if role == _ROLE_PROBE:
236-
self._probe_in_flight = False
237-
if self._state is CircuitState.CLOSED:
282+
return CircuitOpenError(retry_after=rejection.retry_after)
283+
284+
def _reject(self, now: float, retry_after: float | None, message: str) -> typing.NoReturn:
285+
if now - self._rejected_emitted_at < _REJECTED_EVENT_INTERVAL:
286+
self._rejections_suppressed += 1
287+
raise _RejectionError(retry_after, None, 0)
288+
self._rejected_emitted_at = now
289+
suppressed, self._rejections_suppressed = self._rejections_suppressed, 0
290+
raise _RejectionError(retry_after, message, suppressed)
291+
292+
def _record_closed(self, request: httpx2.Request, *, failed: bool) -> None:
293+
if self._rate_mode:
294+
self._record_outcome(request, failed=failed)
295+
elif failed:
296+
self._consecutive_failures += 1
297+
if self._consecutive_failures >= self._failure_threshold:
298+
self._open(request, failures=self._consecutive_failures)
299+
300+
def _record_probe_success(self, request: httpx2.Request) -> None:
301+
self._consecutive_successes += 1
302+
if self._consecutive_successes >= self._success_threshold:
303+
self._move_to(CircuitState.CLOSED)
304+
self._consecutive_failures = 0
305+
self._consecutive_successes = 0
238306
if self._rate_mode:
239-
self._record_outcome(request, failed=False)
240-
else:
241-
self._consecutive_failures = 0
242-
elif self._state is CircuitState.HALF_OPEN:
243-
self._consecutive_successes += 1
244-
if self._consecutive_successes >= self._success_threshold:
245-
self._state = CircuitState.CLOSED
246-
self._consecutive_failures = 0
247-
self._consecutive_successes = 0
248-
if self._rate_mode:
249-
self._window.clear() # ty: ignore[unresolved-attribute]
250-
self._emit(request, "circuit.closed", logging.INFO, "circuit closed — service recovered", {})
307+
self._window.clear() # ty: ignore[unresolved-attribute]
308+
self._emit(request, "circuit.closed", logging.INFO, "circuit closed — service recovered", {})
251309

252-
def on_failure(self, role: str, request: httpx2.Request) -> None:
253-
if role == _ROLE_PROBE:
254-
self._probe_in_flight = False
255-
if self._state is CircuitState.CLOSED:
256-
if self._rate_mode:
257-
self._record_outcome(request, failed=True)
258-
else:
259-
self._consecutive_failures += 1
260-
if self._consecutive_failures >= self._failure_threshold:
261-
self._open(request, failures=self._consecutive_failures)
262-
elif self._state is CircuitState.HALF_OPEN:
263-
self._open(request, failures=1) # 1 = the single probe failure that re-opened the circuit
264-
265-
def release_probe(self, role: str) -> None:
266-
"""Release the probe slot without recording success or failure (non-counted exc)."""
267-
if role == _ROLE_PROBE:
268-
self._probe_in_flight = False
310+
def _move_to(self, state: CircuitState) -> None:
311+
self._state = state
312+
self._epoch += _EPOCH_STEP
269313

270314
def _enter_open(self, request: httpx2.Request, message: str, attributes: dict[str, typing.Any]) -> None:
271-
self._state = CircuitState.OPEN
315+
self._move_to(CircuitState.OPEN)
272316
self._opened_at = self._now()
273317
self._consecutive_failures = 0
274318
self._consecutive_successes = 0
@@ -317,22 +361,16 @@ def _emit(
317361

318362

319363
async def _call_async(state: _CircuitBreakerState, request: httpx2.Request, next: AsyncNext) -> httpx2.Response: # noqa: A002
320-
role = state.admit(request)
364+
try:
365+
ticket = state.admit(request)
366+
except _RejectionError as rejection:
367+
raise state.rejected(request, rejection) from None
321368
try:
322369
response = await next(request)
323-
except StatusError as exc:
324-
if state.is_failure_status(exc.response.status_code):
325-
state.on_failure(role, request)
326-
else:
327-
state.on_success(role, request)
370+
except BaseException as exc:
371+
state.record(ticket, state.classify(exc), request)
328372
raise
329-
except (NetworkError, TimeoutError):
330-
state.on_failure(role, request)
331-
raise
332-
except BaseException:
333-
state.release_probe(role)
334-
raise
335-
state.on_success(role, request)
373+
state.record(ticket, _SUCCESS, request)
336374
return response
337375

338376

@@ -342,27 +380,20 @@ def _call_sync(
342380
request: httpx2.Request,
343381
next: Next, # noqa: A002
344382
) -> httpx2.Response:
345-
with lock:
346-
role = state.admit(request)
347383
try:
348-
response = next(request)
349-
except StatusError as exc:
350384
with lock:
351-
if state.is_failure_status(exc.response.status_code):
352-
state.on_failure(role, request)
353-
else:
354-
state.on_success(role, request)
355-
raise
356-
except (NetworkError, TimeoutError):
357-
with lock:
358-
state.on_failure(role, request)
359-
raise
360-
except BaseException:
385+
ticket = state.admit(request)
386+
except _RejectionError as rejection:
387+
raise state.rejected(request, rejection) from None
388+
try:
389+
response = next(request)
390+
except BaseException as exc:
391+
outcome = state.classify(exc)
361392
with lock:
362-
state.release_probe(role)
393+
state.record(ticket, outcome, request)
363394
raise
364395
with lock:
365-
state.on_success(role, request)
396+
state.record(ticket, _SUCCESS, request)
366397
return response
367398

368399

0 commit comments

Comments
 (0)