Spaces:
Runtime error
Runtime error
Aaron Brown commited on
Commit ·
8b3ca35
1
Parent(s): 7450122
fix(services): preserve subprocess services across HTTP request lifecycle
Browse filesThe stateless HTTP handler creates and closes an env per request. In
close(), _stop_services() killed daemons that reset() had just started.
Skip service teardown in close() for subprocess mode — services are
global system processes managed by reset() episode lifecycle instead.
Also removes debug trace logging (file + stderr) added during service
startup investigation.
src/open_range/server/environment.py
CHANGED
|
@@ -573,24 +573,6 @@ class RangeEnvironment(Environment[RangeAction, RangeObservation, RangeState]):
|
|
| 573 |
The snapshot's ``services`` list is normally populated by the renderer.
|
| 574 |
Snapshots without explicit service specs skip subprocess provisioning.
|
| 575 |
"""
|
| 576 |
-
# Debug trace
|
| 577 |
-
import sys
|
| 578 |
-
svc_count = len(snapshot.services) if snapshot.services else 0
|
| 579 |
-
print(f"[OPENRANGE_DEBUG] _start_snapshot_services: "
|
| 580 |
-
f"mode={self._execution_mode} services={svc_count}",
|
| 581 |
-
file=sys.stderr, flush=True)
|
| 582 |
-
_dbg = "/tmp/openrange_svc_debug.log"
|
| 583 |
-
try:
|
| 584 |
-
with open(_dbg, "a") as f:
|
| 585 |
-
f.write(
|
| 586 |
-
f"[{time.time():.3f}] _start_snapshot_services: "
|
| 587 |
-
f"mode={self._execution_mode} "
|
| 588 |
-
f"services={svc_count}\n"
|
| 589 |
-
)
|
| 590 |
-
f.flush()
|
| 591 |
-
except Exception:
|
| 592 |
-
pass
|
| 593 |
-
|
| 594 |
if self._execution_mode != "subprocess":
|
| 595 |
return
|
| 596 |
|
|
@@ -630,18 +612,6 @@ class RangeEnvironment(Environment[RangeAction, RangeObservation, RangeState]):
|
|
| 630 |
"""Run init commands, start daemon, wait for readiness."""
|
| 631 |
logger.info("Starting service: %s (host=%s)", svc.daemon, svc.host)
|
| 632 |
|
| 633 |
-
# Debug file for diagnosing service startup issues
|
| 634 |
-
_dbg = "/tmp/openrange_svc_debug.log"
|
| 635 |
-
|
| 636 |
-
def _dbg_write(msg: str) -> None:
|
| 637 |
-
try:
|
| 638 |
-
with open(_dbg, "a") as f:
|
| 639 |
-
f.write(f"[{time.time():.3f}] {msg}\n")
|
| 640 |
-
except Exception:
|
| 641 |
-
pass
|
| 642 |
-
|
| 643 |
-
_dbg_write(f"=== START {svc.daemon} (host={svc.host}) ===")
|
| 644 |
-
|
| 645 |
# Set env vars
|
| 646 |
env = os.environ.copy()
|
| 647 |
env.update(svc.env_vars)
|
|
@@ -672,10 +642,6 @@ class RangeEnvironment(Environment[RangeAction, RangeObservation, RangeState]):
|
|
| 672 |
else svc.start_command
|
| 673 |
)
|
| 674 |
|
| 675 |
-
_dbg_write(f" log_dir={log_dir}")
|
| 676 |
-
_dbg_write(f" init_commands={init_commands}")
|
| 677 |
-
_dbg_write(f" start_command={start_command}")
|
| 678 |
-
|
| 679 |
# Run init commands synchronously (blocking, no session isolation needed)
|
| 680 |
for cmd in init_commands:
|
| 681 |
try:
|
|
@@ -687,15 +653,12 @@ class RangeEnvironment(Environment[RangeAction, RangeObservation, RangeState]):
|
|
| 687 |
env=env,
|
| 688 |
check=False,
|
| 689 |
)
|
| 690 |
-
_dbg_write(f" init rc={result.returncode} cmd={cmd[:80]}")
|
| 691 |
if result.returncode != 0 and result.stderr:
|
| 692 |
-
_dbg_write(f" init stderr: {result.stderr[:200]}")
|
| 693 |
logger.debug(
|
| 694 |
"Init cmd stderr for %s: %s",
|
| 695 |
svc.daemon, result.stderr[:200],
|
| 696 |
)
|
| 697 |
except Exception as exc:
|
| 698 |
-
_dbg_write(f" init EXCEPTION: {exc}")
|
| 699 |
logger.warning("Init command failed for %s: %s", svc.daemon, exc)
|
| 700 |
|
| 701 |
# Start the daemon using Popen with DEVNULL file descriptors.
|
|
@@ -707,8 +670,6 @@ class RangeEnvironment(Environment[RangeAction, RangeObservation, RangeState]):
|
|
| 707 |
if not effective_cmd.rstrip().endswith("&"):
|
| 708 |
effective_cmd = f"({effective_cmd}) &"
|
| 709 |
|
| 710 |
-
_dbg_write(f" effective_cmd={effective_cmd}")
|
| 711 |
-
|
| 712 |
try:
|
| 713 |
proc = sp.Popen(
|
| 714 |
["bash", "-c", effective_cmd],
|
|
@@ -718,38 +679,24 @@ class RangeEnvironment(Environment[RangeAction, RangeObservation, RangeState]):
|
|
| 718 |
env=env,
|
| 719 |
start_new_session=True,
|
| 720 |
)
|
| 721 |
-
_dbg_write(f" Popen pid={proc.pid}")
|
| 722 |
# Wait for bash to exit (it backgrounds the daemon and exits
|
| 723 |
# immediately). The zombie reaper handles cleanup if we lose
|
| 724 |
# the race.
|
| 725 |
try:
|
| 726 |
-
|
| 727 |
-
_dbg_write(f" bash exited rc={rc}")
|
| 728 |
except sp.TimeoutExpired:
|
| 729 |
-
|
| 730 |
except ChildProcessError:
|
| 731 |
-
|
| 732 |
except Exception as exc:
|
| 733 |
-
_dbg_write(f" Popen EXCEPTION: {exc}")
|
| 734 |
logger.warning("Start command failed for %s: %s", svc.daemon, exc)
|
| 735 |
return
|
| 736 |
|
| 737 |
# Brief pause to let the daemon initialize before probing readiness
|
| 738 |
time.sleep(0.5)
|
| 739 |
|
| 740 |
-
# Check if daemon is running after pause
|
| 741 |
-
try:
|
| 742 |
-
pgrep = sp.run(
|
| 743 |
-
["pgrep", "-x", svc.daemon.split("/")[-1].split()[0]],
|
| 744 |
-
capture_output=True, timeout=3, text=True, check=False,
|
| 745 |
-
)
|
| 746 |
-
_dbg_write(f" pgrep after start: rc={pgrep.returncode} pids={pgrep.stdout.strip()}")
|
| 747 |
-
except Exception:
|
| 748 |
-
_dbg_write(" pgrep failed")
|
| 749 |
-
|
| 750 |
# Wait for readiness
|
| 751 |
self._wait_for_readiness(svc)
|
| 752 |
-
_dbg_write(f" readiness check done for {svc.daemon}")
|
| 753 |
|
| 754 |
def _wait_for_readiness(self, svc: ServiceSpec) -> None:
|
| 755 |
"""Poll the readiness check until success or timeout."""
|
|
@@ -1428,18 +1375,6 @@ class RangeEnvironment(Environment[RangeAction, RangeObservation, RangeState]):
|
|
| 1428 |
Returns:
|
| 1429 |
Initial RangeObservation with the challenge briefing.
|
| 1430 |
"""
|
| 1431 |
-
# Debug trace for service startup investigation
|
| 1432 |
-
import sys
|
| 1433 |
-
print(f"[OPENRANGE_DEBUG] reset() called, mode={self._execution_mode}, "
|
| 1434 |
-
f"runtime={self._runtime is not None}", file=sys.stderr, flush=True)
|
| 1435 |
-
_dbg = "/tmp/openrange_svc_debug.log"
|
| 1436 |
-
try:
|
| 1437 |
-
with open(_dbg, "a") as f:
|
| 1438 |
-
f.write(f"[{time.time():.3f}] reset() called, mode={self._execution_mode}\n")
|
| 1439 |
-
f.flush()
|
| 1440 |
-
except Exception as e:
|
| 1441 |
-
print(f"[OPENRANGE_DEBUG] debug file write failed: {e}", file=sys.stderr, flush=True)
|
| 1442 |
-
|
| 1443 |
self._report_episode_result(completed=False)
|
| 1444 |
self._stop_npcs()
|
| 1445 |
self._teardown_active_project()
|
|
@@ -1821,10 +1756,17 @@ class RangeEnvironment(Environment[RangeAction, RangeObservation, RangeState]):
|
|
| 1821 |
return list(self._npc_traffic_log)
|
| 1822 |
|
| 1823 |
def close(self) -> None:
|
| 1824 |
-
"""Release resources (Docker client, NPC manager, episode state).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1825 |
self._report_episode_result(completed=False)
|
| 1826 |
self._stop_npcs()
|
| 1827 |
-
self.
|
|
|
|
| 1828 |
self._teardown_active_project()
|
| 1829 |
if self._docker_client is not None:
|
| 1830 |
try:
|
|
|
|
| 573 |
The snapshot's ``services`` list is normally populated by the renderer.
|
| 574 |
Snapshots without explicit service specs skip subprocess provisioning.
|
| 575 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 576 |
if self._execution_mode != "subprocess":
|
| 577 |
return
|
| 578 |
|
|
|
|
| 612 |
"""Run init commands, start daemon, wait for readiness."""
|
| 613 |
logger.info("Starting service: %s (host=%s)", svc.daemon, svc.host)
|
| 614 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 615 |
# Set env vars
|
| 616 |
env = os.environ.copy()
|
| 617 |
env.update(svc.env_vars)
|
|
|
|
| 642 |
else svc.start_command
|
| 643 |
)
|
| 644 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 645 |
# Run init commands synchronously (blocking, no session isolation needed)
|
| 646 |
for cmd in init_commands:
|
| 647 |
try:
|
|
|
|
| 653 |
env=env,
|
| 654 |
check=False,
|
| 655 |
)
|
|
|
|
| 656 |
if result.returncode != 0 and result.stderr:
|
|
|
|
| 657 |
logger.debug(
|
| 658 |
"Init cmd stderr for %s: %s",
|
| 659 |
svc.daemon, result.stderr[:200],
|
| 660 |
)
|
| 661 |
except Exception as exc:
|
|
|
|
| 662 |
logger.warning("Init command failed for %s: %s", svc.daemon, exc)
|
| 663 |
|
| 664 |
# Start the daemon using Popen with DEVNULL file descriptors.
|
|
|
|
| 670 |
if not effective_cmd.rstrip().endswith("&"):
|
| 671 |
effective_cmd = f"({effective_cmd}) &"
|
| 672 |
|
|
|
|
|
|
|
| 673 |
try:
|
| 674 |
proc = sp.Popen(
|
| 675 |
["bash", "-c", effective_cmd],
|
|
|
|
| 679 |
env=env,
|
| 680 |
start_new_session=True,
|
| 681 |
)
|
|
|
|
| 682 |
# Wait for bash to exit (it backgrounds the daemon and exits
|
| 683 |
# immediately). The zombie reaper handles cleanup if we lose
|
| 684 |
# the race.
|
| 685 |
try:
|
| 686 |
+
proc.wait(timeout=5)
|
|
|
|
| 687 |
except sp.TimeoutExpired:
|
| 688 |
+
pass
|
| 689 |
except ChildProcessError:
|
| 690 |
+
pass
|
| 691 |
except Exception as exc:
|
|
|
|
| 692 |
logger.warning("Start command failed for %s: %s", svc.daemon, exc)
|
| 693 |
return
|
| 694 |
|
| 695 |
# Brief pause to let the daemon initialize before probing readiness
|
| 696 |
time.sleep(0.5)
|
| 697 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 698 |
# Wait for readiness
|
| 699 |
self._wait_for_readiness(svc)
|
|
|
|
| 700 |
|
| 701 |
def _wait_for_readiness(self, svc: ServiceSpec) -> None:
|
| 702 |
"""Poll the readiness check until success or timeout."""
|
|
|
|
| 1375 |
Returns:
|
| 1376 |
Initial RangeObservation with the challenge briefing.
|
| 1377 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1378 |
self._report_episode_result(completed=False)
|
| 1379 |
self._stop_npcs()
|
| 1380 |
self._teardown_active_project()
|
|
|
|
| 1756 |
return list(self._npc_traffic_log)
|
| 1757 |
|
| 1758 |
def close(self) -> None:
|
| 1759 |
+
"""Release resources (Docker client, NPC manager, episode state).
|
| 1760 |
+
|
| 1761 |
+
In subprocess mode, services are global system processes shared across
|
| 1762 |
+
env instances. They are managed by reset() (episode lifecycle), not by
|
| 1763 |
+
close() — the stateless HTTP handler creates and closes an env per
|
| 1764 |
+
request, and killing services here would undo the work done in reset().
|
| 1765 |
+
"""
|
| 1766 |
self._report_episode_result(completed=False)
|
| 1767 |
self._stop_npcs()
|
| 1768 |
+
if self._execution_mode != "subprocess":
|
| 1769 |
+
self._stop_services()
|
| 1770 |
self._teardown_active_project()
|
| 1771 |
if self._docker_client is not None:
|
| 1772 |
try:
|