# 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-a-new-session-rather-than-a-continuation-the-sse-replay-gap-invariant-and-its-silent-du.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-new-session-rather-than-a-continuation-the-sse-replay-gap-invariant-and-its-silent-du.warrant.json
# Markdown SHA-256:   44cbae0c7604117f91a0872d31f358d6434289e24be9bb77d9b891bfef037c3a
# Code AST SHA-256:   567244de68a5fc68eb70fc647adc5f935af2a3d844b2ed5b7754f83c2388e61e
# Verified Classes:   ReplayGapViolation, ResumptionProbe
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ReplayGapViolation(RuntimeError):
    """Raised when an SSE resumption cannot be proven contiguous with the
    client's Last-Event-ID and no explicit truncation signal was received."""


@dataclass(frozen=True)
class ResumptionProbe:
    last_event_id: int          # cursor the client presented
    first_received_id: int      # first event id observed after reconnect
    truncation_header: bool     # server sent X-MCP-Replay-Truncated: true
    session_reset: bool         # server returned fresh id namespace / 404


def idempotency_token(logical_op: str, args_digest: str) -> str:
    # Stable across retries; NOT derived from JSON-RPC message id.
    return hashlib.sha256(f"{logical_op}:{args_digest}".encode()).hexdigest()


def classify_resumption(probe: ResumptionProbe) -> str:
    if probe.session_reset:
        return "fresh_session"
    if probe.truncation_header:
        return "admitted_gap"
    expected = probe.last_event_id + 1
    if probe.first_received_id == expected:
        return "true_resumption"
    if probe.first_received_id > expected:
        # Silent gap: events last_event_id+1 .. first_received_id-1 are lost.
        raise ReplayGapViolation(
            f"cursor {probe.last_event_id} -> first received "
            f"{probe.first_received_id}: {probe.first_received_id - expected} "
            f"events evicted from replay buffer with no truncation signal; "
            f"in-flight tool results in that range are indeterminate"
        )
    # first_received_id < expected: server replayed earlier than requested
    # (cursor regression) — also unsafe, treat as gap.
    raise ReplayGapViolation(
        f"cursor regression: presented {probe.last_event_id}, "
        f"received {probe.first_received_id}"
    )


def resume_or_reconcile(probe: ResumptionProbe, in_flight_ops: list[str]) -> str:
    try:
        verdict = classify_resumption(probe)
    except ReplayGapViolation:
        # Do NOT retry in-flight side-effecting ops under new JSON-RPC ids.
        # Escalate: reconcile each op by idempotency token against server state.
        for op in in_flight_ops:
            _reconcile(op)
        return "reconciled"
    if verdict == "true_resumption":
        return "continue"          # in-flight calls stay pending, no retry
    # fresh_session / admitted_gap: re-init, replay only idempotency-keyed ops
    return "reinitialize"


def _reconcile(op: str) -> None:
    # Query server for the observed outcome of `op` by idempotency token
    # before deciding whether to re-issue. Placeholder for the real probe.
    raise ReplayGapViolation(
        f"reconciliation required for {op}: outcome unknown due to replay gap"
    )
