# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-multiplexed-mcp-stream-starvation-when-http-2-flow-control-windows-and-agent-backpressure-budgets-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-multiplexed-mcp-stream-starvation-when-http-2-flow-control-windows-and-agent-backpressure-budgets-disagree.warrant.json
# Markdown SHA-256:   3de4619b5e15e33f7c48d3a4bd526d0eedb16f358c629bc7f52b7c2e58bb506f
# Code AST SHA-256:   489e32d59994ee80f431533296dc1ec5a356130dc560893868a4a1a4adc2a241
# Verified Classes:   MultiplexedStreamStarvation, StreamState, ConnectionState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class MultiplexedStreamStarvation(RuntimeError):
    """Raised when a stream's advertised window has been zero past the watchdog threshold
    while the connection is otherwise healthy — i.e., the agent, not the peer, is starving it."""


@dataclass
class StreamState:
    stream_id: int
    advertised_window: int
    last_window_update_ts: float
    agent_budget_remaining: int
    priority: int
    reset: bool = False


@dataclass
class ConnectionState:
    last_ping_ack_ts: float
    goaway_received: bool = False
    rtt_seconds: float = 0.05
    keepalive_interval: float = 5.0


def watchdog_threshold(conn: ConnectionState) -> float:
    return max(3.0 * conn.rtt_seconds, 2.0 * conn.keepalive_interval)


def connection_healthy(conn: ConnectionState, now: float) -> bool:
    if conn.goaway_received:
        return False
    return (now - conn.last_ping_ack_ts) <= 2.0 * conn.keepalive_interval


def detect_and_release(
    stream: StreamState,
    conn: ConnectionState,
    donor_streams: list[StreamState],
    now: float | None = None,
    release_attempt_seconds: float = 1.0,
) -> None:
    """Detect self-starvation on `stream` and either release budget from donors or
    reset the stream with a distinguishable error code. Raises on unrecoverable state."""
    now = now if now is not None else time.monotonic()

    if stream.reset:
        return

    if stream.advertised_window > 0:
        return

    if not connection_healthy(conn, now):
        # Peer-dead or GOAWAY: this is not self-starvation, do not misattribute.
        return

    stalled_for = now - stream.last_window_update_ts
    if stalled_for <= watchdog_threshold(conn):
        return

    # Attempt budget release from lower-priority donors.
    needed = max(stream.agent_budget_remaining, 1) - stream.agent_budget_remaining
    needed = max(needed, 1)
    reclaimed = 0
    for donor in sorted(donor_streams, key=lambda s: s.priority):
        if donor.stream_id == stream.stream_id or donor.reset:
            continue
        if donor.priority >= stream.priority:
            continue
        take = min(donor.agent_budget_remaining, needed - reclaimed)
        donor.agent_budget_remaining -= take
        reclaimed += take
        if reclaimed >= needed:
            break

    if reclaimed >= needed:
        stream.agent_budget_remaining += reclaimed
        # Consumer resumes; caller is responsible for emitting WINDOW_UPDATE / MAX_STREAM_DATA.
        stream.last_window_update_ts = now
        return

    # Cannot release budget: reset with a distinguishable code so transport and agent logs agree.
    if stalled_for > watchdog_threshold(conn) + release_attempt_seconds:
        stream.reset = True
        raise MultiplexedStreamStarvation(
            f"stream {stream.stream_id} self-starved for {stalled_for:.2f}s "
            f"(threshold {watchdog_threshold(conn):.2f}s); resetting with "
            f"agent_backpressure_cancel instead of client_cancel"
        )

    # Within release window but insufficient budget: surface for caller to escalate.
    raise MultiplexedStreamStarvation(
        f"stream {stream.stream_id} window-zero for {stalled_for:.2f}s; "
        f"reclaimed {reclaimed} of {needed} required budget units"
    )
