# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-stream-session-when-sse-backpressure-coalesces-the-resumption-cursor-past-unflushed-tool-call-deltas.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-stream-session-when-sse-backpressure-coalesces-the-resumption-cursor-past-unflushed-tool-call-deltas.warrant.json
# Markdown SHA-256:   50fa810a1107dfa9481d00ea647b324266fad1234b289988c61700610a4f28c0
# Code AST SHA-256:   7fb1a78f2e35367cda31af3a4c53cae02a04887f107d4fe47dea01b272685e72
# Verified Classes:   StreamResumptionGap, FlushConfirmedReplayLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StreamResumptionGap(RuntimeError):
    """Raised when a resumed MCP SSE stream skips event IDs that were
    assigned but never flushed, producing a silent prefix of tool-call
    argument deltas."""
    pass


class FlushConfirmedReplayLog:
    """Replay log whose retention watermark tracks socket flush, not enqueue."""

    def __init__(self) -> None:
        self._frames: dict[int, dict] = {}
        self._flushed_through: int = 0   # highest ID confirmed written to socket
        self._assigned_through: int = 0  # highest ID enqueued

    def enqueue(self, frame: dict) -> int:
        self._assigned_through += 1
        frame_id = self._assigned_through
        frame["id"] = frame_id
        self._frames[frame_id] = frame
        return frame_id

    def confirm_flushed(self, frame_id: int) -> None:
        # Advance watermark only on confirmed drain; retain everything above it.
        if frame_id > self._flushed_through:
            self._flushed_through = frame_id
        # Retire only frames strictly below the flushed watermark.
        for fid in [f for f in self._frames if f < self._flushed_through]:
            del self._frames[fid]

    def resume_from(self, last_event_id: int) -> list[dict]:
        # Replay everything retained above the client's cursor. If the client's
        # cursor is below the flushed watermark, the gap is unrecoverable here.
        if last_event_id < self._flushed_through:
            raise StreamResumptionGap(
                f"client cursor {last_event_id} precedes flushed watermark "
                f"{self._flushed_through}; frames were retired before delivery "
                f"and cannot be replayed"
            )
        return [self._frames[fid] for fid in sorted(self._frames) if fid > last_event_id]


def assemble_tool_call_deltas(received_ids: list[int], start_cursor: int) -> None:
    """Client-side contiguity assertion: a gap in delta IDs is a resumption
    failure, never a coalescing optimization."""
    expected = start_cursor + 1
    for fid in received_ids:
        if fid != expected:
            raise StreamResumptionGap(
                f"delta sequence gap: expected id {expected}, received {fid}; "
                f"tool-call arguments would be silently truncated to a parseable prefix"
            )
        expected += 1
