Skip to content

fix(pusher): circuit breaker + graceful degradation (#6022) - #6030

Merged
beastoin merged 5 commits into
mainfrom
fix/pusher-circuit-breaker-main
Mar 25, 2026
Merged

beastoin merged 5 commits into
mainfrom
fix/pusher-circuit-breaker-main

Conversation

@beastoin

Copy link
Copy Markdown
Collaborator

Fixes #6022 — P0: Pusher retry exhaustion cascade.

Cherry-pick of PR #6025 (merged to feat/opus-encoding-5418) rebased onto main for deployment.

Three bugs fixed:

  1. No circuit breaker across sessions — added pod-level circuit breaker (CLOSED→OPEN at ≥20 failures/30s →HALF_OPEN after 60s cooldown, 1 probe →CLOSED on success)
  2. Exception swallowed in _connect() causing infinite retry — connect_to_trigger_pusher() now records success/failure on the breaker and fails fast if breaker trips during retries
  3. No graceful degradation — initial connect failure no longer closes client WS with 1011; instead enters degraded mode with dedicated reconnect loop, DG streaming continues uninterrupted

Files changed:

  • backend/utils/pusher.py — PusherCircuitBreaker singleton, PusherCircuitBreakerOpen exception
  • backend/utils/metrics.py — 3 Prometheus metrics (state gauge, rejection counter, degraded sessions gauge)
  • backend/routers/transcribe.py — PusherReconnectState enum, _mark_disconnected(), _pusher_reconnect_loop(), start_degraded(), degraded-aware conversation routing
  • backend/tests/unit/test_pusher_circuit_breaker.py — 32 unit tests
  • backend/test.sh — test registration

by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

lgtm

@beastoin
beastoin merged commit 3b3e99b into main Mar 25, 2026
2 checks passed
@beastoin
beastoin deleted the fix/pusher-circuit-breaker-main branch March 25, 2026 08:25
@greptile-apps

greptile-apps Bot commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes three Pusher reliability bugs (#6022) by introducing a pod-level PusherCircuitBreaker singleton, a per-session PusherReconnectState machine, and graceful degradation so that initial Pusher failures no longer hard-close the client WebSocket with code 1011.

Key changes:

  • backend/utils/pusher.py — PusherCircuitBreaker (CLOSED→OPEN at ≥20 failures/30s, HALF_OPEN after 60s cooldown, single-probe gating) + PusherCircuitBreakerOpen exception; connect_to_trigger_pusher now records success/failure on the breaker and raises PusherCircuitBreakerOpen to fast-fail callers.
  • backend/routers/transcribe.py — PusherReconnectState enum replaces three scattered pusher_connected = False; await connect() sites with a single _pusher_reconnect_loop() task; start_degraded() handles initial-connect failures; conversation routing is degraded-aware.
  • backend/utils/metrics.py — three new Prometheus gauges/counters for observability.
  • backend/tests/unit/test_pusher_circuit_breaker.py — 32 unit tests covering all circuit breaker transitions and integration scenarios.

Issues found:

  • is_active=lambda: websocket_active was unintentionally removed from the multi-channel process_audio_dg call (likely a cherry-pick artifact from fix(pusher): circuit breaker + reconnect state machine + graceful degradation #6025), which can cause zombie Deepgram connections when a session ends mid-connection-setup.
  • PUSHER_SESSION_DEGRADED.inc() fires at the start of the reconnect loop (including transient RECONNECT_BACKOFF sessions), inflating the gauge beyond sessions that are truly in DEGRADED state.
  • The pusher_receive retry-exhaustion handler only checks DEGRADED state for fallback routing, missing HALF_OPEN_PROBE, unlike is_degraded() which covers both.

Confidence Score: 4/5

  • Safe to merge after fixing the unintentional is_active removal; the core circuit breaker and graceful degradation logic is sound.
  • The circuit breaker design, state machine logic, and test coverage are solid. One targeted P1 fix remains: restoring is_active=lambda: websocket_active to the multi-channel process_audio_dg call, which was inadvertently dropped during the cherry-pick. The two P2 issues (metric semantics, HALF_OPEN_PROBE fallback routing) are non-blocking monitoring/edge-case improvements. Once the P1 line is restored this PR is ready.
  • backend/routers/transcribe.py — verify the is_active restoration at line 984–991 and the PUSHER_SESSION_DEGRADED increment placement.

Important Files Changed

Filename Overview
backend/utils/pusher.py Adds pod-level PusherCircuitBreaker singleton (CLOSED→OPEN at ≥20 failures/30s → HALF_OPEN after 60s cooldown) and integrates it into connect_to_trigger_pusher; one piece of unreachable dead code at line 169.
backend/utils/metrics.py Adds three Prometheus metrics (PUSHER_CIRCUIT_BREAKER_STATE gauge, PUSHER_CIRCUIT_BREAKER_REJECTIONS counter, PUSHER_SESSION_DEGRADED gauge); straightforward and clean.
backend/routers/transcribe.py Introduces per-session PusherReconnectState machine, _mark_disconnected(), _pusher_reconnect_loop(), start_degraded(), and degraded-aware conversation routing; contains two issues: unintentional removal of is_active from multi-channel DG setup, and PUSHER_SESSION_DEGRADED metric incremented too early in the reconnect lifecycle.
backend/tests/unit/test_pusher_circuit_breaker.py 32 well-structured unit tests covering circuit breaker state transitions, probe gating, metric updates, and full recovery lifecycle; good coverage of the new PusherCircuitBreaker logic.
backend/test.sh Registers the new test_pusher_circuit_breaker.py module in the CI test runner script; straightforward addition.

Sequence Diagram

sequenceDiagram
    participant WS as Client WebSocket
    participant TH as transcribe.py (_stream_handler)
    participant RL as _pusher_reconnect_loop
    participant CB as PusherCircuitBreaker (pod-level)
    participant PW as Pusher WebSocket

    WS->>TH: connect
    TH->>CB: can_attempt()?
    CB-->>TH: True (CLOSED)
    TH->>PW: connect_to_trigger_pusher()
    PW-->>TH: ws (success)
    TH->>CB: record_success()
    Note over TH: pusher_connected=True, state=CONNECTED

    PW--xTH: ConnectionClosed
    TH->>TH: _mark_disconnected()
    Note over TH: state=RECONNECT_BACKOFF
    TH->>RL: create_task(_pusher_reconnect_loop)
    Note over RL: PUSHER_SESSION_DEGRADED.inc()

    loop RECONNECT_BACKOFF (up to 6 attempts)
        RL->>CB: can_attempt()?
        CB-->>RL: True/False
        alt circuit breaker OPEN
            CB-->>RL: PusherCircuitBreakerOpen
            RL->>RL: state=DEGRADED (fast-path)
        else normal retry
            RL->>PW: connect()
            alt success
                PW-->>RL: ws connected
                Note over RL: state=CONNECTED, break
            else failure
                RL->>RL: reconnect_attempts++
            end
        end
    end

    Note over RL: 6 failures → state=DEGRADED
    RL->>TH: route pending convs to _create_conversation_fallback

    loop DEGRADED (60s cooldown, then HALF_OPEN_PROBE)
        RL->>RL: wait min(remaining, 5s)
        Note over RL: after 60s → state=HALF_OPEN_PROBE
        RL->>PW: single probe connect()
        alt probe success
            PW-->>RL: ws connected
            Note over RL: state=CONNECTED, break
        else probe failure
            RL->>RL: state=DEGRADED, reset degraded_since
        end
    end

    Note over RL: PUSHER_SESSION_DEGRADED.dec() (finally)
Loading

Comments Outside Diff (2)

  1. backend/routers/transcribe.py, line 984-991 (link)

    P1 Unintentional removal of is_active from multi-channel Deepgram setup

    This PR removes is_active=lambda: websocket_active from the process_audio_dg call in the multi-channel STT initialization path. The parameter is still accepted by process_audio_dg (and passed down to connect_to_deepgram_with_backoff), where it's used to abort connection retries if the session ends mid-setup.

    Without it, if the WebSocket session closes while the multi-channel Deepgram connection is being established (e.g. the client disconnects during the retry loop), the retry logic will continue even though websocket_active is already False. This wastes resources and delays cleanup.

    This looks like an unintended artifact from the cherry-pick of fix(pusher): circuit breaker + reconnect state machine + graceful degradation #6025. The parallel single-channel path and the Pusher _connect() still pass is_active correctly.

  2. backend/utils/pusher.py, line 158-169 (link)

    P2 Line 169 is unreachable dead code

    When retries > 0 (all normal call-sites use retries=3 or retries=5), the last iteration of the loop (attempt == retries - 1) always re-raises via raise on line 159, so execution never reaches line 169. The only path that reaches it is retries=0, which is not a valid production argument.

    Additionally, if it ever were reached, Exception(f'...', uid) constructs an exception with a tuple (message, uid) as args — str(ex) would render as "('Could not open socket: All retry attempts failed.', '<uid>')", which is confusing in logs.

    Consider removing this dead line (the raise on line 159 already handles the last-attempt failure) or replacing it with an assert False to make the invariant explicit.

Reviews (1): Last reviewed commit: "chore(test): add circuit breaker tests t..." | Re-trigger Greptile

Comment on lines +1487 to +1488
logger.info(f"Pusher reconnect loop started {uid} {session_id}")
PUSHER_SESSION_DEGRADED.inc()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 PUSHER_SESSION_DEGRADED metric incremented too early

PUSHER_SESSION_DEGRADED.inc() is called when the reconnect loop starts — which happens on any disconnect (even a transient one that recovers in seconds during RECONNECT_BACKOFF). The metric name pusher_sessions_degraded implies sessions that have exhausted retries and are in the actual DEGRADED state.

As written, a brief Pusher blip that self-heals in 1-2 retries will still appear in the pusher_sessions_degraded gauge, inflating alerts and dashboards.

Consider incrementing the gauge only when the state machine transitions to DEGRADED, and decrementing when it exits:

# In _pusher_reconnect_loop, remove the .inc() here
# Instead, inside the RECONNECT_BACKOFF block after transition:
reconnect_state = PusherReconnectState.DEGRADED
PUSHER_SESSION_DEGRADED.inc()   # <-- move here
degraded_since = time.monotonic()

And in the finally block, only decrement if we ever entered DEGRADED:

finally:
    if reconnect_state in (PusherReconnectState.DEGRADED, PusherReconnectState.HALF_OPEN_PROBE):
        PUSHER_SESSION_DEGRADED.dec()

Comment on lines +1437 to +1439
# Route to fallback if in degraded mode
if reconnect_state == PusherReconnectState.DEGRADED:
await _fallback_process_conversation(cid)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Fallback routing misses HALF_OPEN_PROBE state

When a pending conversation exhausts its Pusher retries, the code routes it to fallback only if reconnect_state == PusherReconnectState.DEGRADED. However, is_degraded() (used for all other conversation routing decisions) returns True for both DEGRADED and HALF_OPEN_PROBE. A session stuck in HALF_OPEN_PROBE with pusher_connected=False will drop conversations that exceed MAX_RETRIES_PER_REQUEST without routing them to fallback.

Suggested change
# Route to fallback if in degraded mode
if reconnect_state == PusherReconnectState.DEGRADED:
await _fallback_process_conversation(cid)
if reconnect_state in (PusherReconnectState.DEGRADED, PusherReconnectState.HALF_OPEN_PROBE):
await _fallback_process_conversation(cid)

This aligns with is_degraded() and ensures no conversation is silently abandoned.

beastoin added a commit that referenced this pull request Mar 25, 2026
The _pusher_reconnect_loop added in PR #6030 uses random.random() for
backoff jitter but the random module was never imported, causing
NameError on every reconnect attempt. This means the circuit breaker
never reconnects — sessions die on first pusher disconnect.

60 errors across 15 pods since deploy.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

P0: Pusher retry exhaustion cascade — circuit breaker + graceful degradation

1 participant