# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resumption-as-unsafe-rather-than-merely-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resumption-as-unsafe-rather-than-merely-stale.warrant.json
# Markdown SHA-256:   703b6d0a74fb4c5449ce288a320c4f43fb762abdae710c8a43be4f5afac53c87
# Code AST SHA-256:   1f97848cb3b0d3db461a0e77d4b7edcbffde8e4d9f4a1d5c2123e6508c998860
# Verified Classes:   UnsafeResumptionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsafeResumptionError(RuntimeError):
    """Raised when a client attempts to resume an MCP SSE stream from a
    cursor that is ahead of its durably applied state, or against an
    expired retention window, or across a multiplexed ID space it has
    not fully consumed."""


def compute_resume_token(
    delivered_upto: int,
    applied_upto: int,
    server_retention_ttl_s: float,
    token_age_s: float,
    multiplexed_streams_unconsumed: bool,
) -> int:
    # Invariant: resume_token must equal applied_upto, never delivered_upto.
    if applied_upto > delivered_upto:
        raise UnsafeResumptionError(
            f"applied_upto={applied_upto} exceeds delivered_upto={delivered_upto}; "
            "applied log is ahead of transport, state is corrupt"
        )

    if token_age_s > server_retention_ttl_s:
        raise UnsafeResumptionError(
            f"resumption token age {token_age_s}s exceeds server retention "
            f"{server_retention_ttl_s}s; token is unresumable, require re-initialize"
        )

    if multiplexed_streams_unconsumed:
        raise UnsafeResumptionError(
            "session multiplexes streams under a shared monotonic ID space and "
            "at least one stream is not consumed to applied_upto; a scalar "
            "Last-Event-ID cannot express partial consumption, refuse to resume"
        )

    # Safe: resume from applied, replay (applied, delivered] with dedup.
    return applied_upto


def reconnect(session, now_s: float) -> int:
    token = compute_resume_token(
        delivered_upto=session.delivered_upto,
        applied_upto=session.applied_upto,
        server_retention_ttl_s=session.retention_ttl_s,
        token_age_s=now_s - session.last_applied_at_s,
        multiplexed_streams_unconsumed=session.has_unconsumed_streams(),
    )
    session.enter_replaying()
    return token
