# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-resumption-token-divergence-in-mcp-streamable-http-transport-under-backpressure-aware-chunked-delivery.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-resumption-token-divergence-in-mcp-streamable-http-transport-under-backpressure-aware-chunked-delivery.warrant.json
# Markdown SHA-256:   33c7ec5a634def1348effd8f2c9c8ada22d31ac1a8486fa65dcadabcb2a879f7
# Code AST SHA-256:   274398783d496fe39809a624997684830b932001f5271015f3d3490569e2919c
# Verified Classes:   ResumptionDivergenceError, SessionCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResumptionDivergenceError(RuntimeError):
    """Raised when client contiguous-ack frontier exceeds server replayable frontier."""


@dataclass
class SessionCursor:
    client_contiguous_ack: int          # highest N such that e1..eN all received
    server_replayable_from: Optional[int] = None  # advertised in session metadata


def parse_chunk_event_ids(chunk: str) -> list[int]:
    ids = []
    for line in chunk.splitlines():
        if line.startswith("id:"):
            ids.append(int(line[3:].strip()))
    return ids


def advance_frontier(cursor: SessionCursor, chunk: str) -> SessionCursor:
    ids = parse_chunk_event_ids(chunk)
    if not ids:
        return cursor
    expected = cursor.client_contiguous_ack + 1
    for eid in ids:
        if eid != expected:
            # Gap inside a single chunk: coalescing dropped an event.
            raise ResumptionDivergenceError(
                f"non-contiguous event in chunk: expected {expected}, got {eid}"
            )
        expected += 1
    cursor.client_contiguous_ack = expected - 1
    return cursor


def resume(cursor: SessionCursor, server_meta: dict) -> int:
    replayable_from = server_meta.get("replayable_from")
    if replayable_from is None:
        raise ResumptionDivergenceError(
            "server did not advertise replayable_from; cannot verify resumption"
        )
    cursor.server_replayable_from = replayable_from
    # Client has acknowledged past what the server can replay: hole is unrecoverable.
    if cursor.client_contiguous_ack >= replayable_from:
        raise ResumptionDivergenceError(
            f"client ack {cursor.client_contiguous_ack} >= "
            f"server replayable_from {replayable_from}; "
            f"events {replayable_from}..{cursor.client_contiguous_ack} lost"
        )
    return cursor.client_contiguous_ack + 1
