# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-streamable-session-versus-a-poisoned-sse-to-streamable-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-streamable-session-versus-a-poisoned-sse-to-streamable-upgrade.warrant.json
# Markdown SHA-256:   ecf6276a358a47cb5b4e526f74fd718e8e5062dae9b621fc488a028759b04e98
# Code AST SHA-256:   49cbc47cd29732da1ef3e16cf7d930661606c2c2b32e9d7a877eca69f7660374
# Verified Classes:   PoisonedUpgradeError, SessionBindingError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class PoisonedUpgradeError(RuntimeError):
    """Raised when an SSE-to-streamable upgrade response is structurally ambiguous."""


class SessionBindingError(RuntimeError):
    """Raised when a session ID is not honored by the handler that emitted it."""


def validate_upgrade_response(status: int, headers: dict, first_frame: str | None) -> str:
    """Return the validated Mcp-Session-Id, or raise if the upgrade is poisoned."""
    if status != 200:
        raise PoisonedUpgradeError(f"upgrade returned status {status}")
    content_type = headers.get("content-type", "")
    if "text/event-stream" not in content_type:
        raise PoisonedUpgradeError(f"unexpected content-type {content_type!r}")
    session_id = headers.get("mcp-session-id")
    if session_id is None:
        raise PoisonedUpgradeError(
            "no Mcp-Session-Id on streamable upgrade response; "
            "treat as legacy SSE, not streamable"
        )
    if first_frame is not None and first_frame.startswith("event: endpoint"):
        raise PoisonedUpgradeError(
            "response carries both Mcp-Session-Id and legacy endpoint frame; "
            "handler identity is ambiguous"
        )
    return session_id


def validate_resumption(status: int, requested_last_event_id: int, replayed_ids: list[int]) -> None:
    """Raise if the event log was rotated under a resumption attempt."""
    if status == 404:
        raise SessionBindingError("session not recognized on resumption; re-initialize")
    if not replayed_ids:
        return
    if min(replayed_ids) <= requested_last_event_id:
        raise PoisonedUpgradeError(
            f"replayed event id {min(replayed_ids)} <= requested "
            f"{requested_last_event_id}; event log rotated, replay would lose events"
        )
