# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-resumed-mcp-streamable-session-as-a-new-event-source-rather-than-a-continuation-of-the-old-one.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-resumed-mcp-streamable-session-as-a-new-event-source-rather-than-a-continuation-of-the-old-one.warrant.json
# Markdown SHA-256:   31a7215418f76ba1ed6f3dc810bc9cbb3be77729782af6c719f17c3f4f2e62da
# Code AST SHA-256:   3e7024ae61eecd5bf0ca30ce4b4946697f4fddca225c4fd8f4ebc0bd3016842f
# Verified Classes:   StreamContinuityError, StreamState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class StreamContinuityError(RuntimeError):
    """Raised when a resumed MCP streamable session cannot be treated as continuous."""


@dataclass
class StreamState:
    session_id: str
    last_event_id: Optional[int] = None
    in_flight_tool: Optional[str] = None
    last_event_wallclock: float = 0.0
    progress_cadence_s: float = 30.0
    continuity_degraded: bool = False
    _seen_ids: set[int] = field(default_factory=set)


def on_reconnect(
    state: StreamState,
    now: float,
    replayed_ids: list[int],
) -> StreamState:
    """
    Decide whether a resumed stream is a continuation or a new event source.

    Implements the new-source invariant: an empty replay during in-flight work
    is *unknown*, never *zero missed events*.
    """
    if state.in_flight_tool is None:
        # No async work to lose; safe to treat as continuation.
        return state

    gap_s = now - state.last_event_wallclock

    # Condition (1) unverified: empty replay while work is in flight.
    if not replayed_ids:
        if gap_s > state.progress_cadence_s:
            state.continuity_degraded = True
            raise StreamContinuityError(
                f"session {state.session_id}: empty replay after {gap_s:.1f}s "
                f"(cadence {state.progress_cadence_s}s) during in-flight "
                f"tool {state.in_flight_tool!r}; stream cannot be assumed continuous"
            )
        return state

    # Condition (3) check: IDs must sort strictly after last_event_id.
    first = replayed_ids[0]
    if state.last_event_id is not None and first <= state.last_event_id:
        # Per-connection counter reset detected. ID-based dedup is unsafe.
        state.continuity_degraded = True
        state._seen_ids.clear()  # abandon ID dedup; caller must use content hashes
        raise StreamContinuityError(
            f"session {state.session_id}: replayed id {first} does not sort after "
            f"last_event_id {state.last_event_id}; server uses per-connection "
            f"counters, ID monotonicity invalid"
        )

    for eid in replayed_ids:
        state._seen_ids.add(eid)
    state.last_event_id = replayed_ids[-1]
    return state
