Neural Mastery
← Practice
Circuit Breaker State Transitionmedium

Circuit Breaker State Transition

medium Agents in Production 15 min

NumPy allowed · plain Python earns 10 bonus points

Implement the real circuit-breaker state machine, protecting a production agent from repeatedly hammering a failing downstream dependency (a tool API, a model endpoint).

Task

Implement circuit_breaker_state(current_state, consecutive_failures, failure_threshold, cooldown_elapsed). States are 'closed' (normal), 'open' (blocking calls), 'half_open' (testing recovery). From 'closed': go to 'open' if consecutive_failures >= failure_threshold, else stay 'closed'. From 'open': go to 'half_open' if cooldown_elapsed, else stay 'open'. From 'half_open': go to 'closed' if consecutive_failures == 0, else go back to 'open'.

Function Signature

circuit_breaker_state(current_state: str, consecutive_failures: int, failure_threshold: int, cooldown_elapsed: bool) -> str

Examples

Example 1: closed stays closed under threshold
Input: current_state = 'closed' consecutive_failures = 1 failure_threshold = 5 cooldown_elapsed = False
Output: 'closed'
Example 2: closed trips to open at threshold
Input: current_state = 'closed' consecutive_failures = 5 failure_threshold = 5 cooldown_elapsed = False
Output: 'open'
Example 3: open transitions to half_open after cooldown
Input: current_state = 'open' consecutive_failures = 5 failure_threshold = 5 cooldown_elapsed = True
Output: 'half_open'

Constraints

  • current_state in {'closed','open','half_open'}
Python3Saved ✓
def circuit_breaker_state(current_state, consecutive_failures, failure_threshold, cooldown_elapsed):
# Your implementation here
pass

Case 1: closed stays closed under threshold
Input: current_state = 'closed' consecutive_failures = 1 failure_threshold = 5 cooldown_elapsed = False
Expected: 'closed'
Case 2: closed trips to open at threshold
Input: current_state = 'closed' consecutive_failures = 5 failure_threshold = 5 cooldown_elapsed = False
Expected: 'open'
Case 3: open transitions to half_open after cooldown
Input: current_state = 'open' consecutive_failures = 5 failure_threshold = 5 cooldown_elapsed = True
Expected: 'half_open'