Skip to content

Commit ab9f3cc

Browse files
committed
test(sandbox): align service fixtures and harden CLI checks
Signed-off-by: yaoyu-33 <[email protected]>
1 parent 6f6f9ac commit ab9f3cc

3 files changed

Lines changed: 107 additions & 94 deletions

File tree

‎responses_api_agents/codex_agent/tests/test_native_sessions.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1570,10 +1570,18 @@ async def test_adapter_uses_shared_supervisor_and_captures_real_events(local_ses
15701570
async def test_close_confirms_cleanup_before_provider_cancellation(local_session):
15711571
state, _ = local_session
15721572
processes_path = Path(state.session.session_dir).parent / "children.json"
1573+
# A completed tool leaves a service adopted before close. A direct child of
1574+
# the still-running CLI would instead be an in-flight tool and must be stopped.
1575+
service_tool = (
1576+
"import subprocess,sys; "
1577+
"child=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)'], "
1578+
"start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL); "
1579+
"print(child.pid)"
1580+
)
15731581
code = (
15741582
"import json,os,subprocess,sys,time; from pathlib import Path; "
1575-
"child=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)'],start_new_session=True); "
1576-
f"Path({str(processes_path)!r}).write_text(json.dumps([os.getpid(),child.pid])); time.sleep(60)"
1583+
f"service_pid=int(subprocess.check_output([sys.executable,'-c',{service_tool!r}],text=True)); "
1584+
f"Path({str(processes_path)!r}).write_text(json.dumps([os.getpid(),service_pid])); time.sleep(60)"
15771585
)
15781586
payload = {
15791587
"directory": state.session.session_dir,

‎responses_api_agents/openclaw_agent/tests/test_pinned_runtime.py‎

Lines changed: 93 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -39,100 +39,102 @@ async def hold_model_call(request: web.Request) -> web.Response:
3939
app = web.Application()
4040
app.router.add_post("/{path:.*}", hold_model_call)
4141
runner = web.AppRunner(app)
42-
await runner.setup()
43-
site = web.TCPSite(runner, "127.0.0.1", 0)
44-
await site.start()
45-
agent, sandbox = setup
46-
agent.server_client._build_server_base_url.return_value = f"http://127.0.0.1:{runner.addresses[0][1]}"
47-
directory = tmp_path / "session"
48-
(directory / "home/.openclaw").mkdir(parents=True)
49-
workdir = tmp_path / "task"
50-
workdir.mkdir()
51-
request = Request({"type": "http", "session": {}, "path_params": {"rollout_id": "openclaw-smoke-a2"}})
52-
body = seed()
53-
body.sandbox_access.workdir = str(workdir)
54-
sandbox.expected_workdir = str(workdir)
55-
await agent.seed_agent_session(request, body)
56-
state = agent._session_records[body.agent_session_id].state
57-
state.session.session_dir = str(directory)
58-
await agent.responses(request, NeMoGymResponseCreateParamsNonStreaming(input="Wait for the model response."))
59-
payload = json.loads(sandbox.files[f"{directory}/input.json"])
60-
payload["command"][:2] = [node, entrypoint]
61-
identities = directory / "node-identities.jsonl"
62-
preload = directory / "identity.cjs"
63-
preload.write_text(
64-
"const fs=require('node:fs');"
65-
"const stat=fs.readFileSync('/proc/self/stat','utf8').split(') ').pop().split(' ');"
66-
f"fs.appendFileSync({json.dumps(str(identities))},JSON.stringify({{pid:process.pid,pgid:Number(stat[2])}})+'\\n');"
67-
)
68-
payload["env"]["NODE_OPTIONS"] = f"--require={preload}"
69-
payload["env"]["NODE_COMPILE_CACHE"] = str(directory / "compile-cache")
70-
payload["env"]["HOME"] = str(tmp_path / "task-home")
71-
(directory / "home/.openclaw/openclaw.json").write_text(json.dumps(payload["config"]))
72-
(directory / "input.json").write_text(json.dumps(payload))
73-
process = await asyncio.create_subprocess_exec(
74-
sys.executable,
75-
"-I",
76-
process_supervisor.__file__,
77-
"--timeout",
78-
"90",
79-
"--cleanup-timeout",
80-
"1",
81-
"--receipt",
82-
str(directory / "cleanup.json"),
83-
"--stop-file",
84-
str(directory / "stop.request"),
85-
"--",
86-
sys.executable,
87-
"-I",
88-
sandbox_runner.__file__,
89-
str(directory / "input.json"),
90-
stdout=asyncio.subprocess.PIPE,
91-
stderr=asyncio.subprocess.PIPE,
92-
)
9342
try:
94-
# A real model HTTP request proves the CLI completed startup. Holding its
95-
# response makes the forced-stop check independent of model throughput.
96-
await asyncio.wait_for(requested.wait(), 60)
97-
worker = json.loads((directory / "runtime.json").read_text())["pid"]
98-
observed = [json.loads(line) for line in identities.read_text().splitlines()]
99-
assert observed
100-
assert all(item["pgid"] == worker for item in observed), observed
101-
(directory / "stop.request").touch()
102-
process.send_signal(signal.SIGTERM)
103-
stdout, stderr = await asyncio.wait_for(process.communicate(), 15)
104-
assert process.returncode == 0, (stdout, stderr)
105-
receipt = json.loads((directory / "cleanup.json").read_text())
106-
assert receipt["cleanup_confirmed"] is True
107-
assert receipt["timed_out"] is False
108-
for item in observed:
109-
stat = Path(f"/proc/{item['pid']}/stat")
110-
assert not stat.exists() or stat.read_text().rsplit(")", 1)[1].split()[0] == "Z"
111-
finally:
112-
(directory / "stop.request").touch()
113-
if process.returncode is None:
114-
process.send_signal(signal.SIGTERM)
43+
await runner.setup()
44+
site = web.TCPSite(runner, "127.0.0.1", 0)
45+
await site.start()
46+
agent, sandbox = setup
47+
agent.server_client._build_server_base_url.return_value = f"http://127.0.0.1:{runner.addresses[0][1]}"
48+
directory = tmp_path / "session"
49+
(directory / "home/.openclaw").mkdir(parents=True)
50+
workdir = tmp_path / "task"
51+
workdir.mkdir()
52+
request = Request({"type": "http", "session": {}, "path_params": {"rollout_id": "openclaw-smoke-a2"}})
53+
body = seed()
54+
body.sandbox_access.workdir = str(workdir)
55+
sandbox.expected_workdir = str(workdir)
56+
await agent.seed_agent_session(request, body)
57+
state = agent._session_records[body.agent_session_id].state
58+
state.session.session_dir = str(directory)
59+
await agent.responses(request, NeMoGymResponseCreateParamsNonStreaming(input="Wait for the model response."))
60+
payload = json.loads(sandbox.files[f"{directory}/input.json"])
61+
payload["command"][:2] = [node, entrypoint]
62+
identities = directory / "node-identities.jsonl"
63+
preload = directory / "identity.cjs"
64+
preload.write_text(
65+
"const fs=require('node:fs');"
66+
"const stat=fs.readFileSync('/proc/self/stat','utf8').split(') ').pop().split(' ');"
67+
f"fs.appendFileSync({json.dumps(str(identities))},JSON.stringify({{pid:process.pid,pgid:Number(stat[2])}})+'\\n');"
68+
)
69+
payload["env"]["NODE_OPTIONS"] = f"--require={preload}"
70+
payload["env"]["NODE_COMPILE_CACHE"] = str(directory / "compile-cache")
71+
payload["env"]["HOME"] = str(tmp_path / "task-home")
72+
(directory / "home/.openclaw/openclaw.json").write_text(json.dumps(payload["config"]))
73+
(directory / "input.json").write_text(json.dumps(payload))
74+
process = await asyncio.create_subprocess_exec(
75+
sys.executable,
76+
"-I",
77+
process_supervisor.__file__,
78+
"--timeout",
79+
"90",
80+
"--cleanup-timeout",
81+
"1",
82+
"--receipt",
83+
str(directory / "cleanup.json"),
84+
"--stop-file",
85+
str(directory / "stop.request"),
86+
"--",
87+
sys.executable,
88+
"-I",
89+
sandbox_runner.__file__,
90+
str(directory / "input.json"),
91+
stdout=asyncio.subprocess.PIPE,
92+
stderr=asyncio.subprocess.PIPE,
93+
)
11594
try:
116-
if process.returncode is None:
117-
await asyncio.wait_for(process.communicate(), 15)
95+
# A real model HTTP request proves the CLI completed startup. Holding its
96+
# response makes the forced-stop check independent of model throughput.
97+
await asyncio.wait_for(requested.wait(), 60)
98+
worker = json.loads((directory / "runtime.json").read_text())["pid"]
99+
observed = [json.loads(line) for line in identities.read_text().splitlines()]
100+
assert observed
101+
assert all(item["pgid"] == worker for item in observed), observed
102+
(directory / "stop.request").touch()
103+
process.send_signal(signal.SIGTERM)
104+
stdout, stderr = await asyncio.wait_for(process.communicate(), 15)
105+
assert process.returncode == 0, (stdout, stderr)
106+
receipt = json.loads((directory / "cleanup.json").read_text())
107+
assert receipt["cleanup_confirmed"] is True
108+
assert receipt["timed_out"] is False
109+
for item in observed:
110+
stat = Path(f"/proc/{item['pid']}/stat")
111+
assert not stat.exists() or stat.read_text().rsplit(")", 1)[1].split()[0] == "Z"
118112
finally:
119-
# Stop this test's worker group before awaiting pipe EOF on failure.
120-
# Killing only the supervisor could leave inherited output pipes open.
121-
runtime = directory / "runtime.json"
122-
if runtime.exists():
123-
try:
124-
os.killpg(json.loads(runtime.read_text())["pid"], signal.SIGKILL)
125-
except ProcessLookupError:
126-
pass
127-
# Failure-path cleanup is limited to node PIDs recorded by this test.
128-
if identities.exists():
129-
for line in identities.read_text().splitlines():
113+
(directory / "stop.request").touch()
114+
if process.returncode is None:
115+
process.send_signal(signal.SIGTERM)
116+
try:
117+
if process.returncode is None:
118+
await asyncio.wait_for(process.communicate(), 15)
119+
finally:
120+
# Stop this test's worker group before awaiting pipe EOF on failure.
121+
# Killing only the supervisor could leave inherited output pipes open.
122+
runtime = directory / "runtime.json"
123+
if runtime.exists():
130124
try:
131-
os.kill(json.loads(line)["pid"], signal.SIGKILL)
125+
os.killpg(json.loads(runtime.read_text())["pid"], signal.SIGKILL)
132126
except ProcessLookupError:
133127
pass
134-
if process.returncode is None:
135-
process.kill()
136-
await asyncio.wait_for(process.communicate(), 5)
137-
release.set()
138-
await runner.cleanup()
128+
# Failure-path cleanup is limited to node PIDs recorded by this test.
129+
if identities.exists():
130+
for line in identities.read_text().splitlines():
131+
try:
132+
os.kill(json.loads(line)["pid"], signal.SIGKILL)
133+
except ProcessLookupError:
134+
pass
135+
if process.returncode is None:
136+
process.kill()
137+
await asyncio.wait_for(process.communicate(), 5)
138+
finally:
139+
release.set()
140+
await runner.cleanup()

‎responses_api_agents/opencode_agent/tests/test_task_environment.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,13 @@ def test_runner_removes_stale_task_environment_receipt_before_launch(tmp_path: P
141141

142142
@pytest.mark.parametrize("task_environment", ["valid", "missing", "malformed", "plugin_error"])
143143
def test_pinned_cli_reports_whether_required_plugin_initialized(tmp_path: Path, task_environment: str) -> None:
144-
binary = os.environ.get("GYM_TEST_OPENCODE_BINARY") or shutil.which("opencode")
144+
configured_binary = os.environ.get("GYM_TEST_OPENCODE_BINARY")
145+
binary = configured_binary or shutil.which("opencode")
145146
if binary is None:
146147
pytest.skip("Set GYM_TEST_OPENCODE_BINARY to the pinned OpenCode 1.17.11 executable")
147148
version = subprocess.run([binary, "--version"], capture_output=True, text=True, timeout=30)
149+
if configured_binary is None and (version.returncode != 0 or version.stdout.strip() != "1.17.11"):
150+
pytest.skip("PATH OpenCode is not 1.17.11; set GYM_TEST_OPENCODE_BINARY to the pinned executable")
148151
assert version.returncode == 0 and version.stdout.strip() == "1.17.11"
149152
plugin = tmp_path / "task_environment.mjs"
150153
shutil.copyfile(Path(sandbox_runner.__file__).with_name(plugin.name), plugin)

0 commit comments

Comments
 (0)