# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-mcp-http-native-transport-but-resumes-a-session-against-a-stateless-stream-replica.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-mcp-http-native-transport-but-resumes-a-session-against-a-stateless-stream-replica.warrant.json
# Markdown SHA-256:   fc141aa5958065e6c1607ea1c703a389a59bebbfb30d94a523b934e16140d98c
# Code AST SHA-256:   25887a4dfd110e5bdf06d4b2a06581cbf75612b096c539e83e4bf329d3ce6ba5
# Verified Classes:   SessionResumptionError, SessionRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionResumptionError(RuntimeError):
    """Raised when a resumed MCP stream cannot be validated against local state."""
    pass


class SessionRegistry:
    def __init__(self, replica_id: str) -> None:
        self.replica_id = replica_id
        self._sessions: dict[str, int] = {}  # session_id -> highest event id retained

    def mint(self, session_id: str) -> None:
        self._sessions[session_id] = 0

    def resume(self, session_id: str, last_event_id: int) -> int:
        if session_id not in self._sessions:
            # Unknown session: never mint implicitly, never serve from empty queue.
            raise SessionResumptionError(
                f"replica {self.replica_id} did not mint session {session_id!r}; "
                "refusing to resume (client must re-initialize or be routed to owner)"
            )
        retained = self._sessions[session_id]
        if last_event_id < retained:
            raise SessionResumptionError(
                f"Last-Event-ID {last_event_id} precedes retained window {retained} "
                f"for session {session_id!r}; resumption would lose events"
            )
        return retained + 1


def handle_resume(registry: SessionRegistry, session_id: str, last_event_id: int) -> int:
    try:
        return registry.resume(session_id, last_event_id)
    except SessionResumptionError as exc:
        # Surface as a distinguishable 404 rather than a generic transport failure.
        raise SessionResumptionError(f"404 unknown-or-stale-session: {exc}") from exc
