# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-resumption-from-silently-forking-an-mcp-session-s-tool-call-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-resumption-from-silently-forking-an-mcp-session-s-tool-call-ledger.warrant.json
# Markdown SHA-256:   7d29d2d21e9f4984f508d9f1508e87fbddfc73b9188631745afc5d00ff66914e
# Code AST SHA-256:   83573bcd5a5b45612769ad7e3ea51aed52d6b18f1afd1a940cf63f730369b372
# Verified Classes:   ResumptionForkError, EventRecord, ResumptionGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionForkError(RuntimeError):
    """Raised when an SSE resumption request would replay across an execution
    epoch boundary or force re-execution of a side-effecting tool call."""
    pass


class EventRecord:
    __slots__ = ("event_id", "epoch", "payload", "committed")

    def __init__(self, event_id: str, epoch: int, payload: dict, committed: bool):
        self.event_id = event_id
        self.epoch = epoch
        self.payload = payload
        self.committed = committed


class ResumptionGuard:
    def __init__(self, session_token: str, current_epoch: int, log: list[EventRecord]):
        self.session_token = session_token
        self.current_epoch = current_epoch
        self.log = log
        self.by_id = {r.event_id: r for r in log}

    def resume(self, last_event_id: str, presented_epoch: int) -> list[dict]:
        # Invariant 3: epoch binding. A stale cursor from a prior epoch is
        # never silently honored; it must be reconciled out-of-band.
        if presented_epoch != self.current_epoch:
            raise ResumptionForkError(
                f"resumption cursor {last_event_id} belongs to epoch "
                f"{presented_epoch}, session is at epoch {self.current_epoch}; "
                f"reconcile in-flight tool calls before resuming"
            )

        anchor = self.by_id.get(last_event_id)
        if anchor is None:
            raise ResumptionForkError(
                f"unknown Last-Event-ID {last_event_id} for session "
                f"{self.session_token}"
            )

        # Invariant 1: replay is a pure read of recorded bytes. We never
        # invoke a tool handler here.
        replay = [r for r in self.log if r.epoch == presented_epoch
                  and r.event_id > last_event_id]

        # Invariant 2: emit-at-commit. An event whose side effect is not yet
        # durable must not be replayed as if it were; if we find one, the
        # client's cursor is in the ambiguous window and we must refuse.
        for r in replay:
            if not r.committed:
                raise ResumptionForkError(
                    f"event {r.event_id} is buffered but not committed; "
                    f"replay would advertise an uncommitted side effect — "
                    f"require idempotency-key reconciliation"
                )

        return [r.payload for r in replay]
