# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-streamable-mcp-session-s-last-event-id-resume-as-a-new-session-rather-than-a-continuation-and-how-does.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-streamable-mcp-session-s-last-event-id-resume-as-a-new-session-rather-than-a-continuation-and-how-does.warrant.json
# Markdown SHA-256:   34d4e72a99948305b6f112671a073fcec83193b58eb7f90167e09c23c10c7922
# Code AST SHA-256:   7be53b9d17e2e866c3493408479f96878232c0978b264a00a3d76ccfc628d44f
# Verified Classes:   SilentRenegotiationError, SessionGoneError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SilentRenegotiationError(RuntimeError):
    """Raised when a resume attempt is answered with a different session ID,
    indicating the server renegotiated rather than resumed."""
    pass


class SessionGoneError(RuntimeError):
    """Raised when the server reports the session as unknown or expired (404/410)."""
    pass


def classify_resume_response(
    sent_session_id: str,
    response_status: int,
    response_session_id: str | None,
) -> str:
    """Classify a resume attempt. Returns 'resumed', 'renegotiated', or 'gone'.

    Never returns 'resumed' unless the response session ID matches the one sent.
    """
    if response_status in (404, 410):
        raise SessionGoneError(
            f"session {sent_session_id!r} is gone (status {response_status}); "
            "must renegotiate from a fresh initialize"
        )

    if response_session_id is None:
        raise SilentRenegotiationError(
            f"resume for session {sent_session_id!r} returned no Mcp-Session-Id; "
            "protocol violation, refusing to guess continuity"
        )

    if response_session_id != sent_session_id:
        # The dangerous case: a 200 OK carrying a brand-new session.
        raise SilentRenegotiationError(
            f"resume for session {sent_session_id!r} was silently renegotiated "
            f"into session {response_session_id!r}; do not replay buffered "
            "client state or compare Last-Event-ID across sessions"
        )

    return "resumed"


def apply_resume(
    sent_session_id: str,
    response_status: int,
    response_session_id: str | None,
    last_event_id_sent: int,
    events_received: list[dict],
) -> list[dict]:
    """Apply a resume only if continuity is proven; otherwise refuse."""
    verdict = classify_resume_response(sent_session_id, response_status, response_session_id)
    if verdict != "resumed":
        # Defensive: classify_resume_response already raises on non-resume,
        # but keep the invariant explicit.
        raise SilentRenegotiationError(
            f"unexpected verdict {verdict!r}; refusing to apply events"
        )
    # Safe: same session, so Last-Event-ID is meaningful and monotonic.
    return [e for e in events_received if e["id"] > last_event_id_sent]
