# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-pin-mcp-streamable-http-sessions-to-a-single-replica-before-backpressure-can-be-trusted.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-pin-mcp-streamable-http-sessions-to-a-single-replica-before-backpressure-can-be-trusted.warrant.json
# Markdown SHA-256:   7c41721b648f6f343c119de93a9f5296b94fa531a7af1feae3ed017802065377
# Code AST SHA-256:   3753871a49854421de7fd1e9a251c1393b60d4ed5c86b87898d4f3b2475b11cf
# Verified Classes:   SessionAffinityError, SessionState, Replica
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SessionAffinityError(RuntimeError):
    """Raised when a session's POST and GET streams resolve to different replicas
    without an authoritative directory or drain signal to reconcile them."""


@dataclass
class SessionState:
    session_id: str
    owner_replica: str
    get_stream_attached: bool = False
    get_stream_replica: Optional[str] = None
    pending_events: int = 0
    drain_rate: float = 0.0
    hard_cap: int = 10_000


@dataclass
class Replica:
    name: str
    sessions: dict = field(default_factory=dict)


def route_get_stream(session: SessionState, replica: Replica, directory_authoritative: bool) -> None:
    """Attach a GET SSE stream to a replica, enforcing the affinity invariant."""
    if session.session_id not in replica.sessions:
        # Replica does not own this session. Lazy shadow creation is forbidden.
        if not directory_authoritative:
            raise SessionAffinityError(
                f"replica {replica.name} received GET for session {session.session_id} "
                f"owned by {session.owner_replica}; directory is non-authoritative so "
                f"a shadow session would diverge silently"
            )
        # Authoritative directory: must redirect to owner, not create a shadow.
        raise SessionAffinityError(
            f"replica {replica.name} is not the owner of session {session.session_id}; "
            f"redirect to {session.owner_replica} via 421 Misdirected Request"
        )

    if session.get_stream_attached and session.get_stream_replica != replica.name:
        raise SessionAffinityError(
            f"session {session.session_id} already has GET stream on "
            f"{session.get_stream_replica}; second attach on {replica.name} "
            f"would split the event queue"
        )

    session.get_stream_attached = True
    session.get_stream_replica = replica.name


def apply_backpressure(session: SessionState, replica: Replica, cross_replica_drain: Optional[float]) -> bool:
    """Return True if the session may accept another request under backpressure."""
    if session.pending_events >= session.hard_cap:
        # At cap; only proceed if the consumer is draining.
        effective_drain = cross_replica_drain if cross_replica_drain is not None else session.drain_rate
        if effective_drain <= 0.0:
            raise SessionAffinityError(
                f"session {session.session_id} at hard cap ({session.hard_cap}) with "
                f"zero drain signal; consumer may be on {session.get_stream_replica} "
                f"while producer is on {replica.name}"
            )
        return True
    return True


def issue_request(session: SessionState, replica: Replica, directory_authoritative: bool,
                  cross_replica_drain: Optional[float]) -> None:
    if session.session_id not in replica.sessions:
        raise SessionAffinityError(
            f"POST for session {session.session_id} landed on non-owner {replica.name}"
        )
    apply_backpressure(session, replica, cross_replica_drain)
    session.pending_events += 1
    if session.get_stream_replica != replica.name and session.get_stream_replica is not None:
        # Event will be queued on a replica whose GET stream is elsewhere.
        if cross_replica_drain is None:
            raise SessionAffinityError(
                f"session {session.session_id}: event queued on {replica.name} but GET "
                f"stream is on {session.get_stream_replica} with no cross-replica drain "
                f"counter; queue will grow unobserved"
            )
