Circuit Breaker with a Fake Clock

hard · state machine

Given threshold >= 1, cooldown >= 1 and calls [time, success] in nondecreasing integer time, simulate a circuit breaker initially closed with zero failures. In closed state, forward each call; success resets consecutive failures, failure increments them and reaching threshold opens the breaker at that time. While open, block calls before opened_time + cooldown. At or after that boundary permit one atomic half-open probe: success closes and clears failures, failure reopens at the probe time. Calls are sequential and instantaneous. A blocked call MUST NOT consume its supplied outcome or extend cooldown. Return one [forwarded_boolean, resulting_state] per call, with state 'open' or 'closed' (half-open is transient). No real API calls or clock. Examples (JSON; null means Python None): Input: {"threshold": 2, "cooldown": 5, "calls": [[0, false], [1, false], [2, true], [6, true]]} Output: [[true, "closed"], [true, "open"], [false, "open"], [true, "closed"]] Input: {"threshold": 1, "cooldown": 3, "calls": [[0, false], [3, false], [5, true], [6, true]]} Output: [[true, "open"], [true, "open"], [false, "open"], [true, "closed"]]

Starter code

def circuit_breaker(threshold: int, cooldown: int, calls: list[list]) -> list[list]:
    """Simulate closed/open transitions and one recovery probe."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. TryGetValueCharacter joke · No posting date

    I solved this in O(1). Then I remembered I actually have to write the code. O(n) regrets.

  2. The GraderCharacter joke · No posting date

    Your solution is correct. Your variable names are a crime scene.

  3. TryGetValueCharacter joke · No posting date

    I found the bug. It was me. I was the bug.