Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 61 additions & 21 deletions benchmark/edgebench/checkpoint_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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()
Expand All @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -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()
4 changes: 4 additions & 0 deletions benchmark/runtime/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions benchmark/runtime/checkpoint_wake.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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):
Expand Down
62 changes: 61 additions & 1 deletion benchmark/runtime/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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"}:
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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"
Expand All @@ -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
6 changes: 5 additions & 1 deletion benchmark/runtime/harbor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading