# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-mcp-sse-stream-resumption-as-a-replay-hazard-rather-than-a-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-mcp-sse-stream-resumption-as-a-replay-hazard-rather-than-a-reconnect.warrant.json
# Markdown SHA-256:   7680455ddca3a8b8df68e14f9891031eddee37b03fc622563421feb89317b709
# Code AST SHA-256:   4fb98200c5c7b20390db948e3d16f760528c05247b2649246940390dee074625
# Verified Classes:   StreamResumptionViolation, StreamCursor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StreamResumptionViolation(RuntimeError):
    """Raised when an MCP SSE resumption cannot be trusted as a continuation
    of the prior stream. Caller must escalate to a fresh invocation, not retry."""
    pass


@dataclass
class StreamCursor:
    session_id: str
    last_event_id: int
    seen: dict = field(default_factory=dict)  # event_id -> content_hash
    done_cursor: Optional[int] = None


def resume_stream(
    cursor: StreamCursor,
    resumed_events: list[dict],
    server_advertises_durable_log: bool,
) -> list[dict]:
    """Validate a resumed SSE stream against the cursor invariant.

    resumed_events: list of {"id": int, "content_hash": str, "event": str}
    Returns the newly-accepted events (to be appended to the assembled result).
    Raises StreamResumptionViolation if the stream cannot be trusted.
    """
    if not server_advertises_durable_log:
        raise StreamResumptionViolation(
            f"session {cursor.session_id}: server does not advertise a durable "
            f"event log; resumption from cursor {cursor.last_event_id} cannot "
            f"guarantee exactly-once replay. Escalate to fresh invocation."
        )

    if not resumed_events:
        raise StreamResumptionViolation(
            f"session {cursor.session_id}: resumed stream empty; cannot "
            f"distinguish clean end from truncated stream."
        )

    first_id = resumed_events[0]["id"]
    if first_id <= cursor.last_event_id:
        raise StreamResumptionViolation(
            f"session {cursor.session_id}: resumed stream starts at id {first_id} "
            f"<= last-seen {cursor.last_event_id}; event IDs are connection-scoped, "
            f"not session-scoped. Replay would be silently deduplicated."
        )

    accepted = []
    prev_id = cursor.last_event_id
    for ev in resumed_events:
        eid = ev["id"]
        if eid <= prev_id:
            raise StreamResumptionViolation(
                f"session {cursor.session_id}: non-monotonic event id {eid} "
                f"after {prev_id}; stream ordering violated."
            )
        if eid in cursor.seen and cursor.seen[eid] != ev["content_hash"]:
            raise StreamResumptionViolation(
                f"session {cursor.session_id}: event id {eid} re-delivered with "
                f"different content (seen {cursor.seen[eid]}, got "
                f"{ev['content_hash']}); stale-cache substitution signature. "
                f"Fail closed — retry will reproduce."
            )
        cursor.seen[eid] = ev["content_hash"]
        accepted.append(ev)
        prev_id = eid

    if resumed_events[-1]["event"] == "done":
        cursor.done_cursor = resumed_events[-1]["id"]
    else:
        raise StreamResumptionViolation(
            f"session {cursor.session_id}: resumed stream ended without a 'done' "
            f"event carrying a final cursor; stream may be truncated."
        )

    cursor.last_event_id = cursor.done_cursor
    return accepted
