# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-stream-resumption-as-a-capability-negotiation-not-a-transport-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-stream-resumption-as-a-capability-negotiation-not-a-transport-retry.warrant.json
# Markdown SHA-256:   1399a3f430c70b27c96e783cdb09fff36c72898c876c38a45a83777cbbe8de9d
# Code AST SHA-256:   fd02978d057a083d5c008032391cd07f4597405b89c8c5494140295c94363264
# Verified Classes:   ResumeNegotiationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ResumeNegotiationError(RuntimeError):
    """Raised when an MCP stream resume cannot be proven contiguous or safe."""
    pass


def resume_stream(client, session, last_event_id, operation):
    # 1. Capability gate: refuse to send Last-Event-ID unless advertised.
    if not session.capabilities.get("resumable_streams", False):
        raise ResumeNegotiationError(
            f"session {session.id} does not advertise resumable_streams; "
            "must restart operation, not resume"
        )

    # 2. Session liveness gate.
    if not session.is_live():
        raise ResumeNegotiationError(
            f"session {session.id} is not live; resume would create a new "
            "session and re-execute side effects"
        )

    # 3. Idempotency gate for side-effecting operations.
    if not operation.is_idempotent() and not operation.has_idempotency_key():
        raise ResumeNegotiationError(
            f"operation {operation.id} has side effects and no idempotency "
            "key; resume is unsafe, restart with reconciliation required"
        )

    stream = client.request_stream(
        session_id=session.id,
        last_event_id=last_event_id,
        accept="text/event-stream",
    )

    # 4. Contiguity gate: first event must be exactly last_event_id + 1.
    first = stream.peek_first_event()
    if first is None:
        raise ResumeNegotiationError(
            "resume returned an empty stream; cannot prove replay occurred"
        )
    if first.id != last_event_id + 1:
        # A 200 with a gap is truncation, not resumption.
        raise ResumeNegotiationError(
            f"resume gap detected: requested after {last_event_id}, "
            f"first replayed event is {first.id}; stream is truncated"
        )

    return stream
