# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-stream-resumption-token-has-silently-diverged-from-its-event-log.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-stream-resumption-token-has-silently-diverged-from-its-event-log.warrant.json
# Markdown SHA-256:   a6e943687ebd3e1a6126e970967687c314f84d7047a83d3692ab88b06de02dc2
# Code AST SHA-256:   1bc94011b4679f634732770c69ea131c717eec51c48f9982b6a9c16226834724
# Verified Classes:   ResumptionDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionDivergenceError(RuntimeError):
    """Raised when a resumed MCP SSE stream does not provably continue the prior stream."""
    pass


def parse_event_id(raw: str) -> tuple[int, int]:
    # Expected form: "{epoch}-{seq}". A malformed ID is itself a divergence signal.
    try:
        epoch_s, seq_s = raw.split("-", 1)
        return int(epoch_s), int(seq_s)
    except (ValueError, AttributeError) as exc:
        raise ResumptionDivergenceError(f"unparseable event id: {raw!r}") from exc


def validate_resume(last_persisted_id: str, first_resumed_id: str) -> None:
    """
    Enforce the continuity invariant: the first event of a resumed stream must
    strictly extend the last persisted ID under the full (epoch, seq) order.

    A server that silently fell back to head after truncation or restart will
    fail this check. There is no legitimate case where it passes wrongly.
    """
    last = parse_event_id(last_persisted_id)
    first = parse_event_id(first_resumed_id)

    if first <= last:
        # Covers epoch rollback (8-0 after 7-842), seq reset within a stale epoch,
        # and exact replay of an already-consumed event. None is a valid continuation.
        raise ResumptionDivergenceError(
            f"resumed stream does not extend prior stream: "
            f"last_persisted={last_persisted_id!r} first_resumed={first_resumed_id!r}; "
            f"treat session as restarted and invalidate all in-flight tool-call state"
        )


def handle_resume(last_persisted_id: str, stream_first_event: dict) -> None:
    first_id = stream_first_event.get("id")
    if first_id is None:
        raise ResumptionDivergenceError(
            "resumed stream emitted an event without an id; continuity unprovable"
        )
    validate_resume(last_persisted_id, first_id)
