# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-streamable-mcp-session-was-silently-downgraded-to-sse-fallback-mid-resumption-and-its-event-id-cursor-no-longer-map.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-streamable-mcp-session-was-silently-downgraded-to-sse-fallback-mid-resumption-and-its-event-id-cursor-no-longer-map.warrant.json
# Markdown SHA-256:   6f7f3eea9a67466f52fbb22b5bbb2876cb5cac3931ad2004605184b9a39cb4a2
# Code AST SHA-256:   0f4adfd17c69e2fc3bc0f62b892e9f00f0e404bbdc6e811cbbb37a3148c86984
# Verified Classes:   SilentSessionDowngrade
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SilentSessionDowngrade(RuntimeError):
    """Raised when a resume response passes HTTP but fails the continuity predicate."""
    pass


def validate_resume(
    request_session_id: str,
    request_framing: str,
    request_last_event_id: int,
    response: dict,
) -> str:
    """
    Enforce the resume continuity invariant. Returns 'resumed' | 'resync' | 'cold_start'.
    Raises SilentSessionDowngrade when the response is structurally ambiguous and
    the caller has not opted into degraded-mode handling.
    """
    resp_session = response.get("session_id")
    resp_framing = response.get("framing")
    resp_first_event = response.get("first_event_id")

    if resp_session is None or resp_framing is None:
        # Missing echo fields: the server did not honor the resume contract.
        raise SilentSessionDowngrade(
            f"Resume response missing session_id/framing echo "
            f"(session={resp_session!r}, framing={resp_framing!r}); "
            f"cannot distinguish downgrade from truncation."
        )

    if resp_session != request_session_id or resp_framing != request_framing:
        # Session re-keyed or transport negotiated down. Prior state is orphaned.
        return "cold_start"

    if resp_first_event is None:
        raise SilentSessionDowngrade(
            "Server echoed session but omitted first_event_id; "
            "cursor continuity is unverifiable."
        )

    if resp_first_event != request_last_event_id + 1:
        # Same session, same framing, but replay buffer gap.
        return "resync"

    return "resumed"


def handle_resume(request: dict, response: dict) -> str:
    outcome = validate_resume(
        request_session_id=request["session_id"],
        request_framing=request["framing"],
        request_last_event_id=request["last_event_id"],
        response=response,
    )
    if outcome == "cold_start":
        # Discard cursor, re-fetch all resources, re-validate in-flight assumptions.
        request["last_event_id"] = None
    elif outcome == "resync":
        request["needs_snapshot"] = True
    return outcome
