# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-replay-cursors-when-an-mcp-streamable-http-session-resumes-against-a-load-balanced-replica-that-never-saw-the-ori.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-replay-cursors-when-an-mcp-streamable-http-session-resumes-against-a-load-balanced-replica-that-never-saw-the-ori.warrant.json
# Markdown SHA-256:   8a4204432c0e8e947c8b18a47205517dd607fdcf072cd2cc75bfcff7b6dbbdc4
# Code AST SHA-256:   465da3c877ad883d667863525ab14a54fe5d6a11c0abe00e3ef5880922eb5a47
# Verified Classes:   UnresolvableResumeCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnresolvableResumeCursor(RuntimeError):
    """Raised when a Last-Event-ID cannot be honored by this replica.

    Signals that the client must resynchronize from a known boundary
    (fresh stream / state snapshot) rather than resume from an offset
    that does not resolve in the shared, durable event log.
    """
    pass


def resume_stream(session_id: str, last_event_id: int | None,
                  shared_log, session_store) -> "EventStream":
    # 1. Session must exist and be valid for this replica's view of the store.
    session = session_store.get(session_id)
    if session is None:
        raise UnresolvableResumeCursor(
            f"session {session_id!r} not found in shared store; "
            f"client must re-establish, not resume"
        )

    # 2. No cursor: fresh stream is always safe.
    if last_event_id is None:
        return shared_log.open_stream(session_id, after=None)

    # 3. Cursor must resolve in the SAME durable, session-scoped log.
    #    Presence in the session record is NOT sufficient (the debounce bug).
    resolved = shared_log.lookup(session_id, last_event_id)
    if resolved is None:
        # Cursor minted by a replica whose events never reached the log,
        # or from a disjoint per-process namespace. Refuse, do not restart.
        raise UnresolvableResumeCursor(
            f"Last-Event-ID {last_event_id} for session {session_id!r} "
            f"does not resolve in the shared event log; "
            f"refusing silent restart (would drop events and poison watermark)"
        )

    # 4. Namespace identity: the log that minted the cursor must be the
    #    log that services the resume. A per-replica counter violates this.
    if resolved.namespace != shared_log.namespace:
        raise UnresolvableResumeCursor(
            f"Last-Event-ID {last_event_id} belongs to namespace "
            f"{resolved.namespace!r}, serviced by {shared_log.namespace!r}; "
            f"cross-replica cursor collision"
        )

    # 5. Durability-before-emission invariant: the log must contain the
    #    cursor, which it does by step 3. Honor the resume.
    return shared_log.open_stream(session_id, after=last_event_id)
