# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-replayed-sse-event-against-a-resumed-mcp-session-before-it-trusts-the-stream-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-replayed-sse-event-against-a-resumed-mcp-session-before-it-trusts-the-stream-upgrade.warrant.json
# Markdown SHA-256:   0598f237d884e218e2b92f79b8534f9471af47d12d2e2fa3e1428fe0b219954b
# Code AST SHA-256:   f0f5cba3df146a50cf35db94e3401744b315b259503d1da3243cd5b103b214ee
# Verified Classes:   ResumptionInvariantError, SessionState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResumptionInvariantError(RuntimeError):
    """Raised when an upgraded MCP SSE stream cannot be reconciled."""


@dataclass
class SessionState:
    acknowledged_ids: set[int] = field(default_factory=set)
    logical_clock: int = 0  # max acknowledged id, NOT max arrival


def reconcile_upgraded_event(state: SessionState, event_id: Optional[int]) -> str:
    """
    Classify an event arriving on a server-initiated SSE upgrade stream.
    Returns one of: 'drop', 'gap_fill', 'apply'.
    Raises ResumptionInvariantError when the id-invariant is violated.
    """
    if event_id is None:
        # No id on a resumed stream: server cannot honor Last-Event-ID.
        # Guessing ordering here is the documented failure mode.
        raise ResumptionInvariantError(
            "event on resumed stream has no id; abort resumption, open fresh session"
        )

    if event_id > state.logical_clock:
        state.acknowledged_ids.add(event_id)
        state.logical_clock = event_id
        return "apply"

    if event_id in state.acknowledged_ids:
        return "drop"

    # event_id <= logical_clock but unseen: gap-fill replay.
    # Apply, but do NOT advance logical_clock — this event is not "newest".
    state.acknowledged_ids.add(event_id)
    return "gap_fill"


def handle_upgrade_stream(state: SessionState, events: list[dict]) -> list[dict]:
    applied = []
    for ev in events:
        action = reconcile_upgraded_event(state, ev.get("id"))
        if action in ("apply", "gap_fill"):
            applied.append({**ev, "_reconcile": action})
    return applied
