Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ All notable changes to SkillEvaluator are documented in this file.

### Fixed

- NeMo Gym detached cleanup defers termination signals until teardown finishes,
preserves cancellation over cleanup errors, and reaps adopted run-owned servers.
- Native NeMo Gym project skill projections run after authored image instructions
and final workspace resets, even when an earlier layer already copied skills.
- Native NeMo Gym OpenCode evaluations project staged skills into the task workdir
Expand Down
57 changes: 56 additions & 1 deletion src/skillevaluator/tier3/nemo_gym/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import re
import signal
import subprocess
import sys
import time
import tomllib
from datetime import UTC, datetime
Expand Down Expand Up @@ -459,6 +460,33 @@ def _handler(_signum: int, _frame: object) -> None:
signal.signal(getattr(signal, name), handler)


@contextlib.contextmanager
def _defer_termination_signals() -> Any:
import threading

if threading.current_thread() is not threading.main_thread():
yield
return
pending = False

def _handler(_signum: int, _frame: object) -> None:
nonlocal pending
pending = True

previous = {
getattr(signal, name): signal.signal(getattr(signal, name), _handler)
for name in ("SIGTERM", "SIGHUP")
if hasattr(signal, name)
}
try:
yield
finally:
for signum, handler in previous.items():
signal.signal(signum, handler)
if pending:
raise KeyboardInterrupt


