# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-replay-against-its-own-tool-call-ledger-when-an-mcp-streamable-http-session-resumes-with-a-stale-last-event-id.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-replay-against-its-own-tool-call-ledger-when-an-mcp-streamable-http-session-resumes-with-a-stale-last-event-id.warrant.json
# Markdown SHA-256:   3c6290451bf7b3cb454129997af3356a3516918cce60a7d23718fd0574ebe066
# Code AST SHA-256:   fdc41bf4f7d9d5f1a884ccf0ddfbe01ab76112c218f00591bc62294996616b7b
# Verified Classes:   McpResumptionLedgerViolation, ResumptionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class McpResumptionLedgerViolation(RuntimeError):
    """Raised when a resumed SSE stream cannot be reconciled with the tool-call ledger."""
    pass


class ResumptionLedger:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.committed_high_water: int = 0
        self.terminal_results: dict[int, dict] = {}  # event_id -> result
        self.dispatched_requests: dict[str, int] = {}  # request_id -> event_id

    def commit_terminal(self, event_id: int, request_id: str, result: dict) -> None:
        # Atomic in real implementation: ledger write + high-water bump together.
        if event_id != self.committed_high_water + 1:
            raise McpResumptionLedgerViolation(
                f"non-contiguous commit: event {event_id} after high-water "
                f"{self.committed_high_water} on session {self.session_id}"
            )
        self.terminal_results[event_id] = result
        self.dispatched_requests[request_id] = event_id
        self.committed_high_water = event_id

    def last_event_id_header(self) -> str:
        return str(self.committed_high_water)


def reconcile_resumed_event(ledger: ResumptionLedger, event_id: int, request_id: str | None) -> str:
    expected = ledger.committed_high_water + 1
    if event_id == expected:
        return "novel"
    if event_id <= ledger.committed_high_water:
        if request_id is not None and request_id in ledger.dispatched_requests:
            return "duplicate"
        # Orphan: server emitted a result the client never recorded as its own.
        raise McpResumptionLedgerViolation(
            f"orphan event {event_id} on session {ledger.session_id}: "
            f"no ledger entry for request {request_id!r}; "
            f"side effect may have landed without client authorization — "
            f"reconcile server state before any retry"
        )
    # event_id > expected: replay started past our high-water mark.
    raise McpResumptionLedgerViolation(
        f"replay gap on session {ledger.session_id}: resumed at event {event_id}, "
        f"expected {expected}; server replay window may have truncated — "
        f"treat session as poisoned"
    )
