# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-replay-from-silently-reordering-tool-call-results-across-an-mcp-session-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-replay-from-silently-reordering-tool-call-results-across-an-mcp-session-resume.warrant.json
# Markdown SHA-256:   04576cc3df4a5e4cd4f1df80e5aff58c1cdf339177dbcc8980d5b7153e837567
# Code AST SHA-256:   42e44791f3995842179413ab8149ccaf996ceb71397db212607eb6540f5d4200
# Verified Classes:   ResumptionBoundaryError, CausalUnitBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionBoundaryError(RuntimeError):
    """Raised when an SSE resume point does not fall on a causal-unit boundary."""
    pass


class CausalUnitBuffer:
    """Ring buffer that evicts whole causal units, never individual events."""

    def __init__(self, max_units: int):
        self.max_units = max_units
        self._units: list[tuple[int, list[dict]]] = []  # (unit_id, events)
        self._next_unit_id = 1

    def begin_unit(self) -> int:
        unit_id = self._next_unit_id
        self._next_unit_id += 1
        self._units.append((unit_id, []))
        while len(self._units) > self.max_units:
            self._units.pop(0)  # evict oldest whole unit
        return unit_id

    def append(self, unit_id: int, event: dict) -> None:
        for uid, events in self._units:
            if uid == unit_id:
                events.append(event)
                return
        raise ResumptionBoundaryError(
            f"unit {unit_id} already evicted; refusing to append orphan event"
        )

    def replay_from(self, last_event_id: int) -> list[dict]:
        # last_event_id is a unit_id (ids are assigned per-unit, not per-event)
        for idx, (uid, events) in enumerate(self._units):
            if uid == last_event_id:
                return [e for _, evs in self._units[idx + 1:] for e in evs]
        # last_event_id not found: it was evicted mid-unit or never existed
        raise ResumptionBoundaryError(
            f"Last-Event-ID {last_event_id} is not a live causal-unit boundary; "
            f"client must re-issue the originating tool call rather than replay"
        )


def handle_resume(buffer: CausalUnitBuffer, last_event_id: int) -> list[dict]:
    try:
        return buffer.replay_from(last_event_id)
    except ResumptionBoundaryError as exc:
        # Surface as 409 so the agent re-issues the tool call instead of
        # silently applying a partial unit to the wrong ledger slot.
        raise ResumptionBoundaryError(
            f"resumption point invalid: {exc}; do not replay, re-issue tool call"
        ) from exc
