# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-mcp-streamable-session-resumption-and-force-a-fresh-sse-negotiation-after-a-last-event-id-replay-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-mcp-streamable-session-resumption-and-force-a-fresh-sse-negotiation-after-a-last-event-id-replay-gap.warrant.json
# Markdown SHA-256:   3516d454ad68395403dffd185c34b00846bdb493c2d51c43edafa7f682afc4c4
# Code AST SHA-256:   4b6ed03c2fa515d879349597da6c0415b7822b39e50ccf2736929419c33fe720
# Verified Classes:   SessionContinuityViolation, StreamState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class SessionContinuityViolation(RuntimeError):
    """Raised when a streamable-session resumption cannot be proven gap-free."""


@dataclass
class StreamState:
    session_token: str
    last_event_id: int = 0
    seen_ids: list = field(default_factory=list)


def resume_or_renegotiate(
    state: StreamState,
    response_session_token: str,
    first_event_id: Optional[int],
    resumption_timeout_s: float = 5.0,
    waited_s: float = 0.0,
) -> str:
    """
    Decide whether to continue the existing streamable session or abandon it
    for a fresh SSE negotiation.

    Returns "resume" or "renegotiate". Raises SessionContinuityViolation when
    the transport reports success but the sequence is provably broken and the
    caller has not opted into renegotiation.
    """
    # Session identity must be stable across the reconnect.
    if response_session_token != state.session_token:
        raise SessionContinuityViolation(
            f"session token changed on resumption: "
            f"held={state.session_token!r} got={response_session_token!r}"
        )

    # No event arrived within the resumption window: zombie resumption.
    if first_event_id is None:
        if waited_s >= resumption_timeout_s:
            return "renegotiate"
        raise SessionContinuityViolation(
            "resumption accepted but no replay event within timeout"
        )

    # Namespace reuse after session reap: event id went backwards.
    if first_event_id <= state.last_event_id:
        raise SessionContinuityViolation(
            f"event id regressed: last={state.last_event_id} "
            f"first_replayed={first_event_id} (session namespace reuse)"
        )

    # Gap: events between last_event_id+1 and first_event_id were lost.
    if first_event_id > state.last_event_id + 1:
        # Unprovable continuity; caller must renegotiate, not resume.
        return "renegotiate"

    # Contiguous: first_event_id == last_event_id + 1.
    return "resume"


def apply_resumption(state: StreamState, decision: str, new_token: str) -> StreamState:
    if decision == "resume":
        return state
    if decision == "renegotiate":
        # Fresh SSE negotiation: new session, reset sequence, re-run prefix.
        return StreamState(session_token=new_token, last_event_id=0, seen_ids=[])
    raise SessionContinuityViolation(f"unknown decision {decision!r}")
