# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resuming-an-mcp-streamable-http-session-silently-accept-a-replayed-event-batch-from-a-rotated-server-endpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resuming-an-mcp-streamable-http-session-silently-accept-a-replayed-event-batch-from-a-rotated-server-endpoint.warrant.json
# Markdown SHA-256:   34c8a3e5d246b80e7eee51fe5734f189ca35cd6401b0c2eba1f9181bd0f1b716
# Code AST SHA-256:   ed2ace3b758ee3dfb6c16bbbb6b447fffb12f64ab1f28013a24473cef9ca1fbe
# Verified Classes:   CrossEpochResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CrossEpochResumeError(RuntimeError):
    """Raised when a resume cursor belongs to a different server epoch
    than the one recorded at checkpoint time, or when the resuming
    server cannot locate the cursor in its own session log."""


def resume_session(
    checkpoint: dict,
    server_response: dict,
    *,
    allow_reset: bool = False,
) -> dict:
    """
    checkpoint: {"session_id": str, "last_event_id": int, "epoch": str}
    server_response: {
        "epoch": str | None,
        "cursor_found": bool,
        "events": list[{"id": int, "epoch": str, ...}],
    }

    Returns the events that are safe to feed into the reasoning loop.
    Raises CrossEpochResumeError if the resume cannot be proven safe.
    """
    cp_epoch = checkpoint["epoch"]
    cp_cursor = checkpoint["last_event_id"]
    srv_epoch = server_response.get("epoch")

    # Invariant 1: the resuming server must present an epoch at all.
    if srv_epoch is None:
        raise CrossEpochResumeError(
            f"server presented no epoch for session {checkpoint['session_id']!r}; "
            "cannot distinguish resume from foreign-namespace replay"
        )

    # Invariant 2: epoch must match the checkpointed epoch exactly.
    if srv_epoch != cp_epoch:
        raise CrossEpochResumeError(
            f"epoch mismatch: checkpoint={cp_epoch!r} server={srv_epoch!r}; "
            "cursor is not meaningful across epochs"
        )

    # Invariant 3: server must have located the cursor in its own log.
    if not server_response["cursor_found"]:
        raise CrossEpochResumeError(
            f"cursor {cp_cursor} not found in server session log; "
            "refusing head-fallback resume"
        )

    # Within-epoch dedup is now safe.
    seen = set()
    safe_events = []
    for ev in server_response["events"]:
        if ev["epoch"] != cp_epoch:
            raise CrossEpochResumeError(
                f"event {ev['id']} carries foreign epoch {ev['epoch']!r}"
            )
        if ev["id"] <= cp_cursor:
            continue  # genuine redelivery
        if ev["id"] in seen:
            continue
        seen.add(ev["id"])
        safe_events.append(ev)

    return {"events": safe_events, "epoch": cp_epoch}
