# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-resumed-mcp-sse-stream-as-a-divergent-event-log-rather-than-a-replayable-feed.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-resumed-mcp-sse-stream-as-a-divergent-event-log-rather-than-a-replayable-feed.warrant.json
# Markdown SHA-256:   0098600779b4410a9898da0600550995fcba3884a95f90d67e1ba1935f06542a
# Code AST SHA-256:   de7e24da42860e0a3523c264d8372c73174fb8972338c2bb9e3169fe8312d458
# Verified Classes:   ResumedStreamDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumedStreamDivergenceError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be reconciled to a
    contiguous, authoritative event log and the client must fall back to
    out-of-band state reconciliation."""


def reconcile_on_reconnect(
    last_event_id: int,
    first_replayed_id: int,
    replay_contiguous: bool,
    inflight_progress_tokens: dict[str, float],
    server_max_replay_age_s: float,
    disconnect_duration_s: float,
) -> dict[str, str]:
    """Decide whether a resumed stream may be trusted as replayable.

    Returns a mapping of progressToken -> 'resolved' | 'indeterminate'
    after reconciliation. Raises ResumedStreamDivergenceError when the
    stream cannot be trusted and reconciliation is required but the
    caller has not supplied an authoritative status probe.
    """
    if not replay_contiguous:
        # Server replayed from a later ID without a gap marker: events
        # between last_event_id and first_replayed_id were evicted.
        gap = first_replayed_id - last_event_id - 1
        if gap > 0 and not _has_gap_marker(last_event_id, first_replayed_id):
            raise ResumedStreamDivergenceError(
                f"non-contiguous replay: {gap} events evicted between "
                f"{last_event_id} and {first_replayed_id}"
            )

    if disconnect_duration_s > server_max_replay_age_s:
        raise ResumedStreamDivergenceError(
            f"disconnect {disconnect_duration_s}s exceeds replay window "
            f"{server_max_replay_age_s}s; buffered terminal events may be lost"
        )

    status = {}
    for token, last_progress in inflight_progress_tokens.items():
        # A progress token active at disconnect has no guaranteed terminal
        # event in the replay window. Never infer completion from the stream.
        status[token] = "indeterminate"
    return status


def _has_gap_marker(a: int, b: int) -> bool:
    # Placeholder for a server extension that explicitly marks a gap.
    return False
