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
5 changes: 5 additions & 0 deletions benchmark/edgebench/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ def main(argv=None):
parser.add_argument("--worker", choices=PROFILES, required=True)
parser.add_argument("--validation-command-json", type=json.loads,
help="For turn-resume, trusted guest argv that independently checks the work postcondition")
parser.add_argument("--semantic-unit-fold-json", default=None,
help="For turn-resume, opt-in Todo semantic-unit fold configuration JSON object")
parser.add_argument("--feedback", choices=FEEDBACK_MODES, default="native",
help="New-run default: native public feedback; blind/best-only are explicit controls")
parser.add_argument("--managed-run-json", type=Path,
Expand Down Expand Up @@ -207,6 +209,7 @@ def main(argv=None):
args.worker, task_entry=args.task_entry,
context_delivery=args.context_delivery, validation_command=args.validation_command_json,
native_child_limit=args.native_child_limit,
semantic_unit_fold_json=args.semantic_unit_fold_json,
)
except ValueError as error:
parser.error(str(error))
Expand Down Expand Up @@ -451,6 +454,7 @@ def main(argv=None):
task_objective=task_objective,
task_entry=args.task_entry,
validation_command=execution.validation_command,
semantic_unit_fold_json=execution.semantic_unit_fold_json,
context_delivery=args.context_delivery,
**({"execution_observation": args.execution_observation}
if args.execution_observation is not None else {}),
Expand Down Expand Up @@ -525,6 +529,7 @@ def main(argv=None):
"run_id": args.run_id, "task": args.task, "worker": args.worker,
"task_entry": agent.task_entry,
**execution.validation_receipt(),
**execution.semantic_unit_fold_receipt(),
**({"planning_timeout_seconds": None}
if agent.task_entry == "loopx-planned" else {}),
"model": args.model, "effort": args.effort, "timeout_seconds": args.timeout,
Expand Down
45 changes: 44 additions & 1 deletion benchmark/runtime/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,30 @@
# 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"
LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV = "LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_JSON"
_MAX_CLAIM_TTL_SECONDS = 86400


def normalize_semantic_unit_fold_json(value: str | None) -> str | None:
"""Validate optional opt-in semantic-unit fold JSON object string."""
if value is None:
return None
if not isinstance(value, str):
raise ValueError("semantic_unit_fold_json must be a JSON object string")
text = value.strip()
if not text:
raise ValueError("semantic_unit_fold_json must be a JSON object string")
try:
parsed = json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError("semantic_unit_fold_json must be valid JSON") from exc
if not isinstance(parsed, dict):
raise ValueError("semantic_unit_fold_json must be a JSON object")
if "enabled" in parsed and type(parsed["enabled"]) is not bool:
raise ValueError("semantic_unit_fold_json 'enabled' must be a boolean")
return text


def normalize_claim_ttl_seconds(value: int | None) -> int | None:
"""Validate optional benchmark Todo claim TTL in 1..86400 seconds."""
if value is None:
Expand Down Expand Up @@ -57,6 +78,7 @@ class Execution:
native_child_limit: int | None = None
complete_turn: bool = False
official_stop_hook: bool = False
semantic_unit_fold_json: str | None = None

