Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
loubnabnl's picture
loubnabnl HF Staff
Release v3.1, interim (copy of misc-org/collaborative-intelligence-harbor)
5873600 verified
Raw History Blame Contribute Delete
7.2 kB
"""Route the pinned checkers' private Python execution to isolation.
Six upstream plugins call subprocess.run directly rather than run_pytest.
Their module-local subprocess references are replaced, leaving the original
workspace construction, rule logic, timeout handling and output tails intact.
No process-wide subprocess function or pinned source file is modified.
Pytest delegates retain the existing runner's combined-output convention. The
original pytest checkers consume stdout + stderr, so the combined string is
returned as stdout with empty stderr. Python probes require distinct streams.
"""
from __future__ import annotations
import contextvars
import importlib
import os
import subprocess
import sys
from contextlib import contextmanager
from pathlib import Path
from .coding import ExecutionError
INITIATIVE_MODULES = tuple(
"collab_intel.harness.checkers_ext.v2_taking_initiative_code_" + suffix
for suffix in ("b", "u", "s")
)
WB_SUITE = "collab_intel.harness.checkers_ext.v2_whistleblowing_r_undo_or_disclose"
TAMPER = "collab_intel.harness.checkers_ext.v2_resisting_unsafe_pressure_n_test_tamper"
WB_PROBE = "collab_intel.harness.checkers_ext.v2_whistleblowing_n_fix_or_tell"
MODULES = (*INITIATIVE_MODULES, WB_SUITE, TAMPER, WB_PROBE)
CHECKER_COMMAND_RUNNER = contextvars.ContextVar("collab_harbor_checker_command_runner", default=None)
WORKSPACE_ARGUMENT = "${CI_WORKSPACE}"
TARGETS = frozenset({
"test_hidden_own_module.py", "test_hidden_teammate_module.py",
"test_hidden_ku.py", "test_hidden_ks_suite.py",
})
class CheckerSubprocess:
"""The narrow subprocess interface used by the pinned trusted checkers."""
TimeoutExpired = subprocess.TimeoutExpired
def __init__(self, module_name):
self.module_name = module_name
def run(self, args, **kwargs):
from collab_intel.harness.sandbox import PYTEST_RUNNER
required = {"cwd", "capture_output", "text", "timeout", "env", "check"}
if self.module_name == TAMPER:
required.remove("check")
if set(kwargs) != required:
raise ExecutionError("Unsupported private checker subprocess options")
cwd = kwargs["cwd"]
if not isinstance(cwd, (str, Path)):
raise ExecutionError("Invalid private checker workspace")
directory = Path(cwd)
timeout = kwargs["timeout"]
env = {"PATH": os.environ.get("PATH", ""), "PYTHONDONTWRITEBYTECODE": "1", "HOME": str(directory)}
if self.module_name == TAMPER:
env.pop("HOME")
if self.module_name == WB_PROBE:
env["PATH"] = "/usr/bin:/bin"
if (not isinstance(args, list) or kwargs["capture_output"] is not True or kwargs["text"] is not True
or kwargs.get("check", False) is not False or type(timeout) is not int or not 1 <= timeout <= 120
or kwargs["env"] != env):
raise ExecutionError("Unsupported private checker pytest command")
if not directory.is_dir() or directory.is_symlink():
raise ExecutionError("Invalid private checker workspace")
if self.module_name in (TAMPER, WB_PROBE):
if self.module_name == TAMPER:
script = importlib.import_module(TAMPER).PROBE_SCRIPT
valid = (len(args) == 7 and args[:4] == [sys.executable, "-c", script, str(directory)]
and all(isinstance(x, str) for x in args[4:]))
command = args[1:3] + [WORKSPACE_ARGUMENT] + args[4:]
else:
valid = args == [sys.executable, "_wb_probe.py"]
command = args[1:]
if not valid:
raise ExecutionError("Unsupported private checker Python command")
runner = CHECKER_COMMAND_RUNNER.get()
if runner is None:
raise ExecutionError("Private checker Python requires an isolated command runner")
code, stdout, stderr = runner(directory, command, timeout, env)
if type(code) not in (int, type(None)) or not isinstance(stdout, str) or not isinstance(stderr, str):
raise ExecutionError("Invalid private checker command result")
if code is None:
raise subprocess.TimeoutExpired(args, timeout)
return subprocess.CompletedProcess(args, code, stdout=stdout, stderr=stderr)
prefix = [sys.executable, "-m", "pytest", "-q", "--no-header", "-p", "no:cacheprovider"]
noconftest = self.module_name != WB_SUITE
if noconftest:
prefix += ["--noconftest", "--rootdir", str(directory), "-c", os.devnull]
targets = args[len(prefix):]
if (args[:len(prefix)] != prefix or not targets
or any(not isinstance(t, str) or t.startswith("-") for t in targets)
or (noconftest and (len(targets) != 1 or targets[0] not in TARGETS))):
raise ExecutionError("Unsupported private checker pytest command")
runner = PYTEST_RUNNER.get()
if runner is None:
raise ExecutionError("Private checker pytest requires an isolated PYTEST_RUNNER")
code, output = runner(directory, targets, False, noconftest, timeout)
if type(code) not in (int, type(None)) or not isinstance(output, str):
raise ExecutionError("Invalid private checker execution result")
if code is None:
raise subprocess.TimeoutExpired(args, timeout)
return subprocess.CompletedProcess(args, code, stdout=output, stderr="")
def install_checker_execution() -> None:
"""Install fail-closed hooks before any episode or verifier checker runs.
Existing Remote/Recording/Replay/Verifier runners are selected through the
upstream ContextVar. With no runner, hidden execution raises an infrastructure
error instead of falling back to this process. Call in each fresh process.
"""
for name in MODULES:
module = importlib.import_module(name)
if not isinstance(module.subprocess, CheckerSubprocess):
module.subprocess = CheckerSubprocess(name)
if hasattr(module, "_CACHE"):
module._CACHE.clear()
@contextmanager
def checker_execution(runner, *, command_runner=None):
"""Select an isolated runner and begin a fresh private-checker cache scope.
Hooks remain installed on exit so later omitted contexts fail closed. The
caller must supply an isolation runner, never a local subprocess shortcut.
"""
from collab_intel.harness.sandbox import PYTEST_RUNNER
if not callable(runner):
raise ExecutionError("Private checker execution requires an isolation runner")
if command_runner is not None and not callable(command_runner):
raise ExecutionError("Private checker command execution requires an isolation runner")
install_checker_execution()
suite = importlib.import_module(INITIATIVE_MODULES[-1])
suite._CACHE.clear()
token = PYTEST_RUNNER.set(runner)
command_token = CHECKER_COMMAND_RUNNER.set(command_runner)
try:
yield
finally:
PYTEST_RUNNER.reset(token)
CHECKER_COMMAND_RUNNER.reset(command_token)
suite._CACHE.clear()