33
44from __future__ import annotations
55
6+ import hashlib
67import json
78import math
89import os
1920
2021from 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