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
33 changes: 31 additions & 2 deletions benchmark/runtime/RUNTIME.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,37 @@ the opt-in. The wake receipt records successful hook discovery.
Use the same pinned task, model, reasoning effort, time and evaluator in
comparison arms. The benchmark adapter still owns feedback, final submission,
and scoring. EdgeBench's SForge auto-resume remains a provider-specific part of
its official profile. Use a fresh trial with the option omitted for a
single-pass Codex baseline.
its official profile. Use a fresh trial with the option omitted for a single-pass Codex baseline.

To run the stronger counterfactual Stop-hook checklist baseline (opt-in and
default-off), add `official_stop_hook_mode: "todo_checklist"` alongside
`execution_mode: plain` and `official_stop_hook: true` (`"simple"` selects the
original prompt-less Stop hook; invalid modes or pairing with non-`plain` /
`official_stop_hook: false` fail validation before host preparation). When
`todo_checklist` is selected, the worker stages a physical trial-local
`baseline-todo/TODO.md` inside `LOOPX_CODEX_HOME` (never inside the workspace
git repository, keeping patches and `git status` unpolluted), appends checklist
and regression-verification guidance to the initial prompt, and checks that
checklist on `Stop`: blocking continuation with unchecked item summaries while
open items remain or no items are checked, and allowing completion (`{}`) once
every item is marked `[x]`. Omitting `official_stop_hook_mode` leaves `plain`
and `official_stop_hook: true` behavior, hooks, prompts, and existing receipt
fields unchanged.

### Control-plane overhead and tax telemetry

Using local monotonic timings (with zero extra RPCs), worker wake receipts and
Harbor phase `context.metadata` record `hook_prepare_seconds`,
`control_overhead_seconds`, `work_wall_seconds`, `control_tax_ratio`
(`control_overhead_seconds / (control_overhead_seconds + work_wall_seconds)`,
summed cleanly across phase wakes without averaging ratios),
`control_telemetry_verified`, and `control_telemetry_status` (`verified`,
`missing_receipt`, or `untimed_receipt`). Missing, corrupt, or untimed current-phase
receipts retain observed preparation/control seconds while leaving
`work_wall_seconds` and `control_tax_ratio` as `null` (`control_telemetry_verified: false`)
rather than synthesizing `0.0` work time or `1.0` control tax. Both LoopX
heartbeat/context-delivery arms and Stop-hook counterfactual baseline arms emit
these fields so net-of-tax outcomes can be compared directly.

### Historical heartbeat formats

Expand Down
108 changes: 107 additions & 1 deletion benchmark/runtime/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
import json
import math
import os
from collections.abc import Mapping
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any


# New benchmark runs and the product both default to six settled work Turns.
Expand Down Expand Up @@ -42,6 +43,98 @@ def claim_ttl_seconds_from_env(env: Mapping[str, str] | None = None) -> int | No
CONTEXTS = ("fresh", "resume")
TASK_ENTRIES = ("seeded-todo", "loopx-planned")
SANDBOXES = ("read-only", "workspace-write", "danger-full-access")
OFFICIAL_STOP_HOOK_MODES = ("simple", "todo_checklist")


def _finite_nonneg(value: Any) -> float | None:
if (
isinstance(value, (int, float))
and type(value) is not bool
and math.isfinite(value)
and value >= 0.0
):
return float(value)
return None


def summarize_control_telemetry(
*,
hook_prepare_seconds: float,
control_overhead_seconds: float,
work_wall_seconds: float,
) -> dict[str, float]:
"""Summarize monotonic hook, control-plane overhead, and work timings."""
hook_s = max(0.0, float(hook_prepare_seconds))
work_s = max(0.0, float(work_wall_seconds))
control_s = max(hook_s, float(control_overhead_seconds))
total_s = control_s + work_s
tax_ratio = (control_s / total_s) if total_s > 0.0 else 0.0
return {
"hook_prepare_seconds": round(hook_s, 6),
"control_overhead_seconds": round(control_s, 6),
"work_wall_seconds": round(work_s, 6),
"control_tax_ratio": round(tax_ratio, 6),
}


