# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-negotiate-a-streaming-capability-but-then-deadlock-on-flow-control.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-negotiate-a-streaming-capability-but-then-deadlock-on-flow-control.warrant.json
# Markdown SHA-256:   a92c388cf5c8d51fe4cdb46520a1b7654166df19d7551d656ada2863ca9e9dd0
# Code AST SHA-256:   2939c307128d7c57085d2e3bf99c1f5ccc864f9f54e94ab27d256d55aba328e2
# Verified Classes:   BackpressureContractError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class BackpressureContractError(RuntimeError):
    """Raised when a streaming session is opened without a bounded flow-control window."""
    pass


DEFAULT_MAX_INFLIGHT_BYTES = 256 * 1024


def open_stream_session(negotiated: dict) -> dict:
    """
    Validate that a negotiated MCP session has an explicit backpressure contract
    before permitting streaming. `negotiated` is the parsed initialize result
    augmented with any transport-extension fields.
    """
    caps = negotiated.get("capabilities", {})
    if not caps.get("streaming", False):
        # Non-streaming is always safe: caller buffers and returns a bounded body.
        return {"mode": "buffered", "max_inflight_bytes": 0}

    window = negotiated.get("streaming", {}).get("max_inflight_bytes")
    if window is None:
        # Capability bit set, but no flow-control contract: do NOT trust it.
        raise BackpressureContractError(
            "server advertised streaming=true but no streaming.max_inflight_bytes "
            "was negotiated; refusing to open an unbounded stream "
            "(would deadlock on a slow or pausing client)"
        )

    if not isinstance(window, int) or window <= 0:
        raise BackpressureContractError(
            f"invalid streaming.max_inflight_bytes={window!r}; must be a positive int"
        )

    if window > DEFAULT_MAX_INFLIGHT_BYTES:
        # Clamp to the transport-safe ceiling rather than honoring an oversized claim.
        window = DEFAULT_MAX_INFLIGHT_BYTES

    return {"mode": "streaming", "max_inflight_bytes": window}


def write_chunk(session: dict, payload: bytes, inflight: int) -> int:
    """Write one chunk, enforcing the negotiated window; returns new inflight count."""
    if session["mode"] != "streaming":
        raise BackpressureContractError("write_chunk called on a buffered session")
    limit = session["max_inflight_bytes"]
    if inflight + len(payload) > limit:
        raise BackpressureContractError(
            f"chunk of {len(payload)}B would exceed negotiated window "
            f"({inflight}+{len(payload)} > {limit}); await drain before writing"
        )
    return inflight + len(payload)
