# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-resumed-mcp-streamable-session-after-sse-fallback-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-resumed-mcp-streamable-session-after-sse-fallback-negotiation.warrant.json
# Markdown SHA-256:   ead5ae5f789ab4deef7abc86af54727973c5ebd07fdf36110967aca21957ce9b
# Code AST SHA-256:   3c3916e54a62a74f8a02f6fdda61da0bf7e3f06e55e87d8b03ae27e1170faaaa
# Verified Classes:   StreamEpochViolation, ResumeGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StreamEpochViolation(RuntimeError):
    """Raised when a resumed SSE stream's first event ID does not continue
    the presented Last-Event-ID, indicating the server started a new epoch
    (e.g., after SSE fallback negotiation to a different node)."""


@dataclass
class ResumeGuard:
    presented_last_event_id: int
    seen_request_ids: set = field(default_factory=set)
    applied_result_hashes: set = field(default_factory=set)
    epoch_basis: int = 0
    reconciled: bool = False

    def on_first_event(self, first_event_id: int) -> None:
        if first_event_id <= self.presented_last_event_id:
            # Server restarted its counter: continuation is a lie.
            self.epoch_basis = first_event_id
            self.reconciled = False
            raise StreamEpochViolation(
                f"resumed stream first id {first_event_id} does not follow "
                f"presented Last-Event-ID {self.presented_last_event_id}; "
                f"treating as new epoch, reconciliation required"
            )
        self.epoch_basis = first_event_id - 1

    def apply_tool_result(self, request_id: str, result_bytes: bytes) -> bool:
        """Returns True if the result should be applied, False if it is a
        duplicate from a lagging-replica replay and must be suppressed."""
        h = hashlib.sha256(result_bytes).hexdigest()
        if request_id in self.seen_request_ids and h in self.applied_result_hashes:
            return False
        self.seen_request_ids.add(request_id)
        self.applied_result_hashes.add(h)
        return True

    def require_reconciliation(self) -> None:
        if not self.reconciled:
            raise StreamEpochViolation(
                "epoch reset detected; session state must be re-queried "
                "before appending further events or awaiting pending requests"
            )