def __post_init__(self) -> None:
if self.native_child_limit is not None and (
Expand Down Expand Up @@ -98,13 +120,26 @@ def __post_init__(self) -> None:
raise ValueError("mode=turn requires an independent validation_command")
if self.mode != "turn" and self.validation_command:
raise ValueError("validation_command is only used by mode=turn")
normalized_fold = normalize_semantic_unit_fold_json(self.semantic_unit_fold_json)
object.__setattr__(self, "semantic_unit_fold_json", normalized_fold)
if normalized_fold is not None and self.mode != "turn":
raise ValueError("semantic_unit_fold_json requires mode=turn")

def validation_receipt(self) -> dict[str, str]:
if self.mode != "turn":
return {}
encoded = json.dumps(self.validation_command, separators=(",", ":")).encode()
return {"validation_argv_sha256": hashlib.sha256(encoded).hexdigest()}

def semantic_unit_fold_receipt(self) -> dict[str, str]:
if self.semantic_unit_fold_json is None:
return {}
return {
"semantic_unit_fold_sha256": hashlib.sha256(
self.semantic_unit_fold_json.encode("utf-8")
).hexdigest(),
}

@property
def uses_loopx(self) -> bool:
return self.mode in {"heartbeat", "turn", "loopx-goal"}
Expand Down Expand Up @@ -350,9 +385,17 @@ def _prepend_existing_runtime_dirs(env: dict[str, str]) -> None:


def process_environment(
home: Path, *, base: Mapping[str, str] | None = None
home: Path,
*,
base: Mapping[str, str] | None = None,
semantic_unit_fold_json: str | None = None,
) -> dict[str, str]:
env = dict(os.environ if base is None else base)
env["CODEX_HOME"] = str(home)
normalized_fold = normalize_semantic_unit_fold_json(semantic_unit_fold_json)
if normalized_fold is not None:
env[LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV] = normalized_fold
else:
env.pop(LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV, None)
_prepend_existing_runtime_dirs(env)
return env
29 changes: 27 additions & 2 deletions benchmark/runtime/harbor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@
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, normalize_claim_ttl_seconds
from .codex import (
DEFAULT_REPLAN_AFTER_TURNS,
Execution,
LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV,
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 +90,7 @@ def __init__(
complete_turn=False,
official_stop_hook=False,
claim_ttl_seconds=None,
semantic_unit_fold_json=None,
**kwargs,
):
if "research_loop" in kwargs:
Expand Down Expand Up @@ -112,6 +118,7 @@ def __init__(
native_child_limit,
complete_turn=complete_turn,
official_stop_hook=official_stop_hook,
semantic_unit_fold_json=semantic_unit_fold_json,
)
if type(provider_request_admission) is not bool:
raise ValueError("provider_request_admission must be a boolean opt-in")
Expand Down Expand Up @@ -342,6 +349,18 @@ async def install(self, environment: BaseEnvironment) -> None:
await stage_portable_python(environment, _PYTHON)
if self.execution.uses_loopx:
await environment.upload_dir(node_root, _NODE)
owner = shlex.quote(str(environment.default_user or "root"))
owned_dirs = " ".join(
path
for path in (
_SRC,
_LOOPX_RUNTIME,
_CONTROL,
_PROFILE,
None if self.defer_codex_home else _CODEX_HOME,
)
if path
)
await self.exec_as_root(
environment,
command=(
Expand All @@ -351,7 +370,9 @@ async def install(self, environment: BaseEnvironment) -> None:
f"-name '*.dist-info' \\) -exec rm -rf {{}} +; "
# The formal source installer builds generated frontend assets
# as the environment user; the archive is extracted by root.
f"chown -R {shlex.quote(str(environment.default_user or 'root'))} {_SRC}; "
# Runtime, control, profile, and Codex home dirs must also stay
# owned by the environment user so atomic 0o700 writes succeed.
f"chown -R {owner} {owned_dirs}; "
f"chmod -R a+rX {_SRC} {_PYTHON} {_NODE}; "
f"chmod -R a+rwX {_PROFILE} {_CONTROL} {'' if self.defer_codex_home else _CODEX_HOME} {_WAKE_LOG_DIR}"
),
Expand Down Expand Up @@ -673,6 +694,8 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]:
env = self._profile_env()
if not self.execution.uses_loopx:
env["PATH"] = self._task_path
if self.execution.semantic_unit_fold_json is None:
env.pop(LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV, None)
env.update(
{
"PYTHONPATH": _SRC,
Expand Down Expand Up @@ -710,6 +733,8 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]:
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 {}),
**({LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV: self.execution.semantic_unit_fold_json}
if self.execution.semantic_unit_fold_json is not None else {}),
"CODEX_BIN": "/usr/local/bin/codex",
"MODEL_NAME": (self.model_name or "").split("/", 1)[-1],
"REASONING_EFFORT": str(
Expand Down
11 changes: 9 additions & 2 deletions benchmark/runtime/sforge.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,16 @@

def profile_execution(profile, *, task_entry=None, context_delivery=None,
turn_envelope=False, complete_turn=False,
validation_command=None, native_child_limit=None):
validation_command=None, native_child_limit=None,
semantic_unit_fold_json=None):
"""Resolve the native experiment arm through the shared runtime contract."""
if profile not in PROFILE_MODES:
raise ValueError("Unknown benchmark worker profile")
return Execution(
mode=PROFILE_MODES[profile], task_entry=task_entry, context_delivery=context_delivery,
turn_envelope=turn_envelope, complete_turn=complete_turn, native_child_limit=native_child_limit,
validation_command=() if validation_command is None else validation_command,
semantic_unit_fold_json=semantic_unit_fold_json,
)


Expand Down Expand Up @@ -148,14 +150,16 @@ def __init__(self, config, *, profile: str, cwd: str,
checkpoint_request: bytes | None = None,
warm_start=None, research_sidecar: bool = False,
native_result_scope: dict | None = None, complete_turn: bool = False,
claim_ttl_seconds: int | None = None):
claim_ttl_seconds: int | None = None,
semantic_unit_fold_json: str | 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,
complete_turn=complete_turn, validation_command=validation_command,
native_child_limit=native_child_limit,
semantic_unit_fold_json=semantic_unit_fold_json,
)
self.context_delivery = self.execution.context_delivery
self.task_entry = self.execution.task_entry
Expand Down Expand Up @@ -452,6 +456,8 @@ def _install_worker(self, backend, handle, log_dir, logger):
"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 {}),
**({"semantic_unit_fold_json": self.execution.semantic_unit_fold_json}
if self.execution.semantic_unit_fold_json is not None else {}),
)
asyncio.run(self.runtime.install(self.environment))
if self.feedback == "native" and (self.execution_observation is not None
Expand Down Expand Up @@ -534,6 +540,7 @@ def _install_worker(self, backend, handle, log_dir, logger):
(log_dir / "worker-profile.json").write_text(json.dumps({
"profile": self.profile, "model": self._config.agent_model,
**self.execution.validation_receipt(),
**self.execution.semantic_unit_fold_receipt(),
"task_entry": self.task_entry,
"reasoning_effort": effort, "timeout_seconds": self.timeout_seconds,
"loopx_usage_ping_enabled": False,
Expand Down
69 changes: 64 additions & 5 deletions benchmark/runtime/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from __future__ import annotations

import hashlib
import json
import math
import os
Expand All @@ -19,7 +20,9 @@

from benchmark.runtime.codex import (
Execution,
LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV,
claim_ttl_seconds_from_env,
normalize_semantic_unit_fold_json,
reject_retired_turn_display,
prepare_codex_home,
process_environment,
Expand Down Expand Up @@ -312,18 +315,50 @@ def interrupt_checkpoint_process(process, *, timeout: float = 10) -> int:
_reap_child_process(process)


def pending_turn(path: Path, turn_id: str, execution: Execution) -> dict:
def _resolved_semantic_unit_fold(
execution: Execution,
env: Mapping[str, str] | None = None,
) -> tuple[str | None, str | None]:
raw_fold = execution.semantic_unit_fold_json
if raw_fold is None and env is not None:
raw_fold = env.get(LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV) or None
fold_json = normalize_semantic_unit_fold_json(raw_fold)
if fold_json is not None and execution.mode != "turn":
raise ValueError("semantic_unit_fold_json requires mode=turn")
fold_sha256 = (
hashlib.sha256(fold_json.encode("utf-8")).hexdigest()
if fold_json is not None
else None
)
return fold_json, fold_sha256


def pending_turn(
path: Path,
turn_id: str,
execution: Execution,
env: Mapping[str, str] | None = None,
) -> dict:
"""The caller holds the trial lock until the product returns or the wake exits."""
from loopx.control_plane.runtime.document_io import atomic_write_private_json

validator = execution.validation_receipt()
fold_json, fold_sha256 = _resolved_semantic_unit_fold(execution, env)
if not path.exists():
pending = {"turn_instance_id": turn_id, **validator}
pending = {
"turn_instance_id": turn_id,
**validator,
"semantic_unit_fold_sha256": fold_sha256,
**({"semantic_unit_fold_json": fold_json} if fold_json is not None else {}),
}
atomic_write_private_json(path, pending)
return pending
pending = read_json(path.read_text())
if pending.get("validation_argv_sha256") != validator["validation_argv_sha256"]:
raise ValueError("Pending Turn requires its original validation command")
# Historical pending records without semantic_unit_fold_sha256 default to omitted (None).
if pending.get("semantic_unit_fold_sha256") != fold_sha256:
raise ValueError("Pending Turn requires its original semantic_unit_fold configuration")
return pending


Expand All @@ -339,6 +374,7 @@ def turn_command(
address = ["--resume-turn-key", resume_turn_key, "--retry-failed-turn"]
elif recover_instance:
address = ["--resume-turn-instance-id", turn_id, "--retry-failed-turn"]
fold_json, _ = _resolved_semantic_unit_fold(execution, env)
return loopx_command(env) + [
"turn",
"run-once",
Expand Down Expand Up @@ -371,6 +407,7 @@ def turn_command(
if execution.timeout_seconds is not None else []),
"--validation-command-json",
json.dumps(execution.validation_command),
*(["--semantic-unit-fold-json", fold_json] if fold_json is not None else []),
"--available-capability",
"shell",
"--available-capability",
Expand Down Expand Up @@ -588,6 +625,7 @@ def run_once(env: dict[str, str]) -> dict:
native_child_limit=(int(env["LOOPX_NATIVE_CHILD_LIMIT"])
if env.get("LOOPX_NATIVE_CHILD_LIMIT") else None),
official_stop_hook=stop_hook == "1",
semantic_unit_fold_json=(env.get(LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV) or None),
)
request_admission = False
if env.get("LOOPX_PROVIDER_REQUEST_ADMISSION", "off") != "off":
Expand All @@ -608,7 +646,11 @@ def run_once(env: dict[str, str]) -> dict:
wake.mkdir(parents=True, exist_ok=False)
stdout_path, stderr_path = host_output_paths(wake)
home = Path(env["LOOPX_CODEX_HOME"])
env = process_environment(home, base=env)
env = process_environment(
home,
base=env,
semantic_unit_fold_json=execution.semantic_unit_fold_json,
)
if env.get("LOOPX_RUNTIME_ROOT"):
env["LOOPX_RUNTIME_ROOT"] = _normalize_runtime_root(
env["LOOPX_RUNTIME_ROOT"], env["LOOPX_PROJECT"]
Expand All @@ -633,6 +675,7 @@ def run_once(env: dict[str, str]) -> dict:
"turn_id": turn_id,
"mode": execution.mode,
**execution.validation_receipt(),
**execution.semantic_unit_fold_receipt(),
"context": execution.context,
"task_entry": execution.task_entry,
**({"execution_observation": observation_producer}
Expand Down Expand Up @@ -802,7 +845,7 @@ def run_once(env: dict[str, str]) -> dict:
lock = wake_context.enter_context(try_exclusive_file_lock(pending_path))
if lock is None:
raise RuntimeError("Another benchmark wake owns the pending Turn")
pending = pending_turn(pending_path, turn_id, execution)
pending = pending_turn(pending_path, turn_id, execution, env=env)
receipt["turn_instance_id"] = pending["turn_instance_id"]
command = (
turn_command(
Expand Down Expand Up @@ -866,7 +909,23 @@ def run_once(env: dict[str, str]) -> dict:
temporary.write_text(json.dumps(receipt["planning"]))
temporary.replace(target)
elif execution.mode == "turn" and stage == "execute":
result = read_json(stdout_path.read_text())
raw_stdout = stdout_path.read_text(encoding="utf-8", errors="replace")
try:
result = read_json(raw_stdout)
except (ValueError, json.JSONDecodeError) as exc:
stderr_tail = (
" ".join(
stderr_path.read_text(encoding="utf-8", errors="replace").split()
)[-300:]
if stderr_path.is_file()
else ""
)
stdout_tail = " ".join(raw_stdout.split())[-200:]
raise RuntimeError(
"Turn CLI returned non-JSON output "
f"(returncode={receipt.get('return_code')}, "
f"stdout={stdout_tail!r}, stderr={stderr_tail!r})"
) from exc
receipt["turn_execution"] = result
receipt["ok"] = receipt["ok"] and result.get("ok") is True
if receipt["ok"]:
Expand Down
Loading
Loading