# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-a-torn-sse-frame-silent-tool-call-duplication-at-the-resumption-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-a-torn-sse-frame-silent-tool-call-duplication-at-the-resumption-boundary.warrant.json
# Markdown SHA-256:   7929c27ddfd047a6eff4127c49fe663a61f13dcae0cc4c3aad990191d5214a35
# Code AST SHA-256:   b39e399f8f678c1a6ab5862bb9392a899b1bb50acbc8f977368c8bba2748caab
# Verified Classes:   ResumptionInvariantViolation, StreamSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ResumptionInvariantViolation(RuntimeError):
    """Raised when an MCP stream resume would replay an event whose effect
    is not durably committed, or when a side-effecting result arrives for a
    JSON-RPC id already dispatched without an idempotency key."""


@dataclass
class StreamSession:
    # Durable application watermark: last event id whose EFFECT is committed.
    committed_through: int = 0
    # Protocol dedup: jsonrpc ids whose result has been dispatched.
    dispatched: set = field(default_factory=set)
    # Side-effect ledger: (jsonrpc_id, idempotency_key) -> effect fingerprint.
    effects: dict = field(default_factory=dict)

    def on_resume(self, last_event_id_seen: int, server_replay_from: int) -> int:
        # Server must replay strictly AFTER the committed watermark, not after
        # the last framed event id the client happened to parse.
        if server_replay_from <= self.committed_through:
            raise ResumptionInvariantViolation(
                f"server replay_from={server_replay_from} <= committed_through="
                f"{self.committed_through}; replay would re-deliver a committed "
                f"effect (torn-frame duplicate)."
            )
        return server_replay_from

    def on_result(self, jsonrpc_id: str, idempotency_key: str | None,
                  payload: bytes, side_effecting: bool) -> None:
        if side_effecting and idempotency_key is None:
            raise ResumptionInvariantViolation(
                f"side-effecting result for id={jsonrpc_id} has no "
                f"idempotency_key; replay cannot be deduplicated."
            )
        fp = hashlib.sha256(payload).hexdigest()
        key = (jsonrpc_id, idempotency_key)
        if key in self.effects and self.effects[key] != fp:
            raise ResumptionInvariantViolation(
                f"conflicting replay for {key}: prior={self.effects[key][:12]} "
                f"new={fp[:12]}; non-idempotent effect diverged."
            )
        if jsonrpc_id in self.dispatched and not side_effecting:
            # duplicate observation of a pure result: safe to drop
            return
        self.effects[key] = fp
        self.dispatched.add(jsonrpc_id)

    def commit(self, event_id: int) -> None:
        # Advance the application watermark ONLY after the effect is durable.
        if event_id <= self.committed_through:
            raise ResumptionInvariantViolation(
                f"non-monotonic commit: {event_id} <= {self.committed_through}"
            )
        self.committed_through = event_id
