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
5.08 kB
"""Isolated Python probe transports with separately preserved output streams."""
from __future__ import annotations
import copy
import json
import urllib.request
from pathlib import Path
from .coding import (
MAX_BYTES,
ExecutionError,
VerifierPytestRunner,
_sync,
execute,
snapshot,
validate_python_command,
)
def command_request(cwd: Path, command: list[str], timeout_s: int, env: dict) -> dict:
"""Normalize only command semantics; source environment values never travel."""
if type(timeout_s) is not int or not 1 <= timeout_s <= 120 or not isinstance(env, dict):
raise ExecutionError("Invalid Python command settings")
if set(env) not in ({"PATH", "PYTHONDONTWRITEBYTECODE"}, {"PATH", "PYTHONDONTWRITEBYTECODE", "HOME"}):
raise ExecutionError("Unsupported Python command environment")
if env.get("PYTHONDONTWRITEBYTECODE") != "1" or ("HOME" in env and env["HOME"] != str(cwd)):
raise ExecutionError("Invalid Python command environment")
return {"mode": "python", "files": snapshot(cwd), "command": validate_python_command(command),
"timeout_s": timeout_s, "home": "HOME" in env}
def command_result(cwd: Path, result: dict) -> tuple[int | None, str, str]:
if (not isinstance(result, dict) or type(result.get("returncode")) not in (int, type(None))
or not isinstance(result.get("stdout"), str) or not isinstance(result.get("stderr"), str)
or "files" not in result):
raise ExecutionError("Invalid Python command result")
if result.get("error"):
raise ExecutionError(str(result["error"]))
_sync(cwd, result["files"])
return result["returncode"], result["stdout"], result["stderr"]
class RemoteCommandRunner:
def __init__(self, url: str):
self.url = url.rstrip("/")
def __call__(self, cwd: Path, command: list[str], timeout_s: int, env: dict) -> tuple[int | None, str, str]:
payload = command_request(cwd, command, timeout_s, env)
request = urllib.request.Request(
self.url + "/execute", data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"}, method="POST",
)
try:
with urllib.request.urlopen(request, timeout=timeout_s + 15) as response:
raw = response.read(MAX_BYTES * 2 + 1)
if len(raw) > MAX_BYTES * 2:
raise ExecutionError("Python command response exceeds limit")
result = json.loads(raw)
if isinstance(result, dict) and result.get("error"):
raise ExecutionError(str(result["error"]))
return command_result(cwd, result)
except ExecutionError:
raise
except Exception as error:
raise ExecutionError("Python command execution worker failed") from error
class VerifierCommandRunner:
"""Use the same root-container/private-mount boundary as verifier pytest."""
def __init__(self):
VerifierPytestRunner()
def __call__(self, cwd: Path, command: list[str], timeout_s: int, env: dict) -> tuple[int | None, str, str]:
return command_result(cwd, execute(command_request(cwd, command, timeout_s, env)))
class RecordingCommandRunner:
def __init__(self, delegate, path: Path):
self.delegate, self.path, self.calls = delegate, Path(path), []
def __call__(self, cwd: Path, command: list[str], timeout_s: int, env: dict) -> tuple[int | None, str, str]:
request = command_request(cwd, command, timeout_s, env)
code, stdout, stderr = self.delegate(cwd, command, timeout_s, env)
result = {"returncode": code, "stdout": stdout, "stderr": stderr, "files": snapshot(cwd)}
command_result(cwd, result)
self.calls.append({"request": request, "result": result})
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps({"schema_version": 1, "fixture": True, "calls": self.calls}, indent=2) + "\n")
return code, stdout, stderr
class ReplayCommandRunner:
def __init__(self, path: Path):
value = json.loads(Path(path).read_text())
if value.get("schema_version") != 1 or value.get("fixture") is not True or not isinstance(value.get("calls"), list):
raise ExecutionError("Invalid fixture command tape")
self.calls, self.cursor = value["calls"], 0
def __call__(self, cwd: Path, command: list[str], timeout_s: int, env: dict) -> tuple[int | None, str, str]:
request = command_request(cwd, command, timeout_s, env)
if self.cursor >= len(self.calls) or self.calls[self.cursor]["request"] != request:
raise ExecutionError(f"Command tape request mismatch at {self.cursor}")
result = copy.deepcopy(self.calls[self.cursor]["result"])
result_tuple = command_result(cwd, result)
self.cursor += 1
return result_tuple
def assert_consumed(self) -> None:
if self.cursor != len(self.calls):
raise ExecutionError("Command tape has unconsumed calls")