# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-poisoned-continuation-rather-than-a-legitimate-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-poisoned-continuation-rather-than-a-legitimate-replay.warrant.json
# Markdown SHA-256:   ce7f1037038605ba962c9fe602d95567a18086d5eda919b471b48c45ba18213d
# Code AST SHA-256:   8d11b599e967d7841b4456287c6924d33c8775a78795c8509cd15c1e8c0d1278
# Verified Classes:   PoisonedContinuationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PoisonedContinuationError(RuntimeError):
    """Raised when an MCP Streamable HTTP resumption cannot be proven
    to continue the same logical exchange as the client's cursor."""


def resume_stream(
    session_id: str,
    cursor: str | None,
    cursor_transport: str,
    server_transport: str,
    first_frame_event_id: str | None,
    consumed_event_id: str | None,
    id_ordering: callable,
) -> str:
    """Decide whether to resume or re-initialize an MCP SSE stream.

    Returns "resume" or "reinitialize". Raises PoisonedContinuationError
    when the server accepted the cursor but the stream cannot be proven
    to continue the same exchange.
    """
    if cursor is None:
        return "reinitialize"

    # Cross-transport cursor: legacy SSE cursor applied to Streamable HTTP.
    if cursor_transport != server_transport:
        raise PoisonedContinuationError(
            f"cursor {cursor!r} minted on transport {cursor_transport!r} "
            f"cannot resume transport {server_transport!r} for session {session_id!r}"
        )

    if first_frame_event_id is None:
        # Server accepted the cursor but emitted nothing; cannot prove continuity.
        raise PoisonedContinuationError(
            f"empty stream after resumption for session {session_id!r}; "
            f"cursor {cursor!r} unproven"
        )

    if consumed_event_id is not None and not id_ordering(
        first_frame_event_id, consumed_event_id
    ):
        # First frame is not strictly past what we already consumed:
        # event-ID namespace reset (worker migration) or silent truncation.
        raise PoisonedContinuationError(
            f"non-monotonic resumption for session {session_id!r}: "
            f"first frame {first_frame_event_id!r} <= consumed {consumed_event_id!r}"
        )

    return "resume"


def guarded_reconnect(session_id: str, **kwargs) -> str:
    try:
        return resume_stream(session_id=session_id, **kwargs)
    except PoisonedContinuationError:
        # Downgrade to a fresh exchange; never splice streams.
        return "reinitialize"
