# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-sse-replay-completion-from-live-stream-resumption-in-mcp-http-native-transport-with-per-tool-authorization-scopes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-sse-replay-completion-from-live-stream-resumption-in-mcp-http-native-transport-with-per-tool-authorization-scopes.warrant.json
# Markdown SHA-256:   c7d3d597c0a6281b917df7e0f41da5239262050fb052366fd2db3f87a050f65e
# Code AST SHA-256:   9f23db2161e2cc0634c89cea85e1cae2c29cec7816a91cba639ebf2de644ceb6
# Verified Classes:   StaleReplayAuthorizationError, ResumeBoundary
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StaleReplayAuthorizationError(RuntimeError):
    """Raised when a replayed event is consumed as if authorized under the current token."""
    pass


class ResumeBoundary:
    def __init__(self, session_id: str, scopes_at_creation: frozenset, current_scopes: frozenset):
        self.session_id = session_id
        self.scopes_at_creation = scopes_at_creation
        self.current_scopes = current_scopes

    def accept_replayed_event(self, event, event_required_scope: str) -> bool:
        # Replayed bytes are not re-authorized bytes.
        if event_required_scope not in self.current_scopes:
            raise StaleReplayAuthorizationError(
                f"session {self.session_id}: replayed event {event.get('id')} requires "
                f"scope {event_required_scope!r} absent from current token; "
                f"scopes_at_creation={sorted(self.scopes_at_creation)} "
                f"current={sorted(self.current_scopes)}"
            )
        return True

    def resume(self, buffered_events, event_scope_map):
        if self.scopes_at_creation != self.current_scopes:
            # Scope delta across the gap: revalidate every buffered event.
            accepted = []
            for ev in buffered_events:
                required = event_scope_map.get(ev.get("method"))
                if required is None:
                    accepted.append(ev)
                    continue
                self.accept_replayed_event(ev, required)
                accepted.append(ev)
            return accepted
        return list(buffered_events)
