# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-http-native-sse-stream-as-a-non-resumable-per-request-event-channel-rather-than-a-durable-subscription.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-http-native-sse-stream-as-a-non-resumable-per-request-event-channel-rather-than-a-durable-subscription.warrant.json
# Markdown SHA-256:   a1640feff355e45e44861849d843c7eaf7d7f40c7feaa5204bb18a12a92b4fb5
# Code AST SHA-256:   44e0442ca656bd1da7f95bce29b50451cf46c75820bd6d4107380ca022643c95
# Verified Classes:   StreamResumptionViolation, RequestScopedStream
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StreamResumptionViolation(RuntimeError):
    """Raised when a client attempts to resume a request-scoped MCP SSE stream
    without a negotiated retention guarantee for the target event ID."""
    pass


class RequestScopedStream:
    def __init__(self, request_id: str, negotiated_resumable: bool, retained_event_ids: set[str]):
        self.request_id = request_id
        self.negotiated_resumable = negotiated_resumable
        self.retained_event_ids = retained_event_ids
        self.settled = False
        self.last_event_id: str | None = None

    def on_event(self, event_id: str, payload: dict) -> None:
        if event_id in self.retained_event_ids:
            # duplicate replay: must be deduplicated, not re-applied
            return
        self.last_event_id = event_id
        if payload.get("type") in ("result", "error"):
            self.settled = True

    def on_disconnect(self) -> None:
        if self.settled:
            return
        # stream ended without terminal message: request is interrupted
        raise StreamResumptionViolation(
            f"stream for request {self.request_id} ended without terminal message; "
            f"last_event_id={self.last_event_id}; resumable={self.negotiated_resumable}"
        )

    def resume(self, last_event_id: str) -> None:
        if not self.negotiated_resumable:
            raise StreamResumptionViolation(
                f"cannot resume request-scoped stream {self.request_id}: "
                f"resumability not negotiated"
            )
        if last_event_id not in self.retained_event_ids:
            raise StreamResumptionViolation(
                f"cannot resume stream {self.request_id}: event {last_event_id} "
                f"is not retained; re-issue the JSON-RPC request instead"
            )
        # retention proven; resume is valid
