# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-resumable-mcp-sse-sessions-from-silently-desynchronizing-when-oauth-2-1-token-refresh-races-the-last-event-id-replay-window.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-resumable-mcp-sse-sessions-from-silently-desynchronizing-when-oauth-2-1-token-refresh-races-the-last-event-id-replay-window.warrant.json
# Markdown SHA-256:   db11f8f2a8c3892a509d98caa50d582c59c33b5e083ba29baf717bf182116b77
# Code AST SHA-256:   b95861f392396ad956c18ccfe9258d01cc1522001e1992e7eb90723dc70d477b
# Verified Classes:   ReplayAuthorizationMismatch, ReplayGapUnacknowledged
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ReplayAuthorizationMismatch(RuntimeError):
    """Raised when an SSE replay would deliver events outside the current token's authority."""
    pass


class ReplayGapUnacknowledged(RuntimeError):
    """Raised when the server cannot honor Last-Event-ID and the client has not acknowledged the gap."""
    pass


# Each retained event carries the auth context under which it was emitted.
# (sub, frozenset(scope)) — recorded at emit time, never rewritten.
EventLog = list[dict]  # {"id": int, "sub": str, "scope": frozenset[str], "payload": dict}


def resume_stream(
    log: EventLog,
    last_event_id: int,
    current_sub: str,
    current_scope: frozenset[str],
    retention_floor: int,
    client_ack_gap: bool,
) -> list[dict]:
    """
    Replay events after last_event_id, enforcing the co-terminous continuity invariant:
      - every replayed event's (sub, scope) must be a subset of the current request's
      - any retention gap must be explicitly acknowledged before data flows
    """
    if last_event_id < retention_floor - 1:
        # Cursor points before the retained window: we cannot prove continuity.
        if not client_ack_gap:
            raise ReplayGapUnacknowledged(
                f"Last-Event-ID {last_event_id} precedes retention floor "
                f"{retention_floor}; gap [{last_event_id + 1}, {retention_floor - 1}] "
                f"must be acknowledged before replay."
            )
        start = retention_floor
    else:
        start = last_event_id + 1

    replay: list[dict] = []
    for ev in log:
        if ev["id"] < start:
            continue
        # Authorization continuity: the event was emitted under some (sub, scope).
        # It may only be replayed if that context is subsumed by the current one.
        if ev["sub"] != current_sub or not ev["scope"].issubset(current_scope):
            raise ReplayAuthorizationMismatch(
                f"Event {ev['id']} emitted under sub={ev['sub']!r} "
                f"scope={sorted(ev['scope'])} but resumption token is "
                f"sub={current_sub!r} scope={sorted(current_scope)}. "
                f"Refusing to replay: would deliver de-authorized tool output."
            )
        replay.append(ev)
    return replay
