# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silently-reordered-sse-replay-across-an-mcp-http-stream-resumption-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silently-reordered-sse-replay-across-an-mcp-http-stream-resumption-boundary.warrant.json
# Markdown SHA-256:   9864ba8cc08c55b9f2901c84eab384631e5723259d1e8bfacd7972e56612a415
# Code AST SHA-256:   7c48d900fb9da0dad4796af509ac13e4a0bafc0a1893bac37ebde929275af9ff
# Verified Classes:   ResumptionCorrelationError, StreamCursor, ResumableToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionCorrelationError(RuntimeError):
    """Raised when a resumed SSE stream cannot be proven to continue the prior history."""


@dataclass
class StreamCursor:
    last_id: int
    call_id: str


class ResumableToolCall:
    def __init__(self, call_id: str, idempotency_key: str):
        self.call_id = call_id
        self.idempotency_key = idempotency_key
        self.cursor: Optional[StreamCursor] = None
        self.outcome_unknown = False

    def observe(self, event_id: int, is_first_after_reconnect: bool) -> None:
        if self.cursor is None:
            self.cursor = StreamCursor(last_id=event_id, call_id=self.call_id)
            return
        if is_first_after_reconnect and event_id <= self.cursor.last_id:
            self.outcome_unknown = True
            raise ResumptionCorrelationError(
                f"call {self.call_id}: resumed stream first id {event_id} does not "
                f"strictly follow pre-drop cursor {self.cursor.last_id}; "
                f"server replay history diverged (buffer eviction, reshard, or failover). "
                f"Marking outcome_unknown; reconcile via idempotency_key={self.idempotency_key}."
            )
        if event_id <= self.cursor.last_id:
            self.outcome_unknown = True
            raise ResumptionCorrelationError(
                f"call {self.call_id}: non-monotonic event id {event_id} after "
                f"{self.cursor.last_id}; stream is not a single ordered history."
            )
        self.cursor.last_id = event_id

    def resume(self, reconnect_last_event_id: int) -> int:
        if self.cursor is None or reconnect_last_event_id != self.cursor.last_id:
            raise ResumptionCorrelationError(
                f"call {self.call_id}: reconnect cursor {reconnect_last_event_id} "
                f"does not match recorded cursor {self.cursor.last_id if self.cursor else None}."
            )
        return self.cursor.last_id
