# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-resumption-window-when-an-mcp-streamable-http-session-resumes-mid-stream-against-a-tool-that-has-already-committed-ba.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-resumption-window-when-an-mcp-streamable-http-session-resumes-mid-stream-against-a-tool-that-has-already-committed-ba.warrant.json
# Markdown SHA-256:   37e1353fd3678e761abe72de26ac9838e306d7c721ee19f1d4e704f3b8751f36
# Code AST SHA-256:   a5622c6276d5ed2a3c08a15c819482708172724db85b3a0659e8e3d8455bc9b8
# Verified Classes:   ResumptionInvariantError, SessionStream
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import asyncio
from dataclasses import dataclass, field
from typing import Optional


class ResumptionInvariantError(RuntimeError):
    """Raised when a resume request cannot be honored without violating
    the flush-anchored watermark invariant or the producer-pause invariant."""


@dataclass
class SessionStream:
    # Monotonic ids assigned by the producer at emit time.
    last_emitted_id: int = 0
    # Highest id whose bytes the transport has acknowledged as flushed.
    last_flushed_id: int = 0
    # Highest id the client has acknowledged via Last-Event-ID.
    last_client_ack_id: int = 0
    # Durable replay log: id -> payload, only appended post-flush.
    replay_log: dict = field(default_factory=dict)
    log_low_water: int = 0
    log_high_water: int = 0
    # Producer gate: paused during replay, resumed after replay flush.
    producer_paused: bool = False
    window: int = 64

    def producer_may_emit(self) -> bool:
        if self.producer_paused:
            return False
        # Single cursor: backpressure derived from flush lag, not queue depth.
        return (self.last_emitted_id - self.last_flushed_id) < self.window

    def record_flush(self, event_id: int, payload: bytes) -> None:
        if event_id != self.last_flushed_id + 1:
            raise ResumptionInvariantError(
                f"flush out of order: got {event_id}, expected {self.last_flushed_id + 1}"
            )
        self.last_flushed_id = event_id
        self.replay_log[event_id] = payload
        self.log_high_water = event_id
        while len(self.replay_log) > self.window:
            evicted = min(self.replay_log)
            del self.replay_log[evicted]
            self.log_low_water = evicted

    async def resume(self, last_event_id: int, writer) -> None:
        if last_event_id > self.log_high_water:
            raise ResumptionInvariantError(
                f"client claims id {last_event_id} above flushed high-water "
                f"{self.log_high_water}: watermark is unverifiable"
            )
        if last_event_id < self.log_low_water:
            raise ResumptionInvariantError(
                f"client id {last_event_id} below replay low-water "
                f"{self.log_low_water}: evicted, must restart tool"
            )
        self.last_client_ack_id = last_event_id
        self.producer_paused = True
        try:
            for eid in range(last_event_id + 1, self.log_high_water + 1):
                await writer.write(self.replay_log[eid])
            # Flush the last replayed event BEFORE unpausing the producer,
            # otherwise producer can enqueue an id that races the replayed one.
            await writer.drain()
        finally:
            self.producer_paused = False


async def emit(session: SessionStream, payload: bytes, writer) -> int:
    if not session.producer_may_emit():
        raise ResumptionInvariantError(
            "producer gate closed: flush lag at window or replay in progress"
        )
    session.last_emitted_id += 1
    eid = session.last_emitted_id
    await writer.write(payload)
    await writer.drain()
    session.record_flush(eid, payload)
    return eid