def _gym_run_processes(token: str, leader_group: int) -> list[int]:
try:
snapshot = subprocess.run(
Expand All @@ -485,8 +513,11 @@ def _gym_run_processes(token: str, leader_group: int) -> list[int]:
def _stop_detached_gym_processes(token: str, leader_group: int, *, force: bool = False) -> None:
from skillevaluator.tier3.harbor.runner import _HARBOR_RUN_CANCEL_POLL_SECONDS, _HARBOR_RUN_REAP_SECONDS

seen: set[int] = set()

def signal_owned(sig: int) -> list[int]:
owned = _gym_run_processes(token, leader_group)
seen.update(owned)
for pid in owned:
with contextlib.suppress(ProcessLookupError):
os.kill(pid, sig)
Expand All @@ -511,6 +542,20 @@ def signal_owned(sig: int) -> list[int]:
except KeyboardInterrupt:
signal_owned(signal.SIGKILL)
raise
finally:
deadline = time.monotonic() + _HARBOR_RUN_REAP_SECONDS
while seen:
for pid in tuple(seen):
try:
reaped, _status = os.waitpid(pid, os.WNOHANG)
except ChildProcessError:
seen.remove(pid)
else:
if reaped:
seen.remove(pid)
if not seen or time.monotonic() >= deadline:
break
time.sleep(_HARBOR_RUN_CANCEL_POLL_SECONDS)


def _run_gym(
Expand Down Expand Up @@ -660,8 +705,18 @@ def _stop() -> None:
raise interrupt from stop_error
raise
finally:
pending_interrupt = sys.exception()
try:
_stop_detached_gym_processes(run_token, process.pid, force=force_detached_cleanup)
with _defer_termination_signals():
try:
_stop_detached_gym_processes(run_token, process.pid, force=force_detached_cleanup)
except GymCleanupError as cleanup_error:
if reporter is not None:
with contextlib.suppress(Exception):
reporter.emit(ProgressEvent(stage="cleanup", state="failed", detail=str(cleanup_error)))
if isinstance(pending_interrupt, KeyboardInterrupt):
raise pending_interrupt from cleanup_error
raise
finally:
reader.join(timeout=_GYM_LOG_DRAIN_SECONDS)

Expand Down
107 changes: 107 additions & 0 deletions tests/test_nemo_gym_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -2741,6 +2741,113 @@ def test_nemo_gym_rejects_unsupported_run_options(
assert f"{flag} is not supported with --backend nemo-gym yet" in errors


@pytest.mark.skipif(os.name != "posix", reason="requires POSIX signals")
@pytest.mark.parametrize("signal_name", ["SIGTERM", "SIGHUP"])
def test_detached_cleanup_defers_termination_until_finished(tmp_path: Path, signal_name) -> None:
import subprocess

from skillevaluator.tier3.nemo_gym import runner

marker = tmp_path / "finished"
script = (
"import os, signal, sys\n"
"from pathlib import Path\n"
"from skillevaluator.tier3.nemo_gym import runner\n"
"def cleanup(*args, **kwargs):\n"
f" os.kill(os.getpid(), signal.{signal_name})\n"
f" Path({str(marker)!r}).touch()\n"
"runner._stop_detached_gym_processes = cleanup\n"
f"with open({str(tmp_path / 'gym.log')!r}, 'w') as log:\n"
f" runner._run_gym([sys.executable, '-c', 'pass'], cwd=Path({str(tmp_path)!r}), "
"env=dict(os.environ), log=log, timeout_s=5)\n"
)
result = subprocess.run(
[sys.executable, "-c", script],
env={**os.environ, "PYTHONPATH": str(Path(runner.__file__).parents[3])},
capture_output=True,
text=True,
timeout=15,
)
assert marker.exists(), f"cleanup interrupted: returncode={result.returncode}"
assert "KeyboardInterrupt" in result.stderr


@pytest.mark.skipif(os.name != "posix", reason="requires POSIX signals")
@pytest.mark.parametrize("interrupted", [True, False])
def test_detached_inspection_failure_preserves_cancellation(tmp_path: Path, monkeypatch, interrupted) -> None:
import signal
import threading

from skillevaluator.tier3.nemo_gym import runner

def fail_cleanup(*_args, **_kwargs):
raise runner.GymCleanupError("Cannot inspect detached processes")

monkeypatch.setattr(runner, "_stop_detached_gym_processes", fail_cleanup)
reporter = _RecordingReporter()
timer = threading.Timer(0.5, lambda: os.kill(os.getpid(), signal.SIGINT)) if interrupted else None
if timer:
timer.start()
try:
with (
(tmp_path / "gym.log").open("w") as log,
pytest.raises(KeyboardInterrupt if interrupted else runner.GymCleanupError) as error,
):
runner._run_gym(
[sys.executable, "-c", "import time; time.sleep(60)" if interrupted else "pass"],
cwd=tmp_path,
env=dict(os.environ),
log=log,
timeout_s=5,
reporter=reporter,
)
finally:
if timer:
timer.cancel()
timer.join()
if interrupted:
assert isinstance(error.value.__cause__, runner.GymCleanupError)
assert any(event.stage == "cleanup" and event.state == "failed" for event in reporter.events)


@pytest.mark.skipif(sys.platform != "linux", reason="needs Linux PR_SET_CHILD_SUBREAPER")
def test_detached_cleanup_reaps_adopted_servers(tmp_path: Path) -> None:
import subprocess

from skillevaluator.tier3.nemo_gym import runner

child = "import time; time.sleep(60)"
leader = (
"import os, subprocess, sys\n"
f"server = subprocess.Popen([sys.executable, '-c', {child!r}], start_new_session=True)\n"
"print(server.pid, flush=True)\n"
)
script = (
"import ctypes, os, subprocess, sys\n"
"from skillevaluator.tier3.nemo_gym.runner import _stop_detached_gym_processes\n"
"assert ctypes.CDLL(None).prctl(36, 1, 0, 0, 0) == 0\n"
f"leader = subprocess.Popen([sys.executable, '-c', {leader!r}], stdout=subprocess.PIPE, text=True,\n"
" env={**os.environ, 'SKILL_EVAL_NEMO_GYM_RUN_TOKEN': 'reap-test-token'})\n"
"pid = int(leader.stdout.readline())\n"
"leader.wait(timeout=5)\n"
"_stop_detached_gym_processes('reap-test-token', leader.pid, force=True)\n"
"try:\n"
" reaped, _ = os.waitpid(pid, os.WNOHANG)\n"
"except ChildProcessError:\n"
" pass\n"
"else:\n"
" assert False, f'adopted server was not reaped: {reaped}'\n"
)
result = subprocess.run(
[sys.executable, "-c", script],
env={**os.environ, "PYTHONPATH": str(Path(runner.__file__).parents[3])},
capture_output=True,
text=True,
timeout=15,
)
assert result.returncode == 0, result.stderr


def test_nemo_gym_rejects_budget_config(tmp_path: Path) -> None:
from skillevaluator.tier3.nemo_gym.backend import nemo_gym_config_errors

Expand Down
Loading