# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-tool-stream-flow-control-as-a-lossy-channel-problem-rather-than-a-queue-depth-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-tool-stream-flow-control-as-a-lossy-channel-problem-rather-than-a-queue-depth-problem.warrant.json
# Markdown SHA-256:   07139a8b40aca49ab1806b875855647692372a269d7a28868f0cc64cac76fb8e
# Code AST SHA-256:   92c53daea53c3f4198fdd94373aefcada914078eda4f3548da386582232c2d20
# Verified Classes:   MCPStreamIntegrityError, MCPBackpressureDropError, StreamGuard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class MCPStreamIntegrityError(RuntimeError):
    """Raised when a tool stream's terminal marker disagrees with consumer-side state."""
    pass


class MCPBackpressureDropError(MCPStreamIntegrityError):
    """Raised when a producer signals a gap or the consumer detects a sequence discontinuity."""
    pass


@dataclass
class StreamGuard:
    expected_count: int | None = None
    expected_hash: str | None = None
    seen: int = 0
    h: "hashlib._Hash" = field(default_factory=hashlib.sha256)
    last_seq: int = -1
    gaps: list[tuple[int, int]] = field(default_factory=list)
    _closed: bool = False

    def ingest(self, seq: int, payload: bytes) -> None:
        if self._closed:
            raise MCPStreamIntegrityError("record after eof; stream already closed")
        if seq != self.last_seq + 1:
            # Sequence discontinuity: transport dropped frames between last_seq and seq.
            self.gaps.append((self.last_seq + 1, seq - 1))
            raise MCPBackpressureDropError(
                f"sequence gap: expected {self.last_seq + 1}, got {seq}; "
                f"stream is lossy and must be resumed from cursor {self.last_seq + 1}"
            )
        self.h.update(payload)
        self.last_seq = seq
        self.seen += 1

    def close(self, terminal_count: int, terminal_hash: str | None) -> None:
        self._closed = True
        if terminal_count != self.seen:
            raise MCPStreamIntegrityError(
                f"terminal count {terminal_count} != consumer count {self.seen}; "
                f"producer-authored eof is untrusted, re-request with range cursor"
            )
        if terminal_hash is not None and terminal_hash != self.h.hexdigest():
            raise MCPStreamIntegrityError(
                "terminal hash mismatch; stream truncated mid-record by transport window"
            )
        if self.gaps:
            raise MCPBackpressureDropError(
                f"stream closed with unhealed gaps {self.gaps}; refusing to summarize"
            )


def drain_tool_stream(frames, guard: StreamGuard) -> StreamGuard:
    """frames: iterable of (seq:int, payload:bytes) or ('eof', count, hash)."""
    for frame in frames:
        if frame[0] == "eof":
            guard.close(frame[1], frame[2] if len(frame) > 2 else None)
            return guard
        guard.ingest(frame[0], frame[1])
    # Iterator exhausted without an eof frame: transport closed the stream.
    raise MCPStreamIntegrityError(
        "stream ended without terminal marker; cannot distinguish completion from truncation"
    )
