# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-affinity-as-a-resumption-invariant-rather-than-a-routing-hint.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-affinity-as-a-resumption-invariant-rather-than-a-routing-hint.warrant.json
# Markdown SHA-256:   942e64482d05adcc349cf29590f604532c8dcda103f7d9179af5f46dd6c00d7f
# Code AST SHA-256:   565d1bead0c4a32daa4dafa228cc084f7ffd55c2922a80485b581fe8530eb254
# Verified Classes:   ForeignResumptionCursor, StreamReplayBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ForeignResumptionCursor(RuntimeError):
    """Raised when a Last-Event-ID cannot be attributed to this replica's stream."""
    pass


class StreamReplayBuffer:
    """Per-replica, per-session SSE replay buffer keyed by replica-local integer IDs."""

    def __init__(self, instance_fingerprint: str):
        self.instance_fingerprint = instance_fingerprint
        self._issued: dict[str, set[int]] = {}   # session_id -> issued event IDs
        self._events: dict[str, list[tuple[int, dict]]] = {}

    def emit(self, session_id: str, event_id: int, payload: dict) -> None:
        self._issued.setdefault(session_id, set()).add(event_id)
        self._events.setdefault(session_id, []).append((event_id, payload))

    def resume(self, session_id: str, last_event_id: str) -> list[dict]:
        # A cursor from another replica (or another build) will not parse as
        # an int this replica ever issued. Reject rather than replay blindly.
        try:
            cursor = int(last_event_id)
        except (TypeError, ValueError):
            raise ForeignResumptionCursor(
                f"Last-Event-ID={last_event_id!r} is not an integer cursor; "
                f"replica {self.instance_fingerprint} cannot attribute it. "
                f"Client must re-initialize and reconcile in-flight tool calls."
            )

        issued = self._issued.get(session_id)
        if issued is None:
            raise ForeignResumptionCursor(
                f"Session {session_id!r} unknown to replica {self.instance_fingerprint}; "
                f"affinity was violated. Reject resumption."
            )
        if cursor not in issued:
            raise ForeignResumptionCursor(
                f"Last-Event-ID={cursor} was never issued for session {session_id!r} "
                f"on replica {self.instance_fingerprint}. Silent gap risk; reject."
            )

        return [p for eid, p in self._events[session_id] if eid > cursor]


def handle_sse_get(buffer: StreamReplayBuffer, session_id: str, last_event_id: str) -> list[dict]:
    try:
        return buffer.resume(session_id, last_event_id)
    except ForeignResumptionCursor as exc:
        # Surface a typed 410 so the client reconciles instead of hanging.
        raise ForeignResumptionCursor(str(exc)) from exc
