Circuit Breaker Transitions Over an Event Stream
Problem Statement
Simulate a circuit breaker protecting a flaky tool. Process a stream of call outcomes and report the breaker's state after each.
Background
The breaker has three states. It starts closed (calls allowed). It trips to open after fail_threshold consecutive failures. While open, calls are blocked; the outcomes in the stream while open are skipped (the breaker does not see them) until a probe. After cooldown events have elapsed since opening, it moves to half_open and allows the next outcome as a probe: a success closes it (reset failure count), a failure re-opens it (reset the cooldown clock).
Simplified model for this exercise: iterate outcomes ("ok"/"fail"). Maintain state, a consecutive-failure counter, and an opened_at index.
- closed: on "fail" increment counter; if it reaches fail_threshold, go open and record opened_at. On "ok" reset counter.
- open: if current_index - opened_at >= cooldown, switch to half_open and process this outcome as a probe; otherwise stay open.
- half_open: "ok" -> closed (counter 0); "fail" -> open (record opened_at = current index, counter = fail_threshold).
Record the state string after processing each outcome.
Your Task
def circuit_states(outcomes, fail_threshold, cooldown):
Return the list of state strings, one per outcome.
Input Format
- outcomes (list of "ok"/"fail"), fail_threshold (int), cooldown (int).
Output Format
- A list of state strings.
Sample
print(circuit_states(["fail","fail","ok","ok"], 2, 1))
Output:
['closed', 'open', 'closed', 'closed']
Example
print(circuit_states(["fail","fail","ok","ok"], 2, 1))
['closed', 'open', 'closed', 'closed']
- Index 0 (
"fail"): The breaker starts inclosedstate. The consecutive failure count increments to 1. Since (the threshold), the state remainsclosed. - Index 1 (
"fail"): The failure count increments to 2. Since , the breaker trips toopenand recordsopened_at = 1. - Index 2 (
"ok"): The state isopen. We check the cooldown condition: . Since (the cooldown), the breaker transitions tohalf_opento probe. The outcome is"ok", so the probe succeeds, and the state resets toclosedwith the failure count reset to 0. - Index 3 (
"ok"): The state isclosed. The outcome is"ok", so the failure count remains 0. The state staysclosed. - The final output is
['closed', 'open', 'closed', 'closed']
Constraints
- States are
"closed","open","half_open". - Trip after
fail_thresholdconsecutive failures. - From open, after
cooldownelapsed indices, the next outcome is a half-open probe.