# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-stream-offsets-when-an-mcp-http-native-session-resumes-after-a-backpressure-induced-partial-frame.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-stream-offsets-when-an-mcp-http-native-session-resumes-after-a-backpressure-induced-partial-frame.warrant.json
# Markdown SHA-256:   c0dae820385ddef47e2cb10498debfbf7d15a2b6797d308926247bd11bd8df9c
# Code AST SHA-256:   c72eebb5c7f76a82bfde2cc3ad9738b17597d5ba24325c74e543cf339b55ac04
# Verified Classes:   StreamResumptionFrameError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StreamResumptionFrameError(RuntimeError):
    """Raised when a resumed MCP stream would concatenate replayed bytes onto a stale partial frame."""
    pass


def resume_stream(last_ack_event_id: int, partial_buffer: bytes, replayed_event_id: int) -> int:
    """
    Decide whether to resume from a replayed event or reject the resumption.

    Invariant: a partial (unterminated) frame must never be appended to a replayed
    event payload. If the acknowledged offset is behind the replayed event and we
    still hold unterminated bytes for that event, the resumption is unsafe.
    """
    has_partial = len(partial_buffer) > 0 and not partial_buffer.endswith(b"\n\n")

    if has_partial and replayed_event_id <= last_ack_event_id + 1:
        # We hold a fragment for the very event the server is about to replay.
        # Appending would corrupt the JSON-RPC frame.
        raise StreamResumptionFrameError(
            f"unsafe resumption: partial buffer ({len(partial_buffer)} bytes) for event "
            f"{replayed_event_id} conflicts with Last-Event-ID {last_ack_event_id}; "
            f"flush buffer and re-request from {last_ack_event_id}"
        )

    # Safe: either no partial buffer, or the replayed event is strictly beyond
    # the fragment we hold, so no byte overlap occurs.
    return replayed_event_id
