# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-establish-event-id-monotonicity-after-an-mcp-stream-resumes-behind-a-load-balancer.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-establish-event-id-monotonicity-after-an-mcp-stream-resumes-behind-a-load-balancer.warrant.json
# Markdown SHA-256:   dce0080be0386368eb2fce8aeab880cf04df9d58604321bccd90987524b655c8
# Code AST SHA-256:   86764e780f3c3000739987aeeb4f5c0422a93120fdcceccfc7ecca8c8648c34a
# Verified Classes:   StreamResumeViolation, StreamEvent, ResumableStreamGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class StreamResumeViolation(RuntimeError):
    """Raised when a resumed SSE stream violates per-session event-ID contiguity."""


@dataclass(frozen=True)
class StreamEvent:
    event_id: int
    session_id: str
    payload: dict


class ResumableStreamGuard:
    """
    Client-side guard enforcing the invariant:
    on resume with Last-Event-ID=N, the first event must have id == N+1
    (or the stream must be correctly idle). Any other first event is a
    resume violation and must force session re-initialization.
    """

    def __init__(self, session_id: str, last_event_id: int):
        self.session_id = session_id
        self.last_event_id = last_event_id
        self._resume_pending = True

    def accept(self, event: StreamEvent) -> StreamEvent:
        if event.session_id != self.session_id:
            raise StreamResumeViolation(
                f"event for session {event.session_id!r} arrived on stream "
                f"for session {self.session_id!r}; replica routing crossed sessions"
            )

        if self._resume_pending:
            expected = self.last_event_id + 1
            if event.event_id != expected:
                kind = (
                    "gap" if event.event_id > expected
                    else "reset-or-namespace-collision"
                )
                raise StreamResumeViolation(
                    f"resume violation on session {self.session_id!r}: "
                    f"sent Last-Event-ID={self.last_event_id}, "
                    f"expected first event id={expected}, got {event.event_id} ({kind}). "
                    f"Force re-init; do not feed this event into the reasoning loop."
                )
            self._resume_pending = False

        if event.event_id != self.last_event_id + 1:
            raise StreamResumeViolation(
                f"non-contiguous event on session {self.session_id!r}: "
                f"last={self.last_event_id}, got {event.event_id}"
            )

        self.last_event_id = event.event_id
        return event

    def consume(self, events: Iterable[StreamEvent]) -> list[StreamEvent]:
        return [self.accept(e) for e in events]


def resume_session(
    guard: ResumableStreamGuard,
    reconnect_stream: Iterable[StreamEvent],
    idle_after_seconds: float | None = None,
    tool_deadline_seconds: float = 120.0,
) -> list[StreamEvent]:
    """
    Consume a reconnected SSE stream under the contiguity invariant.
    If the stream is idle past the tool deadline with no event > last_event_id,
    treat as delivery failure rather than slow tool.
    """
    accepted: list[StreamEvent] = []
    saw_any = False
    for event in reconnect_stream:
        saw_any = True
        accepted.append(guard.accept(event))

    if not saw_any and idle_after_seconds is not None:
        if idle_after_seconds > tool_deadline_seconds:
            raise StreamResumeViolation(
                f"session {guard.session_id!r}: stream idle {idle_after_seconds:.1f}s "
                f"past tool deadline {tool_deadline_seconds:.1f}s with no event "
                f"> {guard.last_event_id}; worker likely completed on an "
                f"unreachable replica. Force re-init and re-issue with dedup key."
            )
    return accepted
