# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-replayed-sse-event-stream-whose-last-event-id-was-silently-re-anchored-by-an-oauth-2-1-token-rotation-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-replayed-sse-event-stream-whose-last-event-id-was-silently-re-anchored-by-an-oauth-2-1-token-rotation-mid-stream.warrant.json
# Markdown SHA-256:   33e64f0f4ce25c146d9917761508211b3edcde9e8b8e370845510a531b85e2cd
# Code AST SHA-256:   5258c30c6f960ceb732e81243907b48cecba12d6c4f8746ce4979b45f64af052
# Verified Classes:   EpochSpliceError, AuthEpoch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class EpochSpliceError(RuntimeError):
    """Raised when a resumed SSE stream crosses an authorization epoch boundary."""
    pass


@dataclass(frozen=True)
class AuthEpoch:
    sub: str
    aud: str
    scope: frozenset
    iat: int

    def fingerprint(self) -> str:
        material = json.dumps(
            {"sub": self.sub, "aud": self.aud,
             "scope": sorted(self.scope), "iat": self.iat},
            sort_keys=True,
        ).encode()
        return hashlib.sha256(material).hexdigest()


def resume_stream(last_event_id: int, new_token_epoch: AuthEpoch,
                  recorded_epoch_fp: str, server_first_event: dict) -> dict:
    """Validate causal continuity across a resumable SSE reconnect.

    server_first_event must carry an 'auth_epoch' field emitted by the
    resource server on the first frame of any resumed stream.
    """
    server_fp = server_first_event.get("auth_epoch")
    if server_fp is None:
        raise EpochSpliceError(
            f"resume at Last-Event-ID={last_event_id}: server emitted no "
            "auth_epoch marker; cannot prove causal continuity across token "
            "rotation. Refusing to merge into in-flight reasoning state."
        )
    if server_fp != recorded_epoch_fp:
        raise EpochSpliceError(
            f"resume at Last-Event-ID={last_event_id}: epoch splice detected. "
            f"recorded={recorded_epoch_fp[:12]} server={server_fp[:12]} "
            f"current_token_epoch={new_token_epoch.fingerprint()[:12]}. "
            "Events after the cursor were authored under a different "
            "authorization context; treat as a new session."
        )
    return server_first_event
