# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-server-initiated-sse-backchannel-when-an-mcp-streamable-session-resumes-after-transport-level-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-server-initiated-sse-backchannel-when-an-mcp-streamable-session-resumes-after-transport-level-reconnect.warrant.json
# Markdown SHA-256:   2e191b7e063868be799ca6bc93e165425ff60acd34bb3618b36a85f7017868a7
# Code AST SHA-256:   6de5cd626553dc221028c71d0e91d88ceafd19d0588c786cbfd054ca94a4af48
# Verified Classes:   BackchannelOrphanedError, StaleCacheError, SSEWriter, Session
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import asyncio
import time
from dataclasses import dataclass, field
from typing import Optional


class BackchannelOrphanedError(RuntimeError):
    """Raised when a server-initiated message targets a terminal SSE writer.

    Signals that the session resumed but the dispatch target was not rebound
    to the new response stream. Client must re-establish the session.
    """


class StaleCacheError(RuntimeError):
    """Raised when the agent reads a resource populated by an orphaned backchannel."""


@dataclass
class SSEWriter:
    stream_id: str
    closed: bool = False
    terminal: bool = False

    def write(self, msg: str) -> None:
        if self.terminal or self.closed:
            # Silent-drop path that causes the bug; guardrail converts to raise.
            raise BackchannelOrphanedError(
                f"emit to terminal writer {self.stream_id}; session dispatch target stale"
            )


@dataclass
class Session:
    session_id: str
    writer: Optional[SSEWriter] = None
    last_event_id: int = 0
    reconciliation_required: bool = False
    cache: dict = field(default_factory=dict)

    def attach(self, new_writer: SSEWriter) -> None:
        # Single-writer invariant: rebind atomically, mark prior terminal.
        if self.writer is not None and not self.writer.terminal:
            self.writer.terminal = True
        self.writer = new_writer
        self.reconciliation_required = True

    def emit(self, msg: str) -> None:
        if self.writer is None:
            raise BackchannelOrphanedError(f"session {self.session_id} has no writer")
        self.writer.write(msg)  # raises if terminal

    def resume(self, new_writer: SSEWriter, last_event_id: int) -> None:
        if last_event_id > self.last_event_id:
            self.last_event_id = last_event_id
        self.attach(new_writer)


def reconcile(session: Session, resources: list[str], reader) -> None:
    """Post-resume barrier: invalidate cache and re-read every dependency."""
    if not session.reconciliation_required:
        return
    session.cache.clear()
    for r in resources:
        try:
            session.cache[r] = reader(r)
        except Exception as e:
            raise StaleCacheError(f"reconciliation failed for {r}: {e}") from e
    session.reconciliation_required = False


async def sampling_watchdog(session: Session, expected_by: float, on_expire) -> None:
    """Force full re-establishment if a sampling response never arrives."""
    await asyncio.sleep(max(0.0, expected_by - time.time()))
    if session.reconciliation_required or session.writer is None or session.writer.terminal:
        on_expire(session.session_id)
        raise BackchannelOrphanedError(
            f"sampling response missing for session {session.session_id}; "
            "backchannel likely orphaned, re-establish session"
        )


# Minimal demonstration of the failure and the guardrail.
async def demo() -> None:
    s = Session(session_id="S")
    w1 = SSEWriter("R1")
    s.attach(w1)

    # Simulate LB idle drop.
    w1.closed = True

    # Resume: new stream, but a naive server leaves dispatch on W1.
    w2 = SSEWriter("R2")
    s.resume(w2, last_event_id=0)

    # Guardrail: emit now targets W2 because attach() rebound dispatch.
    s.emit("notifications/resources/updated")  # ok

    # Naive server path (the bug) would have called w1.write directly:
    try:
        w1.write("sampling/createMessage")
    except BackchannelOrphanedError as e:
        print(f"guardrail caught orphaned emit: {e}")

    # Reconciliation barrier after resume.
    reconcile(s, resources=["file:///watched"], reader=lambda r: "fresh-content")
    assert s.cache["file:///watched"] == "fresh-content"


if __name__ == "__main__":
    asyncio.run(demo())
