# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-transport-backpressure-has-inverted-into-agent-side-state-corruption-during-long-running-streaming-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-transport-backpressure-has-inverted-into-agent-side-state-corruption-during-long-running-streaming-tool-calls.warrant.json
# Markdown SHA-256:   a7dbd0f4d390a9c0fd3b9d0bee499196a34125b27b3009c39c54d601001f19b8
# Code AST SHA-256:   a8a68bf744d6c4f2b8fdea815599ae1610ead3a57845f7ce6d1fa246dd4e4ceb
# Verified Classes:   StreamBackpressureInversion, TokenState, StreamGuard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field


class StreamBackpressureInversion(RuntimeError):
    """Raised when transport congestion has inverted into agent-side state corruption."""


@dataclass
class TokenState:
    token: str
    generation: int
    last_progress: float = -1.0
    terminal: bool = False
    cancel_issued_at: float | None = None


@dataclass
class StreamGuard:
    """Enforces the single-live-token and monotonic-progress invariants."""

    flush_window_s: float = 2.0
    live: dict[str, TokenState] = field(default_factory=dict)
    committed: dict[int, float] = field(default_factory=dict)

    def open_token(self, token: str, generation: int) -> TokenState:
        for other in self.live.values():
            if not other.terminal:
                raise StreamBackpressureInversion(
                    f"refusing token {token!r}: token {other.token!r} "
                    f"(gen {other.generation}) still live on transport; "
                    f"cancel-ack not observed, stream is poisoned"
                )
        st = TokenState(token=token, generation=generation)
        self.live[token] = st
        return st

    def on_progress(self, token: str, value: float, now: float | None = None) -> float:
        now = now if now is not None else time.monotonic()
        st = self.live.get(token)
        if st is None:
            raise StreamBackpressureInversion(
                f"progress for unknown token {token!r}: stale emission after close"
            )
        if st.terminal:
            raise StreamBackpressureInversion(
                f"token {token!r} emitted progress after terminal response"
            )
        if value <= st.last_progress:
            raise StreamBackpressureInversion(
                f"non-monotonic progress on token {token!r}: "
                f"{value} <= {st.last_progress}; ordering guarantee lost"
            )
        if st.cancel_issued_at is not None and now - st.cancel_issued_at > self.flush_window_s:
            raise StreamBackpressureInversion(
                f"cancel on token {token!r} unacked past flush window; "
                f"server write buffer likely saturated and stalling inbound servicing"
            )
        st.last_progress = value
        return value

    def checkpoint(self, token: str, value: float) -> tuple[int, float]:
        st = self.live[token]
        prior = self.committed.get(st.generation, -1.0)
        if value <= prior:
            raise StreamBackpressureInversion(
                f"checkpoint regression: gen {st.generation} value {value} "
                f"<= committed {prior}; refusing to poison resume point"
            )
        self.committed[st.generation] = value
        return st.generation, value

    def detect_dispatcher_starvation(
        self, bytes_advanced: bool, last_dispatch_at: float, now: float | None = None
    ) -> None:
        now = now if now is not None else time.monotonic()
        if bytes_advanced and (now - last_dispatch_at) > self.flush_window_s:
            raise StreamBackpressureInversion(
                "transport draining but dispatcher starved: read loop and "
                "agent loop have decoupled; treat checkpoint as untrusted"
            )

    def close_token(self, token: str, terminal: bool = True) -> None:
        st = self.live.get(token)
        if st is not None:
            st.terminal = terminal
