Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(paper-trade): isolate strategy worker input from MCP stdio

Haozhe Wufe80b5212818
diff --git a/agent/src/tools/paper_trade/strategy_exec.py b/agent/src/tools/paper_trade/strategy_exec.py
index 3403d96ed..ee7f852ca 100644
--- a/agent/src/tools/paper_trade/strategy_exec.py
+++ b/agent/src/tools/paper_trade/strategy_exec.py
@@ -69,7 +69,6 @@ from __future__ import annotations
import ast
import logging
import math
-import multiprocessing
import sys
import types
from dataclasses import dataclass, field
@@ -83,6 +82,7 @@ from .engine import (
EngineError, MatchOutcome, build_day_plan, error_outcome, readiness_error, run_day_loop)
from .limits_cn_a import CnALimitsClient
from .schema import AccountState, Order, PaperTradeStepRequest
+from .strategy_process import start_strategy_process
__all__ = [
"DEFAULT_DAY_TIMEOUT_SECONDS", "StrategyContext", "StrategyContractError", "StrategyOrder",
@@ -424,18 +424,14 @@ def _execute_days(
"days": days,
"symbols": ctx_symbols,
}
- # spawn (never fork): forking a threaded MCP server is POSIX-undefined
- # behavior (#1355 lesson); spawn is the only start method on Windows and
- # the default on macOS, pinned here so Linux behaves identically.
- context = multiprocessing.get_context("spawn")
- parent_conn, child_conn = context.Pipe(duplex=True)
- proc = context.Process(target=_child_main, args=(child_conn, payload), daemon=True)
- started = False
+ # A fresh interpreter with private stdin/stdout pipes never inherits the
+ # MCP transport's blocked stdin read (Windows #2089). Never fork a threaded
+ # server, and never run a user's strategy in the server process.
+ try:
+ proc, parent_conn = start_strategy_process(payload)
+ except OSError as exc:
+ raise _StrategyDayFailure(days[0], StrategyProcessError.__name__) from exc
try:
- proc.start()
- started = True
- # Close the parent's duplicate child endpoint so child death reads as EOF.
- child_conn.close()
msg = _recv(parent_conn, max(_STARTUP_TIMEOUT_SECONDS, day_timeout))
if msg is _TIMEOUT:
raise _StrategyDayFailure(days[0], None)
@@ -462,13 +458,10 @@ def _execute_days(
return tuple(StrategyOrder(**item) for item in msg[2])
return run_loop(order_provider=provide_orders)
finally:
- if started:
- if proc.is_alive():
- proc.kill() # SIGKILL: really interrupts a hung day (no cooperative unwind)
- proc.join(_JOIN_TIMEOUT_SECONDS)
- proc.close()
+ if proc.poll() is None:
+ proc.kill() # Really interrupts a hung day; no cooperative unwind.
+ proc.wait(timeout=_JOIN_TIMEOUT_SECONDS)
parent_conn.close()
- child_conn.close()
def _resolve_timeout(timeout_seconds: float | None) -> float:
diff --git a/agent/src/tools/paper_trade/strategy_process.py b/agent/src/tools/paper_trade/strategy_process.py
new file mode 100644
index 000000000..0e4a2c679
--- /dev/null
+++ b/agent/src/tools/paper_trade/strategy_process.py
@@ -0,0 +1,108 @@
+"""Private strategy IPC using fresh pipes, never the MCP server's stdin.
+
+The existing strategy sandbox still validates and executes the source. Pickle
+is private IPC between these two processes, as with the previous Connection;
+it is never accepted from a client or a persisted file.
+"""
+
+from __future__ import annotations
+
+import pickle
+import queue
+import subprocess
+import sys
+import threading
+from typing import Any
+
+
+class StrategyConnection:
+ """Connection-compatible messages with a bounded parent-side poll."""
+
+ def __init__(self, reader, writer, *, background: bool = False):
+ self.reader = reader
+ self.writer = writer
+ self.messages: queue.Queue = queue.Queue()
+ self.pending = None
+ self.thread = None
+ if background:
+ self.thread = threading.Thread(target=self._read, name="paper-strategy-ipc", daemon=True)
+ self.thread.start()
+
+ def _read(self) -> None:
+ try:
+ while True:
+ self.messages.put((True, pickle.load(self.reader)))
+ except Exception:
+ self.messages.put((False, None))
+
+ def send(self, message: Any) -> None:
+ pickle.dump(message, self.writer, protocol=pickle.HIGHEST_PROTOCOL)
+ self.writer.flush()
+
+ def poll(self, timeout: float) -> bool:
+ if self.pending is None:
+ try:
+ self.pending = self.messages.get(timeout=timeout)
+ except queue.Empty:
+ return False
+ return True
+
+ def recv(self) -> Any:
+ if self.thread is None:
+ return pickle.load(self.reader)
+ success, message = self.pending if self.pending is not None else self.messages.get()
+ self.pending = None
+ if not success:
+ raise EOFError("strategy process closed its protocol")
+ return message
+
+ def close(self) -> None:
+ # Caller reaps the child first, releasing any blocked pipe read.
+ if self.thread is not None:
+ self.thread.join(timeout=1.0)
+ for stream in (self.writer, self.reader):
+ try:
+ stream.close()
+ except OSError:
+ pass
+
+
+def start_strategy_process(payload: dict[str, Any]):
+ """Start an isolated interpreter and deliver the validated source snapshot.
+
+ Args:
+ payload: Source, filename, days and universe already checked by caller.
+
+ Returns:
+ The child process and its private bidirectional message connection.
+ """
+ # Preserve import paths for editable installs and standalone MCP hosts.
+ # -B keeps research execution from writing bytecode into a caller's cwd.
+ bootstrap = (
+ f"import sys; sys.path[:] = {sys.path!r}; "
+ "from src.tools.paper_trade.strategy_process import worker_main; worker_main()"
+ )
+ process = subprocess.Popen(
+ [sys.executable, "-B", "-u", "-c", bootstrap],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
+ close_fds=True,
+ )
+ connection = StrategyConnection(process.stdout, process.stdin, background=True)
+ try:
+ connection.send(payload)
+ except BaseException:
+ process.kill()
+ process.wait()
+ connection.close()
+ raise
+ return process, connection
+
+
+def worker_main() -> None:
+ """Keep strategy/import prints out of the binary protocol stream."""
+ connection = StrategyConnection(sys.stdin.buffer, sys.stdout.buffer)
+ sys.stdout = sys.stderr
+ payload = connection.recv()
+ from .strategy_exec import _child_main
+
+ _child_main(connection, payload)
diff --git a/agent/tests/test_paper_trade_process_transport.py b/agent/tests/test_paper_trade_process_transport.py
new file mode 100644
index 000000000..2a9fb86ff
--- /dev/null
+++ b/agent/tests/test_paper_trade_process_transport.py
@@ -0,0 +1,50 @@
+"""Private worker pipes coexist with an open, blocked MCP-like stdin."""
+
+import queue
+import subprocess
+import sys
+import threading
+
+
+def test_worker_starts_while_host_stdin_is_blocked_and_prints_do_not_corrupt_ipc():
+ driver = r'''
+import sys, threading
+from src.tools.paper_trade.strategy_process import start_strategy_process
+blocked = threading.Thread(target=lambda: sys.stdin.buffer.read(1), daemon=True)
+blocked.start()
+payload = {
+ "source": "print('strategy output')\nclass SignalEngine:\n def generate_signals(self, ctx, trade_date): return []\n",
+ "filename": "synthetic.py", "days": (), "symbols": (),
+}
+process, connection = start_strategy_process(payload)
+try:
+ assert connection.poll(20), 'no worker startup'
+ assert connection.recv() == ('ready',)
+ assert connection.poll(5)
+ assert connection.recv() == ('done',)
+ process.wait(timeout=5)
+finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=5)
+ connection.close()
+assert not connection.thread.is_alive(), 'IPC reader leaked'
+print('private-ipc-ok', flush=True)
+blocked.join(timeout=20)
+assert not blocked.is_alive()
+'''
+ bootstrap = f"import sys; sys.path[:] = {sys.path!r}; exec({driver!r})"
+ host = subprocess.Popen([sys.executable, "-B", "-u", "-c", bootstrap],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ received = queue.Queue()
+ reader = threading.Thread(target=lambda: received.put(host.stdout.readline()), daemon=True)
+ reader.start()
+ try:
+ assert received.get(timeout=30) == b"private-ipc-ok\n"
+ _, stderr = host.communicate(input=b"x", timeout=10)
+ assert host.returncode == 0, stderr.decode(errors="replace")
+ finally:
+ if host.poll() is None:
+ host.kill()
+ host.communicate(timeout=5)
+ reader.join(timeout=1)