# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-state-after-mcp-streamable-http-resumption-across-a-session-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-state-after-mcp-streamable-http-resumption-across-a-session-migration.warrant.json
# Markdown SHA-256:   51cc634ae4eb428f492ac97bae8618756f9d6d0851ba832aafef1b5a50b0b3f9
# Code AST SHA-256:   c68b79e0e3a55aac205827e447984e9521e9b9c6b3436e7350498b1cd79c4822
# Verified Classes:   HollowSessionResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class HollowSessionResumeError(RuntimeError):
    """Raised when an MCP Streamable HTTP resume replays events but the
    session store on the resuming instance cannot satisfy the session
    version invariant. Signals that the caller must downgrade to
    session re-establishment, not silent continuation."""


def admit_resume(
    session_id: str,
    last_event_id: int,
    session_store: dict,   # session_id -> {"version": int, "protocol": str, ...}
    event_log_last_id: int,
) -> dict:
    """Gate a GET /mcp resume on the co-commitment invariant.

    Admissible iff:
      - the session exists on THIS instance, and
      - session_store[session_id]["version"] >= last_event_id, and
      - the event log actually holds the events the client claims to have seen.
    """
    if last_event_id > event_log_last_id:
        # Client claims events the server never durably recorded
        # (log truncation, cross-region failover, or a forged Last-Event-ID).
        raise HollowSessionResumeError(
            f"Last-Event-ID {last_event_id} exceeds durable log high-water "
            f"mark {event_log_last_id}; refusing to fabricate continuity."
        )

    session = session_store.get(session_id)
    if session is None:
        # The exact failure trace: event log has the events, session store
        # does not. Replaying here would mask a hollow session.
        raise HollowSessionResumeError(
            f"Session {session_id!r} absent on resuming instance; "
            f"event log holds ids up to {event_log_last_id} but session "
            f"state was not migrated. Downgrade to re-establishment."
        )

    if session["version"] < last_event_id:
        raise HollowSessionResumeError(
            f"Session {session_id!r} store version {session['version']} "
            f"trails replayed Last-Event-ID {last_event_id}; session state "
            f"is stale relative to the event log."
        )

    return session


def handle_get_resume(req) -> None:
    try:
        session = admit_resume(
            session_id=req.headers["Mcp-Session-Id"],
            last_event_id=int(req.headers["Last-Event-ID"]),
            session_store=req.app.state.session_store,
            event_log_last_id=req.app.state.event_log.last_id(),
        )
    except HollowSessionResumeError as exc:
        # Force the client back to initialize() rather than replaying
        # events under a session this instance cannot honor.
        req.respond(status=404, body={"error": "session_not_found", "detail": str(exc)})
        return

    if req.headers.get("MCP-Protocol-Version") != session["protocol"]:
        raise HollowSessionResumeError(
            f"Protocol skew on resume: client sent "
            f"{req.headers.get('MCP-Protocol-Version')!r}, session negotiated "
            f"{session['protocol']!r}."
        )

    req.stream.replay_from(req.headers["Last-Event-ID"])
