# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-replayed-sse-event-ids-against-a-resumed-mcp-session-when-the-server-s-session-affinity-router-and-the-client-s-last.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-replayed-sse-event-ids-against-a-resumed-mcp-session-when-the-server-s-session-affinity-router-and-the-client-s-last.warrant.json
# Markdown SHA-256:   f81f0424e4c4d89e4122015c7dcab1ce1a576d74422ab01d4734a0ed4194bb64
# Code AST SHA-256:   35328286e35e227da78b2992412a08b51596f5679275270285f20f523ef3838f
# Verified Classes:   EpochContinuityViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EpochContinuityViolation(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven continuous with the pre-disconnect cursor."""
    pass


def reconcile_resume(
    cursor_epoch: str,
    cursor_id: int,
    first_event: dict,
    pending_calls: set[str],
    status_query,
) -> dict:
    """
    Decide whether a resumed stream is same-epoch (safe to dedup) or an epoch
    change (must reconcile against authoritative server state).

    first_event: {"epoch": str | None, "id": int, "call_id": str | None}
    status_query: callable(pending_calls) -> dict[call_id, result]
    """
    ev_epoch = first_event.get("epoch")
    ev_id = first_event["id"]

    same_epoch = (
        ev_epoch is not None
        and ev_epoch == cursor_epoch
        and ev_id > cursor_id
    )

    if same_epoch:
        # Normal replay: dedup by id > cursor, resolve calls as they arrive.
        return {"mode": "replay", "cursor": ev_id, "resolved": {}}

    # Epoch changed, epoch token missing, or id regressed: the cursor is
    # untrustworthy. Do not dedup. Reconcile against server authority.
    if status_query is None:
        raise EpochContinuityViolation(
            f"resume cursor (epoch={cursor_epoch!r}, id={cursor_id}) "
            f"does not match incoming stream (epoch={ev_epoch!r}, id={ev_id}) "
            f"and no status_query is available to reconcile "
            f"{len(pending_calls)} pending tool calls; refusing to guess"
        )

    authoritative = status_query(pending_calls)
    unresolved = pending_calls - set(authoritative)
    if unresolved:
        raise EpochContinuityViolation(
            f"epoch change detected (cursor_epoch={cursor_epoch!r} -> "
            f"{ev_epoch!r}); server status query did not resolve "
            f"{sorted(unresolved)}; ledger cannot be reconciled"
        )

    return {
        "mode": "epoch-reset",
        "cursor": ev_id,
        "epoch": ev_epoch,
        "resolved": authoritative,
    }
