# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-resumable-mcp-stream-has-silently-diverged-from-the-server-s-event-log.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-resumable-mcp-stream-has-silently-diverged-from-the-server-s-event-log.warrant.json
# Markdown SHA-256:   69261a5a9f3bb2029ae1e6b635e1fadc37795d74f22d4ed75cd5a2b9c6fe7e4b
# Code AST SHA-256:   0269283063d62752755ca9debf4c01b3ead7ccb9228cc79b56bce4d30a393e17
# Verified Classes:   StreamResumptionDivergence
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StreamResumptionDivergence(RuntimeError):
    """Raised when a resumed MCP SSE stream is not a strict continuation of applied state."""
    pass


def resume_stream(client, session, applied_cursor: str, non_idempotent_in_flight: bool):
    """
    Reconnect a streamable-HTTP MCP session and verify the resumed stream is a
    strict continuation of the applied-state cursor. Refuses to feed a stream
    that replays at or below the cursor, or whose cursor provenance is unknown.
    """
    if applied_cursor is None:
        # No watermark means we cannot prove continuity. Re-init, don't guess.
        raise StreamResumptionDivergence(
            "no applied-state cursor; resumption is unverifiable, re-initialize session"
        )

    if non_idempotent_in_flight:
        # Event-ID arithmetic cannot reconstruct effect state for non-idempotent
        # calls that may be re-delivered. Force a clean session.
        raise StreamResumptionDivergence(
            "non-idempotent tool in flight across reconnect; "
            "effect ledger cannot be rebuilt from event IDs"
        )

    stream = client.reconnect(session, last_event_id=applied_cursor)

    first_id = stream.peek_first_event_id()
    if first_id is None:
        raise StreamResumptionDivergence(
            "server did not expose first replayed event ID; continuity unprovable"
        )

    if not _strictly_after(first_id, applied_cursor):
        # Server replayed a prefix we already applied, or rewound into evicted
        # territory and resumed from oldest retained. Either way: not a continuation.
        raise StreamResumptionDivergence(
            f"resumed stream starts at {first_id!r} which is not strictly after "
            f"applied cursor {applied_cursor!r}; silent divergence detected"
        )

    return stream


def _strictly_after(a: str, b: str) -> bool:
    # Server-local ID ordering; compare as opaque monotonic tokens, not ints.
    try:
        return int(a) > int(b)
    except ValueError:
        return a > b
