# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-a-transport-drop-and-the-server-has-already-advanced-its-json-rpc-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-a-transport-drop-and-the-server-has-already-advanced-its-json-rpc-cursor.warrant.json
# Markdown SHA-256:   15267b1a5410aab248de203a08e1ad7b974cdc977b1f19df4274aa34f4d44404
# Code AST SHA-256:   cef3e763757e0d9d8c4c6b1bcaf818e4af19b06a835f54159e7364d86cf30c7c
# Verified Classes:   StreamResumptionDiscontinuity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StreamResumptionDiscontinuity(RuntimeError):
    """Raised when a resumed MCP stream's first event is not the successor
    of the client's last-seen event ID, and no explicit resync frame
    preceded it. Indicates silent event-log loss (compaction, TTL, or
    cursor unreachability) that the transport status code did not signal."""
    pass


def verify_resumption_continuity(
    last_seen_event_id: str,
    first_event_after_reconnect: dict,
    resync_frame_seen: bool,
) -> None:
    """
    Enforce the contiguity invariant on MCP HTTP stream resumption.

    last_seen_event_id: the client's persisted cursor (Last-Event-ID).
    first_event_after_reconnect: the first SSE event parsed post-reconnect.
    resync_frame_seen: whether an explicit discontinuity marker preceded it.

    Raises StreamResumptionDiscontinuity if continuity cannot be proven.
    """
    if resync_frame_seen:
        # Server explicitly declared discontinuity; client must re-derive
        # state from the snapshot rather than assume contiguity.
        return

    incoming_id = first_event_after_reconnect.get("id")
    if incoming_id is None:
        raise StreamResumptionDiscontinuity(
            f"Resumed stream delivered an event with no ID after cursor "
            f"{last_seen_event_id!r}; continuity unprovable."
        )

    expected = _successor(last_seen_event_id)
    if incoming_id != expected:
        raise StreamResumptionDiscontinuity(
            f"Resumption gap detected: last_seen={last_seen_event_id!r}, "
            f"expected_successor={expected!r}, received={incoming_id!r}. "
            f"Server event log was likely compacted or pruned past the "
            f"client cursor; intermediate events are lost. Re-derive agent "
            f"state from a snapshot before dispatching further events."
        )


def _successor(event_id: str) -> str:
    # Event IDs are opaque per spec; this assumes the common
    # monotonic-integer-with-prefix convention (e.g. "evt_00412").
    prefix, _, num = event_id.rpartition("_")
    if not num.isdigit():
        # Cannot compute a successor for opaque IDs; require resync.
        raise StreamResumptionDiscontinuity(
            f"Event ID {event_id!r} is not successor-computable; "
            f"client must require an explicit resync frame to resume."
        )
    return f"{prefix}_{int(num) + 1:0{len(num)}d}"
