# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-streamable-http-mcp-session-id-rebind-as-a-context-invalidating-event-rather-than-a-transparent-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-streamable-http-mcp-session-id-rebind-as-a-context-invalidating-event-rather-than-a-transparent-reconnect.warrant.json
# Markdown SHA-256:   866178c1bb3446835e4671670fa8c5f91b4f91f2d5a0728018894e3f178d9f51
# Code AST SHA-256:   85eb2a675854d251ac370190c6c977350327b63dbaf16dac74c0db1672ed905d
# Verified Classes:   SessionRebindError, HandleBinding, AgentSessionState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class SessionRebindError(RuntimeError):
    """Raised when a server-issued handle is used under a rebound MCP session."""


@dataclass
class HandleBinding:
    session_id: str
    cursor: Optional[str] = None
    job_id: Optional[str] = None


@dataclass
class AgentSessionState:
    session_id: Optional[str] = None
    bindings: list[HandleBinding] = field(default_factory=list)
    stale: bool = False

    def observe_session_header(self, new_id: Optional[str]) -> None:
        """Called on every response. A changed id is a rebind, not a reconnect."""
        if new_id is None:
            return
        if self.session_id is not None and new_id != self.session_id:
            # Rebind detected: invalidate every handle bound to the old session.
            self.stale = True
            self.bindings.clear()
        self.session_id = new_id

    def bind_handle(self, cursor: Optional[str] = None, job_id: Optional[str] = None) -> HandleBinding:
        if self.session_id is None:
            raise SessionRebindError("cannot bind handle before session established")
        b = HandleBinding(session_id=self.session_id, cursor=cursor, job_id=job_id)
        self.bindings.append(b)
        return b

    def require_handle(self, binding: HandleBinding) -> HandleBinding:
        """Guard called before reusing a server-issued handle in a later step."""
        if self.stale:
            raise SessionRebindError(
                "session rebound; handle invalidated and plan must be re-derived "
                "from durable state, not the transport cursor"
            )
        if binding.session_id != self.session_id:
            raise SessionRebindError(
                f"handle bound to session {binding.session_id!r} used under "
                f"session {self.session_id!r}"
            )
        return binding


def resume_pagination(state: AgentSessionState, binding: HandleBinding) -> HandleBinding:
    """Resume a paginated tool call. Refuses to resume across a rebind."""
    return state.require_handle(binding)
