# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-resumable-mcp-http-streams-from-replaying-a-tool-call-whose-side-effect-already-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-resumable-mcp-http-streams-from-replaying-a-tool-call-whose-side-effect-already-committed.warrant.json
# Markdown SHA-256:   a5192ccf7525c403e9c8864ae26e5e7c2766e7b7bd761ba58f3c9f91ee236001
# Code AST SHA-256:   9a9aec7b1b4f2b2e0a2a097d985c018c3a32e1342cd22cecefa67d75b43c7ca4
# Verified Classes:   DuplicateEffectError, ResumptionGapError, CommittedEffect, EffectOnceDispatcher
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import threading
from dataclasses import dataclass, field
from typing import Any, Optional


class DuplicateEffectError(RuntimeError):
    """Raised when a tool dispatch would re-execute an already-committed request id."""


class ResumptionGapError(RuntimeError):
    """Raised when Last-Event-ID predates the retained stream log; tail is unrecoverable."""


@dataclass
class CommittedEffect:
    request_id: str
    result: Any
    effect_digest: str


class EffectOnceDispatcher:
    """
    Enforces: a tools/call with a given JSON-RPC id executes its side effect
    at most once. Stream resumption (Last-Event-ID) is a separate concern and
    MUST NOT be used as a proxy for effect dedup.
    """

    def __init__(self, stream_retention_floor: int = 0):
        self._lock = threading.Lock()
        self._committed: dict[str, CommittedEffect] = {}
        self._retention_floor = stream_retention_floor

    def dispatch(self, request_id: str, tool_body, args: dict) -> Any:
        with self._lock:
            prior = self._committed.get(request_id)
            if prior is not None:
                # Idempotent replay: return recorded result, do NOT re-execute.
                return prior.result

            # Execute under the same lock that guards the commit, so the
            # check-then-act race cannot double-fire.
            result = tool_body(**args)
            digest = hashlib.sha256(
                f"{request_id}:{result!r}".encode()
            ).hexdigest()
            self._committed[request_id] = CommittedEffect(
                request_id=request_id, result=result, effect_digest=digest
            )
            return result

    def resume_stream(self, last_event_id: int) -> str:
        if last_event_id < self._retention_floor:
            # Silent fresh-stream-from-zero is the bug; make it loud.
            raise ResumptionGapError(
                f"Last-Event-ID {last_event_id} predates retention floor "
                f"{self._retention_floor}; terminal event for in-flight "
                f"tools/call is unrecoverable — query status by request id, "
                f"do not re-POST."
            )
        return f"resuming-from:{last_event_id}"


def handle_reconnect(dispatcher: EffectOnceDispatcher, request_id: str,
                     last_event_id: int, tool_body, args: dict) -> Any:
    try:
        dispatcher.resume_stream(last_event_id)
    except ResumptionGapError:
        # Gap: we cannot know whether the effect committed. Refuse to guess.
        raise
    # Only dispatch after confirming resume is possible; dispatch is
    # idempotent on request_id regardless.
    return dispatcher.dispatch(request_id, tool_body, args)


def handle_duplicate_without_record(dispatcher: EffectOnceDispatcher,
                                    request_id: str, tool_body, args: dict) -> Any:
    # Demonstrates the failure the guardrail prevents: if a caller bypasses
    # the committed-effects table and re-POSTs, we must refuse.
    with dispatcher._lock:
        if request_id in dispatcher._committed:
            raise DuplicateEffectError(
                f"request id {request_id} already committed; "
                f"re-POST would double the side effect"
            )
    return dispatcher.dispatch(request_id, tool_body, args)
