# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-sse-resumption-as-unsafe-after-a-session-level-last-event-id-replay-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-sse-resumption-as-unsafe-after-a-session-level-last-event-id-replay-gap.warrant.json
# Markdown SHA-256:   aebca330ada304936d1c737d142ecbb3dd7da754852138c01a14c7a332b9923d
# Code AST SHA-256:   c088335af5d2fbcbe5126a522c539d99e69af0c7656326c080484127550434b0
# Verified Classes:   SessionResumptionIntegrityError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class SessionResumptionIntegrityError(RuntimeError):
    """Raised when an MCP SSE resumption response cannot be proven to belong
    to the session the client held before the disconnect."""
    pass


def reconcile_resumption(
    held_session_id: str,
    last_event_id: str,
    resumption_response: dict,
    pending_calls: dict[str, dict],
    replay_window_max_events: int | None,
) -> dict[str, dict]:
    """
    Decide whether a streamable-SSE resumption is safe, and reconcile
    outstanding calls against replayed events.

    Returns the updated pending_calls map with resolved entries removed.
    Raises SessionResumptionIntegrityError when the client must re-establish
    the session instead of resuming.
    """
    returned_session_id = resumption_response.get("session_id")
    if returned_session_id is None:
        raise SessionResumptionIntegrityError(
            "resumption response omitted Mcp-Session-Id; session identity unproven"
        )
    if returned_session_id != held_session_id:
        raise SessionResumptionIntegrityError(
            f"session id changed on resumption: held={held_session_id!r} "
            f"returned={returned_session_id!r}; server rehydrated a fresh "
            f"session, idempotency ledger is not guaranteed"
        )

    if replay_window_max_events is None:
        raise SessionResumptionIntegrityError(
            "server did not advertise a bounded replay window; cannot "
            "distinguish 'no events missed' from 'events silently skipped'"
        )

    replayed = resumption_response.get("replayed_events", [])
    if len(replayed) > replay_window_max_events:
        raise SessionResumptionIntegrityError(
            f"replayed {len(replayed)} events exceeds advertised window "
            f"{replay_window_max_events}; replay is not trustworthy"
        )

    # Reconcile outstanding calls by request-correlation id, not SSE event id.
    resolved: set[str] = set()
    for event in replayed:
        corr_id = event.get("request_id")
        if corr_id is not None and corr_id in pending_calls:
            pending_calls[corr_id]["result"] = event.get("result")
            pending_calls[corr_id]["status"] = "RESOLVED_FROM_REPLAY"
            resolved.add(corr_id)

    # Any call still pending after replay reconciliation must NOT be retried
    # with its prior idempotency key unless the server proves ledger durability.
    if not resumption_response.get("idempotency_ledger_durable", False):
        unresolved = [c for c in pending_calls if c not in resolved]
        if unresolved:
            raise SessionResumptionIntegrityError(
                f"calls {unresolved} remain unresolved and server does not "
                f"guarantee idempotency-ledger durability; retrying would "
                f"risk duplicate execution of non-idempotent tool calls"
            )

    for corr_id in resolved:
        del pending_calls[corr_id]
    return pending_calls
