# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-multiplexes-mcp-servers-over-one-http-stream-and-a-mid-stream-tool-result-arrives-after-the-transport-has-already-been-r.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-multiplexes-mcp-servers-over-one-http-stream-and-a-mid-stream-tool-result-arrives-after-the-transport-has-already-been-r.warrant.json
# Markdown SHA-256:   0e1542efd3dda83e93a44cec9e2bddb9df7658872a46b8eaff3d19ecd6b46e04
# Code AST SHA-256:   0c815df05b3be29a6591efbd8737f15b81f1b7bda60f56a683b619bd1f73519a
# Verified Classes:   TransportReapError, RequestState, InFlightRequest, MultiplexedTransport
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Optional


class TransportReapError(RuntimeError):
    """Raised when a multiplexed transport is reaped with live in-flight requests."""
    pass


class RequestState(Enum):
    IN_FLIGHT = "in_flight"
    RESOLVED = "resolved"
    SYNTHETIC_CLOSED = "synthetic_closed"


@dataclass
class InFlightRequest:
    server: str
    request_id: int
    tool_name: str
    idempotent: bool
    state: RequestState = RequestState.IN_FLIGHT
    idempotency_key: Optional[str] = None


@dataclass
class MultiplexedTransport:
    conn_id: int
    in_flight: Dict[int, InFlightRequest] = field(default_factory=dict)
    dead: bool = False

    def reap(self) -> list:
        """
        Reap the transport. Every in-flight request must transition to a
        synthetic terminal state. A request that is still IN_FLIGHT after
        reap is a continuity violation: the runtime will retry it without
        an idempotency key and may duplicate side effects.
        """
        self.dead = True
        closed = []
        for req in self.in_flight.values():
            if req.state is RequestState.IN_FLIGHT:
                req.state = RequestState.SYNTHETIC_CLOSED
                closed.append(req)
        for req in closed:
            if not req.idempotent and req.idempotency_key is None:
                # Non-idempotent request died on the wire with no dedup token.
                # Retrying would duplicate the side effect; the only safe
                # action is to surface a hard failure to the planner.
                raise TransportReapError(
                    f"conn={self.conn_id} reaped with non-idempotent "
                    f"in-flight request server={req.server} "
                    f"req={req.request_id} tool={req.tool_name}; "
                    f"retry would duplicate side effect"
                )
        return closed

    def resolve(self, request_id: int) -> None:
        req = self.in_flight.get(request_id)
        if req is None:
            raise TransportReapError(
                f"conn={self.conn_id} resolve for unknown req={request_id}"
            )
        if self.dead:
            # Late frame arriving after reap. Dropping it silently is the
            # observed bug; raising forces the caller to reconcile.
            raise TransportReapError(
                f"conn={self.conn_id} late result for req={request_id} "
                f"arrived after reap; server may have already executed "
                f"tool={req.tool_name}"
            )
        req.state = RequestState.RESOLVED


def dispatch(t: MultiplexedTransport, req: InFlightRequest) -> None:
    if t.dead:
        raise TransportReapError(
            f"conn={t.conn_id} dispatch on dead transport req={req.request_id}"
        )
    t.in_flight[req.request_id] = req


# Trigger trace: slow search call holds the read loop, fast code call
# resolves server-side but its frame is behind the slow response.
t = MultiplexedTransport(conn_id=7)
dispatch(t, InFlightRequest("search", 41, "search.query", idempotent=True))
dispatch(t, InFlightRequest("code", 42, "code.execute", idempotent=False))

# Idle-read deadline fires on the slow search call; reaper runs.
# The non-idempotent code.execute is still IN_FLIGHT -> raises, preventing
# the duplicate execution that the naive retry policy would cause.
try:
    t.reap()
except TransportReapError as e:
    # Correct behavior: planner sees a hard failure for req=42, not a
    # retryable transport error, and does not re-execute the script.
    print(f"guardrail fired: {e}")
