# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-an-mcp-resumable-sse-last-event-id-replay-that-the-server-considers-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-an-mcp-resumable-sse-last-event-id-replay-that-the-server-considers-valid.warrant.json
# Markdown SHA-256:   3bc2a13da3bdc2953b2c3261f564230d470e13787c031d896164848bb76cabeb
# Code AST SHA-256:   e98b22d1f2415707d91c2a56f4286c95afb8bafa19a6e67461306185aeebcb74
# Verified Classes:   EpochMismatchedReplayError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EpochMismatchedReplayError(RuntimeError):
    """Raised when a resumable-SSE replay crosses a session epoch boundary."""
    pass


def merge_resumable_replay(
    client_session_epoch: int,
    last_event_id: int,
    replayed_events: list[dict],
    server_session_ttl_s: float,
    gap_since_disconnect_s: float,
) -> list[dict]:
    """
    Decide whether a Last-Event-ID replay may be merged into working state.

    replayed_events: list of dicts with keys 'id' and 'epoch' (epoch may be None
    if the server does not expose generation markers).
    """
    if not replayed_events:
        return []

    first = replayed_events[0]
    replay_epoch = first.get("epoch")

    # Contiguity check is necessary but never sufficient.
    expected = last_event_id + 1
    for ev in replayed_events:
        if ev["id"] != expected:
            raise EpochMismatchedReplayError(
                f"non-contiguous replay: expected id {expected}, got {ev['id']}"
            )
        expected += 1

    if replay_epoch is None:
        # No epoch mechanism: only safe if we are well inside session TTL.
        if gap_since_disconnect_s > server_session_ttl_s:
            raise EpochMismatchedReplayError(
                "replay has no epoch marker and gap exceeds session TTL; "
                "treating as fresh session, refusing to merge"
            )
        return replayed_events

    if replay_epoch != client_session_epoch:
        raise EpochMismatchedReplayError(
            f"replay epoch {replay_epoch} != client session epoch "
            f"{client_session_epoch}; cursor is valid but state generation "
            f"differs — must re-establish session and re-issue idempotently"
        )

    return replayed_events
