# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-mcp-http-native-transport-stream-when-the-resumption-token-is-valid-but-the-event-log-has-been-truncated.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-mcp-http-native-transport-stream-when-the-resumption-token-is-valid-but-the-event-log-has-been-truncated.warrant.json
# Markdown SHA-256:   dfe5bd46acb3993f7c0cf7150e36433d54c5c129079890ef5f79912f308c09f7
# Code AST SHA-256:   4a6bed77efb4313d966b51886a7493b6e5c90dda93b14261676c9ea6538b466e
# Verified Classes:   ResumeContiguityError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ResumeContiguityError(RuntimeError):
    """Raised when a resumed MCP stream skips event IDs without declaring a gap."""
    pass


def classify_resume(last_sent_id: int, first_received_id: int, declared_step: int = 1) -> str:
    if first_received_id == last_sent_id + declared_step:
        return "contiguous"
    if first_received_id > last_sent_id + declared_step:
        return "silent_gap"
    # first_received_id <= last_sent_id: replay of already-seen events; caller dedupes.
    return "replay"


def guard_first_replayed_frame(last_sent_id: int, first_received_id: int,
                               server_declared_gap: bool = False,
                               declared_step: int = 1) -> None:
    outcome = classify_resume(last_sent_id, first_received_id, declared_step)
    if outcome == "silent_gap" and not server_declared_gap:
        raise ResumeContiguityError(
            f"resume from evt-{last_sent_id:06d} delivered evt-{first_received_id:06d} "
            f"with no declared gap; {first_received_id - last_sent_id - declared_step} "
            f"events evicted from server log; re-synchronize full state"
        )
    # contiguous or declared gap: safe to hand the frame to consumers.
