# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-tool-call-ledger-when-an-mcp-session-resumes-across-an-sse-to-streamablehttp-transport-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-tool-call-ledger-when-an-mcp-session-resumes-across-an-sse-to-streamablehttp-transport-boundary.warrant.json
# Markdown SHA-256:   a834885d14a6b69bfaf4fe88076dd23815e129808547012d8858243ef2b6305e
# Code AST SHA-256:   c0f5d591a3894f51def4e3d3f4b6629efc83f4ae0c4e9cd085ddba1712bbecea
# Verified Classes:   IndeterminateCallError, ResumptionManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class IndeterminateCallError(RuntimeError):
    """Raised when a pending tool call cannot be resolved after resumption.

    The call may have succeeded server-side; the client has no ledger entry
    tying it to the presented (session_id, last_event_id) tuple.
    """


@dataclass
class ResumptionManifest:
    session_id: str | None
    last_event_id: str | None
    pending: dict[str, str] = field(default_factory=dict)  # request_id -> tool_name
    idempotency_keys: dict[str, str] = field(default_factory=dict)


def resume_session(
    manifest: ResumptionManifest,
    presented_session_id: str | None,
    presented_last_event_id: str | None,
    server_ledger: dict[str, set[str]],  # session_id -> request_ids owned
    max_backoff_s: float = 60.0,
    session_age_s: float = 0.0,
) -> ResumptionManifest:
    """Reconcile a resumption attempt against the server ledger.

    Invariant: the presented triple must resolve to the same ledger entry
    that owns every request in `manifest.pending`. Any partial match is an
    indeterminate state, not a resumable one.
    """
    if presented_session_id is None and manifest.session_id is not None:
        # Client dropped the session id but still holds a cursor: the cursor
        # is scoped per-session server-side, so it cannot be honored.
        if manifest.pending:
            raise IndeterminateCallError(
                f"cursor {presented_last_event_id!r} presented without session "
                f"{manifest.session_id!r}; {len(manifest.pending)} calls orphaned"
            )
        return ResumptionManifest(None, None)

    if presented_session_id not in server_ledger:
        # Session was reaped. Every pending call is indeterminate until
        # reconciled via idempotency key; do NOT silently re-mint and retry.
        if manifest.pending:
            raise IndeterminateCallError(
                f"session {presented_session_id!r} reaped with "
                f"{len(manifest.pending)} pending calls; reconcile before retry"
            )
        return ResumptionManifest(None, None)

    owned = server_ledger[presented_session_id]
    orphans = set(manifest.pending) - owned
    if orphans:
        raise IndeterminateCallError(
            f"requests {sorted(orphans)} not in ledger for "
            f"session {presented_session_id!r}"
        )

    if session_age_s > max_backoff_s:
        raise IndeterminateCallError(
            f"session age {session_age_s}s exceeds reconnect contract "
            f"{max_backoff_s}s; ledger retention not guaranteed"
        )

    return ResumptionManifest(
        session_id=presented_session_id,
        last_event_id=presented_last_event_id,
        pending=dict(manifest.pending),
        idempotency_keys=dict(manifest.idempotency_keys),
    )
