# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-without-replaying-the-backpressure-watermark.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-without-replaying-the-backpressure-watermark.warrant.json
# Markdown SHA-256:   cb8059ff2ec1e8a85e3a2ba02ddaa75d5fc853f8ad612969a93025ff3bb4d4f0
# Code AST SHA-256:   ae49369cd88ff3991255cbb05a3b538f6f8ffdfcc1e029d59651915c0de832ac
# Verified Classes:   ResumeCreditMismatch, SessionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumeCreditMismatch(RuntimeError):
    """Raised when a resumed MCP session presents credit inconsistent with the server ledger."""
    pass


class SessionLedger:
    """Server-side per-session flow-control ledger, anchored to session_id (not connection)."""

    def __init__(self, session_id: str, window: int):
        self.session_id = session_id
        self.window = window
        self.outstanding = 0          # events sent but not acked by client
        self.last_emitted_id = 0
        self.backlog = []             # events enqueued while client not draining

    def emit(self, event_id: int, payload: dict) -> None:
        if self.outstanding >= self.window:
            self.backlog.append((event_id, payload))
            return
        self.outstanding += 1
        self.last_emitted_id = event_id
        # ... write to wire ...


def resume_session(
    ledger: SessionLedger,
    presented_last_event_id: int,
    presented_remaining_credit: int,
) -> list[tuple[int, dict]]:
    """
    Reconcile a resume handshake against the session ledger.

    Invariant: presented_remaining_credit must equal window - outstanding.
    A client that presents its full window (rather than remaining credit)
    is signaling it forgot the outstanding debt; replaying into it would
    exceed the flow-control bound.
    """
    expected_remaining = ledger.window - ledger.outstanding

    if presented_remaining_credit > expected_remaining:
        # Client reset its window on reconnect. Replaying backlog now would
        # push delivered-events-past-credit above the invariant.
        raise ResumeCreditMismatch(
            f"session {ledger.session_id}: client presented credit "
            f"{presented_remaining_credit}, ledger expects {expected_remaining} "
            f"(window={ledger.window}, outstanding={ledger.outstanding}). "
            f"Client must drain-then-resume or present remaining credit."
        )

    if presented_last_event_id > ledger.last_emitted_id:
        raise ResumeCreditMismatch(
            f"session {ledger.session_id}: client claims last_event_id "
            f"{presented_last_event_id} > server last_emitted_id "
            f"{ledger.last_emitted_id}; client is ahead of the log."
        )

    # Safe to replay: client's credit accounts for outstanding debt, and its
    # last-applied ID is within the log. Replay only events after last_applied,
    # and only up to the client's remaining credit.
    replay = [e for e in ledger.backlog if e[0] > presented_last_event_id]
    if len(replay) > presented_remaining_credit:
        # Cannot replay the full backlog without exceeding credit; truncate
        # and force the client to checkpoint instead.
        raise ResumeCreditMismatch(
            f"session {ledger.session_id}: backlog {len(replay)} exceeds "
            f"remaining credit {presented_remaining_credit}; "
            f"client must resume from checkpoint, not replay."
        )
    return replay
