# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-a-load-balancer-re-pins-its-session-to-a-cold-replica.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-after-a-load-balancer-re-pins-its-session-to-a-cold-replica.warrant.json
# Markdown SHA-256:   a1b991525b54094d27879cc67300fc70b0381caae513854e2d2c31c7b18d0a88
# Code AST SHA-256:   dc98a509ee9737d97b6ec7a79504f6601fa403bc7a23e3c81243e082c7bb9279
# Verified Classes:   StreamCursorEpochMismatch, EventLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StreamCursorEpochMismatch(RuntimeError):
    """Client's Last-Event-ID belongs to a producer epoch this replica cannot honor."""
    pass


class EventLog:
    def __init__(self, epoch: str, events: list[tuple[int, str]]):
        self.epoch = epoch
        self.events = events  # [(seq, payload), ...] durable, per-epoch
        self.high_water = events[-1][0] if events else 0
        self.low_water = events[0][0] if events else 0

    def replay_after(self, cursor: int) -> list[tuple[int, str]]:
        return [(s, p) for (s, p) in self.events if s > cursor]


def resume_stream(
    log: EventLog,
    last_event_id: int | None,
    client_epoch: str | None,
) -> list[tuple[int, str]]:
    if last_event_id is None:
        return []  # fresh stream, no cursor to honor

    # Cold replica: empty log has no opinion. Never treat high_water==0 as
    # "nothing to replay, wait live" -- that silently swallows the cursor.
    if not log.events:
        raise StreamCursorEpochMismatch(
            f"replica epoch {log.epoch!r} has empty log; cannot honor "
            f"Last-Event-ID={last_event_id} from epoch {client_epoch!r}; "
            f"client must re-sync (tools/list, call status) before resuming"
        )

    if client_epoch is not None and client_epoch != log.epoch:
        raise StreamCursorEpochMismatch(
            f"cursor epoch {client_epoch!r} != replica epoch {log.epoch!r}; "
            f"events after {last_event_id} were produced by a different "
            f"producer and cannot be replayed here"
        )

    if last_event_id < log.low_water:
        # Events aged out of the retained window: continuity is broken.
        raise StreamCursorEpochMismatch(
            f"Last-Event-ID={last_event_id} older than retained window "
            f"[{log.low_water}, {log.high_water}]; emit stream_gap and force re-sync"
        )

    if last_event_id > log.high_water:
        raise StreamCursorEpochMismatch(
            f"Last-Event-ID={last_event_id} ahead of high_water={log.high_water} "
            f"on epoch {log.epoch!r}; cursor is foreign, reject rather than hang"
        )

    return log.replay_after(last_event_id)
