# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-replayed-sse-event-ids-with-mutated-mcp-session-state-after-a-mid-stream-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-replayed-sse-event-ids-with-mutated-mcp-session-state-after-a-mid-stream-reconnect.warrant.json
# Markdown SHA-256:   a0fe1e91fe2d55fec60d13f5cfcc2061d3d00b7a0cb8a9f35b3985dfffd8bf46
# Code AST SHA-256:   1036ff0467945222a98f1bb4ce90b3026d5843814c4bbed2963041f2c871fe31
# Verified Classes:   StaleSessionGenerationError, SseEvent, Session
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


class StaleSessionGenerationError(RuntimeError):
    """Raised when a replayed SSE event is applied to a session whose
    generation has advanced past the event's generation."""


@dataclass
class SseEvent:
    event_id: int
    session_generation: int
    payload: dict[str, Any]


@dataclass
class Session:
    session_id: str
    generation: int = 0
    pending_calls: dict[str, dict[str, Any]] = field(default_factory=dict)
    applied_event_ids: set[int] = field(default_factory=set)


def reconcile_replay(
    session: Session,
    replayed: list[SseEvent],
    *,
    strict: bool = True,
) -> list[SseEvent]:
    """Filter replayed SSE events against the session's current generation.

    Events at the current generation are applied. Events below it are
    historical tombstones: the referenced handles must be reconciled
    out-of-band (status query), never applied as deltas.
    """
    if not replayed:
        return []

    # The session generation is authoritative; it may have advanced during
    # the disconnect via async tool completion or capability reload.
    current_gen = session.generation
    applicable: list[SseEvent] = []

    for ev in replayed:
        if ev.event_id in session.applied_event_ids:
            continue  # idempotent: already applied before disconnect
        if ev.session_generation < current_gen:
            # Historical. Do not apply. Reconcile handles referenced.
            handle = ev.payload.get("tool_call_id")
            if handle and handle not in session.pending_calls:
                # Handle was reaped; a status query is required before
                # any re-dispatch. Refuse to proceed silently.
                if strict:
                    raise StaleSessionGenerationError(
                        f"event {ev.event_id} (gen {ev.session_generation}) "
                        f"references reaped handle {handle!r}; session "
                        f"gen is {current_gen}. Reconcile via status query "
                        f"before acting."
                    )
            continue
        if ev.session_generation > current_gen:
            # Server cannot replay the future; indicates a protocol fault.
            raise StaleSessionGenerationError(
                f"event {ev.event_id} gen {ev.session_generation} exceeds "
                f"session gen {current_gen}; server replay invariant broken."
            )
        applicable.append(ev)
        session.applied_event_ids.add(ev.event_id)

    return applicable
