# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-json-rpc-batch-atomicity-when-an-mcp-sse-stream-resumes-mid-batch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-json-rpc-batch-atomicity-when-an-mcp-sse-stream-resumes-mid-batch.warrant.json
# Markdown SHA-256:   c32af8096b7e24d172a7fe18f01150b1eb8dd72dfd32cf11bb1e3b508abb3b05
# Code AST SHA-256:   01363e9a1cba105664d4457f5fdbf93dededc2fb04b645521dd4e3b53d5f100f
# Verified Classes:   BatchIntegrityError, BatchManifest, ResumableBatchClient
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Dict, Set, Optional


class BatchIntegrityError(RuntimeError):
    """Raised when a resumed SSE stream yields a batch that violates atomicity."""
    pass


@dataclass
class BatchManifest:
    batch_id: str
    requested_ids: Set[str]
    received_ids: Set[str] = field(default_factory=set)
    delivered_events: Set[int] = field(default_factory=set)
    last_event_id: Optional[int] = None
    fragments_expected: Optional[int] = None
    fragments_seen: int = 0

    @classmethod
    def new(cls, requested_ids):
        return cls(batch_id=str(uuid.uuid4()), requested_ids=set(requested_ids))


class ResumableBatchClient:
    def __init__(self, server_advertises_batch_fragments: bool):
        self.batch_fragments = server_advertises_batch_fragments
        self.active: Dict[str, BatchManifest] = {}

    def on_send(self, requested_ids) -> BatchManifest:
        m = BatchManifest.new(requested_ids)
        self.active[m.batch_id] = m
        return m

    def on_event(self, manifest: BatchManifest, event_id: int,
                 batch_id: Optional[str], seq: Optional[int],
                 responses: list) -> None:
        # Duplicate event replay (inclusive Last-Event-ID) must be rejected.
        if event_id in manifest.delivered_events:
            raise BatchIntegrityError(
                f"event {event_id} replayed for batch {manifest.batch_id}; "
                f"server used inclusive Last-Event-ID cursor"
            )
        manifest.delivered_events.add(event_id)
        manifest.last_event_id = event_id

        if not self.batch_fragments:
            # No fragment metadata: any multi-event batch is non-resumable.
            # We accept fragments only if the batch completes in one event.
            if len(manifest.delivered_events) > 1:
                raise BatchIntegrityError(
                    f"batch {manifest.batch_id} fragmented across events without "
                    f"batch-fragment capability; atomicity cannot be guaranteed"
                )

        for r in responses:
            rid = str(r["id"])
            if rid in manifest.received_ids:
                raise BatchIntegrityError(
                    f"duplicate JSON-RPC id {rid} in batch {manifest.batch_id}; "
                    f"non-idempotent tool side effect at risk"
                )
            manifest.received_ids.add(rid)

    def on_resume(self, manifest: BatchManifest, last_event_id: int,
                  first_replayed_event_id: int) -> None:
        # The cursor landed inside the batch: the head may already be delivered
        # and the tail may be missing. Without fragment metadata we cannot
        # reconstruct the boundary, so we must fail closed.
        if not self.batch_fragments and manifest.delivered_events:
            raise BatchIntegrityError(
                f"resume at Last-Event-ID {last_event_id} lands inside batch "
                f"{manifest.batch_id}; partial responses already delivered, "
                f"full batch re-issue required"
            )
        if first_replayed_event_id != last_event_id + 1 and self.batch_fragments:
            raise BatchIntegrityError(
                f"resume gap: expected event {last_event_id + 1}, "
                f"got {first_replayed_event_id} for batch {manifest.batch_id}"
            )

    def on_complete(self, manifest: BatchManifest) -> None:
        missing = manifest.requested_ids - manifest.received_ids
        if missing:
            raise BatchIntegrityError(
                f"batch {manifest.batch_id} completed with {len(missing)} "
                f"missing responses: {sorted(missing)[:5]}..."
            )
