diff --git a/benchmark/edgebench/checkpoint_worker.py b/benchmark/edgebench/checkpoint_worker.py index 92d6a4ea79..1f413ebb6f 100644 --- a/benchmark/edgebench/checkpoint_worker.py +++ b/benchmark/edgebench/checkpoint_worker.py @@ -22,6 +22,12 @@ from loopx.file_lock import exclusive_file_lock from benchmark.runtime.checkpoint import _participant_id from benchmark.runtime.checkpoint_handoff import controller_completion_deadline +from benchmark.runtime.research_artifacts import ( + archive_member_content, + is_excluded_tar_member, + is_runner_research_component, + research_component_exclusions, +) from .checkpoint_controller import _controller, _physical, _remaining, _phase_budget, capture @@ -128,7 +134,14 @@ def read(self, *args): return block -def _archive(container, remote: str, destination: Path, *, deadline: float | None = None) -> Path: +def _archive( + container, + remote: str, + destination: Path, + *, + deadline: float | None = None, + exclude_research: bool = False, +) -> Path: """Read through the daemon, rejecting symlinks/devices and archive traversal. Docker's archive reader works while paused, unlike exec-based file readers. @@ -169,36 +182,41 @@ def check(): with tarfile.open(fileobj=_ArchiveReader(raw, deadline) if deadline is not None else raw) as archive: members = [] root = PurePosixPath(remote).name - names = {} - for member in archive: + all_members = {} + for member in archive.getmembers(): check() path = PurePosixPath(member.name) if (path.is_absolute() or ".." in path.parts or not path.parts or - path.parts[0] != root or str(path) in names or + path.parts[0] != root or str(path) in all_members or not (member.isfile() or member.isdir() or member.islnk())): raise ValueError("Worker archive contains undeclared, linked or special members") - names[str(path)] = member + all_members[str(path)] = member members.append(member) # The typed artifact owner observes regular files, not inode # sharing. Docker encodes a second name for the same inode as a # tar hardlink (common in build outputs). Materialize its bytes - # from an inventoried regular member; never resolve a link on - # the host filesystem or permit a link chain/symlink escape. + # from an inventoried regular member and evaluate exclusion on + # the link's own path so local probe and extracted worker + # witnesses agree; never resolve a link on the host filesystem. + kept_members = [] extracted = [] for member in members: check() + path = PurePosixPath(member.name) + content_member = archive_member_content(member, all_members) + regular = member if member.islnk(): - target_path = PurePosixPath(member.linkname) - target = names.get(str(target_path)) - if (target_path.is_absolute() or ".." in target_path.parts or - target is None or not target.isfile()): - raise ValueError("Worker archive contains undeclared, linked or special members") - regular = copy(target) + regular = copy(content_member) regular.name, regular.mode = member.name, member.mode - extracted.append(regular) - else: - extracted.append(member) + if ( + exclude_research + and len(path.parts) > 1 + and is_excluded_tar_member(archive, content_member, path.parts[1:]) + ): + continue + kept_members.append(member) + extracted.append(regular) def filtered(member, path): check() @@ -212,14 +230,21 @@ def filtered(member, path): # bits after safe extraction; never restore owners or special bits. # Otherwise a private 0700 authority directory becomes 0755 and a # matching frozen source is falsely rejected as having changed. - for member in sorted(members, key=lambda entry: len(PurePosixPath(entry.name).parts), reverse=True): + for member in sorted(kept_members, key=lambda entry: len(PurePosixPath(entry.name).parts), reverse=True): check() (destination / member.name).chmod(member.mode & 0o777) check() return _physical(destination / root) -def _archive_component(container, remote: str, destination: Path, *, deadline: float | None = None) -> Path: +def _archive_component( + container, + remote: str, + destination: Path, + *, + deadline: float | None = None, + exclude_research: bool = False, +) -> Path: """Transport a standalone SQLite participant's committed storage too. A paused process can still have committed data only in its WAL. Reading @@ -230,7 +255,13 @@ def _archive_component(container, remote: str, destination: Path, *, deadline: f """ from docker.errors import NotFound - copied = _archive(container, remote, destination, deadline=deadline) + copied = _archive( + container, + remote, + destination, + deadline=deadline, + exclude_research=exclude_research, + ) if not copied.is_file(): return copied with copied.open("rb") as source: @@ -351,15 +382,22 @@ def capture_worker(controller_file: Path, *, token: str, capture_id: str, client.api.timeout = _remaining(deadline) try: copied = _archive_component( - container, entry["source_path"], stage / "workers" / entry["id"], deadline=deadline) + container, + entry["source_path"], + stage / "workers" / entry["id"], + deadline=deadline, + exclude_research=is_runner_research_component(entry), + ) except docker.errors.NotFound as error: # Keep the provider exception for direct capture callers. error.checkpoint_component_id = entry["id"] raise components.append({"id": entry["id"], "source_path": str(copied)}) + exclusions = research_component_exclusions(request["components"]) if prepared is not None: observed = effect_runtime_result("runtime.checkpoint_artifacts", { "action": "probe", "components": components, + **({"component_exclusions": exclusions} if exclusions else {}), }, timeout=_remaining(deadline), retry_safe=False, large_local_snapshot=True) if observed["source_sha256"] != prepared["source_sha256"]: changed = [] @@ -417,12 +455,14 @@ def capture_worker(controller_file: Path, *, token: str, capture_id: str, if prepared is not None: metadata["writer_barrier"] = "docker_pause" probe = effect_runtime_result("runtime.checkpoint_artifacts", {"action": "probe", "components": components, - "deadline_epoch_ms": sealing_epoch_ms}, + "deadline_epoch_ms": sealing_epoch_ms, + **({"component_exclusions": exclusions} if exclusions else {})}, timeout=_remaining(deadline), retry_safe=False, large_local_snapshot=True) return effect_runtime_result("runtime.checkpoint_artifacts", { "action": "capture", "components": components, "destination": str(destination), "expected_source_sha256": probe["source_sha256"], "point_metadata": metadata, "deadline_epoch_ms": sealing_epoch_ms, + **({"component_exclusions": exclusions} if exclusions else {}), }, timeout=_remaining(deadline), retry_safe=False, large_local_snapshot=True) finally: client.close() diff --git a/benchmark/runtime/checkpoint.py b/benchmark/runtime/checkpoint.py index 38719914f4..53bbfdea2b 100644 --- a/benchmark/runtime/checkpoint.py +++ b/benchmark/runtime/checkpoint.py @@ -25,6 +25,7 @@ ) from .checkpoint_handoff import CHECKPOINT_CAPTURE_SECONDS from .codex import reject_retired_turn_display +from .research_artifacts import research_component_exclusions def normalize_checkpoint_request_path(value: str) -> str: @@ -563,9 +564,11 @@ def capture_after_wake(env: dict[str, str], receipt: dict[str, Any], *, metadata["native_session"] = {**native["metadata"], "store_members": [ {**member, "id": native_ids[member["id"]]} for member in native["metadata"]["store_members"]]} + exclusions = research_component_exclusions(components) probe = effect_runtime_result("runtime.checkpoint_artifacts", { "action": "probe", "components": components, "deadline_epoch_ms": deadline * 1000, + **({"component_exclusions": exclusions} if exclusions else {}), }, timeout=max(.1, deadline - time.time()), retry_safe=False, large_local_snapshot=True) if request.get("native_session"): # Native readback precedes the byte witness. A completed later Turn @@ -604,6 +607,7 @@ def capture_after_wake(env: dict[str, str], receipt: dict[str, Any], *, "components": components, "point_metadata": metadata, "expected_source_sha256": probe["source_sha256"], "deadline_epoch_ms": deadline * 1000, + **({"component_exclusions": exclusions} if exclusions else {}), }, timeout=max(.1, deadline - time.time()), retry_safe=False, large_local_snapshot=True) receipt["checkpoint"] = {"captured": True, "destination": str(destination), **captured} except Exception as error: diff --git a/benchmark/runtime/checkpoint_wake.py b/benchmark/runtime/checkpoint_wake.py index 661c8a8010..91c2096c66 100644 --- a/benchmark/runtime/checkpoint_wake.py +++ b/benchmark/runtime/checkpoint_wake.py @@ -157,8 +157,12 @@ def _capture(self, held, deadline): metadata["native_session"] = {**native["metadata"], "store_members": [ {**member, "id": allocated[member["id"]]} for member in native["metadata"]["store_members"]]} metadata["held_decision_component_id"] = decision_id + from .research_artifacts import research_component_exclusions + + exclusions = research_component_exclusions(components) probe = effect_runtime_result("runtime.checkpoint_artifacts", { "action": "probe", "components": components, "deadline_epoch_ms": window * 1000, + **({"component_exclusions": exclusions} if exclusions else {}), }, timeout=max(.1, window - time.time()), retry_safe=False, large_local_snapshot=True) if native is not None: if restored_capture_history(self.env, self.receipt.get("checkpoint_restore"), @@ -183,6 +187,7 @@ def _capture(self, held, deadline): "action": "capture", "components": components, "destination": str(destination), "expected_source_sha256": probe["source_sha256"], "point_metadata": metadata, "deadline_epoch_ms": window * 1000, + **({"component_exclusions": exclusions} if exclusions else {}), }, timeout=max(.1, window - time.time()), retry_safe=False, large_local_snapshot=True) def _write_input(self, process, body, command, deadline, timeout, *, phase_limited): diff --git a/benchmark/runtime/codex.py b/benchmark/runtime/codex.py index f11cb46d57..4becbc0c39 100644 --- a/benchmark/runtime/codex.py +++ b/benchmark/runtime/codex.py @@ -6,12 +6,36 @@ import json import math import os +from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path # New benchmark runs and the product both default to six settled work Turns. DEFAULT_REPLAN_AFTER_TURNS = 6 +LOOPX_BENCHMARK_CLAIM_TTL_ENV = "LOOPX_BENCHMARK_CLAIM_TTL_SECONDS" +_MAX_CLAIM_TTL_SECONDS = 86400 + + +def normalize_claim_ttl_seconds(value: int | None) -> int | None: + """Validate optional benchmark Todo claim TTL in 1..86400 seconds.""" + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= _MAX_CLAIM_TTL_SECONDS: + raise ValueError("claim_ttl_seconds must be an integer between 1 and 86400") + return value + + +def claim_ttl_seconds_from_env(env: Mapping[str, str] | None = None) -> int | None: + """Parse optional LOOPX_BENCHMARK_CLAIM_TTL_SECONDS when explicitly opted in.""" + source = os.environ if env is None else env + raw = source.get(LOOPX_BENCHMARK_CLAIM_TTL_ENV) + if raw is None or not str(raw).strip(): + return None + text = str(raw).strip() + if not text.isdigit(): + raise ValueError(f"{LOOPX_BENCHMARK_CLAIM_TTL_ENV} must be an integer between 1 and 86400") + return normalize_claim_ttl_seconds(int(text)) MODES = ("plain", "native-goal", "heartbeat", "turn", "loopx-goal") @@ -155,11 +179,13 @@ def codex_settings( *, execution: Execution, workspace: Path, model: str, effort: str, base_url: str, wire_api: str, web_search: str = "disabled", model_catalog: Path | None = None, model_catalog_destination: Path | None = None, + claim_ttl_seconds: int | None = None, ) -> str: """Render fixed settings for the worker and its fresh checkpoint receiver. Rendering does not create a home, change a session or handle credentials. """ + claim_ttl = normalize_claim_ttl_seconds(claim_ttl_seconds) if not model or not effort: raise ValueError("model and effort are required") if wire_api not in {"responses", "chat"}: @@ -195,6 +221,7 @@ def codex_settings( 'LOOPX_USAGE_PING = "0"', f"LOOPX_CONTEXT_DELIVERY = {json.dumps(execution.context_delivery)}", *(['LOOPX_EXECUTION_MODE = "heartbeat"'] if execution.context_delivery != "off" else []), + *([f"{LOOPX_BENCHMARK_CLAIM_TTL_ENV} = {json.dumps(str(claim_ttl))}"] if claim_ttl is not None else []), "[features]", f"goals = {str(execution.native_goal).lower()}", "unified_exec = true", @@ -239,6 +266,7 @@ def prepare_codex_home( web_search: str = "disabled", model_catalog: Path | None = None, model_catalog_destination: Path | None = None, + claim_ttl_seconds: int | None = None, ) -> None: """Materialize fixed inputs once; never delete sessions between iterations. @@ -269,6 +297,7 @@ def prepare_codex_home( execution=execution, workspace=workspace, model=model, effort=effort, base_url=base_url, wire_api=wire_api, web_search=web_search, model_catalog=model_catalog, model_catalog_destination=model_catalog_destination, + claim_ttl_seconds=claim_ttl_seconds, ) home.mkdir(parents=True, exist_ok=True) config = home / "config.toml" @@ -290,9 +319,40 @@ def prepare_codex_home( # The provider reads OPENAI_API_KEY. No credential file is copied to logs. +def _prepend_existing_runtime_dirs(env: dict[str, str]) -> None: + """Keep explicit benchmark Node/LoopX runtime directories on worker PATH.""" + candidates: list[str] = [] + extra = env.get("LOOPX_BENCHMARK_PATH_PREPEND", "") + if extra: + for item in extra.split(os.pathsep): + if item and Path(item).is_dir(): + candidates.append(item) + node_dir = env.get("LOOPX_NODE_DIR", "") + if node_dir: + node_bin = Path(node_dir) / "bin" + if node_bin.is_dir(): + candidates.append(str(node_bin)) + cli = env.get("LOOPX_CLI", "") + if cli: + cli_path = Path(cli) + if cli_path.is_absolute() and cli_path.parent.is_dir(): + candidates.append(str(cli_path.parent)) + if not candidates: + return + existing = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry] + merged: list[str] = [] + seen: set[str] = set() + for entry in (*candidates, *existing): + if entry not in seen: + seen.add(entry) + merged.append(entry) + env["PATH"] = os.pathsep.join(merged) + + def process_environment( - home: Path, *, base: dict[str, str] | None = None + home: Path, *, base: Mapping[str, str] | None = None ) -> dict[str, str]: env = dict(os.environ if base is None else base) env["CODEX_HOME"] = str(home) + _prepend_existing_runtime_dirs(env) return env diff --git a/benchmark/runtime/harbor.py b/benchmark/runtime/harbor.py index 85803bd63a..01803ae350 100644 --- a/benchmark/runtime/harbor.py +++ b/benchmark/runtime/harbor.py @@ -21,7 +21,7 @@ from loopx.control_plane.goals.goal_vision_policy import DEFAULT_PLANNING_HORIZON_GOAL from .codex_offline import MODEL_CATALOG_REMOTE, CodexOffline, stage_portable_python -from .codex import DEFAULT_REPLAN_AFTER_TURNS, Execution +from .codex import DEFAULT_REPLAN_AFTER_TURNS, Execution, normalize_claim_ttl_seconds from .layout import _ROOT, _SRC, _CONTROL, _CODEX_HOME, _REGISTRY, _LOOPX_RUNTIME from .scheduler import phase_work_reserve @@ -85,6 +85,7 @@ def __init__( defer_codex_home=False, complete_turn=False, official_stop_hook=False, + claim_ttl_seconds=None, **kwargs, ): if "research_loop" in kwargs: @@ -179,6 +180,7 @@ def __init__( self.native_goal_continue = native_goal_continue self.goal_id, self.agent_id = goal_id, agent_id self.defer_codex_home = defer_codex_home + self.claim_ttl_seconds = normalize_claim_ttl_seconds(claim_ttl_seconds) self._task_path = "/usr/local/bin:/usr/bin:/bin" self._phase_number = 0 self._seeded_todo_id: str | None = None @@ -710,6 +712,8 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]: ), **({"LOOPX_CODEX_TURN_TIMEOUT_SEC": str(self.execution.timeout_seconds)} if self.execution.timeout_seconds is not None else {}), + **({"LOOPX_BENCHMARK_CLAIM_TTL_SECONDS": str(self.claim_ttl_seconds)} + if self.claim_ttl_seconds is not None else {}), "CODEX_BIN": "/usr/local/bin/codex", "MODEL_NAME": (self.model_name or "").split("/", 1)[-1], "REASONING_EFFORT": str( diff --git a/benchmark/runtime/research_artifacts.py b/benchmark/runtime/research_artifacts.py index 76101190c7..cd285306a4 100644 --- a/benchmark/runtime/research_artifacts.py +++ b/benchmark/runtime/research_artifacts.py @@ -5,12 +5,129 @@ """ from __future__ import annotations +from collections.abc import Callable, Mapping, Sequence from copy import deepcopy from pathlib import PurePosixPath +import tarfile +from typing import Any RESEARCH_DIRECTORY = "/tmp/loopx-benchmark-research" RESEARCH_COMPONENT = "benchmark_research" +CORE_DUMP_EXCLUDE_PATTERN = "core-dump:elf-macho" +RESEARCH_EXCLUDE_PATTERNS = ("*.raw.gz", CORE_DUMP_EXCLUDE_PATTERN, "target/", ".cargo-target/") +_ELF_ET_CORE = 4 +_MACHO_MH_CORE = 4 + + +def is_core_dump_name(name: str) -> bool: + """Return True only for POSIX core dump basenames (`core` or `core.*`).""" + return name == "core" or name.startswith("core.") + + +def is_confirmed_core_dump_header(header: bytes) -> bool: + """Return True only when leading file bytes prove an ELF ET_CORE or Mach-O MH_CORE dump.""" + if len(header) >= 18 and header[:4] == b"\x7fELF" and header[4] in (1, 2): + if header[5] == 1: + return int.from_bytes(header[16:18], "little") == _ELF_ET_CORE + if header[5] == 2: + return int.from_bytes(header[16:18], "big") == _ELF_ET_CORE + return False + if len(header) >= 16: + magic = header[:4] + if magic in (b"\xfe\xed\xfa\xce", b"\xfe\xed\xfa\xcf"): + return int.from_bytes(header[12:16], "big") == _MACHO_MH_CORE + if magic in (b"\xce\xfa\xed\xfe", b"\xcf\xfa\xed\xfe"): + return int.from_bytes(header[12:16], "little") == _MACHO_MH_CORE + return False + + +def is_runner_research_component(entry: Any) -> bool: + """Return True only for the runner's reserved research component directory.""" + if not isinstance(entry, Mapping) or entry.get("id") != RESEARCH_COMPONENT: + return False + source_path = entry.get("source_path") + return isinstance(source_path, str) and PurePosixPath(source_path) == PurePosixPath(RESEARCH_DIRECTORY) + + +def research_component_exclusions( + components: Sequence[Mapping[str, Any]], +) -> dict[str, list[str]]: + """Return bounded source-exclusion patterns only when runner-owned benchmark research is attached.""" + if any(is_runner_research_component(entry) for entry in components): + return {RESEARCH_COMPONENT: list(RESEARCH_EXCLUDE_PATTERNS)} + return {} + + +def is_excluded_research_relpath( + parts: tuple[str, ...], + *, + is_dir: bool, + read_header: Callable[[], bytes] | None = None, +) -> bool: + """Match a component-relative path tuple against RESEARCH_EXCLUDE_PATTERNS.""" + if not parts: + return False + for index, name in enumerate(parts): + entry_is_dir = is_dir or index < len(parts) - 1 + for pattern in RESEARCH_EXCLUDE_PATTERNS: + if pattern.endswith("/"): + if entry_is_dir and name == pattern[:-1]: + return True + elif pattern == CORE_DUMP_EXCLUDE_PATTERN: + if ( + not entry_is_dir + and index == len(parts) - 1 + and is_core_dump_name(name) + and read_header is not None + ): + try: + header = read_header() + except OSError: + header = b"" + if is_confirmed_core_dump_header(header): + return True + elif pattern.startswith("*."): + if not entry_is_dir and name.endswith(pattern[1:]): + return True + elif not entry_is_dir and name == pattern: + return True + return False + + +def archive_member_content( + member: tarfile.TarInfo, by_path: Mapping[str, tarfile.TarInfo], +) -> tarfile.TarInfo: + """Resolve Docker's hardlink record to regular bytes inside the declared archive root.""" + if not member.islnk(): + return member + path, target = PurePosixPath(member.name), PurePosixPath(member.linkname) + content = by_path.get(str(target)) + if (target.is_absolute() or ".." in target.parts or not target.parts + or target.parts[:1] != path.parts[:1] or content is None or not content.isfile()): + raise ValueError("Worker archive contains undeclared, linked or special members") + return content + + +def is_excluded_tar_member( + archive: tarfile.TarFile, + member: tarfile.TarInfo, + rel_parts: tuple[str, ...], +) -> bool: + """Check tar member exclusion, confirming ELF/Mach-O core dump headers from archive bytes.""" + def _read_header() -> bytes: + if not member.isfile(): + return b"" + try: + stream = archive.extractfile(member) + except (KeyError, OSError, tarfile.TarError): + return b"" + if stream is None: + return b"" + with stream: + return stream.read(20) + + return is_excluded_research_relpath(rel_parts, is_dir=member.isdir(), read_header=_read_header) def validate_research_scope(workspace: str, submit_paths: list[str]) -> None: diff --git a/benchmark/runtime/sforge.py b/benchmark/runtime/sforge.py index 016855985c..b70c6b3890 100644 --- a/benchmark/runtime/sforge.py +++ b/benchmark/runtime/sforge.py @@ -20,7 +20,14 @@ from benchmark.edgebench.feedback import FEEDBACK_MODES from benchmark.edgebench.feedback_hook import FEEDBACK_PAYLOAD -from .codex import DEFAULT_REPLAN_AFTER_TURNS, Execution, codex_settings, native_child_instructions, prepare_codex_home +from .codex import ( + DEFAULT_REPLAN_AFTER_TURNS, + Execution, + codex_settings, + native_child_instructions, + normalize_claim_ttl_seconds, + prepare_codex_home, +) from .codex_offline import CodexOffline, MODEL_CATALOG_REMOTE, stage_portable_python from .codex_readiness import native_readiness_budget from .harbor import ( @@ -96,6 +103,16 @@ async def upload_dir(self, source, target): raise RuntimeError("SForge directory upload failed") +_CARGO_TARGET_DIR = "/tmp/sforge-cargo-target" + + +class _SForgeBenchmarkCodex(BenchmarkCodex): + """Stage the SForge shell default in the shared installer's single profile write.""" + + def _shell_path_restore(self) -> str: + return super()._shell_path_restore() + f'\nexport CARGO_TARGET_DIR="${{CARGO_TARGET_DIR:-{_CARGO_TARGET_DIR}}}"' + + class SForgeWorker(CodexAgent): """Native SForge lifecycle with an explicitly selected worker profile. @@ -130,8 +147,10 @@ def __init__(self, config, *, profile: str, cwd: str, checkpoint_request_path: str | None = None, checkpoint_request: bytes | None = None, warm_start=None, research_sidecar: bool = False, - native_result_scope: dict | None = None, complete_turn: bool = False): + native_result_scope: dict | None = None, complete_turn: bool = False, + claim_ttl_seconds: int | None = None): super().__init__(config) + self.claim_ttl_seconds = normalize_claim_ttl_seconds(claim_ttl_seconds) self.execution = profile_execution( profile, task_entry=task_entry, context_delivery=context_delivery, turn_envelope=turn_envelope, @@ -413,7 +432,7 @@ def _install_worker(self, backend, handle, log_dir, logger): if self.profile == "official": super().install_stop_hook(backend, handle, log_dir, logger) else: - self.runtime = BenchmarkCodex( + self.runtime = _SForgeBenchmarkCodex( **common, execution_mode=self.execution.mode, iteration_context=self.execution.context, validation_command=self.execution.validation_command, @@ -435,6 +454,8 @@ def _install_worker(self, backend, handle, log_dir, logger): task_objective=self.task_objective, **({"goal_id": self.warm_start.goal_id, "agent_id": self.warm_start.agent_id, "defer_codex_home": True} if self.warm_start is not None else {}), + **({"claim_ttl_seconds": self.claim_ttl_seconds} + if self.claim_ttl_seconds is not None else {}), ) asyncio.run(self.runtime.install(self.environment)) if self.feedback == "native" and (self.execution_observation is not None @@ -460,6 +481,7 @@ def _install_worker(self, backend, handle, log_dir, logger): model_catalog=self.runtime._model_catalog_source, model_catalog_destination=(Path(MODEL_CATALOG_REMOTE) if self.runtime._model_catalog_staged else None), + claim_ttl_seconds=self.claim_ttl_seconds, ).encode("utf-8"), } research_paths = asyncio.run(self.warm_start.stage( @@ -614,6 +636,9 @@ def format_run_cmd(self, prompt_path, *, model=None, cwd="", internet=True, resu raise RuntimeError("Could not protect fresh receiver credentials") self.prepared = True env = self.runtime._worker_env(cwd=self.cwd) + # Keep Rust build artifacts outside both the task workspace and + # RESEARCH_DIRECTORY so checkpoint probes/archives stay bounded. + env.setdefault("CARGO_TARGET_DIR", _CARGO_TARGET_DIR) if self.warm_start is not None: env["LOOPX_WARM_START"] = f"{_CONTROL}/warm-start.json" command = worker_command(env, python=f"{_PYTHON}/bin/python3", source=_SRC, diff --git a/benchmark/runtime/sforge_backend.py b/benchmark/runtime/sforge_backend.py index 7fcd37a3c1..00301f1157 100644 --- a/benchmark/runtime/sforge_backend.py +++ b/benchmark/runtime/sforge_backend.py @@ -2,9 +2,12 @@ from __future__ import annotations +from copy import copy +import errno import inspect import ipaddress import json +import shutil import tarfile import tempfile from pathlib import Path, PurePosixPath @@ -15,6 +18,46 @@ from .harbor import _CODEX_HOME, _CONTROL, _LOOPX_RUNTIME from .provider_failure import observe_terminal_provider_failure +from .research_artifacts import archive_member_content, is_excluded_tar_member + +_RESEARCH_DISK_HEADROOM_FLOOR_BYTES = 10 * 1024**3 + + +class InsufficientDiskHeadroomError(OSError): + """Raised before optional research collection breaches the host disk floor.""" + + +def _minimum_free_bytes(*paths: Path) -> int: + return min(shutil.disk_usage(path).free for path in paths) + + +def _filter_research_members( + archive: tarfile.TarFile, + members: list[tarfile.TarInfo], +) -> list[tarfile.TarInfo]: + """Keep real research outputs while omitting confirmed dumps and ephemeral build dirs.""" + kept: list[tarfile.TarInfo] = [] + by_path = {str(PurePosixPath(member.name)): member for member in members} + retained_names: dict[str, str] = {} + for member in members: + parts = PurePosixPath(member.name).parts + content = archive_member_content(member, by_path) + if len(parts) > 1 and is_excluded_tar_member(archive, content, parts[1:]): + continue + + if content.isfile(): + first_name = retained_names.setdefault(content.name, member.name) + if first_name == member.name and member.islnk(): + # Its original data-bearing name was filtered or has not been seen. + regular = copy(content) + regular.name, regular.mode = member.name, member.mode + member = regular + elif first_name != member.name and member.linkname != first_name: + # Preserve hardlinks and charge the disk budget only once per retained group. + member = copy(member) + member.type, member.linkname, member.size = tarfile.LNKTYPE, first_name, 0 + kept.append(member) + return kept class RecordingDockerBackend(DockerBackend): @@ -191,19 +234,59 @@ def start_feedback(self, handle): raise RuntimeError("Best-only publisher is unavailable") self.feedback.start(self, handle) - def _extract_artifact_archive(self, handle, remote, target): + def _extract_artifact_archive( + self, + handle, + remote, + target, + *, + research_cleanup: bool = False, + ): """Collect one native archive without materializing it as Python bytes.""" + free_before: int | None = None + if research_cleanup: + target.parent.mkdir(parents=True, exist_ok=True) + free_before = _minimum_free_bytes(Path(tempfile.gettempdir()), target.parent) + if free_before <= _RESEARCH_DISK_HEADROOM_FLOOR_BYTES: + raise InsufficientDiskHeadroomError( + errno.ENOSPC, + "host temp/log disk headroom below 10 GiB floor before research collection", + ) chunks, _ = self._raw(handle).get_archive(str(remote)) try: # A seekable spool preserves the existing tar extraction/filter # behavior. Its lifetime is independent of TarFile reference cycles. + written = 0 with tempfile.TemporaryFile() as archive_file: for chunk in chunks: + written += len(chunk) + if ( + free_before is not None + and free_before - written < _RESEARCH_DISK_HEADROOM_FLOOR_BYTES + ): + raise InsufficientDiskHeadroomError( + errno.ENOSPC, + "research archive spool aborted before breaching 10 GiB free-disk floor", + ) archive_file.write(chunk) archive_file.seek(0) target.mkdir(exist_ok=True) with tarfile.open(fileobj=archive_file) as archive: - archive.extractall(target, filter="data") + if not research_cleanup: + archive.extractall(target, filter="data") + else: + members = _filter_research_members(archive, archive.getmembers()) + extract_bytes = sum(m.size for m in members if m.isfile()) + if ( + free_before is not None + and free_before - written - extract_bytes + < _RESEARCH_DISK_HEADROOM_FLOOR_BYTES + ): + raise InsufficientDiskHeadroomError( + errno.ENOSPC, + "research archive extraction aborted before breaching 10 GiB free-disk floor", + ) + archive.extractall(target, members=members, filter="data") finally: close = getattr(chunks, "close", None) if close is not None: @@ -242,8 +325,19 @@ def cleanup_container(self, handle, logger=None): for remote, name in sources: try: self._extract_artifact_archive( - handle, PurePosixPath(remote), self.log_dir / name) + handle, + PurePosixPath(remote), + self.log_dir / name, + research_cleanup=(name == "research"), + ) observations.append({"artifact": name, "collected": True}) + except InsufficientDiskHeadroomError as error: + observations.append({ + "artifact": name, + "collected": False, + "error_kind": type(error).__name__, + "reason": "insufficient_host_disk_headroom", + }) except Exception as error: observations.append({"artifact": name, "collected": False, "error_kind": type(error).__name__}) diff --git a/benchmark/runtime/worker.py b/benchmark/runtime/worker.py index d658188567..06771c810a 100644 --- a/benchmark/runtime/worker.py +++ b/benchmark/runtime/worker.py @@ -15,8 +15,11 @@ from dataclasses import replace from pathlib import Path +from collections.abc import Mapping + from benchmark.runtime.codex import ( Execution, + claim_ttl_seconds_from_env, reject_retired_turn_display, prepare_codex_home, process_environment, @@ -81,6 +84,18 @@ def loopx_command(env: dict[str, str]) -> list[str]: ] +def _claim_ttl_guidance(env: Mapping[str, str]) -> str: + ttl = claim_ttl_seconds_from_env(env) + if ttl is None: + return "" + return ( + f"\nLong-wake lease TTL opt-in (`LOOPX_BENCHMARK_CLAIM_TTL_SECONDS={ttl}`): " + f"when claiming a Todo with `loopx todo claim`, pass `--ttl-seconds {ttl}` " + f"(or renew via `loopx task-lease renew --ttl-seconds {ttl}` before expiry) " + "so long execution wakes retain their lease.\n" + ) + + def heartbeat_body(env: dict[str, str], turn_id: str, *, native_goal: bool, decision_handoff_socket: str | None = None, resume_codex_session_id: str | None = None) -> str: @@ -138,7 +153,12 @@ def heartbeat_body(env: dict[str, str], turn_id: str, *, native_goal: bool, from .interruption_recovery import recovery_handoff _, handoff = recovery_handoff(env) - return body + runtime_execution_guidance(env) + ("\nRecovery handoff (content only):\n" + handoff if handoff else "") + return ( + body + + runtime_execution_guidance(env) + + _claim_ttl_guidance(env) + + ("\nRecovery handoff (content only):\n" + handoff if handoff else "") + ) @contextmanager @@ -663,6 +683,7 @@ def run_once(env: dict[str, str]) -> dict: execution, timeout_seconds=(remaining - reserve if execution.timeout_seconds is None else min(execution.timeout_seconds, remaining - reserve)) ) + claim_ttl_seconds = claim_ttl_seconds_from_env(env) prepare_codex_home( home, execution=execution, @@ -677,6 +698,7 @@ def run_once(env: dict[str, str]) -> dict: model_catalog=( Path(env["LOOPX_MODEL_CATALOG"]) if env.get("LOOPX_MODEL_CATALOG") else None ), + claim_ttl_seconds=claim_ttl_seconds, ) native_hook_args = () if execution.official_stop_hook: @@ -883,7 +905,12 @@ def run_once(env: dict[str, str]) -> dict: ) if (execution.mode == "heartbeat" and stage == "execute" and not receipt["ok"] and not receipt.get("budget_exhausted")): - receipt["host_failure"] = heartbeat_host_failure(wake, receipt) + try: + receipt["host_failure"] = heartbeat_host_failure(wake, receipt) + except Exception as exc: + receipt["host_failure_record_error"] = ( + f"{type(exc).__name__}: {str(exc)[:300]}" + ) (wake / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") return receipt diff --git a/benchmark/tests/test_codex_readiness_budget.py b/benchmark/tests/test_codex_readiness_budget.py index fc2fd72b7a..ce4e25c2ba 100644 --- a/benchmark/tests/test_codex_readiness_budget.py +++ b/benchmark/tests/test_codex_readiness_budget.py @@ -179,6 +179,7 @@ def test_edgebench_runner_passes_selected_setup_budget_before_model(tmp_path, mo game_mode=False, submit_paths=["solver.py"], work=SimpleNamespace(agent_query="Original acceptance."), judge=SimpleNamespace(selection="score_first", score_direction="maximize"))) backend = SimpleNamespace(observe_local_images=lambda **keys: {}, + registration_options=lambda provider: {}, exec_run=lambda *a, **k: SimpleNamespace(exit_code=0)) monkeypatch.setattr(run, "RecordingDockerBackend", lambda **k: backend) diff --git a/benchmark/tests/test_research_artifacts.py b/benchmark/tests/test_research_artifacts.py index 5a3789c66f..7f9424bd07 100644 --- a/benchmark/tests/test_research_artifacts.py +++ b/benchmark/tests/test_research_artifacts.py @@ -4,8 +4,17 @@ import pytest from benchmark.runtime.research_artifacts import ( - RESEARCH_COMPONENT, RESEARCH_DIRECTORY, selected_research_components, - validate_research_scope, with_research_capture, + CORE_DUMP_EXCLUDE_PATTERN, + RESEARCH_COMPONENT, + RESEARCH_DIRECTORY, + is_confirmed_core_dump_header, + is_excluded_research_relpath, + is_excluded_tar_member, + is_runner_research_component, + research_component_exclusions, + selected_research_components, + validate_research_scope, + with_research_capture, ) @@ -116,3 +125,253 @@ def boundary(**kwargs): with pytest.raises(RuntimeError, match="synthetic launch boundary"): run.main(argv) assert json.loads(source.read_bytes()) == request + + +def _elf_bytes(e_type: int, *, little_endian: bool = True) -> bytes: + buf = bytearray(64) + buf[0:4] = b"\x7fELF" + buf[4] = 2 + buf[5] = 1 if little_endian else 2 + buf[16:18] = e_type.to_bytes(2, "little" if little_endian else "big") + return bytes(buf) + + +def _macho_bytes(filetype: int, *, little_endian: bool = True) -> bytes: + buf = bytearray(32) + if little_endian: + buf[0:4] = b"\xcf\xfa\xed\xfe" + buf[12:16] = filetype.to_bytes(4, "little") + else: + buf[0:4] = b"\xfe\xed\xfa\xcf" + buf[12:16] = filetype.to_bytes(4, "big") + return bytes(buf) + + +def test_core_dump_filter_preserves_normal_core_dirs_and_plain_files(): + import io + import tarfile + + assert research_component_exclusions([{"id": RESEARCH_COMPONENT, "source_path": RESEARCH_DIRECTORY}]) == { + RESEARCH_COMPONENT: ["*.raw.gz", CORE_DUMP_EXCLUDE_PATTERN, "target/", ".cargo-target/"], + } + assert is_confirmed_core_dump_header(_elf_bytes(4, little_endian=True)) + assert is_confirmed_core_dump_header(_elf_bytes(4, little_endian=False)) + assert is_confirmed_core_dump_header(_macho_bytes(4, little_endian=True)) + assert is_confirmed_core_dump_header(_macho_bytes(4, little_endian=False)) + assert not is_confirmed_core_dump_header(_elf_bytes(2)) + assert not is_confirmed_core_dump_header(_macho_bytes(2)) + assert not is_confirmed_core_dump_header(b"core-dump text") + assert not is_excluded_research_relpath(("core", "analysis.md"), is_dir=False, read_header=lambda: b"# notes") + assert not is_excluded_research_relpath(("topic", "core"), is_dir=False, read_header=lambda: b"text") + assert is_excluded_research_relpath(("core",), is_dir=False, read_header=lambda: _elf_bytes(4)) + assert is_excluded_research_relpath(("sub", "core.77"), is_dir=False, read_header=lambda: _macho_bytes(4)) + + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w") as archive: + entries = ( + ("loopx-benchmark-research/core/analysis.md", b"# analysis\n"), + ("loopx-benchmark-research/topic/core", b"ordinary topic notes\n"), + ("loopx-benchmark-research/bin/core", _elf_bytes(2)), + ("loopx-benchmark-research/core", _elf_bytes(4)), + ("loopx-benchmark-research/sub/core.123", _macho_bytes(4)), + ("loopx-benchmark-research/dump.raw.gz", b"gz"), + ("loopx-benchmark-research/target/release/app", b"elf"), + ) + for name, data in entries: + info = tarfile.TarInfo(name) + info.size = len(data) + archive.addfile(info, io.BytesIO(data)) + buf.seek(0) + with tarfile.open(fileobj=buf, mode="r") as archive: + kept = [ + m.name for m in archive.getmembers() + if not is_excluded_tar_member(archive, m, tuple(m.name.split("/")[1:])) + ] + assert kept == [ + "loopx-benchmark-research/core/analysis.md", + "loopx-benchmark-research/topic/core", + "loopx-benchmark-research/bin/core", + ] + + +def test_caller_chosen_benchmark_research_id_preserves_declared_files_end_to_end(tmp_path): + from loopx.control_plane.effect_runtime import effect_runtime_result + + caller_dir = tmp_path / "caller-research" + caller_dir.mkdir() + (caller_dir / "experiment.raw.gz").write_bytes(b"raw-gz-payload") + (caller_dir / "notes.md").write_text("# caller notes\n", encoding="utf-8") + + components = [{"id": RESEARCH_COMPONENT, "source_path": str(caller_dir)}] + assert not is_runner_research_component(components[0]) + exclusions = research_component_exclusions(components) + assert exclusions == {} + + probe = effect_runtime_result( + "runtime.checkpoint_artifacts", + {"action": "probe", "components": components, **({"component_exclusions": exclusions} if exclusions else {})}, + ) + unit = tmp_path / "captured-unit" + capture = effect_runtime_result( + "runtime.checkpoint_artifacts", + { + "action": "capture", + "components": components, + "destination": str(unit), + "expected_source_sha256": probe["source_sha256"], + "point_metadata": {"caller": True}, + **({"component_exclusions": exclusions} if exclusions else {}), + }, + ) + effect_runtime_result( + "runtime.checkpoint_artifacts", + {"action": "verify", "root": str(unit), "expected_sha256": capture["sha256"]}, + ) + restored = tmp_path / "materialized" + effect_runtime_result( + "runtime.checkpoint_artifacts", + { + "action": "materialize", + "root": str(unit), + "expected_sha256": capture["sha256"], + "destination": str(restored), + }, + ) + comp_root = restored / "components" / RESEARCH_COMPONENT + assert (comp_root / "experiment.raw.gz").read_bytes() == b"raw-gz-payload" + assert (comp_root / "notes.md").read_text(encoding="utf-8") == "# caller notes\n" + + +def test_archive_exclude_research_skips_ephemeral_dumps(tmp_path): + import base64 + import io + import json + import tarfile + from types import SimpleNamespace + from benchmark.edgebench import checkpoint_worker + + elf_core = b"\x7fELF\x02\x01" + b"\x00" * 10 + (4).to_bytes(2, "little") + b"\x00" * 46 + payload = io.BytesIO() + with tarfile.open(fileobj=payload, mode="w") as archive: + for d in ("loopx-benchmark-research", "loopx-benchmark-research/topic", "loopx-benchmark-research/sub"): + dinfo = tarfile.TarInfo(d) + dinfo.type = tarfile.DIRTYPE + dinfo.mode = 0o700 + archive.addfile(dinfo) + for rel, body in ( + ("loopx-benchmark-research/candidate.py", b"print('ok')\n"), + ("loopx-benchmark-research/topic/core", b"ordinary topic evidence\n"), + ("loopx-benchmark-research/dump.raw.gz", b"gz"), + ("loopx-benchmark-research/core", elf_core), + ("loopx-benchmark-research/target/release/bin", b"bin"), + ("loopx-benchmark-research/.cargo-target/x.rlib", b"rlib"), + ): + info = tarfile.TarInfo(rel) + info.size = len(body) + info.mode = 0o644 + archive.addfile(info, io.BytesIO(body)) + for link_rel in ("loopx-benchmark-research/alias_note", "loopx-benchmark-research/sub/core.2"): + linfo = tarfile.TarInfo(link_rel) + linfo.type = tarfile.LNKTYPE + linfo.linkname = "loopx-benchmark-research/core" + linfo.mode = 0o644 + archive.addfile(linfo) + + stat_hdr = base64.b64encode(json.dumps({"linkTarget": ""}).encode("utf-8")).decode("ascii") + response = SimpleNamespace( + headers={"x-docker-container-path-stat": stat_hdr}, + iter_content=lambda chunk_size, decode_unicode=False: iter([payload.getvalue()]), + close=lambda: None, + ) + container = SimpleNamespace( + id="c1", + client=SimpleNamespace( + api=SimpleNamespace( + _url=lambda tpl, cid: tpl.format(cid), + _get=lambda url, **kwargs: response, + _raise_for_status=lambda resp: None, + ) + ), + ) + extracted = checkpoint_worker._archive( + container, "/tmp/loopx-benchmark-research", tmp_path / "dest", exclude_research=True, + ) + assert (extracted / "candidate.py").read_bytes() == b"print('ok')\n" + assert (extracted / "topic/core").read_bytes() == b"ordinary topic evidence\n" + assert (extracted / "alias_note").read_bytes() == elf_core + assert not (extracted / "dump.raw.gz").exists() + assert not (extracted / "core").exists() + assert not (extracted / "sub/core.2").exists() + assert not (extracted / "target").exists() + assert not (extracted / ".cargo-target").exists() + + +def test_archive_exclude_research_hardlink_matches_local_probe_witness(tmp_path): + import base64 + import io + import json + import os + import tarfile + from types import SimpleNamespace + from benchmark.edgebench import checkpoint_worker + from benchmark.runtime.research_artifacts import RESEARCH_EXCLUDE_PATTERNS + from loopx.control_plane.effect_runtime import effect_runtime_result + + elf_core = b"\x7fELF\x02\x01" + b"\x00" * 10 + (4).to_bytes(2, "little") + b"\x00" * 46 + local_root = tmp_path / "local" / "loopx-benchmark-research" + (local_root / "sub").mkdir(parents=True) + local_root.chmod(0o700) + (local_root / "sub").chmod(0o700) + (local_root / "candidate.py").write_text("score = 1\n", encoding="utf-8") + (local_root / "core").write_bytes(elf_core) + os.link(local_root / "core", local_root / "alias_note") + os.link(local_root / "core", local_root / "sub" / "core.2") + + exclusions = {RESEARCH_COMPONENT: list(RESEARCH_EXCLUDE_PATTERNS)} + prepared = effect_runtime_result( + "runtime.checkpoint_artifacts", + { + "action": "probe", + "components": [{"id": RESEARCH_COMPONENT, "source_path": str(local_root)}], + "component_exclusions": exclusions, + }, + ) + + payload = io.BytesIO() + with tarfile.open(fileobj=payload, mode="w") as archive: + archive.add(local_root, arcname="loopx-benchmark-research") + stat_hdr = base64.b64encode(json.dumps({"linkTarget": ""}).encode("utf-8")).decode("ascii") + response = SimpleNamespace( + headers={"x-docker-container-path-stat": stat_hdr}, + iter_content=lambda chunk_size, decode_unicode=False: iter([payload.getvalue()]), + close=lambda: None, + ) + container = SimpleNamespace( + id="c1", + client=SimpleNamespace( + api=SimpleNamespace( + _url=lambda tpl, cid: tpl.format(cid), + _get=lambda url, **kwargs: response, + _raise_for_status=lambda resp: None, + ) + ), + ) + extracted = checkpoint_worker._archive( + container, "/tmp/loopx-benchmark-research", tmp_path / "dest", exclude_research=True, + ) + observed = effect_runtime_result( + "runtime.checkpoint_artifacts", + { + "action": "probe", + "components": [{"id": RESEARCH_COMPONENT, "source_path": str(extracted)}], + "component_exclusions": exclusions, + }, + ) + assert observed["source_sha256"] == prepared["source_sha256"] + assert observed["source_witness"] == prepared["source_witness"] + assert [row["path"] for row in observed["source_witness"][RESEARCH_COMPONENT]] == [ + "", + "alias_note", + "candidate.py", + "sub", + ] diff --git a/benchmark/tests/test_sforge_artifact_spooling.py b/benchmark/tests/test_sforge_artifact_spooling.py index 89763592cd..1ff7091236 100644 --- a/benchmark/tests/test_sforge_artifact_spooling.py +++ b/benchmark/tests/test_sforge_artifact_spooling.py @@ -3,6 +3,7 @@ import io import json import tarfile +from pathlib import PurePosixPath from types import SimpleNamespace import pytest @@ -163,3 +164,110 @@ def native_cleanup(*args): with pytest.raises(RuntimeError if remains else OSError): backend.cleanup_container(SimpleNamespace(name="owned-container")) assert calls == ["observer-close", "native-cleanup"] + ([] if remains else ["released"]) + + +def test_research_collection_respects_disk_floor_and_filters_ephemeral_dumps(tmp_path, monkeypatch): + elf_core = b"\x7fELF\x02\x01" + b"\x00" * 10 + (4).to_bytes(2, "little") + b"\x00" * 46 + elf_exec = b"\x7fELF\x02\x01" + b"\x00" * 10 + (2).to_bytes(2, "little") + b"\x00" * 46 + macho_core = b"\xcf\xfa\xed\xfe" + b"\x00" * 8 + (4).to_bytes(4, "little") + b"\x00" * 16 + payload_buf = io.BytesIO() + with tarfile.open(fileobj=payload_buf, mode="w") as archive: + for rel, body in ( + ("loopx-benchmark-research/candidate.py", b"print('ok')\n"), + ("loopx-benchmark-research/core/analysis.md", b"# real notes\n"), + ("loopx-benchmark-research/topic/core", b"plain topic evidence\n"), + ("loopx-benchmark-research/exec_dir/core", elf_exec), + ("loopx-benchmark-research/dump.raw.gz", b"gz" * 100), + ("loopx-benchmark-research/core", elf_core), + ("loopx-benchmark-research/sub/core.99", macho_core), + ("loopx-benchmark-research/target/release/bin", b"elf"), + ("loopx-benchmark-research/.cargo-target/x.rlib", b"rlib"), + ): + info = tarfile.TarInfo(rel) + info.size = len(body) + info.mode = 0o644 + archive.addfile(info, io.BytesIO(body)) + research_tar = payload_buf.getvalue() + + def build_backend(name: str): + backend = object.__new__(transport.RecordingDockerBackend) + backend.checkpoint = backend.feedback = None + backend.research_sidecar = True + backend.log_dir = tmp_path / name + monkeypatch.setattr(transport.DockerBackend, "cleanup_container", lambda *a: None) + + def get_archive(remote): + data = research_tar if "research" in str(remote) else archive_bytes() + return iter([data]), {} + + monkeypatch.setattr(backend, "_raw", lambda handle: SimpleNamespace(get_archive=get_archive)) + return backend + + # Below 10 GiB headroom floor: skip research archive before calling get_archive. + low_backend = build_backend("low-disk") + monkeypatch.setattr( + transport, "_minimum_free_bytes", lambda *_: transport._RESEARCH_DISK_HEADROOM_FLOOR_BYTES + ) + low_backend.cleanup_container("owned-container") + low_obs = json.loads((low_backend.log_dir / "artifact-collection.json").read_text()) + research_entry = [row for row in low_obs if row["artifact"] == "research"][0] + assert research_entry == { + "artifact": "research", + "collected": False, + "error_kind": "InsufficientDiskHeadroomError", + "reason": "insufficient_host_disk_headroom", + } + + # Above 10 GiB floor: keep real notes/non-dump files named core while stripping confirmed dumps/build dirs. + ok_backend = build_backend("ok-disk") + monkeypatch.setattr( + transport, "_minimum_free_bytes", lambda *_: transport._RESEARCH_DISK_HEADROOM_FLOOR_BYTES + 100_000_000 + ) + ok_backend.cleanup_container("owned-container") + root = ok_backend.log_dir / "research" / "loopx-benchmark-research" + assert (root / "candidate.py").read_bytes() == b"print('ok')\n" + assert (root / "core/analysis.md").read_bytes() == b"# real notes\n" + assert (root / "topic/core").read_bytes() == b"plain topic evidence\n" + assert (root / "exec_dir/core").read_bytes() == elf_exec + assert not (root / "dump.raw.gz").exists() + assert not (root / "core").is_file() + assert not (root / "sub/core.99").exists() + assert not (root / "target").exists() + assert not (root / ".cargo-target").exists() + + +@pytest.mark.parametrize("data_name", ["core", "evidence.bin"]) +def test_research_hardlinks_keep_the_same_evidence_in_terminal_receipt(tmp_path, monkeypatch, data_name): + from benchmark.runtime.research_artifacts import RESEARCH_DIRECTORY + + root = PurePosixPath(RESEARCH_DIRECTORY).name + names = ["core", "core.5", "evidence.bin", "another-evidence.bin"] + content = b"\x7fELF\x02\x01" + bytes(10) + (4).to_bytes(2, "little") + bytes(46) + data = tmp_path / data_name + data.write_bytes(content) + payload = io.BytesIO() + with tarfile.open(fileobj=payload, mode="w") as archive: + archive.add(data, arcname=f"{root}/{data_name}") + for name in names: + if name != data_name: + alias = tmp_path / name + alias.hardlink_to(data) + archive.add(alias, arcname=f"{root}/{name}") + + backend = collector(tmp_path) + backend.research_sidecar = True + monkeypatch.setattr(transport, "_minimum_free_bytes", lambda *_: 20 * 1024**3) + monkeypatch.setattr(transport.DockerBackend, "cleanup_container", lambda *args: None) + + def get_archive(remote): + return iter([payload.getvalue() if remote == RESEARCH_DIRECTORY else archive_bytes()]), {} + + monkeypatch.setattr(backend, "_raw", lambda _: SimpleNamespace(get_archive=get_archive)) + backend.cleanup_container("owned-container") + + receipt = json.loads((backend.log_dir / "artifact-collection.json").read_text()) + assert {"artifact": "research", "collected": True} in receipt + collected = backend.log_dir / "research" / root + assert sorted(p.name for p in collected.iterdir()) == ["another-evidence.bin", "evidence.bin"] + assert (collected / "evidence.bin").read_bytes() == content + assert (collected / "another-evidence.bin").samefile(collected / "evidence.bin") diff --git a/benchmark/tests/test_sforge_runtime.py b/benchmark/tests/test_sforge_runtime.py index 4bf424e516..dcc265153f 100644 --- a/benchmark/tests/test_sforge_runtime.py +++ b/benchmark/tests/test_sforge_runtime.py @@ -1268,6 +1268,9 @@ def exec_run(handle, command, **kwargs): worker.install_stop_hook(backend, None, tmp_path, None) assert (["rm", "-f", "/usr/local/bin/sforge-submit"] in commands) is (feedback != "native") assert json.loads((tmp_path / "worker-profile.json").read_text())["feedback"] == feedback + if profile not in {"official", "single"}: + profile_text = worker.runtime._shell_path_restore() + assert 'export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-/tmp/sforge-cargo-target}"' in profile_text def test_warm_context_receipt_is_separate_from_native_stderr(tmp_path): diff --git a/benchmark/tests/test_shared_codex_runtime.py b/benchmark/tests/test_shared_codex_runtime.py index 9ea2d107f9..a6774c0046 100644 --- a/benchmark/tests/test_shared_codex_runtime.py +++ b/benchmark/tests/test_shared_codex_runtime.py @@ -1761,3 +1761,85 @@ def request(method, params): def test_context_benchmark_setting_rejects_broad_or_other_host_activation(value): with pytest.raises(ValueError, match="context_delivery"): Execution(context_delivery=value) + + +def test_run_once_writes_receipt_when_heartbeat_host_failure_raises(tmp_path, monkeypatch): + env = _sqlite_heartbeat_env(tmp_path, monkeypatch) + Path(env["CODEX_BIN"]).write_text( + f"#!{sys.executable}\nimport json, sys\n" + "print(json.dumps({'type': 'thread.started', 'thread_id': 'session-a'}))\n" + "sys.stdin.read(); sys.exit(1)\n" + ) + Path(env["CODEX_BIN"]).chmod(0o755) + monkeypatch.setattr(worker, "heartbeat_body", lambda *a, **kw: "synthetic work") + monkeypatch.setattr( + worker, "heartbeat_host_failure", + lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("node effect runtime dead")), + ) + receipt = run_once(env) + assert receipt["ok"] is False + assert "RuntimeError: node effect runtime dead" in receipt["host_failure_record_error"] + saved = json.loads((Path(env["LOOPX_WAKE_LOG_DIR"]) / receipt["turn_id"] / "receipt.json").read_text()) + assert saved["host_failure_record_error"] == receipt["host_failure_record_error"] + + +def test_opt_in_runtime_path_and_claim_ttl_env(tmp_path, monkeypatch): + from benchmark.runtime.codex import ( + claim_ttl_seconds_from_env, + codex_settings, + process_environment, + ) + + skills = tmp_path / "skills" + skills.mkdir() + baseline = codex_settings( + execution=Execution(mode="heartbeat"), workspace=tmp_path, model="fixture", + effort="high", base_url="http://localhost:8123/v1", wire_api="responses", + ) + assert "LOOPX_BENCHMARK_CLAIM_TTL_SECONDS" not in baseline + + with pytest.raises(ValueError, match="86400"): + claim_ttl_seconds_from_env({"LOOPX_BENCHMARK_CLAIM_TTL_SECONDS": "99999"}) + assert claim_ttl_seconds_from_env({"LOOPX_BENCHMARK_CLAIM_TTL_SECONDS": "18000"}) == 18000 + + opted_in = tomllib.loads( + codex_settings( + execution=Execution(mode="heartbeat"), workspace=tmp_path, model="fixture", + effort="high", base_url="http://localhost:8123/v1", wire_api="responses", + claim_ttl_seconds=18000, + ) + ) + assert opted_in["shell_environment_policy"]["set"]["LOOPX_BENCHMARK_CLAIM_TTL_SECONDS"] == "18000" + + node_dir = tmp_path / "node-root" + (node_dir / "bin").mkdir(parents=True) + cli_bin = tmp_path / "profile-bin" / "loopx" + cli_bin.parent.mkdir(parents=True) + cli_bin.write_text("#!/bin/sh\nexit 0\n") + env = process_environment( + tmp_path / "home", + base={"PATH": "/usr/bin:/bin", "LOOPX_NODE_DIR": str(node_dir), "LOOPX_CLI": str(cli_bin)}, + ) + assert env["PATH"].split(os.pathsep)[:3] == [str(node_dir / "bin"), str(cli_bin.parent), "/usr/bin"] + + monkeypatch.setattr( + worker.subprocess, + "run", + lambda *a, **kw: SimpleNamespace( + stdout=json.dumps({"ok": True, "turn_instance_id": "turn-1", "task_body": "base"}) + ), + ) + rendered = worker.heartbeat_body( + env | {"LOOPX_REGISTRY": str(tmp_path / "reg.json"), "LOOPX_RUNTIME_ROOT": str(tmp_path / "rt"), + "LOOPX_GOAL_ID": "g", "LOOPX_AGENT_ID": "a", "LOOPX_PROJECT": str(tmp_path), + "LOOPX_WAKE_LOG_DIR": str(tmp_path / "wakes"), "LOOPX_CONTEXT_DELIVERY": "off", + "LOOPX_BENCHMARK_CLAIM_TTL_SECONDS": "18000"}, + "turn-1", native_goal=False, + ) + assert "--ttl-seconds 18000" in rendered + + pytest.importorskip("harbor") + from benchmark.runtime.harbor import BenchmarkCodex + + agent = BenchmarkCodex(logs_dir=tmp_path, model_name="openai/fixture", claim_ttl_seconds=18000) + assert agent._worker_env(cwd="/task")["LOOPX_BENCHMARK_CLAIM_TTL_SECONDS"] == "18000" diff --git a/benchmark/tests/test_task_entry.py b/benchmark/tests/test_task_entry.py index 3ad3175c9b..26e00809ca 100644 --- a/benchmark/tests/test_task_entry.py +++ b/benchmark/tests/test_task_entry.py @@ -1378,6 +1378,7 @@ def _fake_session_wake(wake_env, *a, **kw): observed["wake_rt"] = wake_env["LOOPX_RUNTIME_ROOT"] return SimpleNamespace( session_id="sess-" + context, + binding={"session_id": "sess-resume"} if context == "resume" else None, receipt={"action": "start_new" if context == "fresh" else "resume", "session_id": "sess-" + context}, goal_ref=None, admission=None, diff --git a/loopx/control_plane/effect_runtime.py b/loopx/control_plane/effect_runtime.py index 3fb613fccb..13866472c2 100644 --- a/loopx/control_plane/effect_runtime.py +++ b/loopx/control_plane/effect_runtime.py @@ -498,7 +498,19 @@ def _uses_stdio_runtime() -> bool: def _pid_is_alive(value: object) -> bool: - return process_is_alive(value) + if not process_is_alive(value): + return False + # Unreaped Linux zombies still satisfy kill(pid, 0), yet an all-zombie + # thread group has terminated and must not poison runtime lock/locator recovery. + if ( + sys.platform == "linux" + and isinstance(value, int) + and not isinstance(value, bool) + and value > 0 + and _linux_thread_group_is_zombie(value) + ): + return False + return True def _recorded_pid_alive(value: object) -> bool | None: @@ -864,6 +876,7 @@ def _stop_effect_runtime( if not _pid_is_alive(pid) or ( not_caller_child and _linux_thread_group_is_zombie(pid) ): + _reap_exited_runtime_child(info) stopped = True break # A zombie leader can still have threads writing into the namespace. diff --git a/loopx/control_plane/runtime/checkpoint_artifacts.ts b/loopx/control_plane/runtime/checkpoint_artifacts.ts index d2ea3977ba..c8c82cc963 100644 --- a/loopx/control_plane/runtime/checkpoint_artifacts.ts +++ b/loopx/control_plane/runtime/checkpoint_artifacts.ts @@ -76,7 +76,104 @@ async function digest(path: string): Promise { for await (const block of createReadStream(path)) hash.update(block); return hash.digest("hex"); } -async function members(root: string, sourceObservation: boolean): Promise { +function normalizeComponentExclusions( + raw: unknown, + sources: readonly Component[], +): Map { + const map = new Map(); + if (raw === undefined) return map; + const record = requireJsonObject(raw, "checkpoint component_exclusions"); + const ids = new Set(sources.map(entry => entry.id)); + for (const [id, patternsRaw] of Object.entries(record)) { + if (!ids.has(id)) throw new Error("checkpoint component_exclusions references an unknown component"); + if (!Array.isArray(patternsRaw) || patternsRaw.length === 0) { + throw new Error("checkpoint component_exclusions entries must be non-empty pattern lists"); + } + const patterns = patternsRaw.map(item => { + const pattern = requireNonEmptyString(item, "checkpoint exclude pattern"); + if (pattern.includes("\\") || pattern.includes("\0") || pattern.includes("..")) { + throw new Error("checkpoint exclude pattern contains unsupported characters"); + } + const body = pattern.endsWith("/") ? pattern.slice(0, -1) : pattern; + if (!body || body.includes("/")) { + throw new Error("checkpoint exclude pattern must be a single name or suffix glob"); + } + return pattern; + }); + map.set(id, patterns); + } + return map; +} +const CORE_DUMP_EXCLUSION_PATTERN = "core-dump:elf-macho"; + +function isCoreDumpName(base: string): boolean { + return base === "core" || base.startsWith("core."); +} + +function isConfirmedCoreDumpHeader(header: Uint8Array): boolean { + if (header.length >= 18 && + header[0] === 0x7f && header[1] === 0x45 && header[2] === 0x4c && header[3] === 0x46 && + (header[4] === 1 || header[4] === 2)) { + if (header[5] === 1) return header[16] === 0x04 && header[17] === 0x00; + if (header[5] === 2) return header[16] === 0x00 && header[17] === 0x04; + return false; + } + if (header.length >= 16) { + const beMagic = header[0] === 0xfe && header[1] === 0xed && header[2] === 0xfa && + (header[3] === 0xce || header[3] === 0xcf); + if (beMagic) { + return header[12] === 0x00 && header[13] === 0x00 && header[14] === 0x00 && header[15] === 0x04; + } + const leMagic = (header[0] === 0xce || header[0] === 0xcf) && + header[1] === 0xfa && header[2] === 0xed && header[3] === 0xfe; + if (leMagic) { + return header[12] === 0x04 && header[13] === 0x00 && header[14] === 0x00 && header[15] === 0x00; + } + } + return false; +} + +async function isConfirmedCoreDumpFile(filePath: string): Promise { + try { + const handle = await open(filePath, "r"); + try { + const header = Buffer.alloc(20); + const {bytesRead} = await handle.read(header, 0, 20, 0); + return isConfirmedCoreDumpHeader(header.subarray(0, bytesRead)); + } finally {await handle.close();} + } catch { + return false; + } +} + +async function isExcludedEntry( + fullPath: string, + relativeName: string, + isDirectory: boolean, + patterns: readonly string[], +): Promise { + if (relativeName === "" || patterns.length === 0) return false; + const slash = relativeName.lastIndexOf("/"); + const base = slash === -1 ? relativeName : relativeName.slice(slash + 1); + for (const pattern of patterns) { + if (pattern.endsWith("/")) { + if (isDirectory && base === pattern.slice(0, -1)) return true; + } else if (pattern === CORE_DUMP_EXCLUSION_PATTERN || pattern === "core") { + const matchesName = pattern === "core" ? base === "core" : isCoreDumpName(base); + if (!isDirectory && matchesName && await isConfirmedCoreDumpFile(fullPath)) return true; + } else if (pattern.startsWith("*.")) { + if (!isDirectory && base.endsWith(pattern.slice(1))) return true; + } else if (!isDirectory && base === pattern) { + return true; + } + } + return false; +} +async function members( + root: string, + sourceObservation: boolean, + excludePatterns: readonly string[] = [], +): Promise { await physical(root); const output: Member[] = []; async function visit(path: string, name: string): Promise { @@ -94,6 +191,7 @@ async function members(root: string, sourceObservation: boolean): Promise { @@ -125,9 +223,15 @@ async function members(root: string, sourceObservation: boolean): Promise { +async function witness( + entries: Component[], + sourceObservation = true, + exclusions: ReadonlyMap = new Map(), +): Promise { const result: JsonObject = {}; - for (const entry of entries) result[entry.id] = await members(entry.source_path, sourceObservation); + for (const entry of entries) { + result[entry.id] = await members(entry.source_path, sourceObservation, exclusions.get(entry.id) ?? []); + } return result; } function unchanged(a: unknown, b: unknown, message = "checkpoint source moved; retry at a new owned barrier"): void { @@ -192,20 +296,27 @@ async function flushCopiedFile(path: string): Promise { finally {await chmod(path, mode);} } } -async function copyComponent(source: string, destination: string, snapshotDatabases = true): Promise { - let frontier = [{source, destination, nested: false}]; +async function copyComponent( + source: string, + destination: string, + snapshotDatabases = true, + excludePatterns: readonly string[] = [], +): Promise { + let frontier = [{source, destination, nested: false, relativeName: ""}]; while (frontier.length) { frontier = (await mapMembers(frontier, async entry => { - const {source, destination, nested} = entry, stat = await lstat(source); + const {source, destination, nested, relativeName} = entry, stat = await lstat(source); if (stat.isSymbolicLink()) throw new Error("checkpoint source became a symlink"); // An explicitly selected standalone sidecar remains a byte artifact. // Directory participants seal their databases through the existing WAL // snapshot owner rather than copying those databases' live sidecars. if (snapshotDatabases && nested && await sqliteSidecar(source, ["-wal", "-shm", "-journal"])) return []; + if (await isExcludedEntry(source, relativeName, stat.isDirectory(), excludePatterns)) return []; if (stat.isDirectory()) { await mkdir(destination, {mode: 0o700}); return (await readdir(source)).sort().map(child => ({source: join(source, child), - destination: join(destination, child), nested: true})); + destination: join(destination, child), nested: true, + relativeName: relativeName ? `${relativeName}/${child}` : child})); } if (!stat.isFile()) throw new Error("checkpoint source contains an unsupported file type"); if (snapshotDatabases && await sqliteFile(source)) await snapshotSqliteDatabase(source, destination); @@ -508,7 +619,12 @@ export async function checkpointArtifacts(value: unknown): Promise { request.action === "capture" ? ["action", "components", "destination", "point_metadata", "expected_source_sha256"] : request.action === "materialize" ? ["action", "root", "expected_sha256", "destination"] : null; if (fields === null) throw new Error("unsupported checkpoint artifact operation"); - if (!hasExactAuthorityKeys(request, [...fields, ...(request.deadline_epoch_ms === undefined ? [] : ["deadline_epoch_ms"])])) { + const allowsExclusions = request.action === "probe" || request.action === "capture"; + if (!hasExactAuthorityKeys(request, [ + ...fields, + ...(request.deadline_epoch_ms === undefined ? [] : ["deadline_epoch_ms"]), + ...(allowsExclusions && request.component_exclusions !== undefined ? ["component_exclusions"] : []), + ])) { throw new Error("checkpoint request fields are invalid"); } const deadline = request.deadline_epoch_ms; @@ -521,7 +637,8 @@ export async function checkpointArtifacts(value: unknown): Promise { withinDeadline(); if (request.action === "probe") { const sources = components(request.components); - const observed = await witness(sources); + const exclusions = normalizeComponentExclusions(request.component_exclusions, sources); + const observed = await witness(sources, true, exclusions); return {source_witness: observed, source_sha256: canonicalAuthoritySha256(observed)}; } if (request.action === "verify") return verify(absolute(request.root, "checkpoint root"), request.expected_sha256); @@ -540,12 +657,15 @@ export async function checkpointArtifacts(value: unknown): Promise { return {...verification, materialized: true, activation_performed: false}; } const sources = components(request.components); + const exclusions = normalizeComponentExclusions(request.component_exclusions, sources); if (sources.some(c => destination === c.source_path || destination.startsWith(c.source_path + sep) || c.source_path.startsWith(destination + sep))) throw new Error("checkpoint output overlaps its source"); - const before = await witness(sources); + const before = await witness(sources, true, exclusions); if (request.expected_source_sha256 !== canonicalAuthoritySha256(before)) throw new EffectRuntimeConflictError("checkpoint source moved before capture"); await mkdir(join(staging, "components"), {mode: 0o700}); - for (const c of sources) await copyComponent(c.source_path, join(staging, "components", c.id)); - unchanged(before, await witness(sources)); + for (const c of sources) { + await copyComponent(c.source_path, join(staging, "components", c.id), true, exclusions.get(c.id) ?? []); + } + unchanged(before, await witness(sources, true, exclusions)); const artifacts = await witness(sources.map(c => ({id: c.id, source_path: join(staging, "components", c.id)})), false); // Byte-copy members must match the reviewed source, including ABA movement // that could otherwise escape a before/after comparison. SQLite is sealed @@ -569,7 +689,7 @@ export async function checkpointArtifacts(value: unknown): Promise { const manifest = {...body, sha256: canonicalAuthoritySha256(body)}; await durableWriteJson(join(staging, "checkpoint.json"), manifest); await verify(staging, manifest.sha256); - unchanged(before, await witness(sources)); + unchanged(before, await witness(sources, true, exclusions)); withinDeadline(); await publishCheckpointDirectory(staging, destination); return {...await verify(destination, manifest.sha256), source_stability_verified: true}; diff --git a/scripts/external_scheduler_worker.py b/scripts/external_scheduler_worker.py index 5b2bdc2a28..210fb51cc4 100644 --- a/scripts/external_scheduler_worker.py +++ b/scripts/external_scheduler_worker.py @@ -566,6 +566,25 @@ def _log(line: str) -> None: print(f"{stamp} {line}", flush=True) +def _disable_core_dumps() -> None: + """Keep crashed child runtimes from spilling multi-GB core files into /tmp.""" + if os.name != "posix": + return + import resource + + soft, hard = resource.getrlimit(resource.RLIMIT_CORE) + if soft != 0: + resource.setrlimit(resource.RLIMIT_CORE, (0, hard)) + + +def _wake_stderr_tail(result: CappedProcessResult, *, limit: int = 400) -> str: + raw = getattr(result, "stderr", b"") + if not isinstance(raw, (bytes, bytearray)) or not raw: + return "" + collapsed = " ".join(bytes(raw).decode("utf-8", errors="replace").split()) + return collapsed[-limit:] if collapsed else "" + + def _shell_argv(command: str) -> list[str]: if os.name == "nt": # pragma: no cover - exercised on Windows hosts. return [os.environ.get("COMSPEC", "cmd.exe"), "/d", "/s", "/c", command] @@ -867,6 +886,7 @@ def save(fields: dict[str, Any]) -> None: wake_rc = None wake_failure_kind = None wake_failed = False + wake_stderr_tail = "" if args.wake_cmd: environment = None if host_guard: @@ -1005,6 +1025,8 @@ def save(fields: dict[str, Any]) -> None: # commit, resolves the independent witness. _save_host_pending(state_path, False) wake_status = "wake_failed" if wake_failed else "wake_ok" + if wake_failed: + wake_stderr_tail = _wake_stderr_tail(wake_result) _log( f"status=should_run {wake_status} " f"action={decision.action} class={decision.cadence_class} " @@ -1012,6 +1034,7 @@ def save(fields: dict[str, Any]) -> None: f"todo={selected_id or '-'} " f"reason={shlex.quote(decision.reason)}" + (f" wake_rc={wake_rc}" if wake_rc is not None else "") + + (f" stderr_tail={shlex.quote(wake_stderr_tail)}" if wake_stderr_tail else "") ) if wake_failed: save({ @@ -1196,6 +1219,7 @@ def main(argv: Sequence[str] | None = None) -> int: args.registry = str(global_registry_path()) except ValueError as exc: parser.error(str(exc)) + _disable_core_dumps() return run_worker(args) diff --git a/tests/control_plane/test_effect_runtime_locator_recovery.py b/tests/control_plane/test_effect_runtime_locator_recovery.py index bde4ae6e18..c03f2abda8 100644 --- a/tests/control_plane/test_effect_runtime_locator_recovery.py +++ b/tests/control_plane/test_effect_runtime_locator_recovery.py @@ -443,3 +443,39 @@ def test_readiness_reports_a_live_locator_when_node_is_unavailable( assert lifecycle["locator_state"] == "valid" assert lifecycle["recorded_pid_alive"] is True assert lifecycle["diagnostic_code"] == "node_unavailable" + + +def test_linux_zombie_thread_group_is_reported_not_alive_during_locator_recovery( + tmp_path: Path, + monkeypatch, +) -> None: + _isolate_runtime(tmp_path, monkeypatch) + monkeypatch.setattr(effect_runtime.sys, "platform", "linux") + monkeypatch.setattr(effect_runtime, "process_is_alive", lambda pid: pid == 424242) + zombie = True + monkeypatch.setattr(effect_runtime, "_linux_thread_group_is_zombie", lambda pid: zombie and pid == 424242) + + assert effect_runtime._pid_is_alive(424242) is False + fingerprint = effect_runtime._runtime_fingerprint() + info_path = effect_runtime._runtime_info_path(fingerprint) + info_path.parent.mkdir(parents=True) + info_path.write_text( + json.dumps({ + "schema_version": effect_runtime.EFFECT_RUNTIME_INFO_SCHEMA_VERSION, + "fingerprint": fingerprint, + "host": "127.0.0.1", + "port": 1, + "token": "stale-token", + "pid": 424242, + }), + encoding="utf-8", + ) + + readiness = effect_runtime.collect_effect_runtime_readiness() + lifecycle = readiness["runtime_lifecycle"] + assert lifecycle["state"] == "stopped" + assert lifecycle["recorded_pid_alive"] is False + assert lifecycle["diagnostic_code"] == "runtime_locator_pid_not_alive" + + zombie = False + assert effect_runtime._pid_is_alive(424242) is True diff --git a/tests/control_plane_ts/checkpoint_artifacts.test.ts b/tests/control_plane_ts/checkpoint_artifacts.test.ts index 97ad736ab8..df73e2266e 100644 --- a/tests/control_plane_ts/checkpoint_artifacts.test.ts +++ b/tests/control_plane_ts/checkpoint_artifacts.test.ts @@ -409,3 +409,116 @@ test("committed semantic replan can capture before work selection without invent await assert.rejects(checkpointArtifacts({...request, quota: {...quota, agent_identity: {...quota.agent_identity, registered: false}}})); }); + +function elfHeader(eType: number, littleEndian = true): Buffer { + const buf = Buffer.alloc(64); + buf[0] = 0x7f; buf[1] = 0x45; buf[2] = 0x4c; buf[3] = 0x46; + buf[4] = 2; // ELFCLASS64 + buf[5] = littleEndian ? 1 : 2; + if (littleEndian) buf.writeUInt16LE(eType, 16); + else buf.writeUInt16BE(eType, 16); + return buf; +} + +function machoHeader(filetype: number, littleEndian = true): Buffer { + const buf = Buffer.alloc(32); + if (littleEndian) { + buf.writeUInt32BE(0xcffaedfe, 0); // MH_CIGAM_64 + buf.writeUInt32LE(filetype, 12); + } else { + buf.writeUInt32BE(0xfeedfacf, 0); // MH_MAGIC_64 + buf.writeUInt32BE(filetype, 12); + } + return buf; +} + +test("component_exclusions skips ephemeral research outputs in probe and capture without weakening verify", async t => { + const {root, request} = await fixture(t); + const research = join(root, "research"); + await mkdir(join(research, "target/release"), {recursive: true}); + await mkdir(join(research, ".cargo-target/debug"), {recursive: true}); + await mkdir(join(research, "core"), {recursive: true}); + await mkdir(join(research, "topic"), {recursive: true}); + await mkdir(join(research, "bin"), {recursive: true}); + await mkdir(join(research, "nested"), {recursive: true}); + await writeFile(join(research, "dump.raw.gz"), "ephemeral"); + await writeFile(join(research, "core.4242"), elfHeader(4)); // ELF ET_CORE + await writeFile(join(research, "nested/core.9001"), machoHeader(4)); // Mach-O MH_CORE + await writeFile(join(research, "core/analysis.md"), "# real research notes\n"); + await writeFile(join(research, "topic/core"), "ordinary text notes\n"); + await writeFile(join(research, "bin/core"), elfHeader(2)); // ELF ET_EXEC (not ET_CORE) + await writeFile(join(research, "target/release/bin"), "compiled"); + await writeFile(join(research, ".cargo-target/debug/lib.rlib"), "compiled"); + await writeFile(join(research, "candidate.py"), "score = 1\n"); + + const components = [...request.components, {id: "benchmark_research", source_path: research}]; + const exclusions = {benchmark_research: ["*.raw.gz", "core-dump:elf-macho", "target/", ".cargo-target/"]}; + const probe = await checkpointArtifacts({action: "probe", components, component_exclusions: exclusions}); + const names = (probe.source_witness as Record>).benchmark_research.map(m => m.path); + assert.deepEqual(names, [ + "", + "bin", + "bin/core", + "candidate.py", + "core", + "core/analysis.md", + "nested", + "topic", + "topic/core", + ]); + + const captured = await checkpointArtifacts({ + ...request, + components, + expected_source_sha256: probe.source_sha256, + component_exclusions: exclusions, + }); + assert.equal(captured.integrity_verified, true); + assert.deepEqual( + (await readdir(join(root, "captured/components/benchmark_research"))).sort(), + ["bin", "candidate.py", "core", "nested", "topic"], + ); + const restored = await checkpointArtifacts({ + action: "materialize", + root: request.destination, + expected_sha256: captured.sha256, + destination: join(root, "restored"), + }); + assert.equal(restored.integrity_verified, true); + assert.equal( + await readFile(join(root, "restored/components/benchmark_research/core/analysis.md"), "utf8"), + "# real research notes\n", + ); + assert.equal( + await readFile(join(root, "restored/components/benchmark_research/topic/core"), "utf8"), + "ordinary text notes\n", + ); + assert.deepEqual( + await readFile(join(root, "restored/components/benchmark_research/bin/core")), + elfHeader(2), + ); + + // Even a direct bare "core" exclusion must preserve core/ dirs and non-dump topic/core files, + // excluding only a confirmed ELF/Mach-O dump named "core". + await writeFile(join(research, "nested/core"), elfHeader(4, false)); // ELF ET_CORE (big-endian) + const bareProbe = await checkpointArtifacts({ + action: "probe", + components, + component_exclusions: {benchmark_research: ["core"]}, + }); + const bareNames = (bareProbe.source_witness as Record>).benchmark_research.map(m => m.path); + assert.ok(bareNames.includes("core/analysis.md")); + assert.ok(bareNames.includes("topic/core")); + assert.ok(bareNames.includes("bin/core")); + assert.ok(!bareNames.includes("nested/core")); + + await assert.rejects( + checkpointArtifacts({action: "verify", root: request.destination, expected_sha256: captured.sha256, + component_exclusions: exclusions} as never), + /invalid/, + ); + await assert.rejects( + checkpointArtifacts({action: "probe", components, component_exclusions: {unknown_component: ["core"]}}), + /unknown component/, + ); +}); diff --git a/tests/extensions/test_process_runtime.py b/tests/extensions/test_process_runtime.py index be66449e2f..5b4dc67549 100644 --- a/tests/extensions/test_process_runtime.py +++ b/tests/extensions/test_process_runtime.py @@ -16,6 +16,7 @@ import loopx.extensions.process_runtime as process_runtime from loopx.extensions.process_runtime import ( + CappedProcessResult, force_terminate_process, retire_owned_process, remove_owned_tree, @@ -862,3 +863,19 @@ def test_remove_owned_tree_never_clears_a_shared_hard_link_attribute( assert source_object.read_bytes() == b"blob" assert os.stat(source_object).st_mode & stat.S_IWRITE == 0 + + +def test_run_capped_process_retains_stderr_backwards_compatibly() -> None: + legacy = CappedProcessResult(0, b"out") + assert legacy.failure_kind is None + assert legacy.stderr == b"" + + result = run_capped_process( + [sys.executable, "-c", "import sys; sys.stdout.write('ok'); sys.stderr.write('boom trace\\n'); sys.exit(1)"], + stdin=b"", + timeout_seconds=10, + output_limit_bytes=4096, + ) + assert result.returncode == 1 + assert result.stdout == b"ok" + assert b"boom trace" in result.stderr diff --git a/tests/test_external_scheduler_worker.py b/tests/test_external_scheduler_worker.py index 9c0051c26c..c958b468eb 100644 --- a/tests/test_external_scheduler_worker.py +++ b/tests/test_external_scheduler_worker.py @@ -1107,3 +1107,47 @@ def completed_before_lock(*a, **kw): assert worker.run_worker(args) == 0 assert ordinary.exists() and calls.read_text() == "1" assert json.loads(witness.read_text()) == {"pending": False} + + +def test_external_worker_disables_core_dumps_and_logs_wake_stderr_tail( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], +) -> None: + if os.name == "posix": + import resource + + recorded: list[tuple[int, int]] = [] + monkeypatch.setattr(resource, "getrlimit", lambda kind: (1024, 2048)) + monkeypatch.setattr(resource, "setrlimit", lambda kind, limits: recorded.append(limits)) + worker._disable_core_dumps() + assert recorded == [(0, 2048)] + + registry = tmp_path / "registry.json" + registry.write_text("{}") + args = argparse.Namespace( + cli_bin="loopx", + registry=str(registry), + runtime_root=str(tmp_path / "runtime"), + runtime_profile="generic_cli", + goal_id="goal-1", + agent_id="agent-1", + state_file=str(tmp_path / "state.json"), + wake_cmd="false", + wake_host_failure=False, + wake_stop_exit_code=None, + once=True, + error_backoff_seconds=5.0, + quota_timeout_seconds=10.0, + wake_timeout_seconds=10.0, + ) + monkeypatch.setattr(worker, "run_quota_should_run", lambda *a, **kw: _hint_payload(should_run=True)) + from loopx.extensions.process_runtime import CappedProcessResult + + monkeypatch.setattr( + worker, + "_run_wake", + lambda *a, **kw: CappedProcessResult(1, b"", None, b"line 1\nTraceback: runtime node failed\n"), + ) + rc = worker.run_worker(args) + assert rc == 1 + out = capsys.readouterr().out + assert "wake_failed" in out and "stderr_tail=" in out and "Traceback: runtime node failed" in out