# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-http-session-has-silently-forked-across-a-resumable-sse-boundary-after-a-per-tool-oauth-resource-in.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-http-session-has-silently-forked-across-a-resumable-sse-boundary-after-a-per-tool-oauth-resource-in.warrant.json
# Markdown SHA-256:   35c13cba42b41b40384aa1993909161d8380893304eefc41dd4edf3cab3cb706
# Code AST SHA-256:   77a9fbf900570126ef30f7838df1735012e51e33d0df9791665285afe5a0b9db
# Verified Classes:   AudienceForkError, SessionRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class AudienceForkError(RuntimeError):
    """Raised when a resumable MCP session's presented token audience
    diverges from the audience recorded at session negotiation."""
    pass


class SessionRecord:
    def __init__(self, session_id: str, negotiated_resource: str):
        self.session_id = session_id
        self.negotiated_resource = negotiated_resource
        self.replay_buffer: list[dict] = []


def resume_stream(
    session: SessionRecord,
    presented_resource: str,
    last_event_id: int,
) -> list[dict]:
    """Resume an SSE stream, enforcing the audience-session invariant.

    The invariant: every event replayed via Last-Event-ID must have been
    authorized under the same resource indicator as the presented token.
    Streamable HTTP enforces session identity but not audience identity,
    so this check must live here.
    """
    if presented_resource != session.negotiated_resource:
        # Do NOT silently resume: the replay buffer was produced under a
        # different audience and replaying it under this token would fork
        # the session across two authorization contexts.
        raise AudienceForkError(
            f"session {session.session_id!r} negotiated under "
            f"resource={session.negotiated_resource!r} but resume presented "
            f"resource={presented_resource!r}; refusing to replay events "
            f">= {last_event_id} across an audience boundary. "
            f"Start a new Mcp-Session-Id for the new audience."
        )
    return [e for e in session.replay_buffer if e["id"] >= last_event_id]


# --- trace of the observed failure, now guarded ---
sess = SessionRecord("s-7f3a", negotiated_resource="https://api.example/mcp/search")
sess.replay_buffer = [{"id": i, "audience": "search"} for i in range(41, 89)]

try:
    # client speculatively prefetched a 'write' token and resumed with it
    resume_stream(sess, presented_resource="https://api.example/mcp/write", last_event_id=88)
except AudienceForkError as e:
    # Without this guard the server would have resumed at id 89 and
    # delivered search-audience events to a write-audience consumer,
    # surfacing later as a spurious 403 with a mismatched challenge,
    # or as false non-determinism in replay-based verification.
    print(f"fork prevented: {e}")
