# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-mcp-resumable-sse-to-streamable-http-upgrade-after-a-mid-stream-last-event-id-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-mcp-resumable-sse-to-streamable-http-upgrade-after-a-mid-stream-last-event-id-replay.warrant.json
# Markdown SHA-256:   02be08af15797475858bf75cfbc736d15690b4bf2bf95e632efb33c688c6b2da
# Code AST SHA-256:   389deb5f524424137b3cd394170163fdb27b53370d70cdacda6e26e4a1f493b0
# Verified Classes:   UnprovableReplayError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnprovableReplayError(RuntimeError):
    """Raised when a Last-Event-ID cannot be proven to belong to the
    session's event-ID domain; replay would be a forged continuity."""
    pass


def negotiate_upgrade(
    session,
    last_event_id: str | None,
) -> "ReplayDecision":
    if last_event_id is None:
        return ReplayDecision.fresh(session)

    # Domain binding: ID must carry the generation that issued it.
    id_generation = session.parse_generation(last_event_id)
    if id_generation is None:
        raise UnprovableReplayError(
            f"Last-Event-ID {last_event_id!r} has no generation tag; "
            f"cannot bind to session {session.id!r}"
        )

    if id_generation == session.generation and session.covers(last_event_id):
        return ReplayDecision.replay_from(last_event_id)

    # Re-rooted ID space: only valid with a recorded migration watermark.
    watermark = session.migration_watermark_for(id_generation)
    if watermark is not None and watermark.covers(last_event_id):
        return ReplayDecision.replay_from(watermark.map(last_event_id))

    # No proof of membership. Refuse rather than fall through to
    # replay-from-zero, which would silently drop the migration window.
    raise UnprovableReplayError(
        f"Last-Event-ID {last_event_id!r} (gen {id_generation}) is not "
        f"provably in session {session.id!r} (gen {session.generation}); "
        f"no migration watermark. Rejecting upgrade; client must reinitialize."
    )
