# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-last-event-id-resumption-as-unsafe-rather-than-merely-stale-the-replay-window-replay-fence-invariant-in-http-native.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-last-event-id-resumption-as-unsafe-rather-than-merely-stale-the-replay-window-replay-fence-invariant-in-http-native.warrant.json
# Markdown SHA-256:   3e21654f309d06a95dac35fc23fee392f7a56367adda82c4f09a17f1b3082082
# Code AST SHA-256:   36ecabb8bcafbd5fc8b7b6ffe61877ccbb1f82345422d9ebc0184f07d59818db
# Verified Classes:   UnsafeResumptionError, PendingCall, SessionState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class UnsafeResumptionError(RuntimeError):
    """Raised when an MCP SSE resumption cannot be proven to be contiguous replay.

    This is a session-invalidating condition: the caller must not continue the
    reasoning loop until every in-flight tool effect has been reconciled against
    its idempotency record.
    """


@dataclass
class PendingCall:
    request_id: str
    idempotency_key: str
    tool: str


@dataclass
class SessionState:
    session_id: str
    generation: int
    last_event_id: int
    pending: dict[str, PendingCall] = field(default_factory=dict)


def resume_stream(
    state: SessionState,
    *,
    resumed_session_id: str,
    resumed_generation: int,
    first_event_id: Optional[int],
    replayed_request_ids: list[str],
) -> None:
    """Validate a resumed SSE stream against the replay-fence invariant.

    Safety holds only if:
      1. the session token's generation matches the generation we last saw;
      2. the first replayed event is exactly last_event_id + 1 (no gap, no resync);
      3. every replayed response corresponds to a request still in the pending table.

    Any violation means the server either evicted our position (silent resync) or
    replayed across a generation boundary. In both cases the event IDs are not
    comparable to our position and the stream must not be applied.
    """
    if resumed_session_id != state.session_id:
        raise UnsafeResumptionError(
            f"session token mismatch: expected {state.session_id!r}, "
            f"got {resumed_session_id!r}"
        )

    if resumed_generation != state.generation:
        # Cross-generation replay: event IDs restart or are re-based, so
        # last_event_id is meaningless against this log.
        raise UnsafeResumptionError(
            f"generation boundary crossed: expected gen {state.generation}, "
            f"got gen {resumed_generation}; pending table is invalid"
        )

    if first_event_id is None:
        # Server returned 200 with no replay (common silent-resync shape).
        raise UnsafeResumptionError(
            "server accepted Last-Event-ID but replayed no events; "
            "cannot distinguish replay from resync"
        )

    if first_event_id != state.last_event_id + 1:
        # Gap => eviction-resync or server bug. Either way, events between
        # last_event_id and first_event_id are unrecoverable.
        raise UnsafeResumptionError(
            f"non-contiguous replay: expected first event "
            f"{state.last_event_id + 1}, got {first_event_id}; "
            f"events in ({state.last_event_id}, {first_event_id}) are lost"
        )

    unknown = [rid for rid in replayed_request_ids if rid not in state.pending]
    if unknown:
        # A response for a request we are not tracking means either we
        # re-issued and forgot, or the server replayed across a boundary.
        # Applying it would corrupt the transcript.
        raise UnsafeResumptionError(
            f"replayed responses for untracked request IDs: {unknown}; "
            f"pending table is {sorted(state.pending)}"
        )


def reconcile_after_unsafe_resumption(
    state: SessionState,
    *,
    effect_log: dict[str, int],
) -> dict[str, str]:
    """Reconcile in-flight tool effects before allowing the loop to proceed.

    effect_log maps idempotency_key -> observed execution count at the tool
    boundary. Returns a per-request disposition the reasoning loop must record.
    """
    dispositions: dict[str, str] = {}
    for request_id, call in state.pending.items():
        observed = effect_log.get(call.idempotency_key, 0)
        if observed == 0:
            dispositions[request_id] = "not_executed"
        elif observed == 1:
            dispositions[request_id] = "executed_once"
        else:
            dispositions[request_id] = f"executed_{observed}_times_DUPLICATE"
    if any(d.endswith("DUPLICATE") for d in dispositions.values()):
        # Duplicates are a hard stop: the loop cannot reason about a world
        # where a side effect ran twice without an explicit repair step.
        raise UnsafeResumptionError(
            f"duplicate side effects detected during reconciliation: "
            f"{dispositions}"
        )
    return dispositions
