# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-last-event-id-resumption-as-unsafe-and-re-establish-a-fresh-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-last-event-id-resumption-as-unsafe-and-re-establish-a-fresh-session.warrant.json
# Markdown SHA-256:   b4307aad41c567a2cb3e54871dee5cca0f3f1cd42612f4bfc642a6cc010a3ed0
# Code AST SHA-256:   1f69c18a8f054cb2ecfc6851d8410769e90e6302deaec211d2fa760ece616f63
# Verified Classes:   ResumptionUnsafeError, StreamResumeGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionUnsafeError(RuntimeError):
    """Raised when a resumed MCP stream cannot be proven to be a replay
    of the same handler execution rather than a re-dispatch."""
    pass


class StreamResumeGuard:
    """Client-side guard for MCP Streamable-HTTP Last-Event-ID resumption.

    Invariant: a resumed stream is accepted only if (a) the first event ID
    is exactly last_seen + 1, (b) the session_generation carried on the
    event matches the pre-drop generation, and (c) the server advertised
    replay-only resumption. Otherwise the caller must open a fresh session.
    """

    def __init__(self, last_seen_id: int, session_generation: str,
                 server_caps: dict, retained_payloads: bool):
        self.last_seen_id = last_seen_id
        self.session_generation = session_generation
        self.server_caps = server_caps
        self.retained_payloads = retained_payloads

    def validate_resume(self, first_event: dict) -> None:
        # (c) capability negotiation
        if self.server_caps.get("resumption") != "replay-only":
            raise ResumptionUnsafeError(
                f"server does not advertise replay-only resumption "
                f"(got {self.server_caps.get('resumption')!r}); "
                f"re-dispatch on resume is indistinguishable from replay"
            )

        # (a) contiguity, not monotonicity
        ev_id = first_event.get("id")
        if not isinstance(ev_id, int) or ev_id != self.last_seen_id + 1:
            raise ResumptionUnsafeError(
                f"event ID gap on resume: expected {self.last_seen_id + 1}, "
                f"got {ev_id!r}; server likely evicted events under "
                f"backpressure and resumed from eviction point"
            )

        # (b) session-generation pinning detects re-dispatch
        gen = first_event.get("session_generation")
        if gen != self.session_generation:
            raise ResumptionUnsafeError(
                f"session generation changed on resume: "
                f"{self.session_generation!r} -> {gen!r}; "
                f"handler was re-dispatched, stream is semantically "
                f"discontinuous despite contiguous event IDs"
            )

        # (d) if we did not retain payloads, we cannot cross-check content
        # divergence at the same ID; treat as unsafe for side-effecting calls
        if not self.retained_payloads and first_event.get("side_effecting"):
            raise ResumptionUnsafeError(
                "cannot verify replay vs re-dispatch: progress payloads "
                "were discarded and tool has side effects; open fresh session"
            )


def resume_or_restart(guard: StreamResumeGuard, first_event: dict) -> str:
    try:
        guard.validate_resume(first_event)
        return "resumed"
    except ResumptionUnsafeError as exc:
        # caller is expected to discard Mcp-Session-Id, re-initialize,
        # and reconcile the in-flight call's side effects out-of-band
        return f"restart-required: {exc}"
