# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-a-capability-renegotiation-it-never-saw.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-a-capability-renegotiation-it-never-saw.warrant.json
# Markdown SHA-256:   762f38416d351999eb555b6a52a7ff9505adf40e60740580986d5df6b8f529d0
# Code AST SHA-256:   ccb9718717753a27055c7b147e390d897d4b9dc28aa86d33b8b86eaafdd6236a
# Verified Classes:   CapabilityEpochMismatch, CapabilityLease, ResumableSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CapabilityEpochMismatch(RuntimeError):
    """Raised when a tool call is issued against a capability epoch that is not
    provably current. This is a hard stop: the agent must re-initialize or
    re-fetch the tool manifest before any further calls."""
    pass


@dataclass(frozen=True)
class CapabilityLease:
    tool_name: str
    epoch: int
    schema_hash: str


class ResumableSession:
    def __init__(self, server_epoch: int):
        self._server_epoch = server_epoch
        self._lease: CapabilityLease | None = None
        self._cursor: int = 0
        self._cursor_at_lease: int = -1

    def apply_control_event(self, event_id: int, new_epoch: int) -> None:
        # Control events advance the cursor and mutate epoch together.
        if event_id <= self._cursor:
            return
        self._cursor = event_id
        self._server_epoch = new_epoch
        # Any epoch change invalidates the lease; it must be re-proved.
        self._lease = None

    def resume_from(self, last_event_id: int, server_epoch: int) -> None:
        # A resume is only safe if the cursor it resumes from is the cursor
        # at which our lease was last validated AND the epoch is unchanged.
        if last_event_id != self._cursor_at_lease:
            raise CapabilityEpochMismatch(
                f"resume from {last_event_id} does not match lease cursor "
                f"{self._cursor_at_lease}; capability state cannot be proven"
            )
        if server_epoch != self._server_epoch:
            raise CapabilityEpochMismatch(
                f"server epoch {server_epoch} != cached epoch "
                f"{self._server_epoch}; renegotiation occurred across gap"
            )

    def bind_lease(self, tool_name: str, schema_hash: str) -> CapabilityLease:
        lease = CapabilityLease(tool_name, self._server_epoch, schema_hash)
        self._lease = lease
        self._cursor_at_lease = self._cursor
        return lease

    def call_tool(self, tool_name: str, args: dict, claimed_epoch: int) -> dict:
        if self._lease is None or self._lease.tool_name != tool_name:
            raise CapabilityEpochMismatch(
                f"no valid lease for tool {tool_name!r}; re-fetch manifest"
            )
        if claimed_epoch != self._server_epoch or claimed_epoch != self._lease.epoch:
            raise CapabilityEpochMismatch(
                f"tool {tool_name!r} called with epoch {claimed_epoch}, "
                f"server epoch is {self._server_epoch}; refusing to coerce args"
            )
        # Only now is it safe to dispatch against the negotiated schema.
        return {"tool": tool_name, "args": args, "epoch": self._server_epoch}
