Skip to content

Autonomous research system for measurable, computer-executable research.

Python

fix(runtime): preserve process identity and guards on macOS (#197)

Glen-SP4f6ecb2d758e
diff --git a/praxist/cli/registry.py b/praxist/cli/registry.py
index fa2b603..325efd4 100644
--- a/praxist/cli/registry.py
+++ b/praxist/cli/registry.py
@@ -374,7 +374,7 @@ def process_start_token(pid: int) -> str:
ticks since boot. Other POSIX hosts fall back to the process start timestamp
reported by ``ps`` so lifecycle commands remain usable without ``/proc``.
"""
- if pid <= 0:
+ if not isinstance(pid, int) or pid <= 0:
return ""
try:
raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")
@@ -390,7 +390,7 @@ def process_start_token(pid: int) -> str:
if not ps:
return ""
try:
- result = subprocess.run(
+ completed = subprocess.run(
[ps, "-p", str(pid), "-o", "lstart="],
check=False,
capture_output=True,
@@ -398,11 +398,12 @@ def process_start_token(pid: int) -> str:
timeout=2,
env={"LANG": "C", "LC_ALL": "C"},
)
- except (OSError, subprocess.TimeoutExpired):
+ if completed.returncode == 0 and completed.stdout:
+ started = " ".join(completed.stdout.split())
+ if started:
+ return f"ps:{started}"
+ except (OSError, ValueError, TypeError, subprocess.TimeoutExpired):
return ""
- started = " ".join(result.stdout.split())
- if result.returncode == 0 and started:
- return f"ps:{started}"
return ""
diff --git a/praxist/plugins/agent_runtimes/claude_sdk/delete_guard.py b/praxist/plugins/agent_runtimes/claude_sdk/delete_guard.py
index 8e55f71..02fad70 100644
--- a/praxist/plugins/agent_runtimes/claude_sdk/delete_guard.py
+++ b/praxist/plugins/agent_runtimes/claude_sdk/delete_guard.py
@@ -402,7 +402,7 @@ _REGISTERED_RUNTIME_TMP_LINKS: set[tuple[Path, Path]] = set()
def _cleanup_runtime_tmp_link(link: Path, target: Path) -> None:
try:
st = link.lstat()
- if stat.S_ISLNK(st.st_mode) and link.resolve(strict=False) == target:
+ if stat.S_ISLNK(st.st_mode) and link.resolve(strict=False) == target.resolve(strict=False):
link.unlink()
except (OSError, RuntimeError):
pass
@@ -464,7 +464,7 @@ def _ensure_short_runtime_tmp(
continue
if hasattr(os, "geteuid") and st.st_uid != os.geteuid():
continue
- if candidate.resolve(strict=False) != fallback:
+ if candidate.resolve(strict=False) != fallback.resolve(strict=False):
continue
_register_runtime_tmp_link(candidate, fallback)
return candidate
@@ -3931,6 +3931,7 @@ import sqlite3
import ctypes
import _ctypes
import importlib.machinery
+import importlib.util
import time
import fcntl
from urllib.parse import parse_qs, unquote, urlparse
@@ -3989,9 +3990,15 @@ _RUNTIME_TMP_APPARENT = (
else None
)
_RUNTIME_TEMP_DELETE_DIRS = tuple(
- pathlib.Path(raw).expanduser().resolve()
- for raw in ("/dev/shm", os.environ.get("TMPDIR", ""), "/tmp", "/var/tmp")
- if raw
+ dict.fromkeys(
+ path
+ for raw in ("/dev/shm", os.environ.get("TMPDIR", ""), "/tmp", "/var/tmp")
+ if raw
+ for path in (
+ pathlib.Path(raw).expanduser().absolute(),
+ pathlib.Path(raw).expanduser().resolve(),
+ )
+ )
)
@@ -4378,21 +4385,23 @@ def _is_runtime_temp_delete_path(path, cwd=None) -> bool:
try:
apparent = _apparent_path(path, cwd=cwd)
- resolved_parent = apparent.parent.resolve()
+ apparent_parent = apparent.parent
+ resolved_parent = apparent_parent.resolve()
except Exception:
return False
for root in _RUNTIME_TEMP_DELETE_DIRS:
try:
- relative = apparent.relative_to(root)
- except ValueError:
+ relative = apparent_parent.relative_to(root)
+ resolved_root = root.resolve()
+ except (OSError, RuntimeError, ValueError):
continue
if any(
part.startswith(prefix)
- for part in relative.parts
+ for part in (relative.parts + (apparent.name,))
for prefix in _RUNTIME_TEMP_DELETE_PREFIXES
) and (
- resolved_parent == root
- or root in resolved_parent.parents
+ resolved_parent == resolved_root
+ or resolved_root in resolved_parent.parents
or _under_allowed(resolved_parent)
):
return True
@@ -4406,12 +4415,18 @@ def _is_stdlib_tempfile_cleanup(path, cwd=None) -> bool:
return False
try:
apparent = _apparent_path(path, cwd=cwd)
- resolved_parent = apparent.parent.resolve()
+ apparent_parent = apparent.parent
+ resolved_parent = apparent_parent.resolve()
st = apparent.lstat()
except (FileNotFoundError, OSError):
return False
if not any(
- resolved_parent == root or root in resolved_parent.parents
+ (apparent_parent == root or root in apparent_parent.parents)
+ and (
+ resolved_parent == root.resolve()
+ or root.resolve() in resolved_parent.parents
+ or _under_allowed(resolved_parent)
+ )
for root in _RUNTIME_TEMP_DELETE_DIRS
):
return False
@@ -6618,6 +6633,24 @@ if _orig_posix_spawnp is not None:
for _name in list(globals()):
if _name.startswith("_orig_") and _name != "_orig_for":
globals()[_name] = None
+
+# Preserve an existing interpreter/site customization, but only after Praxist's
+# filesystem and subprocess guards are active. Resolve candidates so an alias of
+# this generated directory cannot recursively load the guard itself.
+try:
+ _this_file = pathlib.Path(__file__).resolve()
+ for _path_entry in list(sys.path):
+ if not _path_entry:
+ continue
+ _candidate = pathlib.Path(_path_entry) / "sitecustomize.py"
+ if _candidate.is_file() and _candidate.resolve() != _this_file:
+ _spec = importlib.util.spec_from_file_location("_next_sitecustomize", _candidate)
+ if _spec and _spec.loader:
+ _module = importlib.util.module_from_spec(_spec)
+ _spec.loader.exec_module(_module)
+ break
+except Exception:
+ pass
'''
return (
body.replace("__PRAXIST_PROTECTED_ROOT_ENV_KEYS__", repr(PROTECTED_ROOT_ENV_KEYS))
diff --git a/praxist/plugins/tools/evaluation_tools/adapter.py b/praxist/plugins/tools/evaluation_tools/adapter.py
index 3eecb75..aca1173 100644
--- a/praxist/plugins/tools/evaluation_tools/adapter.py
+++ b/praxist/plugins/tools/evaluation_tools/adapter.py
@@ -15,6 +15,7 @@ import logging
import math
import os
import re
+import tempfile
import time
from contextlib import suppress
from datetime import datetime
@@ -709,6 +710,12 @@ async def _handle_wait_for_file_impl(args: dict[str, Any]) -> dict[str, Any]:
allowed_roots.append(repo_root)
except IndexError:
pass
+ try:
+ temp_root = Path(tempfile.gettempdir()).resolve()
+ if temp_root not in DANGEROUS_ROOTS:
+ allowed_roots.append(temp_root)
+ except (OSError, RuntimeError):
+ pass
allowed_roots.append(Path("/tmp").resolve())
def _path_allowed(rp: Path) -> bool:
diff --git a/praxist/plugins/workflow_stages/research_loop/backend/experiment_exec.py b/praxist/plugins/workflow_stages/research_loop/backend/experiment_exec.py
index e60c490..132a159 100644
--- a/praxist/plugins/workflow_stages/research_loop/backend/experiment_exec.py
+++ b/praxist/plugins/workflow_stages/research_loop/backend/experiment_exec.py
@@ -4,11 +4,39 @@ from __future__ import annotations
import json
import os
+import shutil
+import subprocess
import sys
import time
from pathlib import Path
+def _pid_start_time(pid: int) -> int | str | None:
+ """Return the launcher's process-instance token without project imports."""
+
+ try:
+ suffix = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1]
+ return int(suffix.split()[19])
+ except (OSError, ValueError, IndexError):
+ pass
+ ps = shutil.which("ps")
+ if not ps:
+ return None
+ try:
+ completed = subprocess.run(
+ [ps, "-p", str(pid), "-o", "lstart="],
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=2,
+ env={"LANG": "C", "LC_ALL": "C"},
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ started = " ".join(completed.stdout.split())
+ return f"ps:{started}" if completed.returncode == 0 and started else None
+
+
def main() -> int:
"""Wait for scheduler commit, then replace this barrier with the task command."""
@@ -18,11 +46,7 @@ def main() -> int:
go_path = Path(sys.argv[2])
attempt_id = sys.argv[3]
command = sys.argv[4:]
- try:
- suffix = Path(f"/proc/{os.getpid()}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1]
- pid_start_time = int(suffix.split()[19])
- except (OSError, ValueError, IndexError):
- pid_start_time = None
+ pid_start_time = _pid_start_time(os.getpid())
temporary = ready_path.with_suffix(".tmp")
temporary.write_text(
json.dumps(
diff --git a/praxist/plugins/workflow_stages/research_loop/backend/experiment_process.py b/praxist/plugins/workflow_stages/research_loop/backend/experiment_process.py
index 806fbee..ac84695 100644
--- a/praxist/plugins/workflow_stages/research_loop/backend/experiment_process.py
+++ b/praxist/plugins/workflow_stages/research_loop/backend/experiment_process.py
@@ -41,29 +41,28 @@ def _linux_process_group_activity(pgid: int) -> bool | None:
if sys.platform != "linux":
return None
proc_root = Path("/proc")
- if not proc_root.is_dir():
+ if not proc_root.is_dir(): # pragma: no cover - non-procfs Linux
return None
observed_member = False
try:
- entries = os.scandir(proc_root)
+ with os.scandir(proc_root) as entries:
+ for entry in entries:
+ if not entry.name.isdigit():
+ continue
+ try:
+ stat = Path(entry.path, "stat").read_bytes()
+ fields = stat.rsplit(b")", 1)[1].split()
+ state, member_pgid = fields[0].decode("ascii"), int(fields[2])
+ if member_pgid != pgid:
+ continue
+ observed_member = True
+ if state not in {"X", "x", "Z"}:
+ return True
+ except (OSError, IndexError, ValueError):
+ continue
except OSError:
return None
- with entries:
- for entry in entries:
- if not entry.name.isdigit():
- continue
- try:
- stat = Path(entry.path, "stat").read_bytes()
- fields = stat.rsplit(b")", 1)[1].split()
- state, member_pgid = fields[0].decode("ascii"), int(fields[2])
- except (OSError, IndexError, ValueError):
- continue
- if member_pgid != pgid:
- continue
- observed_member = True
- if state not in {"X", "x", "Z"}:
- return True
return False if observed_member else None
diff --git a/praxist/plugins/workflow_stages/research_loop/backend/experiment_scheduler.py b/praxist/plugins/workflow_stages/research_loop/backend/experiment_scheduler.py
index 6271afe..babb2ec 100644
--- a/praxist/plugins/workflow_stages/research_loop/backend/experiment_scheduler.py
+++ b/praxist/plugins/workflow_stages/research_loop/backend/experiment_scheduler.py
@@ -3801,18 +3801,23 @@ class ExperimentSchedulerService:
pgid = int(payload.get("pgid", 0) or 0)
recorded_attempt = str(payload.get("attempt_id", ""))
recorded_start = payload.get("pid_start_time")
- current_start = _pid_start_time(pid)
- command = (Path("/proc") / str(pid) / "cmdline").read_bytes().split(b"\0")
- ready_argument = str(ready_path).encode("utf-8")
- attempt_argument = attempt_id.encode("utf-8")
- if ready_argument not in command:
- raise ValueError("READY process does not own this attempt path")
- if recorded_attempt and recorded_attempt != attempt_id:
+ if pid <= 0 or pgid <= 1:
+ raise ValueError("READY process identity is invalid")
+ if recorded_attempt != attempt_id:
raise ValueError("READY attempt identity mismatch")
- if recorded_attempt and attempt_argument not in command:
- raise ValueError("READY process command lacks attempt identity")
- if recorded_start is not None and int(recorded_start) != current_start:
+ current_start = _pid_start_time(pid)
+ if recorded_start is None or current_start is None:
+ raise ValueError("READY process start identity is unavailable")
+ if str(recorded_start) != str(current_start):
raise ValueError("READY process identity was reused")
+ if Path("/proc").is_dir():
+ command = (Path("/proc") / str(pid) / "cmdline").read_bytes().split(b"\0")
+ ready_argument = str(ready_path).encode("utf-8")
+ attempt_argument = attempt_id.encode("utf-8")
+ if ready_argument not in command:
+ raise ValueError("READY process does not own this attempt path")
+ if attempt_argument not in command:
+ raise ValueError("READY process command lacks attempt identity")
return {"pid": pid, "pgid": pgid}
except (OSError, ValueError, TypeError, json.JSONDecodeError):
time.sleep(0.05)
@@ -3855,12 +3860,12 @@ class ExperimentSchedulerService:
return False
recorded_start = event.get("pid_start_time")
if recorded_start is not None:
- try:
- return int(recorded_start) == _pid_start_time(pid)
- except (TypeError, ValueError):
- return False
+ current_start = _pid_start_time(pid)
+ return current_start is not None and str(recorded_start) == str(current_start)
if attempt_dir is None:
return False
+ if not Path("/proc").is_dir():
+ return False
try:
arguments = (Path("/proc") / str(pid) / "cmdline").read_bytes().split(b"\0")
except OSError:
diff --git a/praxist/plugins/workflow_stages/research_loop/backend/protected_pids.py b/praxist/plugins/workflow_stages/research_loop/backend/protected_pids.py
index 6561ddb..6992447 100644
--- a/praxist/plugins/workflow_stages/research_loop/backend/protected_pids.py
+++ b/praxist/plugins/workflow_stages/research_loop/backend/protected_pids.py
@@ -76,7 +76,7 @@ def _run_dir_from_protected_env() -> Path | None:
override = os.environ.get(ENV_PROTECTED_DIR)
if not override:
return None
- protected_dir = Path(override)
+ protected_dir = Path(override).expanduser().resolve(strict=False)
return protected_dir.parent if protected_dir.name == "protected_pids" else None
@@ -271,9 +271,10 @@ def _pid_start_time(pid: int) -> int | str | None:
suffix = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1]
return int(suffix.split()[19])
except (OSError, ValueError, IndexError):
- from praxist.cli.registry import process_start_token
+ pass
+ from praxist.cli.registry import process_start_token
- return process_start_token(pid) or None
+ return process_start_token(pid) or None
def _entry_process_identity_matches(entry: ProtectedEntry) -> bool:
@@ -281,7 +282,8 @@ def _entry_process_identity_matches(entry: ProtectedEntry) -> bool:
if entry.pid_start_time is None:
return True
- return _pid_start_time(entry.pid) == entry.pid_start_time
+ current = _pid_start_time(entry.pid)
+ return current is not None and str(current) == str(entry.pid_start_time)
def _entry_is_alive(entry: ProtectedEntry) -> bool:
diff --git a/praxist/plugins/workflow_stages/research_loop/backend/resource_scheduler.py b/praxist/plugins/workflow_stages/research_loop/backend/resource_scheduler.py
index 89c07bd..5e5cda2 100644
--- a/praxist/plugins/workflow_stages/research_loop/backend/resource_scheduler.py
+++ b/praxist/plugins/workflow_stages/research_loop/backend/resource_scheduler.py
@@ -807,12 +807,14 @@ def _process_group_alive(item: dict[str, Any]) -> bool:
return False
-def _pid_start_time(pid: int) -> int | None:
+def _pid_start_time(pid: int) -> int | str | None:
try:
suffix = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1]
return int(suffix.split()[19])
except (OSError, ValueError, IndexError):
- return None
+ from praxist.cli.registry import process_start_token
+
+ return process_start_token(pid) or None
def _resource_owner_group(run_id: str) -> set[str]:
diff --git a/tests/hardening/test_task_project_boundary.py b/tests/hardening/test_task_project_boundary.py
index b57fb99..b7e85c1 100644
--- a/tests/hardening/test_task_project_boundary.py
+++ b/tests/hardening/test_task_project_boundary.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
import subprocess
+import sys
import tempfile
import unittest
from pathlib import Path
@@ -137,7 +138,7 @@ class TaskProjectBoundaryTest(unittest.TestCase):
evaluator_help = subprocess.run(
[
- "python",
+ sys.executable,
str(task_root / "evaluations" / "primary" / "run.py"),
"--help",
],
diff --git a/tests/unit/test_central_experiment_scheduler.py b/tests/unit/test_central_experiment_scheduler.py
index dfdc39b..9bf418c 100644
--- a/tests/unit/test_central_experiment_scheduler.py
+++ b/tests/unit/test_central_experiment_scheduler.py
@@ -612,7 +612,7 @@ class ExperimentSchedulerTest(unittest.TestCase):
def test_recovered_queued_task_reapplies_task_runtime_boundary(self) -> None:
with tempfile.TemporaryDirectory() as td:
- root = Path(td)
+ root = Path(td).resolve()
task_root = root / "task"
evaluator = task_root / "evaluations" / "run.py"
task_python = task_root / ".venv" / "bin" / "python"
@@ -679,7 +679,7 @@ class ExperimentSchedulerTest(unittest.TestCase):
def test_recovered_job_rebases_task_owned_paths_after_checkout_moves(self) -> None:
with tempfile.TemporaryDirectory() as td:
- root = Path(td)
+ root = Path(td).resolve()
old_root = root / "old" / "task"
new_root = root / "new" / "task"
old_workspace = root / "old"
@@ -972,7 +972,7 @@ class ExperimentSchedulerTest(unittest.TestCase):
def test_task_child_drops_runner_python_paths_unless_task_declares_them(self) -> None:
with tempfile.TemporaryDirectory() as td:
- task_root = Path(td) / "task"
+ task_root = Path(td).resolve() / "task"
task_root.mkdir()
service = ExperimentSchedulerService(
run_dir=Path(td) / "run",
@@ -1425,6 +1425,8 @@ class ExperimentSchedulerTest(unittest.TestCase):
resumed.stop()
def test_launch_intent_finds_delayed_ready_process_without_requeue(self) -> None:
+ if not Path("/proc").is_dir():
+ self.skipTest("/proc filesystem required for process cmdline inspection")
with tempfile.TemporaryDirectory() as td:
run_dir = Path(td) / "run"
interrupted = ExperimentSchedulerService(
@@ -1940,6 +1942,23 @@ class ExperimentSchedulerTest(unittest.TestCase):
{"pid": 1, "pgid": 1, "pid_start_time": "bad"}, attempt_dir=None
)
)
+ with (
+ patch.object(Path, "is_dir", return_value=False),
+ patch(
+ "praxist.plugins.workflow_stages.research_loop.backend."
+ "experiment_scheduler._pid_start_time",
+ return_value="ps:stable-start",
+ ),
+ ):
+ self.assertTrue(
+ service._event_process_matches(
+ {"pid": 1, "pgid": 1, "pid_start_time": "ps:stable-start"},
+ attempt_dir=Path(td),
+ )
+ )
+ self.assertFalse(
+ service._event_process_matches({"pid": 1, "pgid": 1}, attempt_dir=Path(td))
+ )
self.assertFalse(
service._event_process_matches({"pid": 1, "pgid": 1}, attempt_dir=None)
)
@@ -2163,6 +2182,56 @@ class ExperimentSchedulerTest(unittest.TestCase):
{"pid": 123, "pgid": 123},
)
+ portable_payload = json.dumps(
+ {
+ "pid": 123,
+ "pgid": 123,
+ "attempt_id": "attempt-a1",
+ "pid_start_time": "ps:stable-start",
+ }
+ )
+ with (
+ patch.object(Path, "read_text", return_value=portable_payload),
+ patch.object(Path, "is_dir", return_value=False),
+ patch(
+ "praxist.plugins.workflow_stages.research_loop.backend."
+ "experiment_scheduler._pid_start_time",
+ return_value="ps:stable-start",
+ ),
+ ):
+ self.assertEqual(
+ ExperimentSchedulerService._read_ready_process(attempt_dir, "attempt-a1"),
+ {"pid": 123, "pgid": 123},
+ )
+
+ for invalid_portable in (
+ {**json.loads(portable_payload), "attempt_id": "other"},
+ {**json.loads(portable_payload), "pid_start_time": None},
+ ):
+ with (
+ self.subTest(portable_payload=invalid_portable),
+ patch.object(Path, "read_text", return_value=json.dumps(invalid_portable)),
+ patch.object(Path, "is_dir", return_value=False),
+ patch(
+ "praxist.plugins.workflow_stages.research_loop.backend."
+ "experiment_scheduler._pid_start_time",
+ return_value="ps:stable-start",
+ ),
+ patch(
+ "praxist.plugins.workflow_stages.research_loop.backend."
+ "experiment_scheduler.time.monotonic",
+ side_effect=[0.0, 0.0, 3.0],
+ ),
+ patch(
+ "praxist.plugins.workflow_stages.research_loop.backend."
+ "experiment_scheduler.time.sleep"
+ ),
+ ):
+ self.assertEqual(
+ ExperimentSchedulerService._read_ready_process(attempt_dir, "attempt-a1"),
+ {},
+ )
+
invalid_payloads = [
({**json.loads(payload), "attempt_id": "other"}, command),
(json.loads(payload), b"python\0" + str(ready_path).encode() + b"\0"),
@@ -2398,7 +2467,7 @@ class ExperimentSchedulerTest(unittest.TestCase):
finally:
os.chdir(previous)
self.assertTrue(service.run_dir.is_absolute())
- self.assertEqual(service.run_dir, Path(td) / "relative-run")
+ self.assertEqual(service.run_dir, Path(td).resolve() / "relative-run")
def test_unknown_explicit_profile_is_rejected_without_default_fallback(self) -> None:
with tempfile.TemporaryDirectory() as td:
@@ -2460,10 +2529,10 @@ class ExperimentSchedulerTest(unittest.TestCase):
def test_final_launcher_preserves_submitter_environment_and_cwd(self) -> None:
with tempfile.TemporaryDirectory() as td:
- run_dir = Path(td) / "run"
- work_dir = Path(td) / "peer-workspace"
+ run_dir = Path(td).resolve() / "run"
+ work_dir = Path(td).resolve() / "peer-workspace"
work_dir.mkdir()
- output = Path(td) / "context.json"
+ output = Path(td).resolve() / "context.json"
service = ExperimentSchedulerService(
run_dir=run_dir,
settings=_settings(maximum=1),
@@ -2498,7 +2567,7 @@ class ExperimentSchedulerTest(unittest.TestCase):
def test_relative_evaluator_runs_from_task_root_with_isolated_python_environment(self) -> None:
with tempfile.TemporaryDirectory() as td:
- root = Path(td)
+ root = Path(td).resolve()
run_dir = root / "run"
task_root = root / "task"
caller_cwd = run_dir / "gen_0" / "peer_workspace"
@@ -3160,6 +3229,8 @@ class ExperimentSchedulerTest(unittest.TestCase):
self.assertNotIn(job.job_id, service._queue)
def test_legacy_event_and_manifest_pair_recovers_live_job(self) -> None:
+ if not Path("/proc").is_dir():
+ self.skipTest("/proc filesystem required for process environment inspection")
with tempfile.TemporaryDirectory() as td:
run_dir = Path(td) / "run"
process_env = {
@@ -3388,8 +3459,8 @@ class ExperimentSchedulerTest(unittest.TestCase):
def test_launch_intent_recovers_waiting_barrier_without_duplicate_execution(self) -> None:
with tempfile.TemporaryDirectory() as td:
- run_dir = Path(td) / "run"
- marker = Path(td) / "executed"
+ run_dir = Path(td).resolve() / "run"
+ marker = Path(td).resolve() / "executed"
first = ExperimentSchedulerService(
run_dir=run_dir,
settings=_settings(maximum=1),
@@ -3493,7 +3564,7 @@ class ExperimentSchedulerTest(unittest.TestCase):
def test_recovery_requeues_waiting_barrier_after_task_checkout_moves(self) -> None:
with tempfile.TemporaryDirectory() as td:
- root = Path(td)
+ root = Path(td).resolve()
run_dir = root / "run"
old_task = root / "old" / "task"
new_task = root / "new" / "task"
@@ -3847,6 +3918,8 @@ class ExperimentSchedulerTest(unittest.TestCase):
return_value="ps:stable-start",
):
self.assertTrue(protected_pids._entry_process_identity_matches(entry))
+ with patch.object(protected_pids, "_pid_start_time", return_value=None):
+ self.assertFalse(protected_pids._entry_process_identity_matches(entry))
def test_run_owned_endpoint_prevents_peer_from_downgrading_to_legacy(self) -> None:
with tempfile.TemporaryDirectory() as td:
@@ -4370,7 +4443,7 @@ class ExperimentSchedulerTest(unittest.TestCase):
def test_nested_task_child_reuses_the_shared_task_runtime_boundary(self) -> None:
with tempfile.TemporaryDirectory() as td:
- root = Path(td)
+ root = Path(td).resolve()
task_root = root / "task"
run_dir = root / "run"
caller_cwd = run_dir / "attempt"
diff --git a/tests/unit/test_central_resource_allocator.py b/tests/unit/test_central_resource_allocator.py
index 9326332..49fc31e 100644
--- a/tests/unit/test_central_resource_allocator.py
+++ b/tests/unit/test_central_resource_allocator.py
@@ -257,9 +257,18 @@ class ResourceAllocatorTest(unittest.TestCase):
{"record_type": "allocation", "pid": 123, "pgid": 0}
)
)
- with patch.object(Path, "read_text", side_effect=OSError("gone")):
+ with (
+ patch.object(Path, "read_text", side_effect=OSError("gone")),
+ patch("praxist.cli.registry.process_start_token", return_value=""),
+ ):
self.assertIsNone(resource_scheduler._pid_start_time(999999))
+ with (
+ patch.object(Path, "read_text", side_effect=OSError("no procfs")),
+ patch("praxist.cli.registry.process_start_token", return_value="ps:stable-start"),
+ ):
+ self.assertEqual(resource_scheduler._pid_start_time(4321), "ps:stable-start")
+
def test_legacy_config_and_driver_failures_fall_back_without_crashing(self) -> None:
legacy = SchedulerSettings.from_dict(
{
diff --git a/tests/unit/test_central_scheduler_boundaries.py b/tests/unit/test_central_scheduler_boundaries.py
index 377a4f2..72ec888 100644
--- a/tests/unit/test_central_scheduler_boundaries.py
+++ b/tests/unit/test_central_scheduler_boundaries.py
@@ -172,11 +172,36 @@ class LaunchBarrierBoundaryTest(unittest.TestCase):
["experiment_exec", str(ready), str(go), "attempt-2", "task"],
),
patch.object(Path, "read_text", side_effect=OSError("proc unavailable")),
+ patch.object(experiment_exec.shutil, "which", return_value=None),
patch.object(os, "execvpe", side_effect=OSError("not executable")),
):
self.assertEqual(experiment_exec.main(), 75)
self.assertIsNone(json.loads(ready.read_text(encoding="utf-8"))["pid_start_time"])
+ def test_barrier_uses_ps_identity_without_procfs(self) -> None:
+ completed = subprocess.CompletedProcess(
+ args=["ps"],
+ returncode=0,
+ stdout="Thu Sep 5 10:11:12 2026\n",
+ stderr="",
+ )
+ with (
+ patch.object(Path, "read_text", side_effect=OSError("proc unavailable")),
+ patch.object(experiment_exec.shutil, "which", return_value="/usr/bin/ps"),
+ patch.object(experiment_exec.subprocess, "run", return_value=completed),
+ ):
+ observed = experiment_exec._pid_start_time(4321)
+
+ self.assertEqual(observed, "ps:Thu Sep 5 10:11:12 2026")
+
+ def test_barrier_tolerates_ps_identity_probe_failure(self) -> None:
+ with (
+ patch.object(Path, "read_text", side_effect=OSError("proc unavailable")),
+ patch.object(experiment_exec.shutil, "which", return_value="/usr/bin/ps"),
+ patch.object(experiment_exec.subprocess, "run", side_effect=OSError("ps unavailable")),
+ ):
+ self.assertIsNone(experiment_exec._pid_start_time(4321))
+
def test_barrier_times_out_without_scheduler_commit(self) -> None:
with (
tempfile.TemporaryDirectory() as td,
@@ -518,7 +543,7 @@ class SchedulerClientBoundaryTest(unittest.TestCase):
def test_static_shell_wrappers_use_the_declared_task_interpreter(self) -> None:
with tempfile.TemporaryDirectory() as td:
- root = Path(td)
+ root = Path(td).resolve()
task_root = root / "task"
run_cwd = root / "run"
evaluator = task_root / "evaluations" / "run.py"
@@ -567,7 +592,7 @@ class SchedulerClientBoundaryTest(unittest.TestCase):
def test_static_env_chdir_runs_task_evaluator_from_non_task_cwd(self) -> None:
with tempfile.TemporaryDirectory() as td:
- root = Path(td)
+ root = Path(td).resolve()
task_root = root / "task"
run_cwd = root / "run"
evaluator = task_root / "evaluations" / "v2" / "run.py"
diff --git a/tests/unit/test_claude_delete_guard_contracts.py b/tests/unit/test_claude_delete_guard_contracts.py
index cfbe7ff..3e1251b 100644
--- a/tests/unit/test_claude_delete_guard_contracts.py
+++ b/tests/unit/test_claude_delete_guard_contracts.py
@@ -6,11 +6,100 @@ import subprocess
import sys
import tempfile
import unittest
+import uuid
from pathlib import Path
from unittest import mock
class ClaudeDeleteGuardContractsTest(unittest.TestCase):
+ def test_runtime_temp_prefix_cannot_escape_through_parent_symlink(self) -> None:
+ from praxist.plugins.agent_runtimes.claude_sdk.delete_guard import (
+ prepare_delete_guard_env,
+ )
+
+ with tempfile.TemporaryDirectory(dir=Path.home()) as tmp:
+ run_dir = Path(tmp) / "task" / "experiments" / "run"
+ protected_dir = run_dir / "shared_findings"
+ protected_dir.mkdir(parents=True)
+ protected_file = protected_dir / "finding.json"
+ protected_file.write_text("keep", encoding="utf-8")
+ escape_link = Path("/tmp") / f"pym-praxist-guard-{uuid.uuid4().hex}"
+ escape_link.symlink_to(protected_dir, target_is_directory=True)
+ guarded = prepare_delete_guard_env(
+ {**os.environ, "PRAXIST_RUN_DIR": str(run_dir), "PEER_ID": "gen0_peer0"},
+ workspace=run_dir,
+ agent_name="gen0_peer0",
+ )
+ runtime_tmp = Path(guarded["TMPDIR"])
+ try:
+ probe = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "import os,sys; os.unlink(sys.argv[1])",
+ str(escape_link / protected_file.name),
+ ],
+ env=guarded,
+ cwd=run_dir,
+ text=True,
+ capture_output=True,
+ timeout=20,
+ )
+ self.assertNotEqual(probe.returncode, 0)
+ self.assertTrue(protected_file.exists())
+ finally:
+ escape_link.unlink(missing_ok=True)
+ runtime_tmp.unlink(missing_ok=True)
+
+ def test_chained_sitecustomize_runs_after_delete_guard_activation(self) -> None:
+ from praxist.plugins.agent_runtimes.claude_sdk.delete_guard import (
+ prepare_delete_guard_env,
+ )
+
+ with tempfile.TemporaryDirectory(dir=Path.home()) as tmp:
+ task_root = Path(tmp) / "task"
+ run_dir = task_root / "experiments" / "run"
+ protected_dir = run_dir / "shared_findings"
+ startup_dir = task_root / "startup"
+ protected_dir.mkdir(parents=True)
+ startup_dir.mkdir(parents=True)
+ protected_file = protected_dir / "finding.json"
+ protected_file.write_text("keep", encoding="utf-8")
+ (startup_dir / "sitecustomize.py").write_text(
+ "import os\n"
+ "try:\n"
+ " os.unlink(os.environ['PRAXIST_TEST_PROTECTED_FILE'])\n"
+ "except PermissionError:\n"
+ " print('chained_sitecustomize_guarded')\n",
+ encoding="utf-8",
+ )
+ guarded = prepare_delete_guard_env(
+ {
+ **os.environ,
+ "PYTHONPATH": str(startup_dir),
+ "PRAXIST_RUN_DIR": str(run_dir),
+ "PEER_ID": "gen0_peer0",
+ "PRAXIST_TEST_PROTECTED_FILE": str(protected_file),
+ },
+ workspace=run_dir,
+ agent_name="gen0_peer0",
+ )
+ runtime_tmp = Path(guarded["TMPDIR"])
+ try:
+ probe = subprocess.run(
+ [sys.executable, "-c", "pass"],
+ env=guarded,
+ cwd=run_dir,
+ text=True,
+ capture_output=True,
+ timeout=20,
+ )
+ self.assertEqual(probe.returncode, 0, probe.stderr)
+ self.assertIn("chained_sitecustomize_guarded", probe.stdout)
+ self.assertTrue(protected_file.exists())
+ finally:
+ runtime_tmp.unlink(missing_ok=True)
+
def test_long_run_path_uses_short_tmpdir_for_multiprocessing(self) -> None:
from praxist.plugins.agent_runtimes.claude_sdk.delete_guard import (
prepare_delete_guard_env,
@@ -248,7 +337,7 @@ class ClaudeDeleteGuardContractsTest(unittest.TestCase):
from praxist.plugins.agent_runtimes.claude_sdk import delete_guard
with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
+ root = Path(tmp).resolve()
target = root / "target"
target.mkdir()
matching = root / "matching"
diff --git a/tests/unit/test_cli_start.py b/tests/unit/test_cli_start.py
index 58a0a76..ad9c44f 100644
--- a/tests/unit/test_cli_start.py
+++ b/tests/unit/test_cli_start.py
@@ -1363,7 +1363,7 @@ class StartCliEndToEndTest(unittest.TestCase):
self.assertIn("praxist --monitor --run-id", err)
def test_dispatcher_hint_shell_quotes_explicit_run_dir(self) -> None:
- run_dir = Path(self.workspace.name) / "run with spaces;printf unsafe"
+ run_dir = Path(self.workspace.name).resolve() / "run with spaces;printf unsafe"
code, out, err = self._run(
["start", "--task-path", str(self.task), "--run-dir", str(run_dir)]
)
diff --git a/tests/unit/test_cli_stop.py b/tests/unit/test_cli_stop.py
index 98be0ed..155f177 100644
--- a/tests/unit/test_cli_stop.py
+++ b/tests/unit/test_cli_stop.py
@@ -532,7 +532,7 @@ class StopRunTest(_StateDirMixin, unittest.TestCase):
with patch.object(Path, "read_bytes", return_value=payload):
self.assertEqual(
stop._run_dir_from_process_environment(123),
- Path("/tmp/exact-run"),
+ Path("/tmp/exact-run").resolve(),
)
def test_cwd_fallback_is_limited_to_run_owned_peer_workspaces(self) -> None:
diff --git a/tests/unit/test_cli_takeover.py b/tests/unit/test_cli_takeover.py
index 8a34fbf..065cddd 100644
--- a/tests/unit/test_cli_takeover.py
+++ b/tests/unit/test_cli_takeover.py
@@ -129,7 +129,7 @@ class TakeoverCliTest(unittest.TestCase):
def test_explicit_configured_provider_launches_without_shell(self) -> None:
with tempfile.TemporaryDirectory() as raw:
- root = Path(raw)
+ root = Path(raw).resolve()
completed = subprocess.CompletedProcess([], 0)
with (
patch("praxist.cli.takeover.shutil.which", return_value="/usr/bin/codex"),
@@ -153,7 +153,7 @@ class TakeoverCliTest(unittest.TestCase):
def test_explicit_claude_operator_uses_claude_skill_syntax(self) -> None:
with tempfile.TemporaryDirectory() as raw:
- root = Path(raw)
+ root = Path(raw).resolve()
completed = subprocess.CompletedProcess([], 0)
with (
patch("praxist.cli.takeover.shutil.which", return_value="/usr/bin/claude"),
diff --git a/tests/unit/test_cli_uninstall.py b/tests/unit/test_cli_uninstall.py
index 32ebc3b..e1f4d4a 100644
--- a/tests/unit/test_cli_uninstall.py
+++ b/tests/unit/test_cli_uninstall.py
@@ -72,7 +72,7 @@ class PraxistUninstallTest(unittest.TestCase):
def test_default_skill_targets_include_each_managed_agent_host(self) -> None:
with tempfile.TemporaryDirectory() as tmp_raw:
- root = Path(tmp_raw)
+ root = Path(tmp_raw).resolve()
codex = root / "codex"
claude = root / "claude"
for target in (codex, claude):
diff --git a/tests/unit/test_codex_sdk_adapter.py b/tests/unit/test_codex_sdk_adapter.py
index ca2576c..eaa31c6 100644
--- a/tests/unit/test_codex_sdk_adapter.py
+++ b/tests/unit/test_codex_sdk_adapter.py
@@ -911,7 +911,7 @@ class RuntimeExecutionTest(unittest.IsolatedAsyncioTestCase):
self.addAsyncCleanup(runtime.aclose)
harness = _SdkHarness()
with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
+ root = Path(tmp).resolve()
run_dir = root / "run"
run_dir.mkdir()
codex_home = root / "operator-codex"
diff --git a/tests/unit/test_codex_sdk_auth.py b/tests/unit/test_codex_sdk_auth.py
index 1ae4097..b0210c1 100644
--- a/tests/unit/test_codex_sdk_auth.py
+++ b/tests/unit/test_codex_sdk_auth.py
@@ -394,7 +394,7 @@ class ChatGptCredentialDiscoveryTest(unittest.TestCase):
from praxist.plugins.agent_runtimes.codex_sdk._auth import stage_chatgpt_home
with tempfile.TemporaryDirectory() as tmp:
- operator_home = Path(tmp)
+ operator_home = Path(tmp).resolve()
marker = operator_home / "config.toml"
marker.write_text('model = "operator-default"\n', encoding="utf-8")
staged = stage_chatgpt_home(operator_home)
diff --git a/tests/unit/test_packaging_contracts.py b/tests/unit/test_packaging_contracts.py
index d05449f..9d5aee6 100644
--- a/tests/unit/test_packaging_contracts.py
+++ b/tests/unit/test_packaging_contracts.py
@@ -109,7 +109,7 @@ class PyprojectPackagingContracts(unittest.TestCase):
def test_fake_workflow_uses_packaged_fixture_plugins_when_available(self) -> None:
with TemporaryDirectory(prefix="praxist_packaged_fixtures_") as tmp_raw:
- package_root = Path(tmp_raw) / "site-packages" / "praxist"
+ package_root = Path(tmp_raw).resolve() / "site-packages" / "praxist"
module_path = package_root / "testing" / "fake_workflow_fixture.py"
fixture_root = package_root / "testing" / "fixtures" / "plugins"
fixture_root.mkdir(parents=True)
diff --git a/tests/unit/test_peer_memory_contracts.py b/tests/unit/test_peer_memory_contracts.py
index 3be6246..2d8930c 100644
--- a/tests/unit/test_peer_memory_contracts.py
+++ b/tests/unit/test_peer_memory_contracts.py
@@ -1777,7 +1777,7 @@ class PeerMemoryHealthAggregationTest(unittest.TestCase):
from praxist.plugins.workflow_stages.research_loop.backend import peer_memory
with tempfile.TemporaryDirectory() as tmp:
- run_dir = Path(tmp) / "run"
+ run_dir = Path(tmp).resolve() / "run"
for peer_id, score in (("gen0_peer0", 0.71), ("gen0_peer1", 0.66)):
self._write_state(run_dir, peer_id, {"last_session_success": True})
self._write_result(run_dir, peer_id, score)
diff --git a/tests/unit/test_research_loop_runtime_contracts.py b/tests/unit/test_research_loop_runtime_contracts.py
index a2ae7f0..ba323c8 100644
--- a/tests/unit/test_research_loop_runtime_contracts.py
+++ b/tests/unit/test_research_loop_runtime_contracts.py
@@ -1252,7 +1252,7 @@ class RuntimeResourceGuardContractsTest(unittest.TestCase):
from praxist.plugins.workflow_stages.research_loop.backend import protected_pids
with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
+ root = Path(tmp).resolve()
task_root = root / "task"
caller_cwd = root / "run" / "gen_0" / "peer"
evaluator = task_root / "evaluations" / "run.py"
diff --git a/tests/unit/test_run_report.py b/tests/unit/test_run_report.py
index 052d13e..26e5850 100644
--- a/tests/unit/test_run_report.py
+++ b/tests/unit/test_run_report.py
@@ -26,6 +26,7 @@ from praxist.plugins.workflow_stages.research_loop.backend.run_report import (
class RunReportTest(unittest.TestCase):
def _write_fixture(self, root: Path, *, frontier_score: float = 1.2) -> tuple[Path, Path]:
+ root = root.resolve()
task_dir = root / "task"
run_dir = task_dir / "experiments" / "run_2026-01-01_report"
(task_dir / "assets" / "baselines").mkdir(parents=True)
@@ -229,7 +230,7 @@ class RunReportTest(unittest.TestCase):
def test_report_uses_run_docs_when_run_dir_is_outside_task_dir(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
+ root = Path(tmp).resolve()
task_dir, source_run_dir = self._write_fixture(root)
run_dir = root / "external_run"
run_dir.mkdir()
diff --git a/tests/workflows/test_current_function_migration.py b/tests/workflows/test_current_function_migration.py
index 04580e4..0ddcb3d 100644
--- a/tests/workflows/test_current_function_migration.py
+++ b/tests/workflows/test_current_function_migration.py
@@ -22,7 +22,7 @@ from praxist.plugins.workflow_stages.research_loop.startup import (
class CurrentFunctionMigrationTest(unittest.TestCase):
def test_terminal_finalization_requests_final_report_after_completed_work(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
+ root = Path(tmp).resolve()
run_dir = root / "run_terminal_report"
with patch.dict(os.environ, {}, clear=False):
prepared = prepare_research_loop_plugin_run(
@@ -65,7 +65,7 @@ class CurrentFunctionMigrationTest(unittest.TestCase):
def test_failed_zero_generation_run_still_requests_final_report(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
+ root = Path(tmp).resolve()
run_dir = root / "run_failed_before_generation"
with patch.dict(os.environ, {}, clear=False):
prepared = prepare_research_loop_plugin_run(
@@ -128,7 +128,7 @@ class CurrentFunctionMigrationTest(unittest.TestCase):
def test_startup_loads_external_task_project_and_writes_replay_files(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
+ root = Path(tmp).resolve()
run_dir = root / "run_gate8_toy"
with patch.dict(os.environ, {}, clear=False):
prepared = prepare_research_loop_plugin_run(