def aggregate_control_telemetry(
records: Iterable[Mapping[str, Any]],
*,
extra_control_seconds: float = 0.0,
missing_receipts: int = 0,
) -> dict[str, float | bool | str | None]:
"""Aggregate worker telemetry; preserve unknown work/ratio when timing coverage is incomplete."""
record_list = list(records)
missing_count = (
missing_receipts
if isinstance(missing_receipts, int)
and not isinstance(missing_receipts, bool)
and missing_receipts > 0
else 0
)
extra_s = _finite_nonneg(extra_control_seconds) or 0.0
hook_s = 0.0
control_s = extra_s
work_s = 0.0
for record in record_list:
hook_val = _finite_nonneg(record.get("hook_prepare_seconds"))
control_val = _finite_nonneg(record.get("control_overhead_seconds"))
work_val = _finite_nonneg(record.get("work_wall_seconds"))
if hook_val is not None:
hook_s += hook_val
if control_val is not None:
control_s += control_val
if work_val is not None:
work_s += work_val
all_wakes_timed = bool(record_list) and missing_count == 0 and all(
_finite_nonneg(record.get("work_wall_seconds")) is not None
and _finite_nonneg(record.get("control_overhead_seconds")) is not None
for record in record_list
)
if not all_wakes_timed:
normalized_control = max(hook_s, control_s)
return {
"hook_prepare_seconds": round(hook_s, 6),
"control_overhead_seconds": round(normalized_control, 6),
"work_wall_seconds": None,
"control_tax_ratio": None,
"control_telemetry_verified": False,
"control_telemetry_status": (
"missing_receipt"
if (not record_list or missing_count > 0)
else "untimed_receipt"
),
}
summary = summarize_control_telemetry(
hook_prepare_seconds=hook_s,
control_overhead_seconds=control_s,
work_wall_seconds=work_s,
)
return {
**summary,
"control_telemetry_verified": True,
"control_telemetry_status": "verified",
}


@dataclass(frozen=True)
Expand All @@ -57,6 +150,7 @@ class Execution:
native_child_limit: int | None = None
complete_turn: bool = False
official_stop_hook: bool = False
official_stop_hook_mode: str | None = None

def __post_init__(self) -> None:
if self.native_child_limit is not None and (
Expand All @@ -73,6 +167,18 @@ def __post_init__(self) -> None:
raise ValueError("Historical turn_envelope and complete_turn treatments require the recorded product and runner revisions")
if type(self.official_stop_hook) is not bool or (self.official_stop_hook and self.mode != "plain"):
raise ValueError("official_stop_hook requires plain execution and a boolean opt-in")
if self.official_stop_hook_mode is not None:
if (
type(self.official_stop_hook_mode) is not str
or self.official_stop_hook_mode not in OFFICIAL_STOP_HOOK_MODES
):
raise ValueError(
f"official_stop_hook_mode supports only {OFFICIAL_STOP_HOOK_MODES}"
)
if not self.official_stop_hook or self.mode != "plain":
raise ValueError(
"official_stop_hook_mode requires official_stop_hook=True and plain execution"
)
if self.mode not in MODES or self.context not in CONTEXTS:
raise ValueError("unsupported execution mode or iteration context")
if self.task_entry is None:
Expand Down
87 changes: 80 additions & 7 deletions benchmark/runtime/harbor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import tempfile
import time
from pathlib import Path, PurePosixPath
from typing import Iterable
from typing import Any, Iterable

from harbor.agents.installed.base import with_prompt_template
from harbor.environments.base import BaseEnvironment
Expand All @@ -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,
aggregate_control_telemetry,
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 @@ -84,6 +89,7 @@ def __init__(
defer_codex_home=False,
complete_turn=False,
official_stop_hook=False,
official_stop_hook_mode=None,
claim_ttl_seconds=None,
**kwargs,
):
Expand Down Expand Up @@ -112,6 +118,7 @@ def __init__(
native_child_limit,
complete_turn=complete_turn,
official_stop_hook=official_stop_hook,
official_stop_hook_mode=official_stop_hook_mode,
)
if type(provider_request_admission) is not bool:
raise ValueError("provider_request_admission must be a boolean opt-in")
Expand Down Expand Up @@ -186,6 +193,7 @@ def __init__(
self._task_path = "/usr/local/bin:/usr/bin:/bin"
self._phase_number = 0
self._seeded_todo_id: str | None = None
self._last_phase_telemetry: dict[str, float | bool | str | None] | None = None
if task_objective is not None and (not isinstance(task_objective, str)
or not task_objective.strip()):
raise ValueError("Task objective must be a non-empty string")
Expand Down Expand Up @@ -420,6 +428,8 @@ async def install(self, environment: BaseEnvironment) -> None:
**self._host_context_receipt(),
**self._planning_receipt(),
**({"official_stop_hook": True} if self.execution.official_stop_hook else {}),
**({"official_stop_hook_mode": self.execution.official_stop_hook_mode}
if self.execution.official_stop_hook_mode is not None else {}),
**({"provider_request_admission": "on"} if self.provider_request_admission else {}),
"home_scope": "trial",
"loopx_usage_ping_enabled": False,
Expand Down Expand Up @@ -694,6 +704,7 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]:
if self.checkpoint_request_path is not None else {}),
"LOOPX_CONTEXT_DELIVERY": self.execution.context_delivery,
"LOOPX_OFFICIAL_STOP_HOOK": "1" if self.execution.official_stop_hook else "0",
"LOOPX_OFFICIAL_STOP_HOOK_MODE": self.execution.official_stop_hook_mode or "",
# A trial's explicit None must not inherit a container opt-in.
"LOOPX_NATIVE_CHILD_LIMIT": (
str(self.execution.native_child_limit)
Expand Down Expand Up @@ -803,6 +814,41 @@ def _write_aggregate_trajectory(
)
return trajectories

def _wake_dirs(self) -> set[Path]:
wakes_dir = self.logs_dir / "wakes"
if wakes_dir.is_symlink() or not wakes_dir.is_dir():
return set()
return {
path.resolve()
for path in wakes_dir.iterdir()
if not path.is_symlink() and path.is_dir()
}

def _read_wake_receipts(
self, *, exclude: Iterable[Path] = ()
) -> tuple[list[dict[str, Any]], int]:
"""Collect current-phase wake receipt dicts alongside missing/corrupt wake count."""
seen = set(exclude)
receipts: list[dict[str, Any]] = []
missing_count = 0
for wake_dir in sorted(self._wake_dirs()):
if wake_dir in seen:
continue
path = wake_dir / "receipt.json"
if path.is_symlink() or not path.is_file():
missing_count += 1
continue
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError):
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
missing_count += 1
continue
if not isinstance(payload, dict):
missing_count += 1
continue
receipts.append(payload)
return receipts, missing_count

