# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-mcp-session-resumption-across-an-event-stream-replay-window.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-mcp-session-resumption-across-an-event-stream-replay-window.warrant.json
# Markdown SHA-256:   a23ee34760225a681d750cb41042567e5001e07f0df49074a93e4943fccc3db9
# Code AST SHA-256:   e9fe56669cdb88416efde611e7fe0c57ca0189c2339d39796204fa8742483d64
# Verified Classes:   SessionResumptionRefused
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SessionResumptionRefused(RuntimeError):
    """Raised when an MCP session cannot be safely resumed."""
    pass


def resume_session(
    presented_session_id: str,
    presented_incarnation: str,
    last_event_id: int,
    session_store,
) -> "Session":
    record = session_store.get(presented_session_id)

    if record is None:
        raise SessionResumptionRefused(
            f"session {presented_session_id!r} not found; client must re-initialize"
        )

    if record.incarnation != presented_incarnation:
        raise SessionResumptionRefused(
            f"session {presented_session_id!r} incarnation mismatch: "
            f"presented {presented_incarnation!r}, stored {record.incarnation!r}"
        )

    oldest_retained = record.stream.oldest_retained_event_id()
    if last_event_id < oldest_retained:
        raise SessionResumptionRefused(
            f"replay window truncated for session {presented_session_id!r}: "
            f"requested Last-Event-ID {last_event_id} < oldest retained "
            f"{oldest_retained}; gap would be silently lost"
        )

    if record.has_indeterminate_tool_call():
        raise SessionResumptionRefused(
            f"session {presented_session_id!r} has an in-flight non-idempotent "
            f"tool call of indeterminate outcome; cannot resume safely"
        )

    return record
