# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resume-an-mcp-streamable-session-against-a-replayed-sse-event-log-and-silently-double-apply-the-last-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resume-an-mcp-streamable-session-against-a-replayed-sse-event-log-and-silently-double-apply-the-last-tool-call.warrant.json
# Markdown SHA-256:   2efd59708c37a8abf536c9281de170f8c82bbdd76ecc085dd1c2ffc2973ba6f0
# Code AST SHA-256:   960853398ae1a51b0aa98526da554d0bcb863924353a354cdcb23dc5894d7e64
# Verified Classes:   StreamResumptionViolation, ActionLedger, ReplayedEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import json
from dataclasses import dataclass, field
from typing import Iterable


class StreamResumptionViolation(RuntimeError):
    """Raised when an MCP streamable-session resume would violate
    the action-ledger / event-cursor continuity invariant."""


@dataclass
class ActionLedger:
    """Durable record fusing transport cursor and semantic action state.

    Invariant: `applied_event_id` and `effects` are committed in the SAME
    durable write. A replayed event with id <= applied_event_id is dropped
    before it can reach the reasoning loop.
    """

    applied_event_id: int = 0
    # request_id -> effect_committed
    inflight: dict[str, bool] = field(default_factory=dict)
    # event_id -> request_id that produced it
    event_to_request: dict[int, str] = field(default_factory=dict)
    # tools declared safe to re-issue on ambiguous resume
    idempotent_tools: set[str] = field(default_factory=lambda: {"fetch_url"})

    def commit(self, event_id: int, request_id: str | None) -> None:
        # Single atomic step: advance cursor AND record effect together.
        self.applied_event_id = event_id
        if request_id is not None:
            self.event_to_request[event_id] = request_id
            self.inflight[request_id] = True

    def already_applied(self, event_id: int) -> bool:
        return event_id <= self.applied_event_id


@dataclass
class ReplayedEvent:
    event_id: int
    request_id: str | None
    tool_name: str | None


def reconcile_resume(
    ledger: ActionLedger,
    replayed: Iterable[ReplayedEvent],
    server_buffer_min_id: int,
    requested_last_event_id: int,
) -> list[ReplayedEvent]:
    """Return only events that are genuinely new to the semantic layer.

    Raises on the two boundary conditions:
      1. Server could not honor Last-Event-ID (gap -> unresumable session).
      2. A replayed response refers to a request the ledger never sent
         (cursor/ledger divergence -> cannot safely decide re-issue).
    """
    replayed = list(replayed)

    # Guard 1: buffer gap means stream continuity is lost. Fail closed;
    # do NOT pretend to resume from a partial log.
    if requested_last_event_id + 1 < server_buffer_min_id:
        raise StreamResumptionViolation(
            f"unresumable session: requested Last-Event-ID={requested_last_event_id} "
            f"but server buffer starts at {server_buffer_min_id}; "
            f"events in [{requested_last_event_id + 1}, {server_buffer_min_id - 1}] "
            f"are permanently lost. Re-derive state from environment."
        )

    fresh: list[ReplayedEvent] = []
    for ev in replayed:
        if ledger.already_applied(ev.event_id):
            # Stream replay of an already-applied effect: drop it.
            continue
        if ev.request_id is not None and ev.request_id not in ledger.inflight:
            # A response for a request we have no record of sending.
            # We cannot tell "never sent" from "sent, ledger lost".
            # Re-issuing here is the double-apply bug.
            raise StreamResumptionViolation(
                f"replayed event {ev.event_id} carries response for unknown "
                f"request {ev.request_id!r}; ledger/cursor diverged. "
                f"Refusing to re-issue. Treat as ambiguous and reconcile "
                f"against tool idempotency contract before any resend."
            )
        fresh.append(ev)
    return fresh


def resume_and_maybe_reissue(
    ledger: ActionLedger,
    replayed: Iterable[ReplayedEvent],
    server_buffer_min_id: int,
    requested_last_event_id: int,
    pending_tool: str,
) -> list[str]:
    """Drive resume; only re-issue when provably safe."""
    fresh = reconcile_resume(
        ledger, replayed, server_buffer_min_id, requested_last_event_id
    )
    to_reissue: list[str] = []
    for ev in fresh:
        if ev.request_id is not None and ev.tool_name not in ledger.idempotent_tools:
            # Response arrived for a non-idempotent tool with no committed
            # effect: the effect state is ambiguous. Do not resend.
            raise StreamResumptionViolation(
                f"ambiguous effect for non-idempotent tool {ev.tool_name!r} "
                f"on request {ev.request_id!r}; manual reconciliation required"
            )
        ledger.commit(ev.event_id, ev.request_id)
        to_reissue.append(ev.request_id) if ev.request_id else None
    return to_reissue
