# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-http-server-recycles-its-sse-event-id-namespace-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-http-server-recycles-its-sse-event-id-namespace-mid-session.warrant.json
# Markdown SHA-256:   d85ab9ee3cf86c3ee0e71ac8fe5ddc439a8c257e74a9443446fdb305fa0e5f23
# Code AST SHA-256:   f74cef57986d575d2acfd7e09ab3f2c44db572414e62adf4ebfe2d07105c3fd1
# Verified Classes:   EventIdRegressionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EventIdRegressionError(RuntimeError):
    """Raised when a resumed SSE stream presents an event ID below the
    session high-water mark without a declared session-scoped ID contract.
    Signals a silent continuity violation, not a transport error."""


def validate_resume_stream(
    last_seen_id: int,
    first_event_id: int,
    server_declares_session_scoped_ids: bool,
) -> None:
    """Guard against per-replica event-ID namespace recycling.

    A stateless MCP HTTP server restarts its event counter per worker.
    On resume, the first event ID can be far below the client's high-water
    mark. If the server has NOT declared session-scoped IDs, this means
    the client's dedup filter would silently discard live events.
    """
    if first_event_id > last_seen_id:
        return  # normal forward progress
    if server_declares_session_scoped_ids:
        # Session-scoped IDs are monotonic by contract; a regression here
        # is a real server bug, still fatal.
        raise EventIdRegressionError(
            f"session-scoped ID contract violated: "
            f"first_event_id={first_event_id} <= last_seen_id={last_seen_id}"
        )
    # No contract: regression means the stream is a fresh namespace.
    # Refuse to apply monotonic dedup; force application-level reconcile.
    raise EventIdRegressionError(
        f"event-ID namespace recycled: first_event_id={first_event_id} "
        f"< last_seen_id={last_seen_id} on a non-session-scoped server; "
        f"client must re-issue tool call with idempotency key instead of "
        f"trusting Last-Event-ID resumption"
    )


def resume_mcp_stream(client, session, last_event_id: int) -> None:
    stream = client.get_event_stream(last_event_id=last_event_id)
    first = next(stream)
    validate_resume_stream(
        last_seen_id=last_event_id,
        first_event_id=first.id,
        server_declares_session_scoped_ids=session.declares_session_scoped_ids,
    )
    for event in stream:
        session.apply(event)
