Skip to content

Commit b4a73d5

Browse files
committed
feat(benchmark): wire opt-in --semantic-unit-fold-json into turn-resume runner (#9571)
* feat(benchmark): wire opt-in --semantic-unit-fold-json into turn-resume runner Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> * fix(benchmark): pin semantic_unit_fold identity across pending Turn retries Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --------- Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 5ac2841 commit b4a73d5

6 files changed

Lines changed: 827 additions & 9 deletions

File tree

‎benchmark/edgebench/run.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ def main(argv=None):
119119
parser.add_argument("--worker", choices=PROFILES, required=True)
120120
parser.add_argument("--validation-command-json", type=json.loads,
121121
help="For turn-resume, trusted guest argv that independently checks the work postcondition")
122+
parser.add_argument("--semantic-unit-fold-json", default=None,
123+
help="For turn-resume, opt-in Todo semantic-unit fold configuration JSON object")
122124
parser.add_argument("--feedback", choices=FEEDBACK_MODES, default="native",
123125
help="New-run default: native public feedback; blind/best-only are explicit controls")
124126
parser.add_argument("--managed-run-json", type=Path,
@@ -207,6 +209,7 @@ def main(argv=None):
207209
args.worker, task_entry=args.task_entry,
208210
context_delivery=args.context_delivery, validation_command=args.validation_command_json,
209211
native_child_limit=args.native_child_limit,
212+
semantic_unit_fold_json=args.semantic_unit_fold_json,
210213
)
211214
except ValueError as error:
212215
parser.error(str(error))
@@ -451,6 +454,7 @@ def main(argv=None):
451454
task_objective=task_objective,
452455
task_entry=args.task_entry,
453456
validation_command=execution.validation_command,
457+
semantic_unit_fold_json=execution.semantic_unit_fold_json,
454458
context_delivery=args.context_delivery,
455459
**({"execution_observation": args.execution_observation}
456460
if args.execution_observation is not None else {}),
@@ -525,6 +529,7 @@ def main(argv=None):
525529
"run_id": args.run_id, "task": args.task, "worker": args.worker,
526530
"task_entry": agent.task_entry,
527531
**execution.validation_receipt(),
532+
**execution.semantic_unit_fold_receipt(),
528533
**({"planning_timeout_seconds": None}
529534
if agent.task_entry == "loopx-planned" else {}),
530535
"model": args.model, "effort": args.effort, "timeout_seconds": args.timeout,

‎benchmark/runtime/codex.py‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,30 @@
1515
# New benchmark runs and the product both default to six settled work Turns.
1616
DEFAULT_REPLAN_AFTER_TURNS = 6
1717
LOOPX_BENCHMARK_CLAIM_TTL_ENV = "LOOPX_BENCHMARK_CLAIM_TTL_SECONDS"
18+
LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV = "LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_JSON"
1819
_MAX_CLAIM_TTL_SECONDS = 86400
1920

2021

22+
def normalize_semantic_unit_fold_json(value: str | None) -> str | None:
23+
"""Validate optional opt-in semantic-unit fold JSON object string."""
24+
if value is None:
25+
return None
26+
if not isinstance(value, str):
27+
raise ValueError("semantic_unit_fold_json must be a JSON object string")
28+
text = value.strip()
29+
if not text:
30+
raise ValueError("semantic_unit_fold_json must be a JSON object string")
31+
try:
32+
parsed = json.loads(text)
33+
except json.JSONDecodeError as exc:
34+
raise ValueError("semantic_unit_fold_json must be valid JSON") from exc
35+
if not isinstance(parsed, dict):
36+
raise ValueError("semantic_unit_fold_json must be a JSON object")
37+
if "enabled" in parsed and type(parsed["enabled"]) is not bool:
38+
raise ValueError("semantic_unit_fold_json 'enabled' must be a boolean")
39+
return text
40+
41+
2142
def normalize_claim_ttl_seconds(value: int | None) -> int | None:
2243
"""Validate optional benchmark Todo claim TTL in 1..86400 seconds."""
2344
if value is None:
@@ -151,6 +172,7 @@ class Execution:
151172
complete_turn: bool = False
152173
official_stop_hook: bool = False
153174
official_stop_hook_mode: str | None = None
175+
semantic_unit_fold_json: str | None = None
154176

155177
def __post_init__(self) -> None:
156178
if self.native_child_limit is not None and (
@@ -204,13 +226,26 @@ def __post_init__(self) -> None:
204226
raise ValueError("mode=turn requires an independent validation_command")
205227
if self.mode != "turn" and self.validation_command:
206228
raise ValueError("validation_command is only used by mode=turn")
229+
normalized_fold = normalize_semantic_unit_fold_json(self.semantic_unit_fold_json)
230+
object.__setattr__(self, "semantic_unit_fold_json", normalized_fold)
231+
if normalized_fold is not None and self.mode != "turn":
232+
raise ValueError("semantic_unit_fold_json requires mode=turn")
207233

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

240+
def semantic_unit_fold_receipt(self) -> dict[str, str]:
241+
if self.semantic_unit_fold_json is None:
242+
return {}
243+
return {
244+
"semantic_unit_fold_sha256": hashlib.sha256(
245+
self.semantic_unit_fold_json.encode("utf-8")
246+
).hexdigest(),
247+
}
248+
214249
@property
215250
def uses_loopx(self) -> bool:
216251
return self.mode in {"heartbeat", "turn", "loopx-goal"}
@@ -456,9 +491,17 @@ def _prepend_existing_runtime_dirs(env: dict[str, str]) -> None:
456491

457492

458493
def process_environment(
459-
home: Path, *, base: Mapping[str, str] | None = None
494+
home: Path,
495+
*,
496+
base: Mapping[str, str] | None = None,
497+
semantic_unit_fold_json: str | None = None,
460498
) -> dict[str, str]:
461499
env = dict(os.environ if base is None else base)
462500
env["CODEX_HOME"] = str(home)
501+
normalized_fold = normalize_semantic_unit_fold_json(semantic_unit_fold_json)
502+
if normalized_fold is not None:
503+
env[LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV] = normalized_fold
504+
else:
505+
env.pop(LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV, None)
463506
_prepend_existing_runtime_dirs(env)
464507
return env

‎benchmark/runtime/harbor.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
DEFAULT_REPLAN_AFTER_TURNS,
2626
Execution,
2727
aggregate_control_telemetry,
28+
LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV,
2829
normalize_claim_ttl_seconds,
2930
)
3031
from .layout import _ROOT, _SRC, _CONTROL, _CODEX_HOME, _REGISTRY, _LOOPX_RUNTIME
@@ -91,6 +92,7 @@ def __init__(
9192
official_stop_hook=False,
9293
official_stop_hook_mode=None,
9394
claim_ttl_seconds=None,
95+
semantic_unit_fold_json=None,
9496
**kwargs,
9597
):
9698
if "research_loop" in kwargs:
@@ -119,6 +121,7 @@ def __init__(
119121
complete_turn=complete_turn,
120122
official_stop_hook=official_stop_hook,
121123
official_stop_hook_mode=official_stop_hook_mode,
124+
semantic_unit_fold_json=semantic_unit_fold_json,
122125
)
123126
if type(provider_request_admission) is not bool:
124127
raise ValueError("provider_request_admission must be a boolean opt-in")
@@ -350,6 +353,18 @@ async def install(self, environment: BaseEnvironment) -> None:
350353
await stage_portable_python(environment, _PYTHON)
351354
if self.execution.uses_loopx:
352355
await environment.upload_dir(node_root, _NODE)
356+
owner = shlex.quote(str(environment.default_user or "root"))
357+
owned_dirs = " ".join(
358+
path
359+
for path in (
360+
_SRC,
361+
_LOOPX_RUNTIME,
362+
_CONTROL,
363+
_PROFILE,
364+
None if self.defer_codex_home else _CODEX_HOME,
365+
)
366+
if path
367+
)
353368
await self.exec_as_root(
354369
environment,
355370
command=(
@@ -359,7 +374,9 @@ async def install(self, environment: BaseEnvironment) -> None:
359374
f"-name '*.dist-info' \\) -exec rm -rf {{}} +; "
360375
# The formal source installer builds generated frontend assets
361376
# as the environment user; the archive is extracted by root.
362-
f"chown -R {shlex.quote(str(environment.default_user or 'root'))} {_SRC}; "
377+
# Runtime, control, profile, and Codex home dirs must also stay
378+
# owned by the environment user so atomic 0o700 writes succeed.
379+
f"chown -R {owner} {owned_dirs}; "
363380
f"chmod -R a+rX {_SRC} {_PYTHON} {_NODE}; "
364381
f"chmod -R a+rwX {_PROFILE} {_CONTROL} {'' if self.defer_codex_home else _CODEX_HOME} {_WAKE_LOG_DIR}"
365382
),
@@ -683,6 +700,8 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]:
683700
env = self._profile_env()
684701
if not self.execution.uses_loopx:
685702
env["PATH"] = self._task_path
703+
if self.execution.semantic_unit_fold_json is None:
704+
env.pop(LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV, None)
686705
env.update(
687706
{
688707
"PYTHONPATH": _SRC,
@@ -721,6 +740,8 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]:
721740
if self.execution.timeout_seconds is not None else {}),
722741
**({"LOOPX_BENCHMARK_CLAIM_TTL_SECONDS": str(self.claim_ttl_seconds)}
723742
if self.claim_ttl_seconds is not None else {}),
743+
**({LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV: self.execution.semantic_unit_fold_json}
744+
if self.execution.semantic_unit_fold_json is not None else {}),
724745
"CODEX_BIN": "/usr/local/bin/codex",
725746
"MODEL_NAME": (self.model_name or "").split("/", 1)[-1],
726747
"REASONING_EFFORT": str(

‎benchmark/runtime/sforge.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,16 @@
5454

5555
def profile_execution(profile, *, task_entry=None, context_delivery=None,
5656
turn_envelope=False, complete_turn=False,
57-
validation_command=None, native_child_limit=None):
57+
validation_command=None, native_child_limit=None,
58+
semantic_unit_fold_json=None):
5859
"""Resolve the native experiment arm through the shared runtime contract."""
5960
if profile not in PROFILE_MODES:
6061
raise ValueError("Unknown benchmark worker profile")
6162
return Execution(
6263
mode=PROFILE_MODES[profile], task_entry=task_entry, context_delivery=context_delivery,
6364
turn_envelope=turn_envelope, complete_turn=complete_turn, native_child_limit=native_child_limit,
6465
validation_command=() if validation_command is None else validation_command,
66+
semantic_unit_fold_json=semantic_unit_fold_json,
6567
)
6668

6769

@@ -148,14 +150,16 @@ def __init__(self, config, *, profile: str, cwd: str,
148150
checkpoint_request: bytes | None = None,
149151
warm_start=None, research_sidecar: bool = False,
150152
native_result_scope: dict | None = None, complete_turn: bool = False,
151-
claim_ttl_seconds: int | None = None):
153+
claim_ttl_seconds: int | None = None,
154+
semantic_unit_fold_json: str | None = None):
152155
super().__init__(config)
153156
self.claim_ttl_seconds = normalize_claim_ttl_seconds(claim_ttl_seconds)
154157
self.execution = profile_execution(
155158
profile, task_entry=task_entry,
156159
context_delivery=context_delivery, turn_envelope=turn_envelope,
157160
complete_turn=complete_turn, validation_command=validation_command,
158161
native_child_limit=native_child_limit,
162+
semantic_unit_fold_json=semantic_unit_fold_json,
159163
)
160164
self.context_delivery = self.execution.context_delivery
161165
self.task_entry = self.execution.task_entry
@@ -452,6 +456,8 @@ def _install_worker(self, backend, handle, log_dir, logger):
452456
"defer_codex_home": True} if self.warm_start is not None else {}),
453457
**({"claim_ttl_seconds": self.claim_ttl_seconds}
454458
if self.claim_ttl_seconds is not None else {}),
459+
**({"semantic_unit_fold_json": self.execution.semantic_unit_fold_json}
460+
if self.execution.semantic_unit_fold_json is not None else {}),
455461
)
456462
asyncio.run(self.runtime.install(self.environment))
457463
if self.feedback == "native" and (self.execution_observation is not None
@@ -534,6 +540,7 @@ def _install_worker(self, backend, handle, log_dir, logger):
534540
(log_dir / "worker-profile.json").write_text(json.dumps({
535541
"profile": self.profile, "model": self._config.agent_model,
536542
**self.execution.validation_receipt(),
543+
**self.execution.semantic_unit_fold_receipt(),
537544
"task_entry": self.task_entry,
538545
"reasoning_effort": effort, "timeout_seconds": self.timeout_seconds,
539546
"loopx_usage_ping_enabled": False,

‎benchmark/runtime/worker.py‎

Lines changed: 64 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from __future__ import annotations
55

6+
import hashlib
67
import json
78
import math
89
import os
@@ -19,7 +20,9 @@
1920

2021
from benchmark.runtime.codex import (
2122
Execution,
23+
LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV,
2224
claim_ttl_seconds_from_env,
25+
normalize_semantic_unit_fold_json,
2326
reject_retired_turn_display,
2427
prepare_codex_home,
2528
process_environment,
@@ -313,18 +316,50 @@ def interrupt_checkpoint_process(process, *, timeout: float = 10) -> int:
313316
_reap_child_process(process)
314317

315318

316-
def pending_turn(path: Path, turn_id: str, execution: Execution) -> dict:
319+
def _resolved_semantic_unit_fold(
320+
execution: Execution,
321+
env: Mapping[str, str] | None = None,
322+
) -> tuple[str | None, str | None]:
323+
raw_fold = execution.semantic_unit_fold_json
324+
if raw_fold is None and env is not None:
325+
raw_fold = env.get(LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV) or None
326+
fold_json = normalize_semantic_unit_fold_json(raw_fold)
327+
if fold_json is not None and execution.mode != "turn":
328+
raise ValueError("semantic_unit_fold_json requires mode=turn")
329+
fold_sha256 = (
330+
hashlib.sha256(fold_json.encode("utf-8")).hexdigest()
331+
if fold_json is not None
332+
else None
333+
)
334+
return fold_json, fold_sha256
335+
336+
337+
def pending_turn(
338+
path: Path,
339+
turn_id: str,
340+
execution: Execution,
341+
env: Mapping[str, str] | None = None,
342+
) -> dict:
317343
"""The caller holds the trial lock until the product returns or the wake exits."""
318344
from loopx.control_plane.runtime.document_io import atomic_write_private_json
319345

320346
validator = execution.validation_receipt()
347+
fold_json, fold_sha256 = _resolved_semantic_unit_fold(execution, env)
321348
if not path.exists():
322-
pending = {"turn_instance_id": turn_id, **validator}
349+
pending = {
350+
"turn_instance_id": turn_id,
351+
**validator,
352+
"semantic_unit_fold_sha256": fold_sha256,
353+
**({"semantic_unit_fold_json": fold_json} if fold_json is not None else {}),
354+
}
323355
atomic_write_private_json(path, pending)
324356
return pending
325357
pending = read_json(path.read_text())
326358
if pending.get("validation_argv_sha256") != validator["validation_argv_sha256"]:
327359
raise ValueError("Pending Turn requires its original validation command")
360+
# Historical pending records without semantic_unit_fold_sha256 default to omitted (None).
361+
if pending.get("semantic_unit_fold_sha256") != fold_sha256:
362+
raise ValueError("Pending Turn requires its original semantic_unit_fold configuration")
328363
return pending
329364

330365

@@ -340,6 +375,7 @@ def turn_command(
340375
address = ["--resume-turn-key", resume_turn_key, "--retry-failed-turn"]
341376
elif recover_instance:
342377
address = ["--resume-turn-instance-id", turn_id, "--retry-failed-turn"]
378+
fold_json, _ = _resolved_semantic_unit_fold(execution, env)
343379
return loopx_command(env) + [
344380
"turn",
345381
"run-once",
@@ -372,6 +408,7 @@ def turn_command(
372408
if execution.timeout_seconds is not None else []),
373409
"--validation-command-json",
374410
json.dumps(execution.validation_command),
411+
*(["--semantic-unit-fold-json", fold_json] if fold_json is not None else []),
375412
"--available-capability",
376413
"shell",
377414
"--available-capability",
@@ -601,6 +638,7 @@ def run_once(env: dict[str, str]) -> dict:
601638
if env.get("LOOPX_NATIVE_CHILD_LIMIT") else None),
602639
official_stop_hook=stop_hook == "1",
603640
official_stop_hook_mode=stop_hook_mode,
641+
semantic_unit_fold_json=(env.get(LOOPX_BENCHMARK_SEMANTIC_UNIT_FOLD_ENV) or None),
604642
)
605643
request_admission = False
606644
if env.get("LOOPX_PROVIDER_REQUEST_ADMISSION", "off") != "off":
@@ -621,7 +659,11 @@ def run_once(env: dict[str, str]) -> dict:
621659
wake.mkdir(parents=True, exist_ok=False)
622660
stdout_path, stderr_path = host_output_paths(wake)
623661
home = Path(env["LOOPX_CODEX_HOME"])
624-
env = process_environment(home, base=env)
662+
env = process_environment(
663+
home,
664+
base=env,
665+
semantic_unit_fold_json=execution.semantic_unit_fold_json,
666+
)
625667
if env.get("LOOPX_RUNTIME_ROOT"):
626668
env["LOOPX_RUNTIME_ROOT"] = _normalize_runtime_root(
627669
env["LOOPX_RUNTIME_ROOT"], env["LOOPX_PROJECT"]
@@ -646,6 +688,7 @@ def run_once(env: dict[str, str]) -> dict:
646688
"turn_id": turn_id,
647689
"mode": execution.mode,
648690
**execution.validation_receipt(),
691+
**execution.semantic_unit_fold_receipt(),
649692
"context": execution.context,
650693
"task_entry": execution.task_entry,
651694
**({"execution_observation": observation_producer}
@@ -836,7 +879,7 @@ def run_once(env: dict[str, str]) -> dict:
836879
lock = wake_context.enter_context(try_exclusive_file_lock(pending_path))
837880
if lock is None:
838881
raise RuntimeError("Another benchmark wake owns the pending Turn")
839-
pending = pending_turn(pending_path, turn_id, execution)
882+
pending = pending_turn(pending_path, turn_id, execution, env=env)
840883
receipt["turn_instance_id"] = pending["turn_instance_id"]
841884
command = (
842885
turn_command(
@@ -908,7 +951,23 @@ def run_once(env: dict[str, str]) -> dict:
908951
temporary.write_text(json.dumps(receipt["planning"]))
909952
temporary.replace(target)
910953
elif execution.mode == "turn" and stage == "execute":
911-
result = read_json(stdout_path.read_text())
954+
raw_stdout = stdout_path.read_text(encoding="utf-8", errors="replace")
955+
try:
956+
result = read_json(raw_stdout)
957+
except (ValueError, json.JSONDecodeError) as exc:
958+
stderr_tail = (
959+
" ".join(
960+
stderr_path.read_text(encoding="utf-8", errors="replace").split()
961+
)[-300:]
962+
if stderr_path.is_file()
963+
else ""
964+
)
965+
stdout_tail = " ".join(raw_stdout.split())[-200:]
966+
raise RuntimeError(
967+
"Turn CLI returned non-JSON output "
968+
f"(returncode={receipt.get('return_code')}, "
969+
f"stdout={stdout_tail!r}, stderr={stderr_tail!r})"
970+
) from exc
912971
receipt["turn_execution"] = result
913972
receipt["ok"] = receipt["ok"] and result.get("ok") is True
914973
if receipt["ok"]:

0 commit comments

Comments
 (0)