# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-mcp-session-after-the-server-has-silently-rotated-its-sse-event-id-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-mcp-session-after-the-server-has-silently-rotated-its-sse-event-id-epoch.warrant.json
# Markdown SHA-256:   1467e4eb0425effb03b2646fb1c460d18c13e2da60cf3a27f9e670457b209154
# Code AST SHA-256:   0bfb08f522b87fa5c22a18bf9f866f13914cec71f0b95c0050661e65787fccef
# Verified Classes:   StaleEpochResumptionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleEpochResumptionError(RuntimeError):
    """Raised when a streamable-session resumption returns silence that cannot
    be proven to mean 'caught up' rather than 'cursor belongs to a dead epoch'."""


def resume_streamable_session(
    last_event_id: str,
    last_seen_generation: str | None,
    server_response: dict,
) -> dict:
    """
    server_response is the parsed result of the SSE resumption handshake:
      {
        "status": 200,
        "replayed_events": [...],
        "server_generation": "gen-7" | None,
      }
    """
    replayed = server_response.get("replayed_events", [])
    server_gen = server_response.get("server_generation")

    # Case 1: events were replayed -> real continuity, but verify epoch anyway.
    if replayed:
        if last_seen_generation is not None and server_gen is not None:
            if server_gen != last_seen_generation:
                # Replayed events come from a different epoch than our cursor.
                # They may be a fresh stream, not a continuation.
                raise StaleEpochResumptionError(
                    f"replayed events under generation {server_gen!r} but client "
                    f"cursor was from {last_seen_generation!r}; replay is not a "
                    f"valid continuation of the prior stream"
                )
        return {"events": replayed, "continuity": "verified"}

    # Case 2: zero replayed events. This is the dangerous boundary.
    if last_seen_generation is None or server_gen is None:
        # No epoch discriminator -> cannot prove caught-up. Must resync.
        raise StaleEpochResumptionError(
            f"empty resumption for Last-Event-ID={last_event_id!r} with no epoch "
            f"token; cannot distinguish caught-up from lost-epoch. "
            f"Authoritative re-sync required before continuing."
        )

    if server_gen != last_seen_generation:
        # Explicit epoch mismatch: the server restarted its ID namespace.
        raise StaleEpochResumptionError(
            f"epoch mismatch on resume: cursor {last_event_id!r} from "
            f"{last_seen_generation!r}, server now at {server_gen!r}; "
            f"events between epochs are unreachable, re-sync required."
        )

    # Same epoch, zero replay -> genuinely caught up. Safe to continue.
    return {"events": [], "continuity": "caught_up"}


def continue_agent_loop(state: dict, resumption: dict) -> dict:
    try:
        result = resume_streamable_session(
            last_event_id=state["last_event_id"],
            last_seen_generation=state.get("last_seen_generation"),
            server_response=state["resumption_response"],
        )
    except StaleEpochResumptionError as exc:
        # Guardrail: invalidate cached belief, force authoritative re-read.
        state["needs_resync"] = True
        state["resync_reason"] = str(exc)
        raise StaleEpochResumptionError(
            f"agent loop halted for authoritative re-sync: {exc}"
        ) from exc

    state["last_seen_generation"] = resumption.get(
        "server_generation", state.get("last_seen_generation")
    )
    return result
