# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-an-mcp-streamable-http-sse-event-that-arrives-after-session-resumption-with-a-stale-last-event-id-and-why-does-the-re.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-an-mcp-streamable-http-sse-event-that-arrives-after-session-resumption-with-a-stale-last-event-id-and-why-does-the-re.warrant.json
# Markdown SHA-256:   3416e1455698cb06487c9d48874c56dbf4aa4fb38a204c155ae64a774f7b1175
# Code AST SHA-256:   2f739ae2ee80f4623468550fafbb55889c978f6eadd1e2c17058d275f1339d93
# Verified Classes:   StreamResumptionDivergence, SessionStreamState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field
from typing import Any


class StreamResumptionDivergence(RuntimeError):
    """Raised when a resumed MCP SSE stream delivers a terminal result that
    conflicts with one already consumed for the same JSON-RPC request id."""
    pass


@dataclass
class SessionStreamState:
    session_id: str
    last_event_id: int = 0
    tombstones: dict[Any, str] = field(default_factory=dict)  # request_id -> canonical payload


def _canonical(payload: Any) -> str:
    return json.dumps(payload, sort_keys=True, separators=(",", ":"))


def ingest_sse_event(state: SessionStreamState, event_id: int, data: str) -> dict:
    """Process one SSE event from a (possibly resumed) MCP stream.

    Enforces the terminal-result tombstone invariant and gap detection.
    """
    # Gap detection: a resumed stream that skips ids cannot be trusted.
    if state.last_event_id and event_id > state.last_event_id + 1:
        raise StreamResumptionDivergence(
            f"stream gap on session {state.session_id}: "
            f"last_event_id={state.last_event_id} next={event_id}; "
            f"resumed stream is not a faithful continuation — abandon and retry"
        )

    msg = json.loads(data)
    state.last_event_id = event_id

    # Only terminal results/errors carry a request id we must tombstone.
    if "result" in msg or "error" in msg:
        req_id = msg.get("id")
        if req_id is None:
            return msg
        canon = _canonical(msg.get("result", msg.get("error")))
        prior = state.tombstones.get(req_id)
        if prior is not None and prior != canon:
            raise StreamResumptionDivergence(
                f"divergent terminal result for request id={req_id} on session "
                f"{state.session_id}: prior={prior} resumed={canon}; "
                f"server likely re-executed a non-idempotent tool call"
            )
        state.tombstones[req_id] = canon

    return msg
