# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-sse-replay-has-silently-desynchronized-a-stateless-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-sse-replay-has-silently-desynchronized-a-stateless-tool-call.warrant.json
# Markdown SHA-256:   d50a86a52b8b5cec08982c7070c6aa1386338bd39fe2bc51e40a6e48c7876cf7
# Code AST SHA-256:   365d46b57e20763e2f8c0a81c09c5a5798aea10d0c05614dc90b4b3bf5c8f35b
# Verified Classes:   StreamResumeContamination, AssemblyState, SSEFrame, ToolCallAssembly
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class StreamResumeContamination(RuntimeError):
    """Raised when a resumed SSE stream cannot be proven to belong to the
    in-flight tool call, so appending would fuse foreign events into the
    partial result assembly."""


class AssemblyState(Enum):
    CLEAN = "clean"
    PARTIAL = "partial"
    INDETERMINATE = "indeterminate"


@dataclass
class SSEFrame:
    event_id: Optional[int]
    call_id: Optional[str]
    payload: dict


@dataclass
class ToolCallAssembly:
    call_id: str
    expected_min_progress: int
    state: AssemblyState = AssemblyState.CLEAN
    last_event_id: Optional[int] = None
    seen_event_ids: set[int] = field(default_factory=set)
    fragments: list[dict] = field(default_factory=list)

    def ingest(self, frame: SSEFrame) -> None:
        # Provenance: every frame must carry the call-scoped correlation id.
        if frame.call_id != self.call_id:
            self.state = AssemblyState.INDETERMINATE
            raise StreamResumeContamination(
                f"frame call_id={frame.call_id!r} does not match in-flight "
                f"call_id={self.call_id!r}; replay contamination suspected"
            )

        # Dedup: at-least-once delivery may resend the last frame.
        if frame.event_id is not None and frame.event_id in self.seen_event_ids:
            return  # idempotent drop; do not double-apply

        # Gap check on resume: successor must be exactly last+1.
        if (
            self.last_event_id is not None
            and frame.event_id is not None
            and frame.event_id != self.last_event_id + 1
        ):
            self.state = AssemblyState.INDETERMINATE
            raise StreamResumeContamination(
                f"event-id gap: expected {self.last_event_id + 1}, "
                f"got {frame.event_id}; resumed stream is not a continuation"
            )

        if frame.event_id is not None:
            self.seen_event_ids.add(frame.event_id)
            self.last_event_id = frame.event_id
        self.fragments.append(frame.payload)
        self.state = AssemblyState.PARTIAL

    def finalize(self) -> dict:
        if self.state is not AssemblyState.PARTIAL:
            raise StreamResumeContamination(
                f"cannot finalize assembly in state {self.state.value}"
            )
        if len(self.fragments) < self.expected_min_progress + 1:
            self.state = AssemblyState.INDETERMINATE
            raise StreamResumeContamination(
                f"terminal result has {len(self.fragments)} fragments, below "
                f"declared minimum {self.expected_min_progress + 1}; truncation"
            )
        self.state = AssemblyState.CLEAN
        return {"call_id": self.call_id, "fragments": self.fragments}


def resume_stream(
    assembly: ToolCallAssembly, replayed: list[SSEFrame]
) -> dict:
    """Reattach a dropped stream. Append only if every replayed frame proves
    provenance and contiguity; otherwise the assembly is indeterminate and the
    caller must reconcile (re-issue if idempotent) rather than merge."""
    for frame in replayed:
        assembly.ingest(frame)  # raises StreamResumeContamination on violation
    return assembly.finalize()
