# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-stream-is-secretly-non-resumable-despite-a-valid-resumability-token.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-stream-is-secretly-non-resumable-despite-a-valid-resumability-token.warrant.json
# Markdown SHA-256:   0dc403a8a556f06accd45a5350e596cab836c1b7b48be325559792a7375719ce
# Code AST SHA-256:   0f46c3e2e4f0f9ff109574bbe834890a4fb67ccf77fff847ba1e2b2aee83b28e
# Verified Classes:   ResumptionGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when an MCP stream resume is non-contiguous without a truncation signal."""
    pass


def validate_resume(
    requested_seq: int,
    first_delivered_seq: int,
    truncation_signaled: bool,
    buffer_generation_evicted: bool,
) -> None:
    """
    Enforce the contiguous-replay invariant at the MCP resume boundary.

    A valid resume satisfies exactly one of:
      - first_delivered_seq == requested_seq + 1  (contiguous replay)
      - truncation_signaled is True               (explicit resync directive)

    Any other outcome means the server silently dropped the delta between
    the client's last-seen event and the current stream head. The client
    MUST NOT continue on cached state.
    """
    if buffer_generation_evicted and not truncation_signaled:
        # Server evicted the buffer backing the token but resumed anyway.
        raise ResumptionGapError(
            f"resumability token for seq={requested_seq} references an evicted "
            f"buffer generation; server degraded to resume-from-head without a "
            f"resync signal. Cached capability/progress state is now stale."
        )

    if truncation_signaled:
        # Explicit resync: caller is required to invalidate derived state.
        return

    expected = requested_seq + 1
    if first_delivered_seq != expected:
        gap = first_delivered_seq - expected
        raise ResumptionGapError(
            f"non-contiguous resume: requested seq={requested_seq}, expected "
            f"first event {expected}, got {first_delivered_seq} "
            f"({gap} events silently dropped). Treat as hard resync: discard "
            f"tool-capability cache and re-issue tools/list before continuing."
        )


def resume_stream(client, requested_seq: int, first_delivered_seq: int,
                  truncation_signaled: bool = False,
                  buffer_generation_evicted: bool = False) -> None:
    validate_resume(
        requested_seq=requested_seq,
        first_delivered_seq=first_delivered_seq,
        truncation_signaled=truncation_signaled,
        buffer_generation_evicted=buffer_generation_evicted,
    )
    # Only reached on a provably contiguous or explicitly-truncated resume.
    client.mark_resumed(contiguous=not truncation_signaled)
