# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-an-mcp-streamable-http-session-has-silently-degraded-into-a-zombie-reconnect-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-an-mcp-streamable-http-session-has-silently-degraded-into-a-zombie-reconnect-loop.warrant.json
# Markdown SHA-256:   6887ad8d739d30692fabac414ef17b0e8f26f1683c3224982a57a4f260bcc22f
# Code AST SHA-256:   af1274d1277c88fd944bfd7be147ee6e3c9035b721bb4dbbf983f4592d8a7aec
# Verified Classes:   ZombieSessionError, SessionLiveness
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ZombieSessionError(RuntimeError):
    """Raised when a streamable-HTTP MCP session is alive at the socket
    layer but its reply stream has stopped advancing (backpressure zombie)."""
    pass


@dataclass
class SessionLiveness:
    ack_high_water: int = 0          # highest JSON-RPC id the server has acked (POST 202)
    reply_high_water: int = 0        # highest JSON-RPC id for which a reply arrived on SSE
    last_heartbeat_ts: float = 0.0
    last_reply_ts: float = 0.0
    last_event_id: str | None = None
    outstanding: dict = field(default_factory=dict)  # id -> enqueue timestamp


def check_liveness(
    live: SessionLiveness,
    *,
    now: float,
    heartbeat_grace: float = 30.0,
    stall_threshold: float = 20.0,
) -> None:
    """Enforce the reply-progress invariant.

    A current heartbeat does NOT prove delivery. We only consider the session
    healthy if the reply high-water mark advances within stall_threshold for
    every outstanding request, regardless of heartbeat freshness.
    """
    heartbeat_fresh = (now - live.last_heartbeat_ts) <= heartbeat_grace
    if not heartbeat_fresh:
        # Socket genuinely dead: clean reconnect path, not a zombie.
        raise ZombieSessionError(
            f"heartbeat stale by {now - live.last_heartbeat_ts:.1f}s; "
            "clean reconnect required"
        )

    # Heartbeats are fresh, but is the reply stream actually moving?
    stalled = [
        rid
        for rid, enq in live.outstanding.items()
        if rid > live.reply_high_water and (now - enq) > stall_threshold
    ]
    if stalled and live.ack_high_water > live.reply_high_water:
        # Divergence: requests acked, replies not delivered, heartbeats current.
        raise ZombieSessionError(
            "reply stream stalled behind backpressure: "
            f"ack_mark={live.ack_high_water} reply_mark={live.reply_high_water} "
            f"stalled_ids={sorted(stalled)} last_event_id={live.last_event_id}; "
            "resume GET stream with Last-Event-ID rather than full re-init"
        )


def resume_stream(live: SessionLiveness, *, reconnect_fn, max_retries: int = 1) -> None:
    """Attempt Last-Event-ID resumption; escalate to full re-init only if the
    reply high-water mark fails to advance after resumption."""
    for attempt in range(max_retries + 1):
        before = live.reply_high_water
        reconnect_fn(last_event_id=live.last_event_id)
        if live.reply_high_water > before:
            return
    raise ZombieSessionError(
        "resumption did not advance reply high-water mark after "
        f"{max_retries + 1} attempts; session state must be rebuilt from checkpoint"
    )
