# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-sse-stream-has-silently-forked-under-mcp-http-native-session-multiplexing.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-sse-stream-has-silently-forked-under-mcp-http-native-session-multiplexing.warrant.json
# Markdown SHA-256:   c1dc20ee0adeab8866c1c64bdb329e7abc192e16bad7913d82a6a76160365335
# Code AST SHA-256:   5d5bd8851c3d8f7a0dcac63b24d9b46ce94c4a67e54af4e4e8861aa6e3f8f6cb
# Verified Classes:   StreamForkError, StreamOwnershipGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class StreamForkError(RuntimeError):
    """Raised when a resumed SSE event cannot be attributed to a locally-originated request."""


@dataclass
class StreamOwnershipGuard:
    # IDs the client itself generated and is still awaiting results for.
    outstanding: set[str] = field(default_factory=set)
    # Logical stream this guard protects; events for other streams are foreign.
    stream_id: str = ""

    def register(self, request_id: str) -> None:
        self.outstanding.add(request_id)

    def resolve(self, request_id: str) -> None:
        self.outstanding.discard(request_id)

    def admit(self, event: dict) -> dict:
        """Gate every event from a resumed stream. Returns the event if owned."""
        owner_stream = event.get("stream_id")
        request_id = event.get("request_id")

        # Structural signal #1: no stream discriminator at all -> cannot prove ownership.
        if owner_stream is None:
            raise StreamForkError(
                f"event id={event.get('id')} carries no stream_id; "
                f"resumption on {self.stream_id!r} is unverifiable"
            )

        # Structural signal #2: event belongs to a sibling stream in the same session.
        if owner_stream != self.stream_id:
            raise StreamForkError(
                f"event id={event.get('id')} belongs to stream {owner_stream!r}, "
                f"not {self.stream_id!r}; session-global counter forked the resume"
            )

        # Structural signal #3: stream matches but request was never issued here.
        if request_id is not None and request_id not in self.outstanding:
            raise StreamForkError(
                f"event id={event.get('id')} references request {request_id!r} "
                f"not outstanding on {self.stream_id!r}"
            )

        return event

    def replay(self, events: Iterable[dict]) -> list[dict]:
        admitted = []
        for ev in events:
            admitted.append(self.admit(ev))
        return admitted
