circuit_breaker
circuit_breaker
¶
Circuit breaker pattern for resilient execution.
Implements the circuit breaker pattern to prevent cascading failures by temporarily blocking calls after repeated failures.
The circuit breaker has three states: - CLOSED: Normal operation, requests flow through - OPEN: Blocking requests after too many failures - HALF_OPEN: Testing if the service has recovered
State transitions: - CLOSED -> OPEN: When failure_count >= failure_threshold - OPEN -> HALF_OPEN: After recovery_timeout has elapsed - HALF_OPEN -> CLOSED: On success in half-open state - HALF_OPEN -> OPEN: On failure in half-open state
Example usage
from marianne.execution.circuit_breaker import CircuitBreaker
breaker = CircuitBreaker(failure_threshold=5, recovery_timeout=300.0)
if await breaker.can_execute(): try: result = await backend.execute(prompt) if result.success: await breaker.record_success() else: await breaker.record_failure() except Exception: await breaker.record_failure() raise else: # Circuit is open - wait or use fallback wait_time = await breaker.time_until_retry()
Classes¶
CircuitState
¶
Bases: str, Enum
State of the circuit breaker.
The circuit breaker transitions between these states based on success/failure patterns:
- CLOSED: Normal operation. Failures are tracked but requests are allowed.
- OPEN: Blocking mode. Requests are rejected until recovery_timeout elapses.
- HALF_OPEN: Testing mode. A single request is allowed to test recovery.
Attributes¶
CLOSED
class-attribute
instance-attribute
¶
Normal operation - requests are allowed and failures are tracked.
OPEN
class-attribute
instance-attribute
¶
Blocking calls - requests are rejected, waiting for recovery timeout.
HALF_OPEN
class-attribute
instance-attribute
¶
Testing recovery - one request is allowed to test if service recovered.
CircuitBreakerStats
dataclass
¶
CircuitBreakerStats(total_successes=0, total_failures=0, times_opened=0, times_half_opened=0, times_closed=0, last_failure_at=None, last_state_change_at=None, consecutive_failures=0, total_input_tokens=0, total_output_tokens=0, total_estimated_cost=0.0)
Statistics for circuit breaker monitoring.
Provides visibility into the circuit breaker's behavior for observability and debugging, including cost tracking.
Attributes¶
total_successes
class-attribute
instance-attribute
¶
Total number of successful operations recorded.
total_failures
class-attribute
instance-attribute
¶
Total number of failed operations recorded.
times_opened
class-attribute
instance-attribute
¶
Number of times the circuit has transitioned to OPEN state.
times_half_opened
class-attribute
instance-attribute
¶
Number of times the circuit has transitioned to HALF_OPEN state.
times_closed
class-attribute
instance-attribute
¶
Number of times the circuit has transitioned to CLOSED from another state.
last_failure_at
class-attribute
instance-attribute
¶
Timestamp of the most recent failure (monotonic time).
last_state_change_at
class-attribute
instance-attribute
¶
Timestamp of the most recent state transition.
consecutive_failures
class-attribute
instance-attribute
¶
Current count of consecutive failures (resets on success).
total_input_tokens
class-attribute
instance-attribute
¶
Total input tokens consumed across all executions.
total_output_tokens
class-attribute
instance-attribute
¶
Total output tokens consumed across all executions.
total_estimated_cost
class-attribute
instance-attribute
¶
Total estimated cost in USD across all executions.
Functions¶
to_dict
¶
Convert stats to dictionary for logging/serialization.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary representation of all statistics. |
Source code in src/marianne/execution/circuit_breaker.py
CircuitBreaker
¶
Circuit breaker for preventing cascading failures.
The circuit breaker monitors execution success/failure and automatically blocks further requests when a failure threshold is exceeded. This prevents overwhelming a failing service and gives it time to recover.
Async-safe: All state modifications are protected by an asyncio.Lock.
Attributes:
| Name | Type | Description |
|---|---|---|
failure_threshold |
int
|
Number of consecutive failures before opening circuit. |
recovery_timeout |
float
|
Seconds to wait before testing recovery (OPEN -> HALF_OPEN). |
state |
float
|
Current circuit state. |
stats |
float
|
Statistics about circuit breaker behavior. |
Initialize circuit breaker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
failure_threshold
|
int
|
Number of consecutive failures before opening the circuit. Default is 5. |
5
|
recovery_timeout
|
float
|
Seconds to wait in OPEN state before transitioning to HALF_OPEN to test recovery. Default is 300 (5 minutes). |
300.0
|
name
|
str
|
Name for this circuit breaker (used in logging). |
'default'
|
Source code in src/marianne/execution/circuit_breaker.py
Attributes¶
failure_threshold
property
¶
Number of consecutive failures before opening circuit.
Functions¶
get_state
async
¶
Get the current circuit state.
This method handles automatic state transitions: - If OPEN and recovery_timeout has elapsed, transitions to HALF_OPEN.
Returns:
| Type | Description |
|---|---|
CircuitState
|
Current CircuitState. |
Source code in src/marianne/execution/circuit_breaker.py
can_execute
async
¶
Check if a request can be executed.
Returns True if: - Circuit is CLOSED (normal operation) - Circuit is HALF_OPEN (testing recovery) - Circuit is OPEN but recovery_timeout has elapsed (transitions to HALF_OPEN)
Returns False if: - Circuit is OPEN and recovery_timeout hasn't elapsed
Returns:
| Type | Description |
|---|---|
bool
|
True if the request should be allowed, False if it should be blocked. |
Source code in src/marianne/execution/circuit_breaker.py
record_success
async
¶
Record a successful operation.
Effects by state: - CLOSED: Resets consecutive failure count - HALF_OPEN: Transitions to CLOSED (recovery confirmed) - OPEN: No effect (shouldn't happen - request blocked)
Source code in src/marianne/execution/circuit_breaker.py
record_failure
async
¶
Record a failed operation.
Effects by state: - CLOSED: Increments failure count, may transition to OPEN - HALF_OPEN: Transitions to OPEN (recovery failed) - OPEN: No effect (shouldn't happen - request blocked)
Source code in src/marianne/execution/circuit_breaker.py
time_until_retry
async
¶
Get time remaining until retry is allowed.
Returns:
| Type | Description |
|---|---|
float | None
|
Seconds until the circuit transitions to HALF_OPEN, or None if |
float | None
|
the circuit is not OPEN. |
Source code in src/marianne/execution/circuit_breaker.py
record_cost
async
¶
Record token usage and estimated cost from an execution.
Updates running totals for cost tracking. Call this after each successful or failed execution that consumed tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_tokens
|
int
|
Number of input tokens consumed. |
required |
output_tokens
|
int
|
Number of output tokens consumed. |
required |
estimated_cost
|
float
|
Estimated cost in USD for this execution. |
required |
Source code in src/marianne/execution/circuit_breaker.py
check_cost_threshold
async
¶
Check if total estimated cost exceeds a threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_cost
|
float
|
Maximum allowed cost in USD. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if threshold is exceeded (should stop), False otherwise. |
Source code in src/marianne/execution/circuit_breaker.py
get_stats
async
¶
Get current statistics.
Returns:
| Type | Description |
|---|---|
CircuitBreakerStats
|
Copy of current CircuitBreakerStats. |
Source code in src/marianne/execution/circuit_breaker.py
reset
async
¶
Reset the circuit breaker to initial state.
This resets: - State to CLOSED - Failure counts to 0 - Last failure time to None
Statistics are NOT reset (use get_stats() to view history).
Source code in src/marianne/execution/circuit_breaker.py
force_open
async
¶
Force the circuit to OPEN state.
Useful for manual intervention or testing.
Source code in src/marianne/execution/circuit_breaker.py
force_close
async
¶
Force the circuit to CLOSED state.
Useful for manual intervention or testing. Also resets failure counts.
Source code in src/marianne/execution/circuit_breaker.py
__repr__
¶
Get string representation of circuit breaker.