# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-resumable-stream-replay-when-an-mcp-server-s-backpressure-window-has-silently-collapsed.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-resumable-stream-replay-when-an-mcp-server-s-backpressure-window-has-silently-collapsed.warrant.json
# Markdown SHA-256:   f337865602a8b30a30ace26ebd40f2563b7713b78ffab3b3d55c62f2dc30aba5
# Code AST SHA-256:   bcd455921d0e577cf5dabea2f62ef2d9e29e7f075fd215e7dee174fe00ab4793
# Verified Classes:   DrainedSnapshotError, ResumeProbe
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DrainedSnapshotError(RuntimeError):
    """Raised when a resumed MCP stream drains its replay buffer and then goes silent,
    indicating the producer was never re-attached to the new writer."""


@dataclass
class ResumeProbe:
    t_drain: float = 0.4   # quiet period implying replay caught up
    t_live: float = 5.0    # max wait for a live frame after drain


def await_post_drain_liveness(
    stream,
    probe: ResumeProbe,
    clock=time.monotonic,
) -> None:
    """Consume a resumed stream until either a live frame arrives after drain,
    or the drain-then-silence signature is confirmed."""
    last_event_at = clock()
    drained = False

    while True:
        now = clock()
        frame = stream.poll(timeout=0.05)

        if frame is not None:
            last_event_at = now
            drained = False
            if frame.kind in ("event", "heartbeat", "end"):
                # A heartbeat or new event after drain proves a live producer.
                if frame.kind != "event" or frame.is_live:
                    return
            continue

        # No frame this poll.
        if not drained and (now - last_event_at) >= probe.t_drain:
            drained = True
            drain_deadline = now + probe.t_live
            continue

        if drained and now >= drain_deadline:
            raise DrainedSnapshotError(
                "resumed stream drained replay buffer with no live producer; "
                "abandon resumption and re-establish a fresh session"
            )
