# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-sse-resumption-as-unsafe-after-a-session-id-reissue-and-how-to-bound-the-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-sse-resumption-as-unsafe-after-a-session-id-reissue-and-how-to-bound-the-failure.warrant.json
# Markdown SHA-256:   7301ea13eb53f85985c8fe8e8120cfdb4cbc192b92e325087933966e0c0afdc2
# Code AST SHA-256:   e35cb9cb40b3cf53709ca555428b06ca8edabbc7f637934fba887172a3a2911b
# Verified Classes:   UnsafeResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnsafeResumeError(RuntimeError):
    """Raised when an SSE resumption cannot be bound to the originating session."""
    pass


def resume_stream(request_session_id: str, last_event_id: str | None,
                  response_status: int, response_session_id: str | None,
                  event_id_is_session_scoped: bool) -> str:
    """
    Decide whether an MCP streamable-HTTP resumption is safe to merge.
    Returns the session ID to continue under, or raises UnsafeResumeError.
    """
    if response_status != 200:
        # Terminal / retryable status: caller re-initializes. Not our failure.
        raise UnsafeResumeError(
            f"resumption returned {response_status}; must re-initialize, not merge"
        )

    if response_session_id is None:
        raise UnsafeResumeError(
            "server did not echo Mcp-Session-Id on resumption; resume is indeterminate"
        )

    if response_session_id != request_session_id:
        # The silent-rebind case: 200 OK but a different logical session.
        raise UnsafeResumeError(
            f"session identity break: sent {request_session_id!r}, "
            f"server bound {response_session_id!r}; discarding all frames"
        )

    if last_event_id is not None and not event_id_is_session_scoped:
        # Bare-integer cursor cannot be proven to belong to this namespace.
        raise UnsafeResumeError(
            f"cursor {last_event_id!r} is not session-scoped; "
            "refusing Last-Event-ID replay, re-issue call idempotently"
        )

    return response_session_id
