# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-silent-event-loss-in-mcp-http-native-transports-when-sse-upgrade-negotiation-is-stateless-and-per-tool-framing-is-str.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-silent-event-loss-in-mcp-http-native-transports-when-sse-upgrade-negotiation-is-stateless-and-per-tool-framing-is-str.warrant.json
# Markdown SHA-256:   ad9eb781c40d171278d231743c3813e1eabce4ac78b4f66e4af9998836bc0e15
# Code AST SHA-256:   5be877ae56a6eff0b5e498511647d03b23cac07c4aab0e3dd715a6ca0d23c5a2
# Verified Classes:   StreamAttributionError, FrameEnvelope, ReassemblyBuffer, StreamRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StreamAttributionError(RuntimeError):
    """Raised when a frame cannot be attributed to a single negotiation handshake."""
    pass


@dataclass
class FrameEnvelope:
    tool_call_id: str
    stream_id: str
    seq: int
    payload: bytes
    terminal: bool = False
    checksum: str | None = None


@dataclass
class ReassemblyBuffer:
    tool_call_id: str
    stream_id: str
    frames: dict[int, bytes] = field(default_factory=dict)
    cancelled: bool = False

    def accept(self, frame: FrameEnvelope) -> None:
        if frame.stream_id != self.stream_id:
            # A frame from a different handshake landed in this buffer.
            # This is the exact condition that produced silent corruption.
            raise StreamAttributionError(
                f"frame stream_id={frame.stream_id!r} does not match "
                f"buffer stream_id={self.stream_id!r} for "
                f"tool_call_id={self.tool_call_id!r}"
            )
        if frame.seq in self.frames and self.frames[frame.seq] != frame.payload:
            raise StreamAttributionError(
                f"non-idempotent seq collision at seq={frame.seq} "
                f"for stream_id={self.stream_id!r}"
            )
        self.frames[frame.seq] = frame.payload


class StreamRegistry:
    """Keyed on (tool_call_id, stream_id); refuses to merge concurrent streams."""

    def __init__(self) -> None:
        self._buffers: dict[tuple[str, str], ReassemblyBuffer] = {}

    def open(self, tool_call_id: str, stream_id: str) -> ReassemblyBuffer:
        # A new upgrade for a tool_call_id that already has a live stream
        # with a *different* stream_id is a collision, not a retry.
        for (tcid, sid), buf in self._buffers.items():
            if tcid == tool_call_id and sid != stream_id and not buf.cancelled:
                raise StreamAttributionError(
                    f"concurrent stream collision: tool_call_id={tool_call_id!r} "
                    f"already has live stream_id={sid!r}, "
                    f"new upgrade requested stream_id={stream_id!r}"
                )
        key = (tool_call_id, stream_id)
        if key not in self._buffers:
            self._buffers[key] = ReassemblyBuffer(tool_call_id, stream_id)
        return self._buffers[key]

    def cancel(self, tool_call_id: str, stream_id: str) -> None:
        buf = self._buffers.get((tool_call_id, stream_id))
        if buf is not None:
            buf.cancelled = True

    def finalize(self, tool_call_id: str, stream_id: str) -> bytes:
        buf = self._buffers.get((tool_call_id, stream_id))
        if buf is None:
            raise StreamAttributionError(
                f"finalize on unknown stream {stream_id!r}"
            )
        seqs = sorted(buf.frames)
        if seqs != list(range(len(seqs))):
            raise StreamAttributionError(
                f"non-contiguous seq set for stream_id={stream_id!r}: {seqs}"
            )
        assembled = b"".join(buf.frames[i] for i in seqs)
        digest = hashlib.sha256(assembled).hexdigest()
        return digest


def handle_upgrade(
    registry: StreamRegistry,
    tool_call_id: str,
    stream_id: str,
    prior_cancelled: bool,
) -> ReassemblyBuffer:
    if prior_cancelled:
        registry.cancel(tool_call_id, stream_id)
    try:
        return registry.open(tool_call_id, stream_id)
    except StreamAttributionError:
        # Fail closed: surface the collision, do not merge.
        raise
