# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-resumption-as-a-fork-rather-than-a-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-resumption-as-a-fork-rather-than-a-continuation.warrant.json
# Markdown SHA-256:   2f5794841bc5ae38f402ded1c10d6da9ab3a4913a7b95fc15298c3b0e5fb7866
# Code AST SHA-256:   6aa46d6f2177447430a453571dd6ed3cf8491f0439ae59b7256a953da91e0701
# Verified Classes:   ResumptionForkDetected, StreamEvent
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass
from typing import Optional


class ResumptionForkDetected(RuntimeError):
    """Raised when a resumed MCP SSE stream does not belong to the original invocation."""


@dataclass
class StreamEvent:
    event_id: str
    invocation_id: Optional[str]
    rpc_id: int
    kind: str  # "progress" | "result" | "error"
    payload: dict


def resume_stream(
    original: StreamEvent,
    reconnect_fn,
    max_replay_events: int = 256,
) -> StreamEvent:
    """
    Resume an MCP Streamable HTTP tool call after a transport drop.

    `original` is the last event the client observed for the in-flight
    tools/call. `reconnect_fn(last_event_id)` returns an iterator of
    StreamEvent objects from the POST /mcp reconnect.

    Returns the terminal result/error event for the original invocation.
    Raises ResumptionForkDetected if the server started a new invocation
    or the stream terminates without proving continuity.
    """
    if original.invocation_id is None:
        raise ResumptionForkDetected(
            "Original event lacks _meta.invocation_id; continuity is unprovable. "
            "Treat reconnect as a new call and reconcile side effects."
        )

    stream = reconnect_fn(original.event_id)
    seen = 0
    terminal: Optional[StreamEvent] = None

    for ev in stream:
        seen += 1
        if seen > max_replay_events:
            raise ResumptionForkDetected(
                f"Resumed stream exceeded {max_replay_events} events without terminal; "
                "server may be replaying unboundedly or looping a new invocation."
            )

        if ev.invocation_id != original.invocation_id:
            raise ResumptionForkDetected(
                f"Fork: resumed stream carries invocation_id={ev.invocation_id!r} "
                f"but original was {original.invocation_id!r}. "
                f"rpc_id={ev.rpc_id}. Server likely re-ran the tool."
            )

        if ev.rpc_id != original.rpc_id:
            raise ResumptionForkDetected(
                f"rpc_id mismatch on resumed stream: {ev.rpc_id} != {original.rpc_id}."
            )

        if ev.kind in ("result", "error"):
            terminal = ev
            break

    if terminal is None:
        raise ResumptionForkDetected(
            "Resumed stream closed without a terminal result/error event for the "
            "original rpc_id. Continuation not proven; do not assume completion."
        )

    return terminal
