# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-http-transport-migrates-from-sse-to-streamable-http-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-http-transport-migrates-from-sse-to-streamable-http-mid-session.warrant.json
# Markdown SHA-256:   c8119da06d72ebbe5b1d1ae9a3e13b55e3e05c482e6c685f4328b76af5f4d275
# Code AST SHA-256:   1e44288eba00e103af544292d07c3faeaa05dce423c220870998adaeacb1429a
# Verified Classes:   SessionResumptionDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionResumptionDivergence(RuntimeError):
    """Raised when a transport-resumed MCP session cannot account for outstanding request IDs."""
    pass


def resume_session(client_pending: dict[int, dict], server_pending: dict[int, dict],
                   replayed_events: list[dict], session_id: str) -> dict[int, dict]:
    """
    Reconcile a client's pending-request table against the server's after a
    transport migration (SSE <-> Streamable HTTP). Returns the set of requests
    that are genuinely resumable. Raises if any outstanding request cannot be
    accounted for, because treating it as resumable would permit a duplicate
    non-idempotent tool call.
    """
    if not session_id:
        raise SessionResumptionDivergence("missing Mcp-Session-Id; cannot prove continuity")

    resumable: dict[int, dict] = {}
    unaccounted: list[int] = []

    for req_id, req in client_pending.items():
        if req_id in server_pending:
            # Handler still alive on the new transport: safe to resume.
            resumable[req_id] = server_pending[req_id]
        else:
            # Not in the server's pending table. Only acceptable if a terminal
            # result for this ID already appears in the replayed event stream.
            terminal = any(
                ev.get("id") == req_id and ("result" in ev or "error" in ev)
                for ev in replayed_events
            )
            if terminal:
                resumable[req_id] = {"terminal": True}
            else:
                unaccounted.append(req_id)

    # Orphaned progress notifications referencing a token with no live request
    # are a divergence signal, not a completion signal.
    live_tokens = {r.get("progressToken") for r in resumable.values() if r.get("progressToken")}
    for ev in replayed_events:
        if ev.get("method") == "notifications/progress":
            tok = ev.get("params", {}).get("progressToken")
            if tok and tok not in live_tokens and not any(
                r.get("terminal") for r in resumable.values()
            ):
                unaccounted.append(-1)  # sentinel: orphaned progress

    if unaccounted:
        raise SessionResumptionDivergence(
            f"session {session_id}: transport resumed but request table diverged; "
            f"unaccounted request IDs {unaccounted}. Do NOT retry blindly — "
            f"reconcile via idempotency key before reissuing tools/call."
        )

    return resumable
