# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-mcp-sse-last-event-id-resumption-as-unsafe-and-replay-the-tool-call-instead-of-resuming-the-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-mcp-sse-last-event-id-resumption-as-unsafe-and-replay-the-tool-call-instead-of-resuming-the-stream.warrant.json
# Markdown SHA-256:   a057964756a36363c535add46acef28c7911d6d738d55fc7da8943c3556c0a50
# Code AST SHA-256:   3725446dbd9d99ba53f9c1693fd167c943490454e21cfbb1b6098661f3bd78a6
# Verified Classes:   StreamResumptionIntegrityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StreamResumptionIntegrityError(RuntimeError):
    """Raised when an SSE resume would splice non-contiguous events onto a call."""
    pass


def apply_resumed_event(call_state: dict, event: dict, server_declares_gap: bool) -> dict:
    """
    call_state: {"call_id": str, "last_applied_id": int, "result": Any|None, "idempotency_key": str}
    event:      {"id": int, "data": dict}
    """
    last = call_state["last_applied_id"]
    incoming = event["id"]

    # Contiguity invariant: resumed events must be exactly last+1 unless the
    # server has explicitly declared the replay window lost.
    if not server_declares_gap and incoming != last + 1:
        raise StreamResumptionIntegrityError(
            f"non-contiguous resume for call {call_state['call_id']}: "
            f"expected id {last + 1}, got {incoming}; "
            f"refusing to splice (window likely evicted or rerouted)"
        )

    if server_declares_gap:
        # Cannot trust the stream; must reconcile against authoritative call state.
        raise StreamResumptionIntegrityError(
            f"server declared replay gap for call {call_state['call_id']} "
            f"at id {incoming}; enter reconciliation via tools/status "
            f"with idempotency_key={call_state['idempotency_key']}"
        )

    call_state["last_applied_id"] = incoming
    call_state["result"] = event["data"].get("result", call_state["result"])
    return call_state
