Files
ai-agent/backend/test_plugin_zygote.py

406 lines
15 KiB
Python

"""Tests and benchmark for the warm pre-forked Python zygote worker pool."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import json
import os
import pathlib
import signal
import stat
import subprocess
import sys
import tempfile
import threading
import time
from types import SimpleNamespace
import pytest
_TMP_KEY_DIR = tempfile.mkdtemp(prefix="aia-test-key-")
os.environ.setdefault("TOOLS_TOKEN_KEY", os.path.join(_TMP_KEY_DIR, "tools-token.key"))
from plugins import runner, zygote # noqa: E402
from plugins.runner import ActionError, run_script # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
@pytest.fixture(autouse=True, scope="module")
def _cleanup_zygote_at_end():
yield
zygote.shutdown()
def _deps():
return SimpleNamespace(users=SimpleNamespace(get=lambda _u: None))
def _install_plugin(
root: pathlib.Path,
files: dict[str, str],
*,
pid: str = "ztest",
actions: dict[str, dict] | None = None,
) -> tuple[PluginStore, dict]:
src = root / "src"
src.mkdir(parents=True, exist_ok=True)
if actions is None:
actions = {
pathlib.Path(rel).stem: {"script": rel, "timeoutSec": 10}
for rel in files
if rel.endswith(".py") or rel.endswith(".sh")
}
manifest = {
"schema": 1,
"id": pid,
"name": f"Plugin {pid}",
"actions": actions,
}
(src / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
for rel, body in files.items():
p = src / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(body, encoding="utf-8")
if rel.endswith(".sh"):
p.chmod(0o755)
store = PluginStore(root / "data")
store.install(OWNER_UID, str(src), is_owner=True, approve=True)
return store, store.get_raw(OWNER_UID, pid)
def test_normal_execution_exit_codes_errors_and_large_stdin(tmp_path):
store, rec = _install_plugin(
tmp_path,
{
"handlers/echo.py": (
"import json, sys\n"
"data = json.loads(sys.stdin.read() or '{}')\n"
"print(json.dumps({'ok': True, 'len': len(data.get('blob', '')), 'msg': data.get('msg')}))\n"
),
"handlers/exit2.py": "import sys\nsys.stderr.write('bad input\\n')\nsys.exit(2)\n",
"handlers/exit3.py": "import sys\nsys.stderr.write('fatal\\n')\nsys.exit(3)\n",
"handlers/exit_str.py": "import sys\nsys.exit('custom exit msg')\n",
"handlers/boom.py": "raise RuntimeError('kaboom')\n",
"handlers/structured.py": (
"import json, sys\n"
"print(json.dumps({'_error': {'status': 404, 'kind': 'not_found', 'message': 'missing item'}}))\n"
"sys.exit(1)\n"
),
"handlers/shell.sh": "#!/bin/sh\nprintf '{\"sh\": true}'\n",
},
)
big_blob = "x" * 131072 # > 64 KB pipe buffer to test non-blocking stdin write
out = run_script(
_deps(), store, OWNER_UID, rec, "handlers/echo.py",
payload={"msg": "héllo 🌍", "blob": big_blob},
)
assert out == {"ok": True, "len": len(big_blob), "msg": "héllo 🌍"}
assert zygote.stats()["alive"] is True
assert zygote.stats()["zygote_calls"] >= 1
with pytest.raises(ActionError) as exc2:
run_script(_deps(), store, OWNER_UID, rec, "handlers/exit2.py")
assert exc2.value.status == 422
assert "bad input" in exc2.value.message
with pytest.raises(ActionError) as exc3:
run_script(_deps(), store, OWNER_UID, rec, "handlers/exit3.py")
assert exc3.value.status == 500
assert "fatal" in exc3.value.message
with pytest.raises(ActionError) as exc_str:
run_script(_deps(), store, OWNER_UID, rec, "handlers/exit_str.py")
assert exc_str.value.status == 422
assert "custom exit msg" in exc_str.value.message
with pytest.raises(ActionError) as exc_boom:
run_script(_deps(), store, OWNER_UID, rec, "handlers/boom.py")
assert exc_boom.value.status == 422
assert "RuntimeError: kaboom" in exc_boom.value.message
with pytest.raises(ActionError) as exc_struct:
run_script(_deps(), store, OWNER_UID, rec, "handlers/structured.py")
assert exc_struct.value.status == 404
assert exc_struct.value.kind == "not_found"
assert exc_struct.value.message == "missing item"
# Non-.py script still executes cleanly via subprocess.run
sh_out = run_script(_deps(), store, OWNER_UID, rec, "handlers/shell.sh")
assert sh_out == {"sh": True}
def test_strict_isolation_and_no_cross_run_leakage(tmp_path, monkeypatch):
zygote.shutdown()
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-super-secret-host-key")
monkeypatch.setenv("SIDECAR_TOKEN", "sidecar-secret-token")
store, rec = _install_plugin(
tmp_path,
{
"cwd_helper.py": "VALUE = 'from-cwd'\n",
"handlers/local_helper.py": "LOCAL = 'from-script-dir'\n",
"handlers/mutate.py": (
"import json, os, sys\n"
"import cwd_helper\n"
"import local_helper\n"
"orig_sys_path0 = sys.path[0]\n"
"# Attempt to pollute globals/env/sys.path for subsequent runs\n"
"os.environ['LEAKED_ENV'] = 'should-not-leak'\n"
"json.dumps = lambda *a, **k: 'HIJACKED'\n"
"sys.path.insert(0, '/tmp/evil-path')\n"
"open('/dev/null').close()\n"
"# Verify backend is unimportable\n"
"try:\n"
" import plugins\n"
" has_backend = True\n"
"except ImportError:\n"
" has_backend = False\n"
"fd_list = sorted(int(x) for x in os.listdir('/proc/self/fd')) if os.path.isdir('/proc/self/fd') else []\n"
"__import__('sys').stdout.write(json.JSONEncoder().encode({\n"
" 'cwd': os.getcwd(),\n"
" 'sys_path0': orig_sys_path0,\n"
" 'cwd_helper': cwd_helper.VALUE,\n"
" 'local_helper': local_helper.LOCAL,\n"
" 'has_anthropic': 'ANTHROPIC_API_KEY' in os.environ,\n"
" 'has_sidecar': 'SIDECAR_TOKEN' in os.environ,\n"
" 'has_backend': has_backend,\n"
" 'plugin_id': os.environ.get('AIA_PLUGIN_ID'),\n"
" 'argv0': sys.argv[0],\n"
" 'fds': fd_list,\n"
"}) + '\\n')\n"
),
"handlers/inspect.py": (
"import json, os, sys\n"
"print(json.dumps({\n"
" 'leaked_env': 'LEAKED_ENV' in os.environ,\n"
" 'evil_in_path': '/tmp/evil-path' in sys.path,\n"
" 'has_anthropic': 'ANTHROPIC_API_KEY' in os.environ,\n"
" 'plugin_id': os.environ.get('AIA_PLUGIN_ID'),\n"
"}))\n"
),
},
)
out1 = run_script(_deps(), store, OWNER_UID, rec, "handlers/mutate.py")
plugin_root = str(pathlib.Path(rec["dir"]).resolve())
assert out1["cwd"] == plugin_root
assert out1["sys_path0"] == plugin_root
assert out1["cwd_helper"] == "from-cwd"
assert out1["local_helper"] == "from-script-dir"
assert out1["has_anthropic"] is False
assert out1["has_sidecar"] is False
assert out1["has_backend"] is False
assert out1["plugin_id"] == "ztest"
assert out1["argv0"].endswith("/handlers/mutate.py")
# Child only sees fds 0, 1, 2 (plus the temporary /proc/self/fd opendir fd while listing)
assert set(out1["fds"]).issubset({0, 1, 2, 3, 4})
# Verify the zygote process itself has ZERO host secrets and locked-down socket perms
st = zygote.stats()
assert st["alive"] is True
z_pid = st["pid"]
proc_env = pathlib.Path(f"/proc/{z_pid}/environ")
if proc_env.exists():
raw_env = proc_env.read_bytes()
assert b"ANTHROPIC_API_KEY" not in raw_env
assert b"SIDECAR_TOKEN" not in raw_env
assert b"sk-super-secret-host-key" not in raw_env
sock_dir = zygote._state.sock_dir
sock_path = zygote._state.sock_path
assert sock_dir and sock_path
assert stat.S_IMODE(os.stat(sock_dir).st_mode) == 0o700
assert stat.S_IMODE(os.stat(sock_path).st_mode) == 0o600
# Run 2 must see a pristine interpreter and environment
out2 = run_script(_deps(), store, OWNER_UID, rec, "handlers/inspect.py")
assert out2 == {
"leaked_env": False,
"evil_in_path": False,
"has_anthropic": False,
"plugin_id": "ztest",
}
def test_timeout_kills_process_group_including_grandchild(tmp_path):
pid_file = tmp_path / "grandchild.pid"
store, rec = _install_plugin(
tmp_path,
{
"handlers/slow.py": (
"import pathlib, subprocess, sys, time\n"
f"p = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])\n"
f"pathlib.Path({str(pid_file)!r}).write_text(str(p.pid))\n"
"p.wait()\n"
),
},
)
with pytest.raises(ActionError) as exc:
run_script(_deps(), store, OWNER_UID, rec, "handlers/slow.py", timeout_sec=1)
assert exc.value.status == 504
assert "timed out" in exc.value.message
# Give the kernel a moment to finish reaping, then verify grandchild is dead.
grandchild_pid = int(pid_file.read_text())
deadline = time.monotonic() + 2.0
alive = True
while time.monotonic() < deadline:
try:
os.kill(grandchild_pid, 0)
time.sleep(0.02)
except ProcessLookupError:
alive = False
break
assert alive is False, f"grandchild PID {grandchild_pid} survived timeout SIGKILL"
def test_concurrent_calls_parallel_no_corruption(tmp_path):
store, rec = _install_plugin(
tmp_path,
{
"handlers/worker.py": (
"import json, os, sys, time\n"
"p = json.loads(sys.stdin.read())\n"
"time.sleep(0.08)\n"
"print(json.dumps({'i': p['i'], 'pid': os.getpid(), 'pad': 'z' * 4096}))\n"
),
},
)
# Warm zygote first so startup time doesn't skew concurrency check
warm = run_script(_deps(), store, OWNER_UID, rec, "handlers/worker.py", payload={"i": -1})
assert warm["i"] == -1
t0 = time.monotonic()
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(
pool.map(
lambda i: run_script(_deps(), store, OWNER_UID, rec, "handlers/worker.py", payload={"i": i}),
range(10),
)
)
elapsed = time.monotonic() - t0
assert [r["i"] for r in results] == list(range(10))
assert all(r["pad"] == "z" * 4096 for r in results)
assert len({r["pid"] for r in results}) == 10
# 10 x 0.08s in parallel must finish well under sequential 0.80s
assert elapsed < 0.65, f"concurrent calls appeared serialized: {elapsed:.3f}s"
def test_crash_recovery_idle_and_midflight(tmp_path):
store, rec = _install_plugin(
tmp_path,
{
"handlers/ping.py": "import json, sys\nprint(json.dumps({'ok': True, 'n': json.loads(sys.stdin.read()).get('n')}))\n",
"handlers/sleep.py": "import json, time\ntime.sleep(0.35)\nprint(json.dumps({'slept': True}))\n",
},
)
assert run_script(_deps(), store, OWNER_UID, rec, "handlers/ping.py", payload={"n": 1})["n"] == 1
old_pid = zygote.stats()["pid"]
assert old_pid is not None
# 1. Kill zygote while idle -> next call transparently restarts it
os.kill(old_pid, signal.SIGKILL)
for _ in range(50):
try:
os.waitpid(old_pid, os.WNOHANG)
except ChildProcessError:
break
if not zygote.stats()["alive"]:
break
time.sleep(0.01)
res2 = run_script(_deps(), store, OWNER_UID, rec, "handlers/ping.py", payload={"n": 2})
assert res2 == {"ok": True, "n": 2}
mid_pid = zygote.stats()["pid"]
assert mid_pid is not None and mid_pid != old_pid
assert zygote.stats()["restarts"] >= 1
# 2. Kill zygote mid-flight during a running call -> both mid-flight and next call succeed
def kill_shortly():
time.sleep(0.08)
try:
os.kill(mid_pid, signal.SIGKILL)
except ProcessLookupError:
pass
killer = threading.Thread(target=kill_shortly)
killer.start()
mid_res = run_script(_deps(), store, OWNER_UID, rec, "handlers/sleep.py")
killer.join()
assert mid_res == {"slept": True}
after_res = run_script(_deps(), store, OWNER_UID, rec, "handlers/ping.py", payload={"n": 3})
assert after_res == {"ok": True, "n": 3}
assert zygote.stats()["pid"] != mid_pid
def test_disable_flag_and_subprocess_monkeypatch_fallback(tmp_path, monkeypatch):
store, rec = _install_plugin(
tmp_path,
{"handlers/ok.py": "import json\nprint(json.dumps({'from': 'script'}))\n"},
)
before_fb = zygote.stats()["fallback_calls"]
monkeypatch.setenv("AIA_PLUGIN_ZYGOTE", "0")
out = run_script(_deps(), store, OWNER_UID, rec, "handlers/ok.py")
assert out == {"from": "script"}
assert zygote.stats()["fallback_calls"] == before_fb + 1
# Verify monkeypatching runner.subprocess.run still intercepts .py scripts
monkeypatch.delenv("AIA_PLUGIN_ZYGOTE", raising=False)
seen = []
def fake_run(cmd, **_kwargs):
seen.append(cmd)
return subprocess.CompletedProcess(cmd, 0, stdout=b'{"mocked": true}', stderr=b"")
monkeypatch.setattr(runner.subprocess, "run", fake_run)
mocked_out = run_script(_deps(), store, OWNER_UID, rec, "handlers/ok.py")
assert mocked_out == {"mocked": True}
assert len(seen) == 1
def test_benchmark_10_calls_zygote_vs_subprocess(tmp_path):
store, rec = _install_plugin(
tmp_path,
{
"handlers/bench.py": (
"import json, os, pathlib, re, sqlite3, sys, urllib.parse\n"
"payload = json.loads(sys.stdin.read() or '{}')\n"
"print(json.dumps({'ok': True, 'i': payload.get('i')}))\n"
),
},
)
# Warm up zygote once before timing 10 calls
run_script(_deps(), store, OWNER_UID, rec, "handlers/bench.py", payload={"i": -1})
t_z0 = time.perf_counter()
for i in range(10):
res = run_script(_deps(), store, OWNER_UID, rec, "handlers/bench.py", payload={"i": i})
assert res["i"] == i
zygote_s = time.perf_counter() - t_z0
orig = os.environ.get("AIA_PLUGIN_ZYGOTE")
os.environ["AIA_PLUGIN_ZYGOTE"] = "0"
try:
t_s0 = time.perf_counter()
for i in range(10):
res = run_script(_deps(), store, OWNER_UID, rec, "handlers/bench.py", payload={"i": i})
assert res["i"] == i
subprocess_s = time.perf_counter() - t_s0
finally:
if orig is None:
os.environ.pop("AIA_PLUGIN_ZYGOTE", None)
else:
os.environ["AIA_PLUGIN_ZYGOTE"] = orig
speedup = subprocess_s / max(zygote_s, 1e-6)
print(f"\nBENCHMARK 10 calls: zygote={zygote_s * 1000:.1f}ms, subprocess={subprocess_s * 1000:.1f}ms, speedup={speedup:.2f}x")
assert zygote_s < subprocess_s