# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-an-mcp-http-native-sse-session-has-silently-forked-its-event-stream-during-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-an-mcp-http-native-sse-session-has-silently-forked-its-event-stream-during-resumption.warrant.json
# Markdown SHA-256:   35c33c8f3e51e4c28436601cc6e5c399e3ce561ee9f409a3de87bab5b8382d7f
# Code AST SHA-256:   7d13c9279f65d47beae299f0ea6feeb7c3545708554a801d51816891491cbf56
# Verified Classes:   ResumptionForkError, StreamCursor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ResumptionForkError(RuntimeError):
    """Raised when a resumed MCP SSE stream is not causally continuous
    with the client's pre-disconnect cursor."""


@dataclass(frozen=True)
class StreamCursor:
    session_id: str
    last_event_id: int
    lineage_token: str  # hash(segment_identity + server_seq_at_cursor)


def _lineage_token(segment_id: str, seq: int) -> str:
    return hashlib.sha256(f"{segment_id}:{seq}".encode()).hexdigest()


def verify_resumption(
    client_cursor: StreamCursor,
    server_session_id: str,
    server_resumed_from: int,
    server_segment_id: str,
    server_seq_at_cursor: int,
    first_event: dict,
    outstanding_calls: set[str],
) -> None:
    if server_session_id != client_cursor.session_id:
        raise ResumptionForkError(
            f"session mismatch: client={client_cursor.session_id} "
            f"server={server_session_id}"
        )

    if server_resumed_from != client_cursor.last_event_id:
        raise ResumptionForkError(
            f"cursor mismatch: client={client_cursor.last_event_id} "
            f"server={server_resumed_from}"
        )

    expected = _lineage_token(server_segment_id, server_seq_at_cursor)
    if expected != client_cursor.lineage_token:
        # IDs are contiguous, transport is healthy, but the log forked.
        raise ResumptionForkError(
            "lineage token mismatch: resumed stream is a fork of the "
            "client's event log; re-initialize session and reconcile "
            "against server snapshot"
        )

    # Causal precondition check on the first resumed event.
    ev_type = first_event.get("type")
    call_id = first_event.get("call_id")
    if ev_type == "tool_cancelled" and call_id not in outstanding_calls:
        raise ResumptionForkError(
            f"causal precondition violated: tool_cancelled for {call_id} "
            f"with no outstanding tool_call in applied set"
        )
    if ev_type == "tool_result" and call_id not in outstanding_calls:
        raise ResumptionForkError(
            f"causal precondition violated: tool_result for {call_id} "
            f"with no outstanding tool_call in applied set"
        )


def resume_stream(client_cursor, server_handshake, outstanding_calls):
    try:
        verify_resumption(
            client_cursor=client_cursor,
            server_session_id=server_handshake["session_id"],
            server_resumed_from=server_handshake["resumed_from"],
            server_segment_id=server_handshake["segment_id"],
            server_seq_at_cursor=server_handshake["seq_at_cursor"],
            first_event=server_handshake["first_event"],
            outstanding_calls=outstanding_calls,
        )
    except ResumptionForkError:
        # Loud, bounded failure: re-initialize rather than silently fork.
        raise
    return server_handshake["first_event"]
