# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-mcp-tool-sandbox-leaks-state-through-a-reused-egress-socket-during-a-mid-task-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-mcp-tool-sandbox-leaks-state-through-a-reused-egress-socket-during-a-mid-task-retry.warrant.json
# Markdown SHA-256:   9b0fb02d3e38f17543475e21d81404de46a66c834eedefc6361ea8f7fa2627a7
# Code AST SHA-256:   a86668f5dce70d5b87645e7538023c03006c602961d03450126e14862c6a5446
# Verified Classes:   EgressReuseViolation, EgressProxy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EgressReuseViolation(RuntimeError):
    """Raised when a tool-call retry would reuse an egress connection
    that still carries state from an aborted attempt."""
    pass


class EgressProxy:
    def __init__(self):
        # connection_id -> {"nonce": str | None, "poisoned": bool, "drained": bool}
        self._conns = {}

    def mark_aborted(self, connection_id: str, attempt_nonce: str) -> None:
        conn = self._conns.setdefault(connection_id, {"nonce": None, "poisoned": False, "drained": False})
        # The attempt was killed mid-flight; any buffered upstream response
        # belongs to this nonce and must never be delivered to another attempt.
        conn["poisoned"] = True
        conn["drained"] = False
        conn["nonce"] = attempt_nonce

    def confirm_drained(self, connection_id: str) -> None:
        conn = self._conns.get(connection_id)
        if conn is None:
            raise EgressReuseViolation(f"unknown connection {connection_id}")
        conn["drained"] = True
        conn["poisoned"] = False
        conn["nonce"] = None

    def acquire_for_retry(self, connection_id: str, retry_nonce: str) -> str:
        conn = self._conns.get(connection_id)
        if conn is None:
            # Fresh connection; safe.
            self._conns[connection_id] = {"nonce": retry_nonce, "poisoned": False, "drained": True}
            return connection_id
        if conn["poisoned"] and not conn["drained"]:
            # Invariant: a retry must not share a channel with the attempt
            # it is retrying. Fail closed rather than replay a stale response.
            raise EgressReuseViolation(
                f"refusing retry on connection {connection_id}: "
                f"aborted attempt nonce={conn['nonce']} not drained; "
                f"retry nonce={retry_nonce} would inherit buffered state"
            )
        if conn["nonce"] is not None and conn["nonce"] != retry_nonce:
            raise EgressReuseViolation(
                f"nonce mismatch on {connection_id}: expected {conn['nonce']}, got {retry_nonce}"
            )
        conn["nonce"] = retry_nonce
        return connection_id


def issue_retry(proxy: EgressProxy, connection_id: str, retry_nonce: str) -> str:
    try:
        return proxy.acquire_for_retry(connection_id, retry_nonce)
    except EgressReuseViolation:
        # Surface to the agent loop as a hard failure; do not silently
        # open a new socket without recording why the old one was tainted.
        raise EgressReuseViolation(
            f"retry on {connection_id} blocked; agent must either "
            f"drain the aborted attempt or open a fresh connection"
        )
