# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-the-mcp-streamable-http-transport-silently-lose-events-across-a-session-resumption-when-the-sse-upgrade-is-negotiated-on-a-pos.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-the-mcp-streamable-http-transport-silently-lose-events-across-a-session-resumption-when-the-sse-upgrade-is-negotiated-on-a-pos.warrant.json
# Markdown SHA-256:   bb0b6afc7493a70650c6b35851eaa026f63e7c9370cfbb0c03fd5cb8e4ab30b6
# Code AST SHA-256:   80c364d0625e150eff64d82f4b64360b34d69c419efce27cf4967c7d318eaad8
# Verified Classes:   ResumptionCursorConsumedError, SessionReplayState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class ResumptionCursorConsumedError(RuntimeError):
    """Raised when a 202 Accepted response has advanced the session replay
    watermark, violating the invariant that a non-streaming response must
    not consume the client's Last-Event-ID cursor."""


@dataclass
class SessionReplayState:
    session_id: str
    last_delivered_event_id: int
    # Events written to the log but not yet confirmed delivered on a stream.
    pending: dict[int, str] = field(default_factory=dict)

    def advance_on_stream_commit(self, event_id: int) -> None:
        # Legal: only called once a 200 + text/event-stream body is committed.
        if event_id <= self.last_delivered_event_id:
            raise ResumptionCursorConsumedError(
                f"event {event_id} <= watermark {self.last_delivered_event_id}"
            )
        self.last_delivered_event_id = event_id
        self.pending.pop(event_id, None)


def decide_response(
    state: SessionReplayState,
    client_last_event_id: int | None,
    will_stream_inline: bool,
) -> str:
    """Return '200-stream' or '202-accepted' and enforce the invariant.

    A 202 must not touch state.last_delivered_event_id. If the caller has
    already advanced the watermark before this decision, we detect and raise.
    """
    if client_last_event_id is not None and not will_stream_inline:
        # We are about to return 202. The cursor must be untouched.
        if state.last_delivered_event_id != client_last_event_id:
            raise ResumptionCursorConsumedError(
                "202 path would consume Last-Event-ID: "
                f"client={client_last_event_id} "
                f"server_watermark={state.last_delivered_event_id} "
                f"session={state.session_id}"
            )
        return "202-accepted"

    if will_stream_inline:
        # Commit to a stream, then (and only then) advance the watermark.
        if client_last_event_id is not None:
            for eid in sorted(state.pending):
                if eid > client_last_event_id:
                    state.advance_on_stream_commit(eid)
        return "200-stream"

    return "202-accepted"


# --- Correct usage ---------------------------------------------------------
state = SessionReplayState(session_id="7f3c", last_delivered_event_id=412)
state.pending = {413: "progress", 414: "progress", 419: "cancelled"}

# Slow tool -> 202. Cursor stays at 412; client must re-present it on GET.
assert decide_response(state, 412, will_stream_inline=False) == "202-accepted"
assert state.last_delivered_event_id == 412  # invariant held

# --- Violation detection ---------------------------------------------------
# A buggy worker advanced the watermark before deciding to return 202:
state.last_delivered_event_id = 419
try:
    decide_response(state, 412, will_stream_inline=False)
except ResumptionCursorConsumedError as exc:
    # This is the silent-gap bug surfacing loudly at the boundary.
    print(f"detected: {exc}")
