The platform for continuously improving AI agents.
import base64
import json
import os
import signal
import subprocess
import sys
import time
from contextlib import contextmanager, suppress
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
import pytest
from agent_runtime.session import ensure, request
pytestmark = pytest.mark.covers("work-once")
def cleanup_processes(root, *records):
for record in records:
owned = (
(
record["pid"],
str(root.resolve() / "kernel" / f"{record['generation']}.json"),
signal.SIGKILL,
os.killpg,
),
(record["supervisor_pid"], f"--root {root}", signal.SIGTERM, os.kill),
)
for pid, identity, stop, send in owned:
command = subprocess.run(
["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True
).stdout
if identity in command:
with suppress(ProcessLookupError):
send(pid, stop)
@pytest.fixture
def session():
# Unix socket paths are short even when pytest's temporary directory is long.
directory = TemporaryDirectory(prefix="wk-", dir="/tmp")
root = Path(directory.name)
health = ensure(root)
current = health
try:
yield root
finally:
try:
current = request(root, {"operation": "health"})
if current["active"]:
request(root, {"operation": "interrupt", "execution": current["active"]})
settle(root, current["active"])
request(root, {"operation": "close"})
finally:
try:
cleanup_processes(root, current, health)
finally:
directory.cleanup()
def settle(root, execution):
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
result = request(root, {"operation": "status", "execution": execution})
health = request(root, {"operation": "health"})
if result["state"] in {"completed", "unknown"} and health["active"] is None:
return result
time.sleep(0.05)
raise AssertionError("Execution did not settle")
def execute(root, code):
execution = str(uuid4())
request(root, {"operation": "submit", "execution": execution, "code": code})
return settle(root, execution)
def test_session_repairs_errors_retains_values_and_replays_files_cleanly(session):
assert execute(session, "values = [2, 4, 6]")["exit_code"] == 0
error = execute(session, "sum(values) / 0")
assert error["exit_code"] == 1 and "ZeroDivisionError" in error["output"]
result = execute(session, "sum(values) / len(values)")
assert "4.0" in result["output"]
recipe = session / "work/recipe.py"
recipe.write_text(
"import json\nfrom pathlib import Path\nrows=json.loads(Path('input.json').read_text())\nPath('result.json').write_text(json.dumps(sorted(x*2 for x in rows)))\n"
)
(session / "work/input.json").write_text("[3, 1, 2]")
assert execute(session, "exec(open('recipe.py').read())")["exit_code"] == 0
before = (session / "work/result.json").read_bytes()
request(session, {"operation": "reset"})
assert execute(session, "values")["error"] == "NameError"
subprocess.run([sys.executable, str(recipe)], cwd=recipe.parent, check=True)
assert json.loads(before) == [2, 4, 6]
assert (session / "work/result.json").read_bytes() == before
def test_session_recovers_lost_reply_without_repeating_code(session):
execution = str(uuid4())
command = {
"operation": "submit",
"execution": execution,
"code": "from pathlib import Path\np=Path('count')\np.write_text(str(int(p.read_text())+1) if p.exists() else '1')",
}
request(session, command)
settle(session, execution)
repeated = request(session, command)
assert repeated["state"] == "completed"
assert (session / "work/count").read_text() == "1"
with pytest.raises(ValueError, match="conflicts"):
request(session, {**command, "code": "print(42)"})
def test_supervisor_restart_fences_unknown_execution_and_reset_restores_execution(session):
execution = str(uuid4())
request(
session,
{"operation": "submit", "execution": execution, "code": "import time\ntime.sleep(60)"},
)
health = request(session, {"operation": "health"})
os.kill(health["supervisor_pid"], signal.SIGKILL)
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
try:
request(session, {"operation": "health"})
except OSError:
break
time.sleep(0.05)
recovered = ensure(session)
assert recovered["fenced"]
assert request(session, {"operation": "status", "execution": execution})["state"] == "unknown"
with pytest.raises(ValueError, match="reset"):
execute(session, "print(1)")
reset = request(session, {"operation": "reset"})
assert reset["generation"] != health["generation"]
assert execute(session, "6 * 7")["exit_code"] == 0
def wait_for_output(root, execution, marker):
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
result = request(root, {"operation": "status", "execution": execution})
if marker in result["output"]:
return
time.sleep(0.05)
raise AssertionError("The cell did not reach its interruptible execution")
def test_interrupt_returns_an_error_and_keeps_the_kernel_usable(session):
generation = request(session, {"operation": "health"})["generation"]
execution = str(uuid4())
request(
session,
{
"operation": "submit",
"execution": execution,
"code": (
"import time\ninterrupt_value = 41\n"
"print('execution-started', flush=True)\ntime.sleep(60)"
),
},
)
wait_for_output(session, execution, "execution-started")
request(session, {"operation": "interrupt", "execution": execution})
result = settle(session, execution)
assert result["error"] == "KeyboardInterrupt"
assert result["timed_out"] is False
assert request(session, {"operation": "health"})["generation"] == generation
following = str(uuid4())
request(
session,
{
"operation": "submit",
"execution": following,
"code": (
"from pathlib import Path\nprint('following-started', flush=True)\n"
"while not Path('release-following').exists():\n time.sleep(0.01)\n"
"print(interrupt_value + 1)"
),
},
)
try:
wait_for_output(session, following, "following-started")
repeated = request(session, {"operation": "interrupt", "execution": execution})
assert repeated == result
finally:
(session / "work/release-following").write_text("continue")
following_result = settle(session, following)
assert following_result["exit_code"] == 0 and "42" in following_result["output"]
assert request(session, {"operation": "health"})["generation"] == generation
@contextmanager
def stopped_kernel(root):
kernel = request(root, {"operation": "health"})["pid"]
os.kill(kernel, signal.SIGSTOP)
try:
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
state = subprocess.run(
["ps", "-p", str(kernel), "-o", "state="],
check=True,
capture_output=True,
text=True,
).stdout.strip()
if state.startswith("T"):
break
time.sleep(0.05)
else:
raise AssertionError("The idle kernel did not stop before submission")
yield kernel
finally:
with suppress(ProcessLookupError):
os.kill(kernel, signal.SIGCONT)
@pytest.mark.parametrize("resume_kernel", [True, False], ids=["queued", "no_reply"])
def test_interrupt_before_kernel_dispatch_is_bounded_and_does_not_repeat_code(
session, resume_kernel
):
assert execute(session, "0")["exit_code"] == 0
generation = request(session, {"operation": "health"})["generation"]
execution = str(uuid4())
command = {
"operation": "submit",
"execution": execution,
"code": "import time\ntime.sleep(60)",
}
with stopped_kernel(session) as kernel:
request(session, command)
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
result = request(session, {"operation": "status", "execution": execution})
if result.get("message_id"):
break
time.sleep(0.05)
else:
raise AssertionError("The stopped kernel's request was not submitted")
requested = time.monotonic()
request(session, {"operation": "interrupt", "execution": execution})
if resume_kernel:
os.kill(kernel, signal.SIGCONT)
deadline = requested + 15
repeated_at = requested
while time.monotonic() < deadline:
result = request(session, {"operation": "status", "execution": execution})
health = request(session, {"operation": "health"})
if result["state"] in {"completed", "unknown"} and health["active"] is None:
break
if not resume_kernel and time.monotonic() - repeated_at >= 1:
request(session, {"operation": "interrupt", "execution": execution})
repeated_at = time.monotonic()
time.sleep(0.05)
else:
raise AssertionError(
"Manual interruption did not settle within its acknowledgement bound"
)
assert request(session, command) == result
if not resume_kernel:
assert result["state"] == "unknown"
if result["state"] == "unknown":
assert result["reason"] == "interrupt_not_acknowledged"
assert "exit_code" not in result and "error" not in result
assert health["fenced"]
with pytest.raises(ValueError, match="reset"):
request(
session,
{"operation": "submit", "execution": str(uuid4()), "code": "print(1)"},
)
reset = request(session, {"operation": "reset"})
assert reset["generation"] != generation
else:
assert result["error"] == "KeyboardInterrupt" and result["exit_code"] == 1
assert result["timed_out"] is False
assert not health["fenced"] and health["generation"] == generation
assert execute(session, "print(42)")["exit_code"] == 0
assert request(session, command) == result
def test_file_outside_the_working_directory_is_refused_with_the_reason_alone(tmp_path):
payload = {"operation": "write", "path": "/workspace/report.md", "text": "x"}
refused = subprocess.run(
[
sys.executable,
"-m",
"agent_runtime.session",
"--root",
str(tmp_path),
"file",
"--payload",
base64.b64encode(json.dumps(payload).encode()).decode(),
],
capture_output=True,
text=True,
)
assert refused.returncode == 1
assert "Traceback" not in refused.stderr
assert str(tmp_path.resolve() / "work") in refused.stderr