# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-half-resumed-mcp-streamable-session-after-sse-fallback-negotiation-silently-re-opens-a-dead-event-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-half-resumed-mcp-streamable-session-after-sse-fallback-negotiation-silently-re-opens-a-dead-event-cursor.warrant.json
# Markdown SHA-256:   176272aac1db73829cc6d4c728ab5fdf00a20227f8ea8964f3876b50da2bd512
# Code AST SHA-256:   0f52b3e0f0ea31c6b6a1b08aa1f1b54f486c4a9fde5cce852294f073c5b7499b
# Verified Classes:   StreamResumptionGapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StreamResumptionGapError(RuntimeError):
    """Raised when a resumed SSE stream cannot prove logical continuity
    with the pre-disconnect cursor. Transport liveness is not continuity."""
    pass


def accept_resumed_event(
    last_seen_id: str | None,
    last_seen_call_id: str,
    first_resumed_event: dict,
    id_scheme_comparable: bool,
) -> None:
    """Validate the first event of a resumed stream before folding it into
    the in-flight tool result. Raises on any unprovable continuity."""

    resumed_id = first_resumed_event.get("id")
    resumed_call_id = first_resumed_event.get("call_id")

    # Mechanism 1: call-scoped correlation token (works with opaque ids).
    if resumed_call_id is not None:
        if resumed_call_id != last_seen_call_id:
            raise StreamResumptionGapError(
                f"resumed event belongs to call {resumed_call_id!r}, "
                f"in-flight call is {last_seen_call_id!r}; "
                f"cursor was silently reset by server"
            )
        return

    # Mechanism 2: monotonic id guard, only valid if ids are comparable.
    if id_scheme_comparable and last_seen_id is not None and resumed_id is not None:
        try:
            if int(resumed_id) <= int(last_seen_id):
                raise StreamResumptionGapError(
                    f"resumed id {resumed_id} does not advance past "
                    f"last-seen id {last_seen_id}; replay buffer likely "
                    f"expired and stream restarted at head"
                )
        except ValueError:
            raise StreamResumptionGapError(
                f"ids {last_seen_id!r}->{resumed_id!r} not comparable "
                f"despite id_scheme_comparable=True; negotiation mismatch"
            )
        return

    # No proof available: refuse to fold, force re-issue.
    raise StreamResumptionGapError(
        "no correlation token and no comparable id; continuity unprovable, "
        "quarantine partial result and re-issue the call"
    )
