# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-replay-integrity-problem-rather-than-a-reconnect-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-replay-integrity-problem-rather-than-a-reconnect-problem.warrant.json
# Markdown SHA-256:   0903a7457338ce1281ae03c47bbd4420d831b7576f802478d39ecf6b804da94f
# Code AST SHA-256:   e134118b92056fab1bafcd8f54c73f860dc8625a487f43e89e4c048aeba840b2
# Verified Classes:   ResumptionReplayGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumptionReplayGapError(RuntimeError):
    """Raised when a resumed MCP session cannot prove replay continuity
    between the client's Last-Event-ID and the first replayed event, or when
    a replayed server-initiated notification would be applied as a
    non-idempotent mutation trigger."""


def apply_resumed_notification(
    *,
    last_event_id: int,
    first_replayed_id: int,
    notification_id: int,
    handler_is_idempotent: bool,
    server_signals_gap: bool,
    already_applied_ids: set[int],
) -> str:
    # Invariant 1: no silent gap. If the server cannot replay from the
    # requested ID, it must say so; otherwise the client is missing events.
    if first_replayed_id > last_event_id + 1 and not server_signals_gap:
        raise ResumptionReplayGapError(
            f"replay gap: client holds Last-Event-ID={last_event_id}, "
            f"server replayed from {first_replayed_id} with no gap signal; "
            f"events {last_event_id + 1}..{first_replayed_id - 1} are lost"
        )

    # Invariant 2: never double-apply a server-initiated notification.
    if notification_id in already_applied_ids:
        return "skipped-duplicate"

    # Invariant 3: a replayed notification may only be applied as a mutation
    # trigger if the handler is idempotent AND continuity is proven.
    continuity_proven = (first_replayed_id == last_event_id + 1) or server_signals_gap
    if not handler_is_idempotent and not continuity_proven:
        raise ResumptionReplayGapError(
            f"notification {notification_id} would be applied as a "
            f"non-idempotent mutation trigger across an unproven replay gap; "
            f"reconcile resource state before applying"
        )

    return "applied"
