"""Carry TCP across the agent sandbox's empty network namespace, over a bound unix socket. The agent sandbox runs with `--net --network=none` (see `solve.py`): it keeps a loopback interface but has no route anywhere else, so the only way in or out is a unix socket bound from the host. `scripts/x2p_anthropic_shim.py` already uses that trick for Anthropic traffic; this is the same idea for the local vLLM judge pool (`scripts/ptb_judge_pool.sbatch`), which the two LLM-graded benchmarks need in order to score anything. Two halves of one pipe, plus a degenerate third mode: host listens on a unix socket, dials the pool over TCP (runs on the compute node) sandbox listens on loopback, dials that unix socket (runs inside the sandbox) balance listens on loopback, dials the pool over TCP (no namespace to cross) `balance` is for the evaluation sandbox, which runs without `--net` and so shares the host's network namespace: nothing has to be smuggled across, but the pool still fronts N independent vLLM servers with no load balancer of its own, and a grading pass is thousands of requests. Unlike the Anthropic shim this does not parse HTTP. It pumps bytes, so keep-alive, chunked responses and SSE streams pass through untouched -- worth having when a grading pass is thousands of requests and a subtly wrong re-framing would only show up as a hang. python3 scripts/ptb_uds_bridge.py host --socket /path/judge.sock --targets h1:8000,h1:8001 python3 scripts/ptb_uds_bridge.py sandbox --socket /run/ptb_judge.sock # prints its port python3 scripts/ptb_uds_bridge.py balance --targets h1:8000,h1:8001 # prints its port """ import argparse import itertools import os import socket import socketserver import sys import threading def pump(src: socket.socket, dst: socket.socket) -> None: """Copy until EOF, then half-close so the peer sees the end of the stream.""" try: while chunk := src.recv(65536): dst.sendall(chunk) except OSError: pass finally: try: dst.shutdown(socket.SHUT_WR) except OSError: pass def splice(a: socket.socket, b: socket.socket) -> None: """Run both directions until each has seen EOF.""" upward = threading.Thread(target=pump, args=(a, b), daemon=True) upward.start() pump(b, a) upward.join() class ThreadingUnixServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): daemon_threads = True allow_reuse_address = True class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): daemon_threads = True allow_reuse_address = True def pool_handler(targets: list[tuple[str, int]]) -> type: """A handler that hands each connection to the next replica in turn. The pool fronts N independent vLLM servers with no load balancer of its own, so without this every grading call would queue on replica 0 and the other GPUs would idle. """ rotation = itertools.cycle(targets) lock = threading.Lock() class Handler(socketserver.BaseRequestHandler): def handle(self) -> None: with lock: host, port = next(rotation) try: upstream = socket.create_connection((host, port), timeout=900) except OSError as error: print(f"judge bridge: cannot reach {host}:{port}: {error}", file=sys.stderr, flush=True) return with upstream: splice(self.request, upstream) return Handler def host_side(socket_path: str, targets: list[tuple[str, int]]) -> None: if os.path.exists(socket_path): os.unlink(socket_path) server = ThreadingUnixServer(socket_path, pool_handler(targets)) os.chmod(socket_path, 0o666) # the sandbox runs as a different uid print(f"judge bridge: {socket_path} -> {', '.join(f'{h}:{p}' for h, p in targets)}", flush=True) try: server.serve_forever() finally: server.server_close() if os.path.exists(socket_path): os.unlink(socket_path) def balance_side(port: int, targets: list[tuple[str, int]]) -> None: server = ThreadingTCPServer(("127.0.0.1", port), pool_handler(targets)) print(server.server_address[1], flush=True) # the caller reads the port from stdout server.serve_forever() def sandbox_side(socket_path: str, port: int) -> None: class Handler(socketserver.BaseRequestHandler): def handle(self) -> None: upstream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) upstream.settimeout(900) try: upstream.connect(socket_path) except OSError as error: print(f"judge shim: cannot reach {socket_path}: {error}", file=sys.stderr, flush=True) upstream.close() return with upstream: splice(self.request, upstream) server = ThreadingTCPServer(("127.0.0.1", port), Handler) print(server.server_address[1], flush=True) # the caller reads the port from stdout server.serve_forever() def parse_targets(raw: str) -> list[tuple[str, int]]: targets = [] for item in raw.replace(",", " ").split(): host, _, port = item.rpartition(":") if not host or not port.isdigit(): sys.exit(f"Bad target {item!r}: expected host:port.") targets.append((host, int(port))) if not targets: sys.exit("No targets given.") return targets def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("side", choices=("host", "sandbox", "balance")) parser.add_argument("--socket", help="host/sandbox mode: the unix socket to listen on or dial") parser.add_argument("--targets", help="host/balance mode: comma-separated host:port of the pool replicas") parser.add_argument("--port", type=int, default=0, help="sandbox/balance mode: 0 picks a free port") args = parser.parse_args() if args.side in ("host", "balance") and not args.targets: sys.exit(f"{args.side} mode needs --targets.") if args.side in ("host", "sandbox") and not args.socket: sys.exit(f"{args.side} mode needs --socket.") if args.side == "host": host_side(args.socket, parse_targets(args.targets)) elif args.side == "balance": balance_side(args.port, parse_targets(args.targets)) else: sandbox_side(args.socket, args.port) if __name__ == "__main__": main()