# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-sse-session-migrates-between-gateway-replicas-mid-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-sse-session-migrates-between-gateway-replicas-mid-resume.warrant.json
# Markdown SHA-256:   8373b9279d170512bfbe3b5d5127084eac66baa7c0b8205e26e69da8c11f318f
# Code AST SHA-256:   eea122f517a998af827b8d87d7e10b4f118c11d01b81633bd9a6d73835fc1d8a
# Verified Classes:   ResumptionContinuityError, EventBuffer, Replica
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ResumptionContinuityError(RuntimeError):
    """Raised when a resumption request would silently break tool-call continuity."""
    pass


@dataclass
class EventBuffer:
    session_id: str
    events: dict = field(default_factory=dict)  # seq -> payload
    max_seq: int = 0
    gc_floor: int = 0  # lowest seq still retained


@dataclass
class Replica:
    replica_id: str
    sessions: dict = field(default_factory=dict)  # session_id -> EventBuffer

    def owns(self, session_id: str) -> bool:
        return session_id in self.sessions

    def emit(self, session_id: str, payload: str) -> int:
        buf = self.sessions.setdefault(session_id, EventBuffer(session_id))
        buf.max_seq += 1
        buf.events[buf.max_seq] = payload
        return buf.max_seq


def handle_resumption(replica: Replica, session_id: str, last_event_id: int) -> list:
    """
    Decide how to answer a streamable-SSE resumption request.
    Returns the list of events to replay. Raises on continuity break.
    """
    if not replica.owns(session_id):
        # Boundary violation: do NOT return 200 with an empty stream.
        raise ResumptionContinuityError(
            f"replica {replica.replica_id} does not own session {session_id!r}; "
            f"must respond 404 and force re-initialize, not 200"
        )

    buf = replica.sessions[session_id]

    if last_event_id < buf.gc_floor:
        # Requested event already garbage-collected; resumption is impossible.
        raise ResumptionContinuityError(
            f"session {session_id!r} requested Last-Event-ID {last_event_id} "
            f"but buffer floor is {buf.gc_floor}; must respond 410, not resume at a later point"
        )

    if last_event_id > buf.max_seq:
        # Client claims to have seen events the server never emitted.
        raise ResumptionContinuityError(
            f"session {session_id!r} Last-Event-ID {last_event_id} exceeds "
            f"max_seq {buf.max_seq}; event-ID namespace mismatch across replicas"
        )

    return [buf.events[seq] for seq in range(last_event_id + 1, buf.max_seq + 1)]


def idempotency_key(session_id: str, tool_name: str, args_repr: str) -> str:
    return hashlib.sha256(f"{session_id}|{tool_name}|{args_repr}".encode()).hexdigest()


# --- Demonstration of the failure trace ---
replica_a = Replica("A")
replica_b = Replica("B")

sid = "S1"
for p in ("progress:40", "progress:41", "progress:42"):
    replica_a.emit(sid, p)

# Client reconnects with Last-Event-ID: 42, gateway routes to B (round-robin).
try:
    handle_resumption(replica_b, sid, last_event_id=42)
except ResumptionContinuityError as e:
    print("caught (correctly):", e)

# Correct routing: B must fail closed; A replays 43.. only.
print("A replay:", handle_resumption(replica_a, sid, last_event_id=42))
