# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-resumable-mcp-sse-stream-whose-last-event-id-was-minted-under-a-different-origin-bound-session-token.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-resumable-mcp-sse-stream-whose-last-event-id-was-minted-under-a-different-origin-bound-session-token.warrant.json
# Markdown SHA-256:   295bbe5ee5a7e2739d93cfcfe37eb909310dbc5ec5fac7349585e60e3ee90dd3
# Code AST SHA-256:   57b8168e1d1bd5453a36d3d5b1c1b887c83a467d16412b674fc0d036caffbd6c
# Verified Classes:   CrossBindingReplayError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CrossBindingReplayError(RuntimeError):
    """Raised when a resumable MCP SSE replay presents a Last-Event-ID
    minted under a different (origin, session_genesis) binding than the
    presented token. Must be treated as a lineage break, not a retryable
    transport error."""


def admit_replay(token: dict, last_event_id: int, buffer: dict) -> dict:
    """
    token: {"origin": str, "genesis": str, "issued_at": float}
    buffer: {event_id: {"genesis": str, "origin": str, "payload": dict}}
    Returns the replay event on success. Raises on any binding mismatch.
    """
    event = buffer.get(last_event_id)
    if event is None:
        # Genuinely evicted: legitimate "resume fresh" path.
        raise KeyError(f"event {last_event_id} evicted; client must re-initialize")

    if event["genesis"] != token["genesis"] or event["origin"] != token["origin"]:
        # Event exists, token is valid, but they are not co-bound.
        # Do NOT 404 here -- that would let the client silently resume fresh
        # while believing it continued its lineage.
        raise CrossBindingReplayError(
            f"Last-Event-ID {last_event_id} minted under "
            f"(origin={event['origin']}, genesis={event['genesis']}) "
            f"but token bound to "
            f"(origin={token['origin']}, genesis={token['genesis']}); "
            f"forcing re-initialize"
        )

    return event


def resume_stream(token: dict, last_event_id: int, buffer: dict) -> dict:
    try:
        return admit_replay(token, last_event_id, buffer)
    except CrossBindingReplayError as exc:
        # Escalate as a hard lineage break; downstream must discard
        # in-flight tool-call state and re-plan from last checkpoint.
        raise CrossBindingReplayError(
            f"lineage break on resume: {exc}; discard in-flight state"
        ) from exc
