# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-stateless-streamable-http-mcp-session-resumed-across-a-load-balancer-boundary-into-a-server-replica-that-no-longe.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-stateless-streamable-http-mcp-session-resumed-across-a-load-balancer-boundary-into-a-server-replica-that-no-longe.warrant.json
# Markdown SHA-256:   977053fbef6543381185a2a7553560b50be183f26f052c611c50ed704f31f03c
# Code AST SHA-256:   c6045c486884cd0b015ce19ea2e23ab963e1f996adcce107d0bbd25f55ba01d8
# Verified Classes:   ResumeCursorUnsatisfiable, ReplayBuffer, DurableEventLog
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ResumeCursorUnsatisfiable(RuntimeError):
    """Raised when a stream resumption cannot prove event continuity."""
    pass


@dataclass
class ReplayBuffer:
    session_id: str
    high_water_mark: int          # last event id emitted for this session
    events: dict                  # event_id -> payload (local replica only)

    def has(self, event_id: int) -> bool:
        return event_id in self.events


@dataclass
class DurableEventLog:
    # keyed by (session_id, event_id); shared across replicas
    store: dict

    def fetch(self, session_id: str, event_id: int):
        return self.store.get((session_id, event_id))


def resume_stream(
    session_id: str,
    last_event_id: int,
    local: ReplayBuffer,
    durable: DurableEventLog,
) -> list:
    """
    Return the events to replay, or raise if continuity cannot be proven.

    The invariant: we may only open a resumed stream if we can produce
    event (last_event_id + 1). An empty local buffer is NOT evidence
    that no events were missed.
    """
    next_id = last_event_id + 1

    # Branch 1: local buffer satisfies the cursor.
    if local.high_water_mark >= next_id and local.has(next_id):
        return [local.events[i] for i in sorted(local.events) if i >= next_id]

    # Branch 2: durable log satisfies the cursor (cross-replica).
    if durable.fetch(session_id, next_id) is not None:
        replayed = []
        cursor = next_id
        while (ev := durable.fetch(session_id, cursor)) is not None:
            replayed.append(ev)
            cursor += 1
        return replayed

    # Branch 3: cannot prove continuity. MUST NOT open a silent stream.
    # A stateless replica with an empty buffer lands here and must
    # surface the gap, not pretend the cursor is at high-water mark.
    raise ResumeCursorUnsatisfiable(
        f"session {session_id}: cannot resume from Last-Event-ID={last_event_id}; "
        f"local high_water_mark={local.high_water_mark}, durable log has no "
        f"event {next_id}. Client must re-initialize or re-query by request_id; "
        f"do not retry the tool blindly."
    )


def handle_resume_request(session_id, last_event_id, local, durable):
    try:
        events = resume_stream(session_id, last_event_id, local, durable)
    except ResumeCursorUnsatisfiable as exc:
        # Emit a leading resume_gap marker so the client knows its view is stale.
        return {"status": 409, "body": {"error": "resume_unavailable", "detail": str(exc)}}
    return {"status": 200, "stream": events}
