# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-http-resumption-from-silently-replaying-a-poisoned-chunk-after-sse-fallback-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-http-resumption-from-silently-replaying-a-poisoned-chunk-after-sse-fallback-negotiation.warrant.json
# Markdown SHA-256:   4f630085b23b93379e86f8587a1c2d23d8e2343ae92c8c1f9b01d0866be8503f
# Code AST SHA-256:   a05f584fcba37d418c8dfbfe6764df5a7a9d72348adc92fbdc031c763e5f3ae9
# Verified Classes:   ResumeAmbiguity, ReplaySuppressed, FrameDeduper
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ResumeAmbiguity(RuntimeError):
    """Raised when a resumed stream cannot be proven ahead of the last executed frame."""


class ReplaySuppressed(Exception):
    """Raised (and caught) when a replayed frame is correctly deduplicated."""


@dataclass
class FrameDeduper:
    session_id: str
    executed: set = field(default_factory=set)
    highest_executed_id: int = -1

    def _key(self, event_id: int, payload: dict) -> str:
        canon = json.dumps(payload, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(
            f"{self.session_id}|{event_id}|{canon}".encode()
        ).hexdigest()

    def admit(self, event_id: int, payload: dict, *, resumed: bool,
              destructive: bool, cursor_ahead: bool) -> None:
        key = self._key(event_id, payload)
        if key in self.executed:
            raise ReplaySuppressed(f"replay of event {event_id} suppressed")
        if resumed and destructive and not cursor_ahead:
            # Cannot prove this frame is novel relative to side effects.
            raise ResumeAmbiguity(
                f"resume cursor not ahead of last executed frame "
                f"(last={self.highest_executed_id}, incoming={event_id}); "
                f"refusing to execute destructive call on ambiguous stream"
            )
        self.executed.add(key)
        self.highest_executed_id = max(self.highest_executed_id, event_id)


def handle_resumed_frame(deduper: FrameDeduper, event_id: int, payload: dict,
                         tool_name: str, cursor_ahead: bool) -> str:
    destructive = tool_name in {"fs.delete", "payments.charge", "db.drop"}
    try:
        deduper.admit(event_id, payload, resumed=True,
                      destructive=destructive, cursor_ahead=cursor_ahead)
    except ReplaySuppressed:
        return "suppressed"
    return "executed"
