# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-against-a-server-that-has-already-rotated-its-per-stream-event-id-namespace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-against-a-server-that-has-already-rotated-its-per-stream-event-id-namespace.warrant.json
# Markdown SHA-256:   080a8ea6788c7cc03ba2e917517b6f0ee950d5c64105344a7c3d26421dcd5482
# Code AST SHA-256:   64383759e0df4b5e594b759e521945b7694be8bd030621620d8f9e4708b0aab0
# Verified Classes:   StreamIncarnationMismatch, WatermarkAheadOfStream, StreamIncarnation, ResumeCursor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Optional


class StreamIncarnationMismatch(RuntimeError):
    """Raised when a Last-Event-ID cannot be resolved against the current stream incarnation."""
    pass


class WatermarkAheadOfStream(RuntimeError):
    """Raised when the client's watermark exceeds the server's next event id (silent-drop hazard)."""
    pass


@dataclass
class StreamIncarnation:
    incarnation_id: str
    next_id: int = 1
    # events buffered for replay within this incarnation only
    buffer: dict = field(default_factory=dict)

    def emit(self, payload: dict) -> int:
        eid = self.next_id
        self.buffer[eid] = payload
        self.next_id += 1
        return eid


@dataclass
class ResumeCursor:
    session_id: str
    incarnation_id: str
    last_event_id: int


def resume_stream(cursor: ResumeCursor, current: StreamIncarnation) -> list[dict]:
    """
    Resolve a resume request. Returns the events to replay.
    Raises if the cursor cannot be safely resolved against the current incarnation.
    """
    if cursor.incarnation_id != current.incarnation_id:
        # The client's watermark refers to a stream this server no longer owns.
        # Silent acceptance here is the failure mode: the client's dedup layer
        # would drop every event from the new incarnation.
        raise StreamIncarnationMismatch(
            f"cursor incarnation {cursor.incarnation_id!r} != "
            f"current {current.incarnation_id!r}; "
            f"client must re-negotiate and re-query in-flight tool calls by call_id"
        )

    if cursor.last_event_id >= current.next_id:
        # Client claims to have seen events the server never emitted on this
        # incarnation. Never a valid steady state; do not replay, do not ack.
        raise WatermarkAheadOfStream(
            f"cursor last_event_id={cursor.last_event_id} >= "
            f"next_id={current.next_id}; refusing silent drop"
        )

    return [current.buffer[i] for i in range(cursor.last_event_id + 1, current.next_id)]


def handle_resume(cursor: ResumeCursor, current: StreamIncarnation) -> dict:
    try:
        replay = resume_stream(cursor, current)
    except StreamIncarnationMismatch as e:
        return {
            "status": 409,
            "error": "stream_incarnation_mismatch",
            "current_incarnation": current.incarnation_id,
            "resume_token": str(uuid.uuid4()),
            "detail": str(e),
        }
    except WatermarkAheadOfStream as e:
        return {
            "status": 409,
            "error": "watermark_ahead_of_stream",
            "next_id": current.next_id,
            "detail": str(e),
        }
    return {"status": 200, "replay": replay}


# --- self-check: the observed failure, now bounded ---
if __name__ == "__main__":
    old = StreamIncarnation(incarnation_id="inc_A")
    for _ in range(31):
        old.emit({"progress": 0.0})

    # replica restart: new incarnation, counter restarts at 1
    new = StreamIncarnation(incarnation_id="inc_B")
    for _ in range(17):
        new.emit({"progress": 0.0})

    stale = ResumeCursor(session_id="s_9f2a", incarnation_id="inc_A", last_event_id=31)
    resp = handle_resume(stale, new)
    assert resp["status"] == 409 and resp["error"] == "stream_incarnation_mismatch", resp

    # same-incarnation resume still replays correctly
    same = ResumeCursor(session_id="s_9f2a", incarnation_id="inc_B", last_event_id=3)
    resp = handle_resume(same, new)
    assert resp["status"] == 200 and len(resp["replay"]) == 13, resp
    print("resumption invariant holds: stale incarnations rejected, in-incarnation replay preserved")
