Skip to content
Closed
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
3 changes: 2 additions & 1 deletion benchmark/runtime/harbor.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,7 @@ async def _prepare_phase(

async def _verify_phase_configuration(
self, environment: BaseEnvironment, *, cwd: str, verify_explore: bool = True,
verify_yardstick: bool = True,
) -> None:
"""Read the treatment without reconfiguring a restored Goal or its queue."""
key, _, expected = self._replan_configuration()
Expand All @@ -665,7 +666,7 @@ async def _verify_phase_configuration(
raise RuntimeError(
f"stride strategy readback mismatch: expected {self.stride_strategy or 'off'}, got {strategy!r}"
)
if self.execution_yardstick_enabled is not None:
if verify_yardstick and self.execution_yardstick_enabled is not None:
actual_yardstick = configured_state.get("execution_profile", {}).get("yardstick_enabled")
if type(actual_yardstick) is not bool or actual_yardstick != self.execution_yardstick_enabled:
raise RuntimeError("execution_yardstick_enabled readback mismatch")
Expand Down
34 changes: 17 additions & 17 deletions benchmark/runtime/sforge.py
Original file line number Diff line number Diff line change
Expand Up @@ -619,23 +619,20 @@ def format_run_cmd(self, prompt_path, *, model=None, cwd="", internet=True, resu
# The sealed Goal, task graph, review counters and strategy
# are the continuing state. Do not bootstrap, seed another
# task, or reset an existing configuration during restore.
if self.execution_yardstick_enabled is not None:
if self.native_child_limit is not None:
retained = asyncio.run(self.runtime._loopx(
self.environment, ["configure-goal", "--goal-id", self.runtime.goal_id], cwd=self.cwd,
))
self.runtime._verify_native_child_configuration(
retained.get("after") or retained.get("before") or {}
)
asyncio.run(self.runtime._apply_warm_start_yardstick(self.environment, cwd=self.cwd))
asyncio.run(self.runtime._write_task_document(self.environment, result.stdout))
asyncio.run(self.runtime._verify_phase_configuration(self.environment, cwd=self.cwd))
else:
if self.native_child_limit is not None:
asyncio.run(self.runtime._verify_phase_configuration(self.environment, cwd=self.cwd))
asyncio.run(self.runtime._write_task_document(self.environment, result.stdout))
if self.native_child_limit is None:
asyncio.run(self.runtime._verify_phase_configuration(self.environment, cwd=self.cwd))
# Read-only pre-context check preserves registry.json bytes
# until _warm_command("context") verifies the sealed source.
pre_verify_kwargs = (
{} if self.execution_yardstick_enabled is None else {"verify_yardstick": False}
)
if self.native_child_limit is not None:
asyncio.run(self.runtime._verify_phase_configuration(
self.environment, cwd=self.cwd, **pre_verify_kwargs,
))
asyncio.run(self.runtime._write_task_document(self.environment, result.stdout))
if self.native_child_limit is None:
asyncio.run(self.runtime._verify_phase_configuration(
self.environment, cwd=self.cwd, **pre_verify_kwargs,
))
else:
is_explore_cold = self.profile == "heartbeat-explore"
asyncio.run(self.runtime._prepare_phase(
Expand All @@ -655,6 +652,9 @@ def format_run_cmd(self, prompt_path, *, model=None, cwd="", internet=True, resu
asyncio.run(self.runtime._write_task_document(self.environment, result.stdout))
if self.warm_start is not None:
self._warm_command("context")
if self.runtime.execution.uses_loopx and self.execution_yardstick_enabled is not None:
asyncio.run(self.runtime._apply_warm_start_yardstick(self.environment, cwd=self.cwd))
asyncio.run(self.runtime._verify_phase_configuration(self.environment, cwd=self.cwd))
if self.warm_start is not None and not self._config.agent_api_base_url:
auth = Path(os.environ["CODEX_AUTH_JSON_PATH"]).resolve()
asyncio.run(self.environment.upload_file(auth, f"{_CODEX_HOME}/auth.json"))
Expand Down
153 changes: 153 additions & 0 deletions benchmark/tests/test_shared_codex_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -2375,3 +2375,156 @@ async def stale_base_cli(environment, args, **kwargs):
w_stale.format_run_cmd(str(tmp_path / "prompt.md"), model="fixture", cwd=str(stale_dir))
assert not any("--explore-graph-enabled" in call for call in seen_args)
assert not (logs_stale / "explore-activation.json").exists()


@pytest.mark.parametrize("yardstick,native_child_limit", [(False, None), (True, None), (False, 3)])
def test_sforge_warm_start_verifies_sealed_registry_before_yardstick_toggle(
tmp_path, monkeypatch, yardstick, native_child_limit,
):
pytest.importorskip("sforge")
pytest.importorskip("harbor")
import contextlib
import hashlib
import io
from sforge.harness.config import SForgeConfig
from benchmark.runtime.sforge import SForgeWorker
from loopx.cli import main

ws = tmp_path / "ws"
ws.mkdir()
monkeypatch.chdir(ws)
auth_file = tmp_path / "auth.json"
auth_file.write_text("{}", encoding="utf-8")
monkeypatch.setenv("CODEX_AUTH_JSON_PATH", str(auth_file))
monkeypatch.setattr("benchmark.runtime.harbor.BenchmarkCodex.install", lambda self, env: asyncio.sleep(0))

reg = tmp_path / "donor-reg.json"
rt = tmp_path / "donor-rt"

def run_cli_sync(args):
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
code = main(["--format", "json", "--registry", str(reg), "--runtime-root", str(rt), *args])
assert code == 0, buf.getvalue()
return json.loads(buf.getvalue())

extra_child = (
["--spawn-allowed", "--max-children", str(native_child_limit)]
if native_child_limit is not None else []
)
run_cli_sync([
"bootstrap", "--project", str(ws), "--goal-id", "benchmark-goal",
"--objective", "Solve warm start task", "--adapter-kind", "read_only_project_map_v0",
"--adapter-status", "connected-read-only", "--write-scope", "**", "--no-global-sync",
*extra_child,
])
initial_yardstick = "--no-execution-yardstick-enabled" if yardstick else "--execution-yardstick-enabled"
run_cli_sync([
"configure-goal", "--goal-id", "benchmark-goal",
"--registered-agent", "benchmark-agent",
"--agent-work-mode", "benchmark-agent=active",
"--execution-replan-after-turns", "6",
"--execution-planning-horizon-goal",
initial_yardstick,
"--explore-graph-enabled", "--explore-harness-enabled",
"--explore-harness-profile", "adaptive-resilient",
"--execute",
])
sealed_sha256 = hashlib.sha256(reg.read_bytes()).hexdigest()

events = []

class DummyEnv:
async def exec(self, command, **_kw):
if command.startswith("cat "):
return SimpleNamespace(return_code=0, stdout="Solve warm task.\n")
return SimpleNamespace(return_code=1, stdout="")

async def upload_file(self, *a, **kw):
return None

async def cli(environment, args, **kwargs):
if any(flag in args for flag in ("--execution-yardstick-enabled", "--no-execution-yardstick-enabled")):
events.append("apply_yardstick")
return run_cli_sync(args)

async def noop(*a, **kw):
return None

def verify_seal_then_admit(self, action, *, user="agent"):
events.append(f"warm:{action}")
if action == "context":
observed_sha256 = hashlib.sha256(reg.read_bytes()).hexdigest()
if observed_sha256 != sealed_sha256:
raise ValueError("restored LoopX registry differs from its sealed source")

monkeypatch.setattr(SForgeWorker, "_warm_command", verify_seal_then_admit)

warm_stub = SimpleNamespace(
goal_id="benchmark-goal",
agent_id="benchmark-agent",
stage=lambda *a, **kw: asyncio.sleep(0, result=()),
research_sidecar=False,
native_child_limit=native_child_limit,
deadline_epoch=time.time() + 600,
verify=lambda _cwd: None,
source_context_dir=lambda: tmp_path / "src-ctx",
)
(tmp_path / "src-ctx").mkdir(exist_ok=True)

worker = SForgeWorker(
SForgeConfig(agent_model="fixture", agent_effort="xhigh"),
profile="heartbeat-explore",
cwd=str(ws),
task_entry="loopx-planned",
warm_start=warm_stub,
execution_yardstick_enabled=yardstick,
native_child_limit=native_child_limit,
feedback_prompt="Solve warm task" if native_child_limit is not None else None,
workspace_instructions="Solve warm task" if native_child_limit is not None else None,
)
worker.backend = SimpleNamespace(
exec_run=lambda *a, **kw: SimpleNamespace(exit_code=0, output=""),
exec_run_with_exit_code=lambda *a, **kw: SimpleNamespace(timed_out=False, exit_code=0, output=""),
copy_to_container=lambda *a: None,
)
logs = tmp_path / "logs-seal"
logs.mkdir()
worker.install_stop_hook(worker.backend, None, logs, None)
worker.environment = DummyEnv()
worker.runtime.environment = DummyEnv()
monkeypatch.setattr(worker.runtime, "_loopx", cli)
monkeypatch.setattr(worker.runtime, "_write_task_document", noop)
monkeypatch.setattr(worker.runtime, "_registry_exists", lambda *a, **kw: asyncio.sleep(0, result=reg.is_file()))

worker.format_run_cmd(str(tmp_path / "prompt.md"), model="fixture", cwd=str(ws))
assert events.index("warm:context") < events.index("apply_yardstick")
assert hashlib.sha256(reg.read_bytes()).hexdigest() != sealed_sha256
after = run_cli_sync(["configure-goal", "--goal-id", "benchmark-goal"])
assert (after.get("after") or after["before"])["execution_profile"]["yardstick_enabled"] is yardstick

# Pre-context registry mutation must reject in _warm_command("context") before _apply_warm_start_yardstick runs.
events.clear()
worker_bad = SForgeWorker(
SForgeConfig(agent_model="fixture", agent_effort="xhigh"),
profile="heartbeat-explore",
cwd=str(ws),
task_entry="loopx-planned",
warm_start=warm_stub,
execution_yardstick_enabled=not yardstick,
native_child_limit=native_child_limit,
feedback_prompt="Solve warm task" if native_child_limit is not None else None,
workspace_instructions="Solve warm task" if native_child_limit is not None else None,
)
worker_bad.backend = worker.backend
logs_bad = tmp_path / "logs-seal-bad"
logs_bad.mkdir()
worker_bad.install_stop_hook(worker_bad.backend, None, logs_bad, None)
worker_bad.environment = DummyEnv()
worker_bad.runtime.environment = DummyEnv()
monkeypatch.setattr(worker_bad.runtime, "_loopx", cli)
monkeypatch.setattr(worker_bad.runtime, "_write_task_document", noop)
monkeypatch.setattr(worker_bad.runtime, "_registry_exists", lambda *a, **kw: asyncio.sleep(0, result=reg.is_file()))
with pytest.raises(ValueError, match="restored LoopX registry differs from its sealed source"):
worker_bad.format_run_cmd(str(tmp_path / "prompt.md"), model="fixture", cwd=str(ws))
assert "apply_yardstick" not in events
108 changes: 108 additions & 0 deletions tests/control_plane/test_full_loopx_checkpoint_restore.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,111 @@ def test_full_state_cannot_be_substituted_for_research_import(retained_point, ch
c = retained_point
with pytest.raises(ValueError):
replace(c["start"], **change).verify(str(c["workspace"]))


@pytest.mark.parametrize("retained_point", [("file", False), ("sqlite", False)], indirect=True)
def test_pre_verify_yardstick_mutation_fails_restored_seal(retained_point, monkeypatch):
c = retained_point
_empty_receiver(c)
warm.restore_worker(c["declaration"], c["workspace"])
# Mutating registry.json before _warm_command("context") breaks the donor seal.
c["cli"]("configure-goal", "--goal-id", "research", "--execution-yardstick-enabled", "--execute")
with pytest.raises(ValueError, match="restored LoopX registry differs from its sealed source"):
verify_restored_loopx_state(c["env"], c["point"], c["metadata"], deadline=time.time() + 60)
with pytest.raises(ValueError, match="restored LoopX registry differs from its sealed source"):
admit_native_checkpoint_session(
c["env"], c["point"], c["sealed"]["sha256"], c["config"],
sandbox="read-only", timeout=60, restore_loopx_state=True,
)


@pytest.mark.parametrize("retained_point", [("file", False), ("sqlite", False)], indirect=True)
def test_post_verify_yardstick_toggle_preserves_multi_wake_and_warm_readback(retained_point, monkeypatch):
c = retained_point
manifest = json.loads((c["point"] / "checkpoint.json").read_bytes())
full_metadata = json.loads(json.dumps(manifest["point_metadata"]))
full_metadata["native_session"].update({
"completed_turn_id": "turn-source-1",
"turn_ids": ["turn-source-1"],
"visible_history_sha256": "a" * 64,
"host_version": "codex-fixture-1",
})
components = [
{"id": entry["id"], "source_path": str(c["point"] / "components" / entry["id"])}
for entry in manifest["components"]
]
probe = effect_runtime_result("runtime.checkpoint_artifacts", {"action": "probe", "components": components})
full_point = c["tmp_path"] / "point-full"
sealed = effect_runtime_result("runtime.checkpoint_artifacts", {
"action": "capture",
"components": components,
"point_metadata": full_metadata,
"expected_source_sha256": probe["source_sha256"],
"destination": str(full_point),
})
full_decl = {"root": str(full_point), "sha256": sealed["sha256"], "deadline_epoch": c["start"].deadline_epoch}

_empty_receiver(c)
warm.restore_worker(full_decl, c["workspace"])

def fork(*args, **kwargs):
c["home"].mkdir(exist_ok=True)
(c["home"] / "config.toml").write_bytes(c["config"].read_bytes())
return {"session_id": "verified-fork", "model_calls": 0}

def native_check(*args, **kwargs):
return {
"metadata": {
**full_metadata["native_session"],
"config_sha256": hashlib.sha256(c["config"].read_bytes()).hexdigest(),
}
}

monkeypatch.setattr("loopx.hosts.codex_checkpoint.fork_native_checkpoint", fork)
monkeypatch.setattr("loopx.hosts.codex_checkpoint.native_session_checkpoint", native_check)

# 1. Verify sealed donor state + admit verified fork BEFORE any registry override.
verify_restored_loopx_state(c["env"], full_point, full_metadata, deadline=time.time() + 60)
admitted = admit_native_checkpoint_session(
c["env"], full_point, sealed["sha256"], c["config"],
sandbox="read-only", timeout=60, restore_loopx_state=True,
)
assert admitted["session_binding_admitted"] is True
assert admitted["session_id"] == "verified-fork"
expected_goal_ref = dict(c["wake"].goal_ref) if c["wake"].goal_ref is not None else None

# 2. Apply authorized post-verify yardstick overrides (True -> False), modifying registry.json.
c["cli"]("configure-goal", "--goal-id", "research", "--execution-yardstick-enabled", "--execute")
c["cli"]("configure-goal", "--goal-id", "research", "--no-execution-yardstick-enabled", "--execute")
assert hashlib.sha256(c["registry"].read_bytes()).hexdigest() != full_metadata["loopx_state"]["registry_sha256"]
cfg = c["cli"]("configure-goal", "--goal-id", "research")
assert (cfg.get("after") or cfg["before"])["execution_profile"]["yardstick_enabled"] is False

# Direct pre-restore seal verifier still fails on mismatch (never weakened).
with pytest.raises(ValueError, match="restored LoopX registry differs from its sealed source"):
verify_restored_loopx_state(c["env"], full_point, full_metadata, deadline=time.time() + 60)

# 3. Subsequent warm admission readback (fresh_replan / recovery via admit_warm_session)
# and Wake-2 CodexAgentSession(context="resume") both succeed against the bound fork.
declaration = {
"root": str(full_point),
"sha256": sealed["sha256"],
"config": str(c["config"]),
"deadline_epoch": int(time.time()) + 600,
}
readback = warm.admit_warm_session(c["env"], declaration)
assert readback["session_binding_admitted"] is True
assert readback["session_id"] == "verified-fork"

from benchmark.runtime.checkpoint_session_refresh import prepare_session_refresh

warm_json = c["tmp_path"] / "warm-resume.json"
warm_json.write_text(json.dumps({**declaration, "goal_id": "research", "agent_id": "researcher", "fresh_replan": False}))
wake2 = CodexAgentSession(c["env"], context="resume", sandbox="read-only", receipt={})
assert wake2.session_id == "verified-fork"
assert wake2.goal_ref == expected_goal_ref
assert prepare_session_refresh(
{**c["env"], "LOOPX_WARM_START": str(warm_json), "LOOPX_ITERATION_CONTEXT": "resume"},
wake2,
c["tmp_path"],
) == ""
Loading