# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-mcp-sse-resumption-state-after-a-gateway-failover-and-why-the-last-event-id-is-not-sufficient.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-mcp-sse-resumption-state-after-a-gateway-failover-and-why-the-last-event-id-is-not-sufficient.warrant.json
# Markdown SHA-256:   f91fa1e649d7b2c578bde6b8a8fe6bbd70f83d5160780b33e59678fd105dfa8c
# Code AST SHA-256:   79853c07506e2f919aa83c78231f1b1f99762bff52aeb843f5ef0504b4ccaac1
# Verified Classes:   SessionResumptionViolation, McpSessionRegistry
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class SessionResumptionViolation(RuntimeError):
    """Raised when an SSE resumption request cannot be honored by the receiving replica."""
    pass


class McpSessionRegistry:
    def __init__(self, replica_id: str):
        self.replica_id = replica_id
        # session_id -> {"epoch": int, "events": list[(int, str)]}
        self._sessions: dict[str, dict] = {}
        self._retained_event_floor = 512

    def _lookup(self, session_id: str):
        return self._sessions.get(session_id)

    def handle_stream_get(self, session_id: str | None, last_event_id: str | None) -> list[str]:
        """
        Resolve a GET /mcp SSE request. Returns the list of events to replay.
        Raises SessionResumptionViolation when the request must be answered with 404.
        """
        if session_id is None:
            raise SessionResumptionViolation("missing Mcp-Session-Id on stream request")

        record = self._lookup(session_id)

        # Boundary: presence of Last-Event-ID turns an unknown session from
        # "create fresh" into "reject". This is the affinity-failover amnesia guard.
        if record is None:
            if last_event_id is not None:
                # We are a replica that never held this session (e.g. gateway
                # rerouted after drain). We cannot distinguish "pruned" from
                # "never existed here", so we must NOT silently start a new stream.
                raise SessionResumptionViolation(
                    f"unknown session {session_id!r} with Last-Event-ID "
                    f"{last_event_id!r} on replica {self.replica_id!r}; "
                    f"refusing to fabricate resumption"
                )
            # Genuinely new stream with no resumption claim: create session.
            self._sessions[session_id] = {"epoch": 1, "events": []}
            return []

        if last_event_id is None:
            return []

        try:
            requested = int(last_event_id)
        except ValueError:
            raise SessionResumptionViolation(
                f"non-integer Last-Event-ID {last_event_id!r} for session {session_id!r}"
            )

        events = record["events"]
        if not events:
            # Session exists but has no events; a resumption claim is incoherent.
            raise SessionResumptionViolation(
                f"session {session_id!r} has empty log but client claims {requested}"
            )

        # Epoch check: an ID from a prior epoch means the session was re-created.
        highest = events[-1][0]
        if requested > highest:
            raise SessionResumptionViolation(
                f"Last-Event-ID {requested} exceeds high-water mark {highest} "
                f"for session {session_id!r}"
            )

        oldest = events[0][0]
        if requested < oldest - 1:
            # Requested position already pruned; cannot honor replay.
            raise SessionResumptionViolation(
                f"Last-Event-ID {requested} older than retained window "
                f"(floor={oldest}) for session {session_id!r}"
            )

        return [payload for (eid, payload) in events if eid > requested]

    def append_event(self, session_id: str, payload: str) -> int:
        record = self._sessions[session_id]
        next_id = (record["events"][-1][0] + 1) if record["events"] else 1
        record["events"].append((next_id, payload))
        if len(record["events"]) > self._retained_event_floor:
            record["events"].pop(0)
        return next_id


def resume_or_fail(registry: McpSessionRegistry, session_id, last_event_id) -> list[str]:
    try:
        return registry.handle_stream_get(session_id, last_event_id)
    except SessionResumptionViolation as exc:
        # Caller maps this to HTTP 404 so the client re-initializes.
        raise SessionResumptionViolation(str(exc)) from exc
