# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-resumable-mcp-streamable-session-has-silently-lost-backpressure-credit-after-a-transport-level-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-resumable-mcp-streamable-session-has-silently-lost-backpressure-credit-after-a-transport-level-reconnect.warrant.json
# Markdown SHA-256:   6a47d08351e4092620920925ce2ae2de2ab5f801e039c9a067e9633e68c1932f
# Code AST SHA-256:   954bcef93dff05b6a5a85c2bf29302f4ddee663213034eebaeed8ce9b5e1eed1
# Verified Classes:   ResumeCreditViolation, ResumeState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class ResumeCreditViolation(RuntimeError):
    """Raised when a streamable-session resume would exceed client drain capacity
    because unacked pre-disconnect bytes were not subtracted from granted credit."""


@dataclass
class ResumeState:
    last_acked_before_disconnect: int   # byte offset the client had acked pre-drop
    last_processed: int                 # byte offset the client has fully processed
    server_head: int                    # byte offset the server will replay up to
    client_read_buffer_free: int        # bytes free in client read buffer now
    client_processing_rate_bps: float   # sustained drain rate
    replay_deadline_s: float            # time the client will allow for replay
    granted_credit_bytes: int           # credit the client is about to send


def audit_resume_credit(s: ResumeState, safety_factor: float = 0.8) -> int:
    """Return the safe credit to grant on resume, or raise if the replay cannot fit.

    Invariant: granted_credit must be <= available capacity minus unacked
    pre-disconnect bytes, and the replayed range must fit the resulting window.
    """
    unacked_pre_disconnect = max(0, s.last_processed - s.last_acked_before_disconnect)
    replay_bytes = max(0, s.server_head - s.last_processed)

    drain_capacity = (
        s.client_read_buffer_free
        + s.client_processing_rate_bps * s.replay_deadline_s
    ) * safety_factor

    # Capacity available for *new* credit after honoring the unacked tail.
    effective_capacity = drain_capacity - unacked_pre_disconnect

    if effective_capacity <= 0:
        raise ResumeCreditViolation(
            f"unacked_pre_disconnect={unacked_pre_disconnect}B exceeds "
            f"drain_capacity={drain_capacity:.0f}B; cannot grant any credit safely"
        )

    if replay_bytes > effective_capacity:
        raise ResumeCreditViolation(
            f"replay_bytes={replay_bytes}B exceeds effective_capacity="
            f"{effective_capacity:.0f}B (unacked={unacked_pre_disconnect}B, "
            f"drain={drain_capacity:.0f}B); server must replay in chunks or "
            f"session must be abandoned"
        )

    safe_credit = int(min(s.granted_credit_bytes, effective_capacity - replay_bytes))
    if safe_credit <= 0:
        raise ResumeCreditViolation(
            "no safe credit remains after reserving replay window; "
            "reduce granted_credit or abandon session"
        )
    return safe_credit


def resume_session(s: ResumeState) -> int:
    try:
        return audit_resume_credit(s)
    except ResumeCreditViolation:
        # Caller must either request chunked replay or abandon the session.
        # Re-raising preserves the distinction from a clean reconnect.
        raise
