# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-session-across-an-sse-to-streamable-http-transport-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-session-across-an-sse-to-streamable-http-transport-migration.warrant.json
# Markdown SHA-256:   3f1512a07e968bc4ce4a5b861a5093c29351e95148059b00630fcb93b1ae414b
# Code AST SHA-256:   f03cdd0229243572a45887cb45c14acf27f0586e2e3e809e7d51bd97c0d8f16a
# Verified Classes:   SessionContinuityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionContinuityError(RuntimeError):
    """Raised when a resume appears to succeed at the transport layer but
    session continuity cannot be positively established."""
    pass


def resume_session(client, session_id, last_event_id, outstanding_ids):
    resp = client.post(
        "/mcp",
        headers={
            "Mcp-Session-Id": session_id,
            "Last-Event-ID": str(last_event_id),
        },
        json={"jsonrpc": "2.0", "id": client.next_id(), "method": "tools/list"},
    )

    if resp.status_code == 404:
        # Loud, recoverable: server does not know this session.
        client.reinitialize()
        return "reinitialized"

    if resp.status_code != 200:
        raise SessionContinuityError(
            f"unexpected resume status {resp.status_code}"
        )

    replayed = resp.json().get("events", [])
    caught_up = any(ev["id"] >= last_event_id for ev in replayed)

    # The dangerous case: 200, no replay, but we still believe requests are live.
    if not caught_up and outstanding_ids:
        # Do NOT trust the session. Probe for liveness of each outstanding id.
        live = client.probe_outstanding(outstanding_ids)
        missing = set(outstanding_ids) - live
        if missing:
            raise SessionContinuityError(
                "resume returned 200 but outstanding requests "
                f"{sorted(missing)} are not live on the resumed session; "
                "continuity unproven (likely session-ID adoption across "
                "transport migration). Fail non-retryably; do not re-issue "
                "non-idempotent tools/call without idempotency keys."
            )

    return "resumed"
