terminal-desk / source /tests /test_gate.py
dnakhla's picture
v4: decisiveness gate (K=3), 17 office/software/finance tasks labelled by the arena's own run; v3c result; corrected screen
7571e08 verified
Raw History Blame Contribute Delete
11.1 kB
"""The decisiveness gate. With TERMINAL_DESK_MAX_ACTIONS=K, evaluate pays 1 only when every check passes and the agent
ran at most K exec or write_file actions since reset. Failed ones count; evaluate, close, session actions and the call
that trips the call cap do not. With the gate off (the default) evaluate reports actions_used and pays as before."""
import json
import os
import subprocess
import sys
import pytest
import test_episodes as episodes # sets TERMINAL_DESK_ROOTS before the server imports
from terminal_desk.core.grading import render_artifact
from terminal_desk.models import Tbench2Action
from terminal_desk.oracles import ORACLE_FILE, oracle_source, run_oracle
from terminal_desk.server import environment
from terminal_desk.server.environment import MAX_CALLS, TerminalDeskEnvironment
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# One v3 family per domain. run_oracle plays what a decisive agent does: write_file the script, exec it, evaluate.
ORACLE_TASKS = ["sw3_dep_lock-L2", "ind3_tank_balance-L2", "sci3_kinetics_fit-L3", "off3_ar_recon-L1",
"fin3_loan_schedule-L3", "math3_route_plan-L2", "sec3_auth_triage-L3", "med3_subtitle_retime-L1"]
def _env(monkeypatch, limit, task_id: str, seed: int = 1) -> TerminalDeskEnvironment:
monkeypatch.setattr(environment, "GATE_LIMIT", limit) # what the server read at start
env = TerminalDeskEnvironment(allow_seed=True)
env.reset(task_id=task_id, seed=seed)
return env
def _do(env, action_type: str, **fields):
return env.step(Tbench2Action(action_type=action_type, **fields))
def _ls(env, n: int) -> None:
for _ in range(n):
obs = _do(env, "exec", command="ls")
assert obs.success and obs.info == {} # step observations carry no counter
def _oracle(env, task_id: str):
out, obs = run_oracle(env, oracle_source(task_id.rpartition("-L")[0]))
assert obs.done and obs.info["tests_passed"] is True, (out, obs.output) # the artifact is right either way
return obs
def _gate_line(used: int, limit: int) -> str:
return f"decisiveness gate: {used} actions used, limit {limit}"
# ---------------------------------------------------------------- the variable
@pytest.mark.parametrize("raw, want", [(None, None), ("", None), (" ", None), ("1", 1), ("3", 3), (" 3\n", 3),
("40", 40)])
def test_limit_is_a_positive_integer_or_off(raw, want):
environ = {} if raw is None else {"TERMINAL_DESK_MAX_ACTIONS": raw}
assert environment.gate_limit_from_env(environ) == want
@pytest.mark.parametrize("raw", ["0", "-1", "+3", "3.0", "1e3", "three", "3 4"])
def test_limit_refuses_anything_else(raw):
with pytest.raises(RuntimeError, match="TERMINAL_DESK_MAX_ACTIONS must be a positive integer"):
environment.gate_limit_from_env({"TERMINAL_DESK_MAX_ACTIONS": raw})
@pytest.mark.parametrize("raw, code, printed", [(None, 0, "None None"), ("3", 0, "3 3"), ("three", 1, "")])
def test_server_reads_the_limit_once_at_start(raw, code, printed):
env = {k: v for k, v in os.environ.items() if k != "TERMINAL_DESK_MAX_ACTIONS"}
if raw is not None:
env["TERMINAL_DESK_MAX_ACTIONS"] = raw
env["PYTHONPATH"] = REPO
probe = ("import os; from terminal_desk.server import environment as e; "
"os.environ['TERMINAL_DESK_MAX_ACTIONS'] = '7'; " # a change after start is not read
"print(e.GATE_LIMIT, e.TerminalDeskEnvironment()._gate_limit)")
proc = subprocess.run([sys.executable, "-c", probe], env=env, cwd=REPO, capture_output=True, text=True, timeout=120)
assert proc.returncode == code and proc.stdout.strip() == printed, proc.stderr[-500:]
if code:
assert "TERMINAL_DESK_MAX_ACTIONS must be a positive integer or empty, got 'three'" in proc.stderr
# ---------------------------------------------------------------- off by default
@pytest.mark.parametrize("task_id", ORACLE_TASKS[:3])
def test_gate_off_reports_actions_and_keeps_the_reward(monkeypatch, task_id):
env = _env(monkeypatch, environment.gate_limit_from_env({}), task_id)
_ls(env, 5)
obs = _oracle(env, task_id)
assert obs.reward == 1.0 and obs.info["actions_used"] == 7 and obs.info["calls"] == 8
assert "gate_limit" not in obs.info and "gate_passed" not in obs.info and "decisiveness gate" not in obs.output
# ---------------------------------------------------------------- K = 3 across domains
@pytest.mark.parametrize("task_id", ORACLE_TASKS)
@pytest.mark.parametrize("extra", [0, 1, 2], ids=["2-actions", "3-actions", "4-actions"])
def test_oracle_pays_only_within_the_limit(monkeypatch, task_id, extra):
# extra=0 is the arena's case: two actions, the budget ends the episode, the arena sends evaluate. It scores 1.
env = _env(monkeypatch, 3, task_id)
_ls(env, extra)
obs = _oracle(env, task_id)
used = 2 + extra
assert obs.info["actions_used"] == used and obs.info["gate_limit"] == 3 and obs.info["calls"] == used + 1
assert obs.info["assertions_passed"] == obs.info["assertions_total"]
if used <= 3:
assert obs.reward == 1.0 and obs.info["gate_passed"] is True and "decisiveness gate" not in obs.output
else:
assert obs.reward == 0.0 and obs.info["gate_passed"] is False
lines = obs.output.splitlines() # the gate's line, then the verifier's tail as it was
assert lines[0] == _gate_line(4, 3) and "decisiveness gate" not in "\n".join(lines[1:])
assert lines[1] == "PASSED tests/test_outputs.py::test_file_exists" and "failed" not in lines[-1]
def test_one_write_meets_a_limit_of_one_and_reset_restarts_the_count(monkeypatch):
env = _env(monkeypatch, 1, "math_count-L1")
episodes._write_oracle(env)
obs = episodes._evaluate(env)
assert obs.reward == 1.0 and obs.info["actions_used"] == 1 and obs.info["gate_passed"] is True
env.reset(task_id="math_count-L1", seed=1)
_ls(env, 1)
episodes._write_oracle(env)
obs = episodes._evaluate(env)
assert obs.reward == 0.0 and obs.info["tests_passed"] is True and obs.output.splitlines()[0] == _gate_line(2, 1)
@pytest.mark.parametrize("extra", [0, 3], ids=["within", "over"])
def test_wrong_artifact_scores_zero_either_side_of_the_limit(monkeypatch, extra):
env = _env(monkeypatch, 3, "fin3_loan_schedule-L1")
_ls(env, extra)
art = env._ep["built"].artifact
content = render_artifact(art)
assert _do(env, "write_file", file_path=art.path, content=content[: len(content) // 2]).success
obs = episodes._evaluate(env)
assert obs.reward == 0.0 and obs.info["tests_passed"] is False and obs.info["actions_used"] == 1 + extra
assert obs.info["gate_passed"] is (extra == 0)
assert (obs.output.splitlines()[0] == _gate_line(4, 3)) is (extra > 0)
# ---------------------------------------------------------------- what counts
def test_failed_exec_and_write_file_count(monkeypatch):
env = _env(monkeypatch, 3, "ind3_tank_balance-L1")
obs = _do(env, "write_file", content="x")
assert not obs.success and "file_path" in obs.error
obs = _do(env, "exec", command="echo \x00")
assert not obs.success and "null byte" in obs.error # the command never started
obs = _oracle(env, "ind3_tank_balance-L1")
assert obs.reward == 0.0 and obs.info["actions_used"] == 4 and obs.output.splitlines()[0] == _gate_line(4, 3)
def test_session_actions_evaluate_and_close_do_not_count(monkeypatch):
env = _env(monkeypatch, 2, "sec3_auth_triage-L1")
soft_failures = [("write", {"command": "x"}), ("view", {"session_id": "s1"}), ("wait", {"session_id": "s1"}),
("kill", {}), ("dance", {})]
for kind, fields in soft_failures * 2:
obs = _do(env, kind, **fields)
assert not obs.success and not obs.done and obs.info == {}
obs = _oracle(env, "sec3_auth_triage-L1") # K=2 passes only if evaluate itself does not count
assert obs.reward == 1.0 and obs.info["actions_used"] == 2 and obs.info["calls"] == 13
env.reset(task_id="sec3_auth_triage-L1", seed=1)
_ls(env, 2)
obs = _do(env, "close")
assert obs.done and obs.reward is None and obs.info == {"actions_used": 2}
assert _do(env, "exec", command="ls").done and env._ep["actions"] == 2 # nothing counts after the episode ends
@pytest.mark.parametrize("filler, reward, used", [("view", 1.0, 1), ("exec", 0.0, MAX_CALLS)])
def test_call_cap_auto_evaluate_applies_the_gate(monkeypatch, filler, reward, used):
env = _env(monkeypatch, 3, "math_count-L1")
episodes._write_oracle(env)
for _ in range(MAX_CALLS - 1):
assert not _do(env, filler, command="echo hi", session_id="s1").done
obs = _do(env, "exec", command="echo hi") # call 33 trips the cap: it is evaluated, not run, so it does not count
assert obs.done and obs.info["calls"] == MAX_CALLS + 1 and obs.info["tests_passed"] is True
assert obs.reward == reward and obs.info["actions_used"] == used and obs.info["gate_passed"] is (reward == 1.0)
assert (obs.output.splitlines()[0] == _gate_line(MAX_CALLS, 3)) is (reward == 0.0)
# ---------------------------------------------------------------- over the server's WebSocket
def test_gate_over_websocket_leaves_steps_and_schema_alone(monkeypatch):
from fastapi.testclient import TestClient
from terminal_desk.server.app import app
monkeypatch.setattr(environment, "GATE_LIMIT", 3) # each session's env is built from what the server read
script = oracle_source("fin3_loan_schedule")
want_schema = json.load(open(episodes.FIXTURE))
with TestClient(app) as client:
assert client.get("/schema").json()["observation"] == want_schema["observation"]
for pad, reward in ((0, 1.0), (2, 0.0)):
with client.websocket_connect("/ws") as ws:
ws.send_json({"type": "reset", "data": {"task_id": "fin3_loan_schedule-L2"}})
assert ws.receive_json()["data"]["observation"]["info"] == {}
actions = [{"action_type": "exec", "command": "ls"}] * pad + [
{"action_type": "write_file", "file_path": ORACLE_FILE, "content": script},
{"action_type": "exec", "command": f"python3 {ORACLE_FILE}"},
]
for action in actions:
ws.send_json({"type": "step", "data": action})
msg = ws.receive_json()
assert msg["type"] == "observation" and not msg["data"]["done"], msg
assert msg["data"]["observation"]["info"] == {}
ws.send_json({"type": "step", "data": {"action_type": "evaluate"}})
data = ws.receive_json()["data"]
info = data["observation"]["info"]
assert data["done"] and data["reward"] == reward and info["tests_passed"] is True
assert (info["actions_used"], info["gate_limit"], info["gate_passed"]) == (2 + pad, 3, reward == 1.0)
assert data["observation"]["output"].startswith("decisiveness gate: 4 actions used, limit 3\n") is (pad > 0)