# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-resumed-mcp-sse-stream-as-a-fresh-logical-session-rather-than-a-byte-continuation-of-the-prior-one.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-resumed-mcp-sse-stream-as-a-fresh-logical-session-rather-than-a-byte-continuation-of-the-prior-one.warrant.json
# Markdown SHA-256:   3ada5d3772b3c2f9def23d84c0ffbdb6c981b3fd6e08658afaab55c4a7564a3c
# Code AST SHA-256:   4a127b43ffa6e3645c853db6ba8a5d7ffd84028d82c90a3e90f64035d850b99b
# Verified Classes:   SessionContinuityLost, McpStreamResumer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionContinuityLost(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven to be the same logical session."""
    pass


class McpStreamResumer:
    def __init__(self, session_id: str, epoch_token: str | None):
        self.session_id = session_id
        self.epoch_token = epoch_token
        self.pending_requests: dict[str, str] = {}  # request_id -> tool_name
        self.last_event_id: int | None = None

    def on_drop(self, last_event_id: int) -> None:
        self.last_event_id = last_event_id

    def resume(self, *, new_epoch_token: str | None, first_event_id: int,
               events_before_ack: list[dict]) -> None:
        # Case 1: server attests a different epoch -> fork/restart.
        if self.epoch_token is not None and new_epoch_token != self.epoch_token:
            raise SessionContinuityLost(
                f"session {self.session_id}: epoch changed on resume "
                f"({self.epoch_token!r} -> {new_epoch_token!r}); "
                f"pending requests {list(self.pending_requests)} are orphaned"
            )

        # Case 2: no epoch attestation and event IDs skipped -> cannot prove continuity.
        if self.epoch_token is None and self.last_event_id is not None:
            if first_event_id > self.last_event_id + 1:
                raise SessionContinuityLost(
                    f"session {self.session_id}: event gap "
                    f"({self.last_event_id} -> {first_event_id}) with no epoch token; "
                    f"treating resume as a fresh logical session"
                )

        # Case 3: pending tool calls must be acknowledged (progress/result/cancel)
        # within the grace window or the resume is rejected.
        acked = {
            ev.get("request_id")
            for ev in events_before_ack
            if ev.get("type") in ("progress", "result", "cancelled")
        }
        orphaned = set(self.pending_requests) - acked
        if orphaned:
            raise SessionContinuityLost(
                f"session {self.session_id}: resumed stream did not acknowledge "
                f"pending requests {sorted(orphaned)}; refusing to resume reasoning"
            )

        self.epoch_token = new_epoch_token if new_epoch_token is not None else self.epoch_token
