# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-stream-notifications-progress-as-a-backpressure-signal-rather-than-a-liveness-heartbeat.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-stream-notifications-progress-as-a-backpressure-signal-rather-than-a-liveness-heartbeat.warrant.json
# Markdown SHA-256:   94cfdf091d3ebc72a98b96d368f2d8797ef9dc14cc6d467e2f2839d742aa31ca
# Code AST SHA-256:   134cb341854ac4ef466daa6c9a97d0eb864348e008e2b266b6c8135924619b74
# Verified Classes:   ProgressBackpressureViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProgressBackpressureViolation(RuntimeError):
    """Raised when progress notifications exceed the client's retained-bytes budget
    without the server having declared a bound, indicating the heartbeat
    interpretation is no longer valid for this call."""
    pass


MAX_RETAINED_BYTES = 4096


def consume_progress(notification: dict, state: dict) -> None:
    """Handle one notifications/progress message.

    state keys: retained (bytearray), discarded (int), declared_bound (int|None),
    token (str), call_id (str).
    """
    if notification.get("progressToken") != state["token"]:
        return  # not ours; do not touch watchdog or buffer

    msg = notification.get("message")
    if msg is None:
        state["last_heartbeat"] = notification.get("progress", 0)
        return

    payload = msg.encode("utf-8", errors="replace")
    bound = state.get("declared_bound")

    if bound is None and len(payload) > MAX_RETAINED_BYTES:
        # Server sent unbounded data on a channel we negotiated as liveness-only.
        # We cannot safely retain it and cannot trust the terminal result to be
        # mergeable. Fail the call explicitly rather than corrupt downstream.
        raise ProgressBackpressureViolation(
            f"call {state['call_id']}: progress message of {len(payload)} bytes "
            f"exceeds client cap {MAX_RETAINED_BYTES} with no declared server bound; "
            f"heartbeat interpretation invalid, refusing to retain"
        )

    if bound is not None and len(payload) > bound:
        raise ProgressBackpressureViolation(
            f"call {state['call_id']}: progress message of {len(payload)} bytes "
            f"exceeds negotiated bound {bound}; server violated capability contract"
        )

    retained = state["retained"]
    retained.extend(payload)
    overflow = len(retained) - MAX_RETAINED_BYTES
    if overflow > 0:
        del retained[:overflow]
        state["discarded"] += overflow
    state["last_heartbeat"] = notification.get("progress", 0)
