# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-sse-last-event-id-resumption-as-a-replay-of-tool-effects-not-just-a-replay-of-tool-results.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-sse-last-event-id-resumption-as-a-replay-of-tool-effects-not-just-a-replay-of-tool-results.warrant.json
# Markdown SHA-256:   fe45afab79535093dce88221c15032c7f5f89882795ba5d9cd31536147bb0835
# Code AST SHA-256:   0c59bb46e66b6aec2d447204a86a0ee0ae5cc57002dc1c9b858d782742b5846e
# Verified Classes:   ResumptionReconciliationError, CallOutcome, InFlightCall, ResumptionState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ResumptionReconciliationError(RuntimeError):
    """Raised when a stream resumption leaves a mutating call's outcome unknown
    and no idempotency warrant permits a safe retry."""
    pass


class CallOutcome(Enum):
    RESOLVED = "resolved"
    UNKNOWN = "unknown"          # dispatched, no result observed, no gap signal
    GAP_UNKNOWN = "gap_unknown"  # server rolled its buffer; outcome unrecoverable


@dataclass
class InFlightCall:
    request_id: str
    idempotency_key: str
    mutating: bool
    outcome: CallOutcome = CallOutcome.UNKNOWN


@dataclass
class ResumptionState:
    last_event_id: str
    server_supports_dedup: bool = False
    calls: dict[str, InFlightCall] = field(default_factory=dict)


def reconcile_after_reconnect(
    state: ResumptionState,
    replayed_results: dict[str, str],   # request_id -> result payload
    resumption_gap: bool,
) -> dict[str, str]:
    """
    Apply replayed events to in-flight calls BEFORE any retry decision.
    Returns the set of calls that are safe to retry (empty in the safe case).
    """
    # 1. Drain replay: any call with a replayed result is resolved; do not retry.
    for rid, payload in replayed_results.items():
        call = state.calls.get(rid)
        if call is not None:
            call.outcome = CallOutcome.RESOLVED

    # 2. A resumption gap means the server could not honor Last-Event-ID.
    #    Every still-unresolved mutating call now has an unrecoverable outcome.
    if resumption_gap:
        for call in state.calls.values():
            if call.outcome is CallOutcome.UNKNOWN and call.mutating:
                call.outcome = CallOutcome.GAP_UNKNOWN

    # 3. Decide retry eligibility. Mutating calls may retry ONLY with a warrant.
    retryable: dict[str, str] = {}
    for rid, call in state.calls.items():
        if call.outcome is CallOutcome.RESOLVED:
            continue
        if call.mutating and not state.server_supports_dedup:
            # No idempotency warrant: a retry is a new effect, not a repair.
            raise ResumptionReconciliationError(
                f"Call {rid} (idempotency_key={call.idempotency_key}) is mutating, "
                f"outcome={call.outcome.value}, and server advertises no dedup. "
                f"Refusing to retry on transport failure alone; escalate to "
                f"out-of-band reconciliation."
            )
        # Safe: read-only, or server dedups on idempotency_key.
        retryable[rid] = call.idempotency_key

    return retryable
