# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-forked-session-rather-than-a-replay-and-how-does-a-half-delivered-to.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-forked-session-rather-than-a-replay-and-how-does-a-half-delivered-to.warrant.json
# Markdown SHA-256:   324673650196ac5715768a802a40eac7f6ceab13d77798cc943ae51a5d0e8f32
# Code AST SHA-256:   425d79ce4fa2ecb708e4f1b752b56a1d471323c1aabcf4d3f9a5ce8d32540c60
# Verified Classes:   StreamGenerationFork, CallBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StreamGenerationFork(RuntimeError):
    """Raised when a resumption crosses stream generations or loses events."""
    pass


@dataclass
class CallBuffer:
    call_id: str
    generation: str
    last_seq: int = 0
    events: list = field(default_factory=list)
    terminated: bool = False

    def accept(self, event: dict) -> None:
        if self.terminated:
            raise StreamGenerationFork(
                f"event after terminal for call {self.call_id}"
            )
        gen = event["generation"]
        seq = event["seq"]
        if gen != self.generation:
            # Fork: server restarted the stream. Prior partial state is orphaned.
            raise StreamGenerationFork(
                f"generation change on call {self.call_id}: "
                f"{self.generation!r} -> {gen!r} at seq {seq} "
                f"(held {len(self.events)} events, last_seq={self.last_seq})"
            )
        if seq != self.last_seq + 1:
            # Lossy replay: gap within the same generation. Partial buffer is
            # not a valid prefix of the server's computation.
            raise StreamGenerationFork(
                f"sequence gap on call {self.call_id}: "
                f"expected {self.last_seq + 1}, got {seq}"
            )
        self.events.append(event)
        self.last_seq = seq
        if event.get("terminal"):
            self.terminated = True


def resume_stream(
    buffer: CallBuffer,
    last_event_id: Optional[str],
    incoming: list[dict],
) -> CallBuffer:
    """Reattach a resumption response to an existing buffer, or fail closed."""
    if last_event_id is not None and not incoming:
        raise StreamGenerationFork(
            f"empty resumption for call {buffer.call_id} at {last_event_id}"
        )
    for event in incoming:
        buffer.accept(event)
    return buffer
