# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-mcp-client-silently-replay-a-stale-tool-call-after-sse-to-streamable-http-session-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-mcp-client-silently-replay-a-stale-tool-call-after-sse-to-streamable-http-session-resumption.warrant.json
# Markdown SHA-256:   f478f68eb2aa8291b62e7133876a81dd90718e06d49df4eb7c0e05d767461a34
# Code AST SHA-256:   bd4c15f891267fe967362c27045a248235d37a21b3a5813ff1bfd1985be26fd2
# Verified Classes:   DuplicateExecutionOnResume, ExecutionRecord, ResumeGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DuplicateExecutionOnResume(RuntimeError):
    """Raised when a streamable-HTTP resume path would re-invoke a tool
    handler for a (session, jsonrpc_id) pair that already has an execution
    record. This is the boundary failure: the resume must replay events,
    not re-execute the request."""
    pass


class ExecutionRecord:
    __slots__ = ("session_id", "jsonrpc_id", "state", "event_log")

    def __init__(self, session_id: str, jsonrpc_id: int):
        self.session_id = session_id
        self.jsonrpc_id = jsonrpc_id
        self.state = "executing"  # -> "complete"
        self.event_log: list[dict] = []


class ResumeGuard:
    """Enforces the invariant: a POST carrying Last-Event-ID must not
    invoke the handler if an execution record exists for (session, id)."""

    def __init__(self):
        self._records: dict[tuple[str, int], ExecutionRecord] = {}

    def begin(self, session_id: str, jsonrpc_id: int) -> ExecutionRecord:
        key = (session_id, jsonrpc_id)
        if key in self._records:
            # A second begin without a resume header is a client bug:
            # it re-sent the body without Last-Event-ID.
            raise DuplicateExecutionOnResume(
                f"session={session_id} id={jsonrpc_id} already has a record "
                f"in state={self._records[key].state}; client must resume "
                f"with Last-Event-ID, not re-send the JSON-RPC body"
            )
        rec = ExecutionRecord(session_id, jsonrpc_id)
        self._records[key] = rec
        return rec

    def resume(self, session_id: str, jsonrpc_id: int, last_event_id: int) -> list[dict]:
        key = (session_id, jsonrpc_id)
        rec = self._records.get(key)
        if rec is None:
            # No record: the original POST never reached the handler.
            # Safe to execute fresh, but the caller must not also carry
            # a Last-Event-ID that implies prior events exist.
            raise DuplicateExecutionOnResume(
                f"session={session_id} id={jsonrpc_id} resume with "
                f"Last-Event-ID={last_event_id} but no execution record; "
                f"refusing to execute fresh under a resume header"
            )
        # Replay only. Never invoke the handler here.
        return [e for e in rec.event_log if e["seq"] > last_event_id]
