# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-tool-call-stream-has-silently-forked-its-replay-cursor-across-a-multiplexed-http-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-tool-call-stream-has-silently-forked-its-replay-cursor-across-a-multiplexed-http-session.warrant.json
# Markdown SHA-256:   5649064efd77bec9c64bb4238d62a22f35cf61f88f071316e84280d060be1ef6
# Code AST SHA-256:   4b5ca01a963217bfe0dd36bdc3fce0d8c0c99bee7fe4f0ad7c0ac6c7d48428ab
# Verified Classes:   CursorForkError, DeliveryReceipt
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import hmac


class CursorForkError(RuntimeError):
    """Raised when a resumable MCP stream's replay cursor diverges from the
    durable log's authoritative lineage under multiplexed backpressure."""


class DeliveryReceipt:
    def __init__(self, event_id: str, payload_hash: str, session_nonce: str, mac: str):
        self.event_id = event_id
        self.payload_hash = payload_hash
        self.session_nonce = session_nonce
        self.mac = mac


def issue_receipt(event_id: str, payload: bytes, session_nonce: str, key: bytes) -> DeliveryReceipt:
    payload_hash = hashlib.sha256(payload).hexdigest()
    mac = hmac.new(
        key,
        f"{event_id}:{payload_hash}:{session_nonce}".encode(),
        hashlib.sha256,
    ).hexdigest()
    return DeliveryReceipt(event_id, payload_hash, session_nonce, mac)


def resume_stream(
    last_event_id: str,
    client_receipt: DeliveryReceipt,
    durable_log: dict[str, bytes],
    session_nonce: str,
    key: bytes,
    backpressure_hwm: int,
    replay_window_depth: int,
) -> str:
    # Invariant 1: backpressure must not outrun the replay window, or the
    # in-flight delivery can be evicted while a resume is still possible.
    if backpressure_hwm >= replay_window_depth:
        raise CursorForkError(
            f"backpressure_hwm={backpressure_hwm} >= replay_window_depth="
            f"{replay_window_depth}: in-flight deliveries can be evicted mid-resume"
        )

    # Invariant 2: the client's receipt must bind event_id to a payload hash
    # the server actually committed. A claim-only Last-Event-ID is insufficient.
    if client_receipt.session_nonce != session_nonce:
        raise CursorForkError(
            f"receipt session_nonce mismatch for {last_event_id}: "
            "receipt belongs to a different session lineage"
        )

    committed = durable_log.get(last_event_id)
    if committed is None:
        raise CursorForkError(
            f"resume cursor {last_event_id} not in durable log: "
            "client claims an event the server never committed"
        )

    expected_mac = hmac.new(
        key,
        f"{last_event_id}:{client_receipt.payload_hash}:{session_nonce}".encode(),
        hashlib.sha256,
    ).hexdigest()
    if not hmac.compare_digest(expected_mac, client_receipt.mac):
        raise CursorForkError(
            f"receipt MAC invalid for {last_event_id}: forged or stale receipt"
        )

    actual_hash = hashlib.sha256(committed).hexdigest()
    if actual_hash != client_receipt.payload_hash:
        # This is the fork: the client holds a receipt for a payload the log
        # does not contain at this event_id. A divergent sibling was committed.
        raise CursorForkError(
            f"payload hash divergence at {last_event_id}: "
            f"client={client_receipt.payload_hash[:12]} log={actual_hash[:12]} — "
            "replay cursor has forked; refusing to resume"
        )

    # Receipt matches committed payload: safe to continue the lineage.
    return last_event_id