def _populate_context(
self, context: AgentContext, before: dict | None = None
) -> None:
Expand All @@ -822,6 +868,14 @@ def token_delta(key: str) -> int | None:
value = delta(key)
return value if type(value) is int else None

telemetry = self._last_phase_telemetry
if telemetry is None:
wakes, missing_wakes = self._read_wake_receipts()
if wakes or missing_wakes:
telemetry = aggregate_control_telemetry(
wakes, missing_receipts=missing_wakes,
)

context.n_input_tokens = token_delta("prompt")
context.n_output_tokens = token_delta("completion")
context.n_cache_tokens = token_delta("cached")
Expand All @@ -833,10 +887,13 @@ def token_delta(key: str) -> int | None:
**self._host_context_receipt(),
**self._planning_receipt(),
**({"official_stop_hook": True} if self.execution.official_stop_hook else {}),
**({"official_stop_hook_mode": self.execution.official_stop_hook_mode}
if self.execution.official_stop_hook_mode is not None else {}),
**({"provider_request_admission": "on"} if self.provider_request_admission else {}),
"home_scope": "trial",
**self._replan_receipt(),
"benchmark_phase": self._phase_number,
**(telemetry if telemetry is not None else {}),
}
self._write_aggregate_trajectory(trajectories)

Expand All @@ -853,6 +910,9 @@ async def run(
if not self.model_name:
raise ValueError("model_name is required")
self._phase_number += 1
self._last_phase_telemetry = None
before_wakes = self._wake_dirs()
prep_elapsed = 0.0
deadline = time.monotonic() + self.scheduler_timeout
pwd = await self.exec_as_agent(environment, command="pwd", timeout_sec=30)
cwd = (pwd.stdout or "").strip()
Expand All @@ -867,10 +927,14 @@ async def run(
if not any(self.logs_dir.glob("sessions/**/*.jsonl")):
before = None
try:
if self.execution.uses_loopx:
await self._prepare_phase(environment, instruction, cwd=cwd)
else:
await self._write_task_document(environment, instruction)
prep_started = time.monotonic()
try:
if self.execution.uses_loopx:
await self._prepare_phase(environment, instruction, cwd=cwd)
else:
await self._write_task_document(environment, instruction)
finally:
prep_elapsed = max(0.0, time.monotonic() - prep_started)
wake_command = [f"{_PYTHON}/bin/python3", "-m", _WORKER_MODULE]
env = self._worker_env(cwd=cwd)
if self.execution.task_entry == "loopx-planned":
Expand Down Expand Up @@ -941,4 +1005,13 @@ async def run(
mounted = environment.capabilities.mounted
if not mounted:
await environment.download_dir("/logs/agent", self.logs_dir)
self._populate_context(context, before)
new_wakes, missing_wakes = self._read_wake_receipts(exclude=before_wakes)
self._last_phase_telemetry = aggregate_control_telemetry(
new_wakes,
extra_control_seconds=prep_elapsed,
missing_receipts=missing_wakes,
)
try:
self._populate_context(context, before)
finally:
self._last_phase_telemetry = None
Loading
Loading