Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
test(benchmarks): add bounded interleaved baseline pilot
svonavae90614482952
diff --git a/tools/benchmarks/cross_encoder_lora/README.md b/tools/benchmarks/cross_encoder_lora/README.mdindex e2ae7b911..dac2ebff3 100644--- a/tools/benchmarks/cross_encoder_lora/README.md+++ b/tools/benchmarks/cross_encoder_lora/README.md@@ -272,6 +272,69 @@ server boundary snapshots. Keep those files in the full durable archive.## Evidence and CPU checks+### Whole-phase triplet feasibility mode++The separate `interleaved` entry point holds three fresh server/SDK pairs resident+for one triplet. It prepares every pair before timing, then runs C1 for all three+roles, C4 for all three, and C16 for all three, using the six existing balanced+role orders. Each arm keeps its contiguous 2,000-request C1 phase, 60-second+C4/C16 admission windows, 30 warmups, drain, and original numerical, memory and+12 statistical limits. The sequential `runner` entry point remains available.++The `baseline-pilot` mode maps **every** logical B/N/R role to the same archived+baseline source and actual B configuration, with no adapter declarations. It+retains the peer numerical and memory checks. Its schema-3 summary reports+`completed_valid` separately from `qualification_passed`, which is always false+for this descriptive mode. A successful diagnostic exit does not qualify a+candidate or authorize a subsequent run. The separately selected `qualification`+mode requires the original B/N/R configurations and source mapping; it cannot+silently substitute baseline-only R. Pilot and candidate observations must not+be pooled or appended until a gate passes.++From a clean frozen checkout, after the ordinary immutable source and fixture+preparation above, the prospective baseline-only invocation is:++```console+mise exec -- uv run --no-sync python -m tools.benchmarks.cross_encoder_lora.interleaved \+ --inputs /tmp/ce-inputs --fixtures /tmp/ce-fixtures --output /tmp/ce-baseline-pilot \+ --mode baseline-pilot --deadline-s 3900 --group-work-s 600+```++These are bounds, not a promise that six groups fit. Strict group admission+reserves 600 seconds of work plus one shared 90-second cleanup interval. Each+worker also has a cumulative 270-second grant-to-ACK active budget, with a+120-second cap for each phase; explicit idle waits consume the group budget.+The smaller group cap can stop work before three full active budgets are spent.+The enclosing prospective operator keeps its 300-second archive reserve within+4,500 seconds, provider lifetime at most 4,800 seconds, and outer bound 5,100+seconds. This entry point does not allocate resources or extend those bounds.++A dedicated socket carries immutable mode, role, actual configuration, source,+group deadline and lease identities; stdout/stderr remain ordinary logs. One+lease covers warmup, measurement, complete drain, atomic phase persistence and+an outside-timer CUDA synchronization with no pending/in-flight model requests.+Inactive workers wait on events, without a benchmark polling loop. All nine+phase ACKs precede any finish grant, coordinator/server result materialization, lifecycle+churn, unload or archive work. Pre-existing server housekeeping and three idle+CUDA contexts remain part of this changed resource condition; single-active+inference does not establish their neutrality.++The coordinator owns each server process group; its SDK child inherits that+group. The dedicated EOF monitor starts before heavy server imports, explicitly+cancels the experiment even under uvicorn's signal handler, and has a bounded+group-kill fallback. Group mode also watches unexpected idle SDK exit. Shared+cleanup signals every owned group before waiting and joins teardown through+repeated cancellation. A hard kill may prevent the interrupted phase from+being finalized; prior atomic files remain evidence, not a reconstructed pass.++This prospective method follows the failed complete `4eb6a0da` sequential+experiment. A separately retained CPU mechanics experiment verified scheduling,+cleanup and sensitivity to an injected arm delay, but only 6/12 baseline gates+passed under either schedule and 0/12 passed with the planted common drift.+Those controls do not demonstrate improved precision, explain the earlier+hardware result, or qualify L4 performance. Six triplets remain the statistical+units; shared-device observations are not independent hardware replications.+`summary.json` schema 2 retains trial outcomes, aggregate metrics, statisticalgates and source hashes. Each entry links its complete `trial.json` by relativepath and SHA-256; raw request arrays and oracle corpora stay in those per-trialdiff --git a/tools/benchmarks/cross_encoder_lora/group_control.py b/tools/benchmarks/cross_encoder_lora/group_control.pynew file mode 100644index 000000000..d598e8f10--- /dev/null+++ b/tools/benchmarks/cross_encoder_lora/group_control.py@@ -0,0 +1,252 @@+"""Dedicated group control and parent-death ownership, outside request timing."""++from __future__ import annotations++import argparse+import asyncio+import json+import math+import os+import queue+import select+import signal+import socket+import sys+import threading+import time+from pathlib import Path+from typing import Any++from tools.benchmarks.cross_encoder_lora.evidence import atomic_json, digest, fingerprint+from tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISION, MAX_TRIAL_SECONDS, ORDERS, require++LIMIT = 65_536+GROUP_WORK_S = 600+GROUP_CLEANUP_S = 90+PHASE_LIMIT_S = 120+RUNNER_LIMIT_S = 3900+STAGES = ("prepare", "C1", "C4", "C16", "finish")+MODES = ("baseline-pilot", "qualification")+NONCE_LENGTH = 32+++def selection(mode: str, role: str) -> tuple[str, str]:+ require(mode in MODES and role in "BNR" and len(role) == 1, "invalid group mode/role")+ return ("B", "B") if mode == "baseline-pilot" or role == "B" else (role, "candidate")+++def validate_binding(binding: dict[str, Any]) -> None:+ require(binding["schema"] == 1 and binding["schedule"] == "whole-phase", "invalid group binding schema")+ arm, archive = selection(binding["mode"], binding["logical_role"])+ require((binding["actual_arm"], binding["source_key"]) == (arm, archive), "role/config/source mismatch")+ require(type(binding["pair"]) is int and 0 <= binding["pair"] < len(ORDERS), "invalid group pair")+ require(isinstance(binding["nonce"], str) and len(binding["nonce"]) == NONCE_LENGTH, "invalid group nonce")+ require(type(binding["coordinator_pid"]) is int and binding["coordinator_pid"] > 0, "invalid coordinator PID")+ for name in ("work_deadline", "hard_deadline", "group_started"):+ require(type(binding[name]) in (float, int) and math.isfinite(binding[name]), "invalid group deadline")+ require(+ 0 < binding["work_deadline"] - binding["group_started"] <= GROUP_WORK_S+ and 0 < binding["hard_deadline"] - binding["work_deadline"] <= GROUP_CLEANUP_S,+ "group deadlines exceed fixed bounds",+ )+ require(binding["active_limit_s"] == MAX_TRIAL_SECONDS, "active budget differs")+ require(binding["phase_limit_s"] == PHASE_LIMIT_S, "phase budget differs")+ if archive == "B":+ require(binding["source_commit"] == BASE_REVISION, "baseline commit differs")+++def validate_source(binding: dict[str, Any], source: Path, arm: str, pair: int) -> None:+ """Called under the prepare lease, before preflight/model initialization."""+ validate_binding(binding)+ require(binding["actual_arm"] == arm and binding["pair"] == pair, "worker arguments differ from binding")+ require(str(source.resolve()) == binding["source_root"], "worker source path differs")+ manifest_path = Path(binding["source_manifest"])+ require(digest(manifest_path) == binding["source_manifest_sha256"], "source manifest changed")+ manifest = json.loads(manifest_path.read_text())+ require(manifest["schema"] == 1 and manifest["dependency_lock_identical"], "source manifest mode differs")+ record = manifest["sources"][binding["source_key"]]+ require(record["commit"] == binding["source_commit"], "source commit differs")+ require(record["sha256"] == binding["archive_sha256"], "source archive binding differs")+ archive = manifest_path.parent / record["archive"]+ require(archive.resolve().is_relative_to(manifest_path.parent.resolve()), "source archive escapes inputs")+ require(digest(archive) == record["sha256"], "source archive changed")+ for name, expected in binding["source_files"].items():+ path = source / name+ require(path.resolve().is_relative_to(source.resolve()) and digest(path) == expected, "source file changed")+++def envelope(binding: dict[str, Any], **fields: Any) -> dict[str, Any]:+ return {"binding_sha256": fingerprint(binding), **fields}+++def decode(line: bytes, binding: dict[str, Any]) -> dict[str, Any]:+ require(bool(line) and len(line) <= LIMIT and line.endswith(b"\n"), "missing/oversized group message")+ value = json.loads(line)+ require(isinstance(value, dict) and value.get("binding_sha256") == fingerprint(binding), "group identity differs")+ return value+++class Member:+ """One raw-fd monitor exists before heavy worker imports or uvicorn handlers.++ Its only writer is the coordinator. EOF cancels the asyncio experiment;+ if teardown or import is stuck, one hard deadline kills this worker's own+ process group (including its SDK child). No model work occurs in this thread.+ """++ def __init__(self, fd: int, binding: dict[str, Any], output: Path) -> None:+ validate_binding(binding)+ require(os.getpgrp() == os.getpid(), "group worker must own its process group")+ require(os.getppid() == binding["coordinator_pid"], "coordinator lineage differs")+ self.binding, self.output = binding, output+ self.socket = socket.socket(fileno=fd)+ self.socket.set_inheritable(False)+ self.socket.settimeout(5)+ self.messages: queue.Queue[dict[str, Any]] = queue.Queue(maxsize=2)+ self.stopped = threading.Event()+ self.wake_read, self.wake_write = os.pipe()+ self.available: asyncio.Event | None = None+ self.failure: str | None = None+ self.loop: asyncio.AbstractEventLoop | None = None+ self.owner: asyncio.Task | None = None+ self.index = 0+ self.current: dict[str, Any] | None = None+ self.history: list[dict[str, Any]] = []+ self.reader = threading.Thread(target=self._monitor, name="group-coordinator", daemon=True)+ self.reader.start()+ self.send(event="hello", pid=os.getpid(), ppid=os.getppid(), process_group=os.getpgrp())++ def _fail(self, reason: str) -> None:+ self.failure = reason+ if self.loop is not None and self.owner is not None:+ try:+ self.loop.call_soon_threadsafe(self.owner.cancel, reason)+ except RuntimeError:+ # A loop that already closed must not disable the raw-fd+ # monitor's independent hard group kill.+ pass++ def _monitor(self) -> None:+ pending = bytearray()+ deadline = self.binding["hard_deadline"]+ try:+ while not self.stopped.is_set():+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ break+ ready, _, _ = select.select([self.socket, self.wake_read], [], [], remaining)+ if self.wake_read in ready:+ return+ if not ready:+ continue+ data = self.socket.recv(4096)+ require(bool(data), "coordinator EOF")+ pending.extend(data)+ while b"\n" in pending:+ end = pending.index(b"\n") + 1+ line = bytes(pending[:end])+ del pending[:end]+ self.messages.put_nowait(decode(line, self.binding))+ if self.loop is not None and self.available is not None:+ self.loop.call_soon_threadsafe(self.available.set)+ require(len(pending) <= LIMIT, "unterminated group message")+ except BaseException as error: # noqa: BLE001 -- losing lifetime monitoring must fail closed+ if not self.stopped.is_set():+ self._fail(f"{type(error).__name__}: {error}")+ deadline = min(deadline, time.monotonic() + GROUP_CLEANUP_S)+ if not self.stopped.is_set():+ self._fail(self.failure or "group hard deadline")+ if not self.stopped.wait(max(0, deadline - time.monotonic())):+ os.killpg(os.getpid(), signal.SIGKILL)++ def bind_task(self) -> None:+ self.loop = asyncio.get_running_loop()+ self.owner = asyncio.current_task()+ self.available = asyncio.Event()+ if not self.messages.empty():+ self.available.set()+ require(self.failure is None, self.failure or "coordinator lost during imports")++ def send(self, **fields: Any) -> None:+ line = (json.dumps(envelope(self.binding, **fields), allow_nan=False) + "\n").encode()+ require(len(line) <= LIMIT, "group output too large")+ self.socket.sendall(line)++ async def grant(self, stage: str) -> None:+ require(+ self.current is None and self.index < len(STAGES) and stage == STAGES[self.index], "group stage reordered"+ )+ assert self.available is not None+ while self.messages.empty():+ require(self.failure is None, self.failure or "group monitor failed")+ remaining = self.binding["work_deadline"] - time.monotonic()+ require(remaining > 0, "group idle deadline")+ self.available.clear()+ if self.messages.empty():+ await asyncio.wait_for(self.available.wait(), remaining)+ value = self.messages.get_nowait()+ require(value.get("command") == "grant" and value.get("stage") == stage, "unexpected group grant")+ require(value.get("ordinal") == self.index, "stale group grant")+ require(isinstance(value.get("lease"), str) and len(value["lease"]) == NONCE_LENGTH, "invalid group lease")+ require(time.monotonic() < self.binding["work_deadline"], "group work deadline")+ self.current = value++ def acknowledge(self, **fields: Any) -> None:+ require(self.current is not None, "group ACK without active lease")+ assert self.current is not None+ event = {+ "event": "ack",+ "stage": self.current["stage"],+ "ordinal": self.index,+ "lease": self.current["lease"],+ "monotonic_s": time.monotonic(),+ **fields,+ }+ self.history.append(event)+ atomic_json(self.output / "group-control.json", {"binding": self.binding, "events": self.history})+ self.send(**event)+ self.current = None+ self.index += 1++ def close(self) -> None:+ self.stopped.set()+ os.write(self.wake_write, b"x")+ self.reader.join(timeout=2)+ require(not self.reader.is_alive(), "group lifetime monitor did not stop")+ self.socket.close()+ os.close(self.wake_read)+ os.close(self.wake_write)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--binding", type=Path, required=True)+ parser.add_argument("--control-fd", type=int, required=True)+ own, remainder = parser.parse_known_args()+ binding = json.loads(own.binding.read_text())+ member = Member(own.control_fd, binding, Path(binding["output"]))+ try:+ # Optional serving dependencies are imported only after the lifetime+ # monitor is live. Ordinary worker.py invocations do not use this path.+ from tools.benchmarks.cross_encoder_lora import worker # noqa: PLC0415++ args = worker.arguments(remainder)+ args.group = member++ async def launch() -> None:+ member.bind_task()+ await worker.run(args)++ asyncio.run(launch())+ finally:+ primary = sys.exception()+ try:+ member.close()+ except BaseException as error:+ if primary is None:+ raise+ primary.add_note(f"Group monitor close failed: {type(error).__name__}: {error}")+++if __name__ == "__main__":+ main()diff --git a/tools/benchmarks/cross_encoder_lora/interleaved.py b/tools/benchmarks/cross_encoder_lora/interleaved.pynew file mode 100644index 000000000..422726b32--- /dev/null+++ b/tools/benchmarks/cross_encoder_lora/interleaved.py@@ -0,0 +1,560 @@+"""Six fresh resident triplets, one whole-phase lease at a time; no provisioning."""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import signal+import socket+import sys+import time+import uuid+from pathlib import Path+from types import FunctionType+from typing import Any++from tools.benchmarks.cross_encoder_lora.evidence import atomic_json, digest+from tools.benchmarks.cross_encoder_lora.group_control import (+ GROUP_CLEANUP_S,+ GROUP_WORK_S,+ LIMIT,+ MODES,+ PHASE_LIMIT_S,+ RUNNER_LIMIT_S,+ STAGES,+ decode,+ envelope,+ selection,+ validate_binding,+)+from tools.benchmarks.cross_encoder_lora.protocol import MAX_TRIAL_SECONDS, ORDERS, compare, require+from tools.benchmarks.cross_encoder_lora.runner import (+ cross_checks,+ extract,+ harness_manifest,+ load_trial,+ source_environment,+ trial_summary,+)+++def admission(now: float, deadline: float, work_s: float = GROUP_WORK_S) -> dict[str, Any]:+ require(0 < work_s <= GROUP_WORK_S, "group work cap differs")+ margin = deadline - (now + work_s + GROUP_CLEANUP_S)+ return {+ "monotonic_s": now,+ "deadline_monotonic_s": deadline,+ "reserve_s": work_s + GROUP_CLEANUP_S,+ "margin_s": margin,+ "admitted": margin > 0,+ }+++def binding_for(+ args: argparse.Namespace,+ manifest: dict[str, Any],+ pair: int,+ role: str,+ nonce: str,+ started: float,+) -> dict[str, Any]:+ arm, source_key = selection(args.mode, role)+ source = (args.output / "sources" / source_key).resolve()+ record = manifest["sources"][source_key]+ value = {+ "schema": 1,+ "schedule": "whole-phase",+ "mode": args.mode,+ "pair": pair,+ "logical_role": role,+ "actual_arm": arm,+ "source_key": source_key,+ "source_commit": record["commit"],+ "archive_sha256": record["sha256"],+ "source_root": str(source),+ "source_manifest": str((args.inputs / "manifest.json").resolve()),+ "source_manifest_sha256": digest(args.inputs / "manifest.json"),+ "source_files": {+ str(path.relative_to(source)): digest(path)+ for path in sorted(source.rglob("*"))+ if path.is_file() and "__pycache__" not in path.parts and path.suffix != ".pyc"+ },+ "nonce": nonce,+ "coordinator_pid": os.getpid(),+ "group_started": started,+ "work_deadline": started + args.group_work_s,+ "hard_deadline": started + args.group_work_s + GROUP_CLEANUP_S,+ "active_limit_s": MAX_TRIAL_SECONDS,+ "phase_limit_s": PHASE_LIMIT_S,+ "output": str((args.output / f"trial-{pair}-{role}").resolve()),+ }+ validate_binding(value)+ return value+++class Peer:+ def __init__(self, binding: dict[str, Any], log: Any) -> None:+ self.binding, self.log = binding, log+ self.process: asyncio.subprocess.Process | None = None+ self.reader: asyncio.StreamReader | None = None+ self.writer: asyncio.StreamWriter | None = None+ self.active_s = 0.0+ self.ordinal = 0+ self.events: list[dict[str, Any]] = []+ self.hello: dict[str, Any] | None = None+ self.finishing = False+ self.stopping = False++ async def start(self, args: argparse.Namespace, binding_path: Path) -> None:+ parent, child = socket.socketpair()+ try:+ command = [+ sys.executable,+ "-m",+ "tools.benchmarks.cross_encoder_lora.group_control",+ "--binding",+ str(binding_path),+ "--control-fd",+ str(child.fileno()),+ "--source",+ self.binding["source_root"],+ "--fixtures",+ str(args.fixtures.resolve()),+ "--output",+ self.binding["output"],+ "--arm",+ self.binding["actual_arm"],+ "--pair",+ str(self.binding["pair"]),+ ]+ if args.snapshot:+ command.extend(["--snapshot", str(args.snapshot.resolve())])+ if args.smoke:+ command.append("--smoke")+ self.process = await asyncio.create_subprocess_exec(+ *command,+ cwd=self.binding["source_root"],+ env=source_environment(Path(self.binding["source_root"])),+ stdout=self.log,+ stderr=asyncio.subprocess.STDOUT,+ pass_fds=(child.fileno(),),+ close_fds=True,+ start_new_session=True,+ )+ self.reader, self.writer = await asyncio.open_connection(sock=parent, limit=LIMIT)+ except BaseException:+ parent.close()+ raise+ finally:+ child.close()++ async def read(self, deadline: float) -> dict[str, Any]:+ assert self.reader is not None+ remaining = deadline - time.monotonic()+ require(remaining > 0, "group control deadline")+ line = await asyncio.wait_for(self.reader.readline(), remaining)+ return decode(line, self.binding)++ async def receive_hello(self) -> None:+ value = await self.read(self.binding["work_deadline"])+ assert self.process is not None+ require(+ value.get("event") == "hello"+ and value.get("pid") == self.process.pid+ and value.get("ppid") == os.getpid()+ and value.get("process_group") == self.process.pid,+ "worker hello ownership differs",+ )+ self.hello = value++ async def lease(self, stage: str) -> dict[str, Any]:+ require(self.ordinal < len(STAGES) and stage == STAGES[self.ordinal], "coordinator stage reordered")+ assert self.writer is not None+ lease = uuid.uuid4().hex+ started = time.monotonic()+ remaining = MAX_TRIAL_SECONDS - self.active_s+ limit = min(remaining, PHASE_LIMIT_S) if stage.startswith("C") else remaining+ deadline = min(self.binding["work_deadline"], started + limit)+ require(deadline > started, "worker cumulative active budget exhausted")+ request = envelope(self.binding, command="grant", stage=stage, ordinal=self.ordinal, lease=lease)+ self.writer.write((json.dumps(request, allow_nan=False) + "\n").encode())+ await asyncio.wait_for(self.writer.drain(), min(5, deadline - time.monotonic()))+ event = {+ "stage": stage,+ "ordinal": self.ordinal,+ "lease": lease,+ "started": started,+ "deadline": deadline,+ "active_before_s": self.active_s,+ }+ self.events.append(event)+ self.finishing = stage == "finish"+ try:+ value = await self.read(deadline)+ require(+ value.get("event") == "ack"+ and value.get("stage") == stage+ and value.get("ordinal") == self.ordinal+ and value.get("lease") == lease,+ "stale/reordered group ACK",+ )+ require(started <= value["monotonic_s"] <= time.monotonic(), "worker ACK clock differs")+ if stage == "prepare":+ require(value["actual_arm"] == self.binding["actual_arm"], "prepared configuration differs")+ require(+ value["manager_present"] is (self.binding["actual_arm"] == "R"), "prepared LoRA manager differs"+ )+ sdk = value["sdk_identity"]+ assert self.process is not None+ require(+ sdk["ppid"] == self.process.pid and sdk["process_group"] == self.process.pid, "SDK lineage differs"+ )+ require(+ sdk["source"] == self.binding["source_root"] and not sdk["forbidden_imports_present"],+ "SDK source differs",+ )+ config_path = Path(self.binding["output"]) / "models/model.yaml"+ require(digest(config_path) == value["config_sha256"], "prepared config hash differs")+ if stage != "finish":+ require(value["quiet"]["pending"] == 0 and value["quiet"]["in_flight"] == 0, "worker ACK was not quiet")+ if stage.startswith("C"):+ concurrency = int(stage[1:])+ record = value["record"]+ require(+ record["concurrency"] == concurrency and record["path"] == f"phase-C{concurrency}.json",+ "ACK phase differs",+ )+ path = Path(self.binding["output"]) / "loadgen" / record["path"]+ # The worker verified the full hash before ACK. Keep only+ # metadata here; even the coordinator's redundant full-file+ # hash read waits until all nine timers have ended.+ require(+ path.stat().st_size == record["bytes"],+ "phase persistence differs",+ )+ event["ack"] = value+ self.ordinal += 1+ return value+ finally:+ event["ended"] = time.monotonic()+ self.active_s += event["ended"] - started+ event["active_total_s"] = self.active_s+ if self.active_s > MAX_TRIAL_SECONDS:+ error = sys.exception()+ if error is None:+ raise AssertionError("worker cumulative active budget exceeded")+ error.add_note("Worker cumulative active budget also exceeded")+++async def cleanup(peers: list[Peer], hard_deadline: float) -> list[dict[str, Any]]:+ """One shared deadline, all signals first; no per-child multiplication."""+ deadline = min(hard_deadline, time.monotonic() + GROUP_CLEANUP_S)+ for peer in peers:+ peer.stopping = True+ if peer.writer is not None:+ peer.writer.close() # sole parent endpoint; explicit worker EOF cancellation+ if peer.process is not None:+ try:+ os.killpg(peer.process.pid, signal.SIGTERM)+ except ProcessLookupError:+ pass+ processes = [peer.process for peer in peers if peer.process is not None]+ waits = [asyncio.create_task(process.wait()) for process in processes]+ if waits:+ _, pending = await asyncio.wait(waits, timeout=max(0, min(35, deadline - time.monotonic() - 5)))+ for process in processes:+ # A worker may have exited while a descendant remains. Signal its+ # entire owned group, not only PIDs whose returncode is still None.+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ if pending:+ _, pending = await asyncio.wait(pending, timeout=max(0, deadline - time.monotonic()))+ require(not pending, "owned worker reap exceeded shared cleanup deadline")+ receipt = []+ for peer in peers:+ if peer.process is not None:+ receipt.append(+ {+ "role": peer.binding["logical_role"],+ "pid": peer.process.pid,+ "returncode": peer.process.returncode,+ "reaped": peer.process.returncode is not None,+ }+ )+ peer.log.close()+ return receipt+++async def watch_peer(peer: Peer, owner: asyncio.Task) -> None:+ assert peer.process is not None+ await peer.process.wait()+ if not peer.finishing and not peer.stopping:+ owner.cancel(f"worker {peer.binding['logical_role']} exited before group finish")+++def verify_phase_files(peers: list[Peer]) -> None:+ require(+ len(peers) == len(ORDERS[0]) and all(peer.ordinal == len(STAGES) - 1 for peer in peers),+ "group timers incomplete",+ )+ for peer in peers:+ for event in peer.events[1:]:+ record = event["ack"]["record"]+ path = Path(peer.binding["output"]) / "loadgen" / record["path"]+ require(+ path.stat().st_size == record["bytes"] and digest(path) == record["sha256"], "phase persistence differs"+ )+++async def join_cleanup(task: asyncio.Task, primary: BaseException | None) -> Any:+ """Repeated coordinator TERM/cancellation cannot abandon owned teardown.++ cleanup itself owns the one absolute deadline. This join does not reset it+ and does not cancel the shared teardown task when its caller is cancelled.+ """+ cancelled = None+ while not task.done():+ try:+ await asyncio.shield(task)+ except asyncio.CancelledError as error:+ cancelled = error+ except BaseException: # noqa: BLE001 -- retrieve the same task exception below+ break # retrieve the completed task's original exception below+ result = task.result()+ if cancelled is not None:+ if primary is None:+ raise cancelled+ primary.add_note("Coordinator cancellation during cleanup retained after owned reaping")+ return result+++async def run_group(args: argparse.Namespace, manifest: dict[str, Any], pair: int) -> dict[str, Any]:+ started = time.monotonic()+ hard_deadline = started + args.group_work_s + GROUP_CLEANUP_S+ group: dict[str, Any] = {+ "pair": pair,+ "order": list(ORDERS[pair]),+ "started": started,+ "work_deadline": started + args.group_work_s,+ "hard_deadline": hard_deadline,+ "completed_valid": False,+ "leases": [],+ "trials": [],+ }+ peers: list[Peer] = []+ watchers: list[asyncio.Task] = []+ owner = asyncio.current_task()+ assert owner is not None+ nonce = uuid.uuid4().hex+ try:+ for role in ORDERS[pair]:+ binding = binding_for(args, manifest, pair, role, nonce, started)+ path = args.output / f"binding-{pair}-{role}.json"+ atomic_json(path, binding)+ peer = Peer(binding, (args.output / f"trial-{pair}-{role}.log").open("wb"))+ peers.append(peer)+ await peer.start(args, path)+ watchers.append(asyncio.create_task(watch_peer(peer, owner)))+ for peer in peers:+ await peer.receive_hello()+ for stage in STAGES:+ # Phase-major scheduling, and finalization only after all nine+ # persisted phase ACKs. No background task grants another lease.+ if stage == "finish":+ verify_phase_files(peers)+ group["phase_hashes_verified_at"] = time.monotonic()+ for peer in peers:+ await peer.lease(stage)+ group["leases"].append({"role": peer.binding["logical_role"], **peer.events[-1]})+ atomic_json(args.output / f"group-{pair}.json", group)+ if stage == "finish":+ assert peer.process is not None+ await asyncio.wait_for(peer.process.wait(), max(0.001, min(10, hard_deadline - time.monotonic())))+ require(peer.process.returncode == 0, "finalized worker exited unsuccessfully")+ # Reopen raw trial payloads only after every timer, every finish grant,+ # SDK reap and server lifecycle check in the triplet is complete.+ for peer in peers:+ path = Path(peer.binding["output"]) / "trial.json"+ require(digest(path) == peer.events[-1]["ack"]["terminal_sha256"], "worker terminal hash differs")+ trial = json.loads(path.read_text())+ require(+ trial.get("group") == peer.binding and trial.get("actual_arm") == peer.binding["actual_arm"],+ "terminal binding differs",+ )+ require(trial["pair"] == pair and trial["arm"] == peer.binding["logical_role"], "terminal role differs")+ require(trial["passed"] and trial["shutdown_complete"], "worker correctness/lifecycle failed")+ trial.update(+ source_commit=peer.binding["source_commit"],+ process_returncode=0,+ terminal_record=str(path.relative_to(args.output)),+ terminal_record_sha256=digest(path),+ )+ group["trials"].append(trial_summary(trial))+ group["completed_valid"] = True+ except BaseException as error:+ group["error"] = {"type": type(error).__name__, "message": str(error)}+ raise+ finally:+ primary = sys.exception()+ task = asyncio.create_task(cleanup(peers, hard_deadline))+ try:+ group["cleanup"] = await join_cleanup(task, primary)+ except BaseException as error:+ group["completed_valid"] = False+ group["cleanup_error"] = {"type": type(error).__name__, "message": str(error)}+ if primary is None:+ raise+ primary.add_note(f"Group cleanup failed: {type(error).__name__}: {error}")+ finally:+ for watcher in watchers:+ watcher.cancel()+ await asyncio.gather(*watchers, return_exceptions=True)+ group["peer_events"] = {peer.binding["logical_role"]: peer.events for peer in peers}+ group["finished"] = time.monotonic()+ try:+ atomic_json(args.output / f"group-{pair}.json", group)+ except BaseException as error:+ if primary is None:+ raise+ primary.add_note(f"Group receipt failed: {type(error).__name__}: {error}")+ return group+++def validate_trials(trials: list[dict[str, Any]], mode: str, *, smoke: bool) -> None:+ schedule = (+ [(0, role) for role in ORDERS[0]] if smoke else [(i, role) for i, order in enumerate(ORDERS) for role in order]+ )+ require([(t["pair"], t["arm"]) for t in trials] == schedule, "group trial schedule incomplete")+ for trial in trials:+ binding = trial["group"]+ validate_binding(binding)+ require(+ binding["mode"] == mode and binding["logical_role"] == trial["arm"] and binding["pair"] == trial["pair"],+ "trial group binding differs",+ )+ require(trial["actual_arm"] == selection(mode, trial["arm"])[0], "actual trial configuration differs")+ require(trial["manager_present"] is (trial["actual_arm"] == "R"), "trial manager differs")+ require(trial["passed"] and trial["shutdown_complete"], "group trial failed")+ require(+ trial["environment"]["qualification"] is (mode == "qualification" and not smoke),+ "trial qualification mode differs",+ )+++async def run(args: argparse.Namespace) -> dict[str, Any]:+ require(args.mode in MODES and 0 < args.deadline_s <= RUNNER_LIMIT_S, "invalid interleaved mode/deadline")+ require(0 < args.group_work_s <= GROUP_WORK_S, "invalid group work deadline")+ args.output = args.output.resolve()+ args.output.mkdir(parents=True, exist_ok=False)+ started = time.monotonic()+ deadline = started + args.deadline_s+ summary: dict[str, Any] = {+ "schema": 3,+ "mode": args.mode,+ "schedule": "whole-phase",+ "smoke": args.smoke,+ "completed_valid": False,+ "qualification_passed": False,+ "passed": False,+ "orders": ORDERS,+ "groups": [],+ "trials": [],+ "admissions": [],+ "harness_manifest": harness_manifest(),+ "runner_clock": {+ "monotonic_start_s": started,+ "wall_start_ns": time.time_ns(),+ "deadline_monotonic_s": deadline,+ "budget_s": args.deadline_s,+ },+ }+ try:+ manifest = extract(args.inputs.resolve(), args.output / "sources")+ summary["source_manifest"] = manifest+ if args.environment_receipt is not None:+ summary["environment_preparation"] = {+ "sha256": digest(args.environment_receipt),+ "receipt": json.loads(args.environment_receipt.read_text()),+ }+ for pair in range(1 if args.smoke else len(ORDERS)):+ check = {"pair": pair, **admission(time.monotonic(), deadline, args.group_work_s)}+ summary["admissions"].append(check)+ require(check["admitted"], "insufficient time for complete bounded group and shared cleanup")+ print(f"Starting whole-phase group {pair + 1} ({args.mode})", flush=True)+ group = await run_group(args, manifest, pair)+ summary["groups"].append(+ {+ "pair": pair,+ "completed_valid": group["completed_valid"],+ "record": f"group-{pair}.json",+ "sha256": digest(args.output / f"group-{pair}.json"),+ }+ )+ summary["trials"].extend(group["trials"])+ atomic_json(args.output / "summary.json", summary)+ print(f"Finished whole-phase group {pair + 1}", flush=True)+ trials = [load_trial(args.output, record) for record in summary["trials"]]+ validate_trials(trials, args.mode, smoke=args.smoke)+ # Smoke still validates all three peers' numerics/memory: fill only the+ # iteration count via a dedicated single-triplet check, not fabricated+ # replicas. Full acceptance always uses the original six-triplet check.+ if args.smoke:+ summary["correctness_memory"] = smoke_cross_checks(trials)+ else:+ summary["correctness_memory"] = cross_checks(trials)+ summary["statistics"] = compare(trials)+ summary["completed_valid"] = True+ summary["qualification_passed"] = (+ not args.smoke and args.mode == "qualification" and summary["statistics"]["passed"]+ )+ summary["passed"] = (+ summary["completed_valid"]+ if args.mode == "baseline-pilot" or args.smoke+ else summary["qualification_passed"]+ )+ require(summary["passed"], "fixed non-inferiority gates did not pass")+ except BaseException as error:+ summary["error"] = {"type": type(error).__name__, "message": str(error)}+ raise+ finally:+ atomic_json(args.output / "summary.json", summary)+ return summary+++def smoke_cross_checks(trials: list[dict[str, Any]]) -> dict[str, Any]:+ # Reuse the exact peer checks without weakening them or inventing six+ # observations. The helper reads ORDERS only to determine the pair count.+ check = FunctionType(cross_checks.__code__, {**cross_checks.__globals__, "ORDERS": ORDERS[:1]})+ return check(trials)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--inputs", type=Path, required=True)+ parser.add_argument("--fixtures", type=Path, required=True)+ parser.add_argument("--snapshot", type=Path)+ parser.add_argument("--environment-receipt", type=Path)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--mode", choices=MODES, required=True)+ parser.add_argument("--deadline-s", type=float, default=RUNNER_LIMIT_S)+ parser.add_argument("--group-work-s", type=float, default=GROUP_WORK_S)+ parser.add_argument("--smoke", action="store_true")+ args = parser.parse_args()++ async def launch() -> None:+ task = asyncio.current_task()+ assert task is not None+ loop = asyncio.get_running_loop()+ for sig in (signal.SIGTERM, signal.SIGINT):+ loop.add_signal_handler(sig, task.cancel)+ await run(args)++ asyncio.run(launch())+++if __name__ == "__main__":+ main()diff --git a/tools/benchmarks/cross_encoder_lora/isolation.py b/tools/benchmarks/cross_encoder_lora/isolation.pyindex 4cadc6031..121c54539 100644--- a/tools/benchmarks/cross_encoder_lora/isolation.py+++ b/tools/benchmarks/cross_encoder_lora/isolation.py@@ -28,14 +28,19 @@ from tools.benchmarks.cross_encoder_lora.protocol import PERFORMANCE_FUTURE_TIMEclass IsolatedLoadgen:"""Leave uvicorn running while awaiting a bounded, same-group SDK child."""- def __init__(self, url: str, source: Path, evidence: Evidence, *, smoke: bool) -> None:+ def __init__(+ self, url: str, source: Path, evidence: Evidence, *, smoke: bool, idle_deadline: float | None = None+ ) -> None:self.url, self.source, self.evidence, self.smoke = url, source.resolve(), evidence, smoke+ self.idle_deadline = idle_deadlineself.token = uuid.uuid4().hexself.process: asyncio.subprocess.Process | None = Noneself.log: Any = Noneself.records: list[dict[str, Any]] = []self.observations: dict[int, dict[str, Any]] = {}self.receipt: dict[str, Any] = {"passed": False, "reaped": False, "phases": self.records}+ self.exit_watcher: asyncio.Task | None = None+ self.expected_exit = Falseasync def _send(self, command: str, concurrency: int | None = None) -> None:assert self.process is not None@@ -75,6 +80,11 @@ class IsolatedLoadgen:]if self.smoke:command.append("--smoke")+ if self.idle_deadline is not None:+ require(+ math.isfinite(self.idle_deadline) and self.idle_deadline > time.monotonic(), "invalid idle deadline"+ )+ command.extend(["--idle-deadline", str(self.idle_deadline)])self.log = (self.evidence.directory / "loadgen.log").open("wb")try:self.process = await asyncio.create_subprocess_exec(@@ -96,6 +106,7 @@ class IsolatedLoadgen:identity["source"] == str(self.source) and identity["forbidden_imports_present"] is False,"loadgen source/import preflight failed",)+ require(hello.get("idle_deadline") == self.idle_deadline, "loadgen idle deadline differs")sdk_path = Path(identity["sdk_path"])require(sdk_path.is_relative_to(self.source / "packages/sie_sdk/src"), "loadgen SDK source escaped its archive"@@ -108,6 +119,10 @@ class IsolatedLoadgen:)self.receipt["identity"] = identityself.evidence.emit("loadgen_started", **identity)+ if self.idle_deadline is not None:+ owner = asyncio.current_task()+ assert owner is not None+ self.exit_watcher = asyncio.create_task(self._watch_group_exit(owner))return selfexcept BaseException as error:try:@@ -116,6 +131,12 @@ class IsolatedLoadgen:error.add_note(f"Loadgen startup cleanup failed: {type(cleanup_error).__name__}: {cleanup_error}")raise+ async def _watch_group_exit(self, owner: asyncio.Task) -> None:+ assert self.process is not None+ await self.process.wait()+ if not self.expected_exit:+ owner.cancel("group SDK child exited before finalization")+async def phase(self, concurrency: int) -> dict[str, Any]:require(len(self.records) < len(PHASES) and concurrency == PHASES[len(self.records)],@@ -174,6 +195,7 @@ class IsolatedLoadgen:)async def _cleanup(self, successful: bool) -> None:+ self.expected_exit = Truetry:if self.process is not None:try:@@ -209,6 +231,9 @@ class IsolatedLoadgen:else:self.receipt["reaped"] = Truefinally:+ if self.exit_watcher is not None:+ self.exit_watcher.cancel()+ await asyncio.gather(self.exit_watcher, return_exceptions=True)if self.log is not None:self.log.close()atomic_json(self.evidence.directory / "loadgen-process.json", self.receipt)@@ -254,6 +279,7 @@ class IsolatedLoadgen:require(terminal.get("passed") is True and "error" not in terminal, "loadgen terminal did not pass")require(terminal.get("identity") == self.receipt["identity"], "loadgen terminal identity differs")require(terminal.get("smoke") is self.smoke, "loadgen terminal mode differs")+ require(terminal.get("idle_deadline") == self.idle_deadline, "loadgen terminal idle deadline differs")require(terminal.get("phases") == self.records, "loadgen terminal phase records differ")require(tuple(record["concurrency"] for record in self.records) == PHASES, "loadgen terminal schedule differs")require(diff --git a/tools/benchmarks/cross_encoder_lora/loadgen.py b/tools/benchmarks/cross_encoder_lora/loadgen.pyindex f1fb26dd8..96ecc04ea 100644--- a/tools/benchmarks/cross_encoder_lora/loadgen.py+++ b/tools/benchmarks/cross_encoder_lora/loadgen.py@@ -6,6 +6,7 @@ import argparseimport gcimport inspectimport json+import mathimport osimport queueimport select@@ -95,8 +96,16 @@ class Control:os.close(self.stop_read)os.close(self.stop_write)- def receive(self, command: str, concurrency: int | None = None) -> dict[str, Any]:- value = self.messages.get(timeout=CONTROL_TIMEOUT_S)+ def receive(+ self, command: str, concurrency: int | None = None, *, idle_deadline: float | None = None+ ) -> dict[str, Any]:+ wait_s = CONTROL_TIMEOUT_S+ if idle_deadline is not None:+ require(command in {"phase", "finish"}, "group idle deadline used for active handshake")+ require(math.isfinite(idle_deadline), "invalid group idle deadline")+ wait_s = idle_deadline - time.monotonic()+ require(wait_s > 0, "group idle deadline expired")+ value = self.messages.get(timeout=wait_s)require("reader_error" not in value, "control reader failed")require(value.get("token") == self.token and value.get("command") == command, "unexpected parent command")require(value.get("concurrency") == concurrency, "parent phase identity differs")@@ -134,10 +143,15 @@ def run(args: argparse.Namespace) -> None:control = Control(args.token)terminal: dict[str, Any] = {"passed": False, "phases": [], "identity": identity(args.source), "smoke": args.smoke}retained_results = []- control.send("hello", identity=terminal["identity"])+ idle_deadline = getattr(args, "idle_deadline", None)+ terminal["idle_deadline"] = idle_deadline+ control.send("hello", identity=terminal["identity"], idle_deadline=idle_deadline)try:for concurrency in PHASES:- control.receive("phase", concurrency)+ if idle_deadline is None:+ control.receive("phase", concurrency)+ else:+ control.receive("phase", concurrency, idle_deadline=idle_deadline)require_sdk_only()callbacks: tuple[Any, ...] = ()observations: dict[str, Any] = {}@@ -198,7 +212,10 @@ def run(args: argparse.Namespace) -> None:# rows until every timed phase is complete.retained_results.append(result)control.send("phase_complete", concurrency, record=record)- control.receive("finish")+ if idle_deadline is None:+ control.receive("finish")+ else:+ control.receive("finish", idle_deadline=idle_deadline)terminal["passed"] = Trueexcept BaseException as error:terminal["error"] = {"type": type(error).__name__, "message": str(error)}@@ -218,6 +235,7 @@ def main() -> None:parser.add_argument("--url", required=True)parser.add_argument("--token", required=True)parser.add_argument("--smoke", action="store_true")+ parser.add_argument("--idle-deadline", type=float)run(parser.parse_args())diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_group_control.py b/tools/benchmarks/cross_encoder_lora/tests/test_group_control.pynew file mode 100644index 000000000..5e84aff02--- /dev/null+++ b/tools/benchmarks/cross_encoder_lora/tests/test_group_control.py@@ -0,0 +1,361 @@+"""Dedicated socket ownership, real uvicorn cancellation and bounded teardown."""++# All Python children and signals are scoped to new owned process groups.+# ruff: noqa: S603++from __future__ import annotations++import asyncio+import json+import os+import signal+import socket+import subprocess+import sys+import time+from pathlib import Path+from typing import cast++import pytest++from tools.benchmarks.cross_encoder_lora.evidence import atomic_json, digest+from tools.benchmarks.cross_encoder_lora.group_control import Member, decode, envelope+from tools.benchmarks.cross_encoder_lora.interleaved import Peer, cleanup, join_cleanup, watch_peer+from tools.benchmarks.cross_encoder_lora.loadgen import Control+from tools.benchmarks.cross_encoder_lora.runner import ROOT, source_environment+from tools.benchmarks.cross_encoder_lora.tests.test_interleaved import binding+from tools.benchmarks.cross_encoder_lora.tests.test_isolation import sdk_server # noqa: F401 -- pytest fixture++HELPER = r"""+import asyncio, json, os, signal, socket, sys+from pathlib import Path+from tools.benchmarks.cross_encoder_lora.group_control import Member+from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json+value=json.loads(Path(sys.argv[1]).read_text())+owner=Member(int(sys.argv[2]), value, Path(value['output']))+# These are imported only after ownership is active, as in the actual entrypoint.+import uvicorn+from tools.benchmarks.cross_encoder_lora.isolation import IsolatedLoadgen+from tools.benchmarks.cross_encoder_lora.runner import ROOT+async def app(scope, receive, send):+ if scope['type']=='lifespan':+ while True:+ message=await receive()+ await send({'type': message['type']+'.complete'})+ if message['type']=='lifespan.shutdown': return+ else:+ await send({'type':'http.response.start','status':200,'headers':[]})+ await send({'type':'http.response.body','body':b'ok'})+async def run():+ owner.bind_task()+ await owner.grant('prepare')+ sock=socket.socket(); sock.bind(('127.0.0.1',0))+ server=uvicorn.Server(uvicorn.Config(app, log_level='warning', access_log=False))+ task=asyncio.create_task(server.serve(sockets=[sock]))+ loadgen=None+ try:+ while not server.started: await asyncio.sleep(.01)+ print('ordinary model/log chatter {not protocol}',flush=True)+ async with IsolatedLoadgen(sys.argv[3],ROOT,Evidence(Path(value['output'])/'sdk'),smoke=True,+ idle_deadline=value['work_deadline']) as loadgen:+ owner.acknowledge(sdk_pid=loadgen.process.pid,uvicorn_handler=repr(signal.getsignal(signal.SIGTERM)))+ await owner.grant('C1')+ record=await loadgen.phase(1)+ owner.acknowledge(record=record)+ await owner.grant('C4')+ finally:+ server.should_exit=True+ await asyncio.wait_for(task,5)+ sock.close()+ atomic_json(Path(value['output'])/'helper-cleanup.json',{'loadgen':loadgen.receipt if loadgen else None})+try:+ asyncio.run(run())+finally:+ owner.close()+"""++[email protected]("failure", ["eof", "wrong_identity", "stale_stage", "sdk_crash"])+def test_actual_uvicorn_eof_cancels_and_reaps_sdk_preserving_phase(+ request: pytest.FixtureRequest, tmp_path: Path, failure: str+) -> None:+ url = request.getfixturevalue("sdk_server")+ value = binding(tmp_path)+ value["coordinator_pid"] = os.getpid()+ path = tmp_path / "binding.json"+ atomic_json(path, value)+ parent, child = socket.socketpair()+ process = None+ with (tmp_path / "worker.log").open("wb") as log:+ try:+ process = subprocess.Popen(+ [sys.executable, "-c", HELPER, str(path), str(child.fileno()), url],+ pass_fds=(child.fileno(),),+ close_fds=True,+ start_new_session=True,+ stdout=log,+ stderr=log,+ env=source_environment(ROOT),+ )+ child.close()+ parent.settimeout(10)+ reader = parent.makefile("rb", buffering=0)+ hello = decode(reader.readline(), value)+ assert hello["pid"] == process.pid++ def grant(stage: str, ordinal: int) -> None:+ parent.sendall(+ (+ json.dumps(envelope(value, command="grant", stage=stage, ordinal=ordinal, lease="b" * 32))+ + "\n"+ ).encode()+ )++ grant("prepare", 0)+ prepared = decode(reader.readline(), value)+ assert (+ "Server.capture_signals" in prepared["uvicorn_handler"]+ or "Server.handle_exit" in prepared["uvicorn_handler"]+ )+ sdk_pid = prepared["sdk_pid"]+ grant("C1", 1)+ complete = decode(reader.readline(), value)+ completed_file = tmp_path / "sdk/loadgen/phase-C1.json"+ original_hash = digest(completed_file)+ assert original_hash == complete["record"]["sha256"]+ if failure == "wrong_identity":+ parent.sendall(b'{"binding_sha256":"wrong"}\n')+ elif failure == "stale_stage":+ grant("C1", 1)+ elif failure == "sdk_crash":+ os.kill(sdk_pid, signal.SIGKILL)+ else:+ reader.close()+ parent.close()+ assert process.wait(timeout=12) != 0+ receipt = json.loads((tmp_path / "helper-cleanup.json").read_text())+ assert receipt["loadgen"]["reaped"]+ assert digest(completed_file) == original_hash+ with pytest.raises(ProcessLookupError):+ os.kill(sdk_pid, 0)+ assert "ordinary model/log chatter" in (tmp_path / "worker.log").read_text()+ finally:+ parent.close()+ child.close()+ if process is not None and process.poll() is None:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait(timeout=5)+++async def test_repeated_cancellation_joins_one_shared_cleanup_and_preserves_primary() -> None:+ reaped = []++ async def cleanup():+ await asyncio.sleep(0.08)+ reaped.extend(range(6))+ return "complete"++ primary = ValueError("original phase failure")+ task = asyncio.create_task(cleanup())+ owner = asyncio.create_task(join_cleanup(task, primary))+ await asyncio.sleep(0.01)+ owner.cancel()+ await asyncio.sleep(0.01)+ owner.cancel()+ assert await owner == "complete"+ assert reaped == list(range(6))+ assert task.done()+ assert str(primary) == "original phase failure"+ assert "owned reaping" in primary.__notes__[0]+++async def test_cancel_during_clean_exit_propagates_after_reaping() -> None:+ reaped = []++ async def cleanup():+ await asyncio.sleep(0.03)+ reaped.append(True)++ task = asyncio.create_task(cleanup())+ owner = asyncio.create_task(join_cleanup(task, None))+ await asyncio.sleep(0.01)+ owner.cancel()+ with pytest.raises(asyncio.CancelledError):+ await owner+ assert reaped+ assert task.done()+++def test_closed_event_loop_cannot_disable_hard_fallback() -> None:+ owner = object.__new__(Member)+ owner.loop = asyncio.new_event_loop()+ owner.loop.close()+ owner.owner = type("Owner", (), {"cancel": lambda *_: None})()+ owner._fail("parent gone")+ assert owner.failure == "parent gone"+++def test_group_idle_deadline_is_finite_and_only_for_idle_commands() -> None:+ owner = object.__new__(Control)++ class Messages:+ def get(self, *, timeout):+ assert 30 < timeout <= 60+ return {"token": "owned", "command": "phase", "concurrency": 4}++ owner.messages = Messages()+ owner.token = "owned" # noqa: S105 -- local control nonce fixture+ assert owner.receive("phase", 4, idle_deadline=time.monotonic() + 60)["concurrency"] == 4+ with pytest.raises(AssertionError, match="active handshake"):+ owner.receive("go", 4, idle_deadline=time.monotonic() + 60)+ with pytest.raises(AssertionError, match="expired"):+ owner.receive("phase", 4, idle_deadline=time.monotonic() - 1)+++COORDINATOR = r"""+import json, os, socket, subprocess, sys, time+from pathlib import Path+from tools.benchmarks.cross_encoder_lora.evidence import atomic_json,digest+from tools.benchmarks.cross_encoder_lora.group_control import decode,envelope+from tools.benchmarks.cross_encoder_lora.runner import ROOT,source_environment+root=Path(sys.argv[1]); value=json.loads((root/'template.json').read_text())+owned=[]; sockets=[]; records=[]+for role in 'BNR':+ directory=root/role; directory.mkdir()+ b={**value,'logical_role':role,'output':str(directory),'coordinator_pid':os.getpid()}+ path=directory/'binding.json';atomic_json(path,b)+ parent,child=socket.socketpair();sockets.append(parent)+ log=(directory/'worker.log').open('wb')+ p=subprocess.Popen([sys.executable,str(root/'helper.py'),str(path),str(child.fileno()),sys.argv[2]],+ pass_fds=(child.fileno(),),close_fds=True,start_new_session=True,stdout=log,stderr=log,env=source_environment(ROOT))+ child.close();parent.settimeout(15);reader=parent.makefile('rb',buffering=0)+ decode(reader.readline(),b)+ def grant(stage,ordinal):+ parent.sendall((json.dumps(envelope(b,command='grant',stage=stage,ordinal=ordinal,lease='b'*32))+'\n').encode())+ grant('prepare',0); prepared=decode(reader.readline(),b)+ grant('C1',1); complete=decode(reader.readline(),b)+ records.append({'pid':p.pid,'sdk_pid':prepared['sdk_pid'],'directory':str(directory),+ 'phase_sha256':complete['record']['sha256']})+ owned.append((p,reader,log))+atomic_json(root/'ready.json',{'children':records})+# Parent is deliberately SIGKILLed by the test. No Python finally is expected.+while True: time.sleep(60)+"""+++def test_actual_coordinator_sigkill_ends_all_three_uvicorn_sdk_pairs(+ request: pytest.FixtureRequest, tmp_path: Path+) -> None:+ url = request.getfixturevalue("sdk_server")+ atomic_json(tmp_path / "template.json", binding(tmp_path))+ (tmp_path / "helper.py").write_text(HELPER)+ process = subprocess.Popen(+ [sys.executable, "-c", COORDINATOR, str(tmp_path), url],+ env=source_environment(ROOT),+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ start_new_session=True,+ )+ rows = []+ try:+ deadline = time.monotonic() + 15+ while not (tmp_path / "ready.json").exists():+ assert process.poll() is None, process.communicate()+ assert time.monotonic() < deadline+ time.sleep(0.02)+ rows = json.loads((tmp_path / "ready.json").read_text())["children"]+ assert len(rows) == 3+ process.kill()+ assert process.wait(timeout=5) == -signal.SIGKILL+ deadline = time.monotonic() + 10+ while not all((Path(row["directory"]) / "helper-cleanup.json").exists() for row in rows):+ assert time.monotonic() < deadline+ time.sleep(0.02)+ for row in rows:+ directory = Path(row["directory"])+ receipt = json.loads((directory / "helper-cleanup.json").read_text())+ assert receipt["loadgen"]["reaped"]+ assert digest(directory / "sdk/loadgen/phase-C1.json") == row["phase_sha256"]+ with pytest.raises(ProcessLookupError):+ os.kill(row["sdk_pid"], 0)+ deadline = time.monotonic() + 10+ for row in rows:+ while True:+ try:+ os.kill(row["pid"], 0)+ except ProcessLookupError:+ break+ assert time.monotonic() < deadline, "server survived coordinator loss"+ time.sleep(0.02)+ finally:+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)+ for row in rows:+ try:+ os.killpg(row["pid"], signal.SIGKILL)+ except ProcessLookupError:+ pass+++async def test_simultaneous_teardown_uses_one_shared_deadline(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ signalled = []+ gates = [asyncio.Event() for _ in range(3)]++ class Process:+ def __init__(self, index):+ self.pid = index + 1+ self.returncode = None++ async def wait(self):+ await gates[self.pid - 1].wait()+ self.returncode = -signal.SIGKILL+ return self.returncode++ def killpg(pid, sig):+ signalled.append((pid, sig, time.monotonic()))+ if sig == signal.SIGKILL:+ gates[pid - 1].set()++ monkeypatch.setattr(os, "killpg", killpg)+ peers = [Peer({"logical_role": role}, (tmp_path / f"{role}.log").open("wb")) for role in "BNR"]+ for index, peer in enumerate(peers):+ peer.process = cast("asyncio.subprocess.Process", Process(index))+ started = time.monotonic()+ receipt = await cleanup(peers, started + 0.5)+ assert time.monotonic() - started < 0.5+ assert [row[1] for row in signalled[:3]] == [signal.SIGTERM] * 3+ assert [row[1] for row in signalled[3:]] == [signal.SIGKILL] * 3+ assert all(row["reaped"] for row in receipt)+++async def test_inactive_worker_failure_cancels_group() -> None:+ done = asyncio.Event()++ class Process:+ async def wait(self):+ await done.wait()++ peer = object.__new__(Peer)+ peer.process = Process()+ peer.binding = {"logical_role": "R"}+ peer.finishing = peer.stopping = False++ async def active_group():+ owner = asyncio.current_task()+ assert owner is not None+ watcher = asyncio.create_task(watch_peer(peer, owner))+ try:+ await asyncio.sleep(10)+ finally:+ await watcher++ task = asyncio.create_task(active_group())+ await asyncio.sleep(0)+ done.set()+ with pytest.raises(asyncio.CancelledError, match="before group finish"):+ await taskdiff --git a/tools/benchmarks/cross_encoder_lora/tests/test_interleaved.py b/tools/benchmarks/cross_encoder_lora/tests/test_interleaved.pynew file mode 100644index 000000000..703720d2a--- /dev/null+++ b/tools/benchmarks/cross_encoder_lora/tests/test_interleaved.py@@ -0,0 +1,355 @@+"""Actual archived loader/SDK triplets and fail-closed group semantics."""++# All subprocesses use the current interpreter and owned temporary artifacts.+# ruff: noqa: S603++from __future__ import annotations++import argparse+import asyncio+import copy+import json+import os+import signal+import subprocess+import sys+import time+from pathlib import Path+from typing import cast++import pytest++from tools.benchmarks.cross_encoder_lora import interleaved, prepare+from tools.benchmarks.cross_encoder_lora.evidence import atomic_json, digest+from tools.benchmarks.cross_encoder_lora.fixtures import prepare as fixtures_prepare+from tools.benchmarks.cross_encoder_lora.group_control import envelope, selection, validate_binding, validate_source+from tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISION+from tools.benchmarks.cross_encoder_lora.runner import ROOT, source_environment+from tools.benchmarks.cross_encoder_lora.tests.test_probe import tiny_snapshot+++def test_strict_group_admission() -> None:+ assert not interleaved.admission(100, 789)["admitted"]+ assert not interleaved.admission(100, 790)["admitted"]+ assert interleaved.admission(100, 791)["admitted"]++[email protected]("role", ["B", "N", "R"])+def test_explicit_role_configuration_source(role: str) -> None:+ assert selection("baseline-pilot", role) == ("B", "B")+ assert selection("qualification", role) == (("B", "B") if role == "B" else (role, "candidate"))+++def binding(tmp_path: Path) -> dict:+ start = time.monotonic()+ return {+ "schema": 1,+ "schedule": "whole-phase",+ "mode": "baseline-pilot",+ "pair": 0,+ "logical_role": "R",+ "actual_arm": "B",+ "source_key": "B",+ "source_commit": BASE_REVISION,+ "nonce": "a" * 32,+ "coordinator_pid": 1,+ "group_started": start,+ "work_deadline": start + 30,+ "hard_deadline": start + 120,+ "active_limit_s": 270,+ "phase_limit_s": 120,+ "output": str(tmp_path),+ }+++ "change",+ [+ {"actual_arm": "R"},+ {"source_key": "candidate"},+ {"source_commit": "f" * 40},+ {"phase_limit_s": 121},+ {"active_limit_s": 271},+ {"pair": True},+ ],+)+def test_binding_rejects_relabeling_and_budget_changes(tmp_path: Path, change: dict) -> None:+ value = binding(tmp_path)+ validate_binding(value)+ value.update(change)+ with pytest.raises(AssertionError):+ validate_binding(value)+++def test_qualification_resident_cannot_be_base(tmp_path: Path) -> None:+ value = {**binding(tmp_path), "mode": "qualification"}+ with pytest.raises(AssertionError, match="mismatch"):+ validate_binding(value)+++def test_manifest_and_extracted_source_hashes_checked_before_load(tmp_path: Path) -> None:+ source = tmp_path / "source"+ source.mkdir()+ (source / "uv.lock").write_text("fixed")+ archive = tmp_path / "B.tar"+ archive.write_bytes(b"archive bytes")+ manifest = tmp_path / "manifest.json"+ atomic_json(+ manifest,+ {+ "schema": 1,+ "dependency_lock_identical": True,+ "sources": {"B": {"commit": BASE_REVISION, "archive": "B.tar", "sha256": digest(archive)}},+ },+ )+ value = {+ **binding(tmp_path),+ "source_root": str(source),+ "source_manifest": str(manifest),+ "source_manifest_sha256": digest(manifest),+ "archive_sha256": digest(archive),+ "source_files": {"uv.lock": digest(source / "uv.lock")},+ }+ validate_source(value, source, "B", 0)+ with pytest.raises(AssertionError, match="arguments"):+ validate_source(value, source, "R", 0)+ (source / "uv.lock").write_text("changed")+ with pytest.raises(AssertionError, match="source file"):+ validate_source(value, source, "B", 0)++[email protected]("mode", ["baseline-pilot", "qualification"])+def test_real_archived_whole_phase_triplet(tmp_path: Path, mode: str) -> None:+ snapshot = tiny_snapshot(tmp_path / "model")+ fixtures = tmp_path / "fixtures"+ fixtures_prepare(fixtures, snapshot, smoke=True)+ inputs = tmp_path / "inputs"+ prepare.prepare(ROOT, inputs, "HEAD")+ output = tmp_path / "out"+ command = [+ sys.executable,+ "-m",+ "tools.benchmarks.cross_encoder_lora.interleaved",+ "--inputs",+ str(inputs),+ "--fixtures",+ str(fixtures),+ "--output",+ str(output),+ "--mode",+ mode,+ "--smoke",+ "--group-work-s",+ "120",+ "--deadline-s",+ "240",+ ]+ result = subprocess.run(+ command, cwd=ROOT, env=source_environment(ROOT), capture_output=True, text=True, timeout=225, check=False+ )+ assert result.returncode == 0, (+ result.stdout+ + result.stderr+ + "\n"+ + "\n".join(path.read_text()[-8000:] for path in sorted(output.glob("*.log")))+ )+ summary = json.loads((output / "summary.json").read_text())+ assert summary["completed_valid"]+ assert summary["passed"]+ assert summary["qualification_passed"] is False+ group = json.loads((output / "group-0.json").read_text())+ assert [event["stage"] for event in group["leases"]] == [+ stage for stage in ("prepare", "C1", "C4", "C16", "finish") for _ in range(3)+ ]+ for left, right in zip(group["leases"], group["leases"][1:], strict=False):+ assert left["ended"] <= right["started"]+ phase_end = max(event["ended"] for event in group["leases"] if event["stage"].startswith("C"))+ assert all(event["started"] >= phase_end for event in group["leases"] if event["stage"] == "finish")+ assert len(group["cleanup"]) == 3+ assert all(row["reaped"] and row["returncode"] == 0 for row in group["cleanup"])+ trials = [json.loads((output / record["terminal_record"]).read_text()) for record in summary["trials"]]+ interleaved.validate_trials(trials, mode, smoke=True)+ assert {row["arm"] for row in trials} == {"B", "N", "R"}+ for trial in trials:+ actual, source_key = selection(mode, trial["arm"])+ assert trial["actual_arm"] == actual+ assert trial["group"]["source_key"] == source_key+ assert trial["manager_present"] == (actual == "R")+ assert trial["loadgen"]["passed"]+ assert trial["loadgen"]["reaped"]+ assert Path(trial["environment"]["adapter_source"]).is_relative_to(output / "sources" / source_key)+ assert all(+ phase["client_observation"]["gc"]["mode"] == "boundary-only" for phase in trial["performance"].values()+ )+ invalid = copy.deepcopy(trials)+ invalid[-1]["actual_arm"] = "B" if mode == "qualification" else "R"+ with pytest.raises(AssertionError, match="configuration"):+ interleaved.validate_trials(invalid, mode, smoke=True)+++def test_incomplete_group_cannot_pass(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ args = argparse.Namespace(+ mode="baseline-pilot",+ deadline_s=1000,+ group_work_s=600,+ output=tmp_path / "out",+ inputs=tmp_path,+ fixtures=tmp_path,+ environment_receipt=None,+ smoke=False,+ )+ monkeypatch.setattr(interleaved, "extract", lambda *_: {})++ async def fail(*_):+ raise RuntimeError("owned child failed")++ monkeypatch.setattr(interleaved, "run_group", fail)+ with pytest.raises(RuntimeError, match="owned child"):+ asyncio.run(interleaved.run(args))+ value = json.loads((args.output / "summary.json").read_text())+ assert not value["completed_valid"]+ assert not value["qualification_passed"]+ assert not value["passed"]++[email protected]("mutation", ["lease", "ordinal", "stage", "phase"])+async def test_phase_ack_must_bind_exact_lease_and_persisted_payload(tmp_path: Path, mutation: str) -> None:+ value = binding(tmp_path)+ (tmp_path / "loadgen").mkdir()+ path = tmp_path / "loadgen/phase-C1.json"+ path.write_text("{}")+ peer = interleaved.Peer(value, (tmp_path / "log").open("wb"))+ peer.ordinal = 1+ peer.reader = asyncio.StreamReader()++ class Writer:+ def write(self, raw):+ request = json.loads(raw)+ ack = envelope(+ value,+ event="ack",+ stage="C1",+ ordinal=1,+ lease=request["lease"],+ monotonic_s=time.monotonic(),+ quiet={"pending": 0, "in_flight": 0},+ record={"concurrency": 1, "path": "phase-C1.json", "bytes": 2, "sha256": digest(path)},+ )+ if mutation == "phase":+ ack["record"]["concurrency"] = 4+ elif mutation == "ordinal":+ ack[mutation] = 0+ else:+ ack[mutation] = "wrong"+ assert peer.reader is not None+ peer.reader.feed_data((json.dumps(ack) + "\n").encode())++ async def drain(self):+ pass++ peer.writer = cast("asyncio.StreamWriter", Writer())+ try:+ with pytest.raises(AssertionError):+ await peer.lease("C1")+ assert peer.ordinal == 1+ finally:+ peer.log.close()+++def test_coordinator_full_file_hashes_wait_for_all_nine_timers(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ peers = []+ read = []+ for role in "BNR":+ directory = tmp_path / role+ (directory / "loadgen").mkdir(parents=True)+ peer = interleaved.Peer({"logical_role": role, "output": str(directory)}, (directory / "log").open("wb"))+ peer.events = [{}]+ for c in (1, 4, 16):+ path = directory / "loadgen" / f"phase-C{c}.json"+ path.write_text("{}")+ peer.events.append({"ack": {"record": {"path": path.name, "bytes": 2, "sha256": digest(path)}}})+ peer.ordinal = 4+ peers.append(peer)+ original = interleaved.digest++ def observed(path):+ read.append(path)+ return original(path)++ monkeypatch.setattr(interleaved, "digest", observed)+ try:+ peers[-1].ordinal = 3+ with pytest.raises(AssertionError, match="timers incomplete"):+ interleaved.verify_phase_files(peers)+ assert not read+ peers[-1].ordinal = 4+ interleaved.verify_phase_files(peers)+ assert len(read) == 9+ peers[-1].events[-1]["ack"]["record"]["sha256"] = "f" * 64+ with pytest.raises(AssertionError, match="persistence"):+ interleaved.verify_phase_files(peers)+ finally:+ for peer in peers:+ peer.log.close()+++def test_actual_coordinator_term_reaps_archived_workers_and_sdk_children(tmp_path: Path) -> None:+ snapshot = tiny_snapshot(tmp_path / "model")+ fixtures = tmp_path / "fixtures"+ fixtures_prepare(fixtures, snapshot, smoke=True)+ inputs = tmp_path / "inputs"+ prepare.prepare(ROOT, inputs, "HEAD")+ output = tmp_path / "out"+ command = [+ sys.executable,+ "-m",+ "tools.benchmarks.cross_encoder_lora.interleaved",+ "--inputs",+ str(inputs),+ "--fixtures",+ str(fixtures),+ "--output",+ str(output),+ "--mode",+ "baseline-pilot",+ "--smoke",+ "--group-work-s",+ "120",+ "--deadline-s",+ "240",+ ]+ with (tmp_path / "coordinator.log").open("wb") as log:+ process = subprocess.Popen(command, cwd=ROOT, env=source_environment(ROOT), stdout=log, stderr=log)+ try:+ deadline = time.monotonic() + 60+ group_path = output / "group-0.json"+ while True:+ assert process.poll() is None, (tmp_path / "coordinator.log").read_text()+ assert time.monotonic() < deadline+ if group_path.exists():+ group = json.loads(group_path.read_text())+ if len(group["leases"]) >= 4:+ break+ time.sleep(0.01)+ completed = output / "trial-0-B/loadgen/phase-C1.json"+ before = digest(completed)+ process.send_signal(signal.SIGTERM)+ assert process.wait(timeout=20) != 0+ group = json.loads(group_path.read_text())+ assert not group["completed_valid"]+ assert group["error"]["type"] == "CancelledError"+ assert digest(completed) == before+ assert all(row["reaped"] for row in group["cleanup"])+ for row in group["cleanup"]:+ with pytest.raises(ProcessLookupError):+ os.kill(row["pid"], 0)+ for role in "BNR":+ receipt = json.loads((output / f"trial-0-{role}/loadgen-process.json").read_text())+ assert receipt["reaped"]+ with pytest.raises(ProcessLookupError):+ os.kill(receipt["identity"]["pid"], 0)+ finally:+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)diff --git a/tools/benchmarks/cross_encoder_lora/worker.py b/tools/benchmarks/cross_encoder_lora/worker.pyindex 01c56d044..8c4d21bf4 100644--- a/tools/benchmarks/cross_encoder_lora/worker.py+++ b/tools/benchmarks/cross_encoder_lora/worker.py@@ -42,6 +42,7 @@ from tools.benchmarks.cross_encoder_lora.client import (describe_response,)from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digest, fingerprint, vector_delta+from tools.benchmarks.cross_encoder_lora.group_control import Member, validate_sourcefrom tools.benchmarks.cross_encoder_lora.isolation import IsolatedLoadgenfrom tools.benchmarks.cross_encoder_lora.protocol import (CONCURRENCIES,@@ -354,7 +355,8 @@ def preflight(args: argparse.Namespace, evidence: Evidence) -> dict[str, Any]:"threads": torch.get_num_threads(),"device": str(torch.cuda.get_device_name(0)) if torch.cuda.is_available() else "cpu","torch_cuda": torch.version.cuda,- "qualification": not args.smoke,+ "qualification": not args.smoke+ and (getattr(args, "group", None) is None or args.group.binding["mode"] == "qualification"),"installed_distributions": sorted((dist.metadata["Name"], dist.version) for dist in importlib.metadata.distributions()),@@ -369,6 +371,7 @@ def preflight(args: argparse.Namespace, evidence: Evidence) -> dict[str, Any]:async def experiment(args: argparse.Namespace, evidence: Evidence, summary: dict[str, Any]) -> None:+ group: Member | None = getattr(args, "group", None)fixtures = args.fixtures.resolve()manifest = json.loads((fixtures / "manifest.json").read_text())snapshot = args.snapshot.resolve() if args.snapshot else Path(manifest["snapshot"])@@ -585,12 +588,34 @@ async def experiment(args: argparse.Namespace, evidence: Evidence, summary: dict"policy": "Existing server histories retained; memory() just completed its existing gc.collect/CUDA synchronization outside timing. No new collection or history release is introduced.",}with unobserved(adapter):- async with IsolatedLoadgen(url, args.source, evidence, smoke=args.smoke) as loadgen:+ async with IsolatedLoadgen(+ url,+ args.source,+ evidence,+ smoke=args.smoke,+ idle_deadline=group.binding["work_deadline"] if group is not None else None,+ ) as loadgen:+ if group is not None:+ group.acknowledge(+ actual_arm=args.arm,+ manager_present=summary["manager_present"],+ config_sha256=digest(evidence.directory / "models/model.yaml"),+ sdk_identity=loadgen.receipt["identity"],+ quiet=group_quiet(worker),+ )for concurrency in (1, *CONCURRENCIES):+ if group is not None:+ await group.grant(f"C{concurrency}")phase = f"performance-C{concurrency}"evidence.emit("gpu_before_phase", phase=phase, telemetry=telemetry())- await loadgen.phase(concurrency)+ record = await loadgen.phase(concurrency)evidence.emit("gpu_after_phase", phase=phase, telemetry=telemetry())+ if group is not None:+ group.acknowledge(record=record, quiet=group_quiet(worker))+ if group is not None:+ # No SDK shutdown, raw payload loading, churn, unload or+ # finalization until all nine group phase ACKs exist.+ await group.grant("finish")# Reaping and all raw-row materialization/validation happen after# every measured phase, so their allocations never enter the# serving heap during a subsequent timed phase.@@ -687,16 +712,33 @@ async def experiment(args: argparse.Namespace, evidence: Evidence, summary: dictsock.close()+def group_quiet(worker: Any) -> dict[str, Any]:+ """A lease ends only after drained requests and an outside-timer CUDA fence."""+ if torch.cuda.is_available():+ torch.cuda.synchronize()+ state = {+ "pending": worker.pending_count,+ "in_flight": len(worker._in_flight),+ "cuda_synchronized": torch.cuda.is_available(),+ }+ require(state["pending"] == 0 and state["in_flight"] == 0, "worker was not quiet at lease boundary")+ return state++async def run(args: argparse.Namespace) -> dict[str, Any]:+ group: Member | None = getattr(args, "group", None)evidence = Evidence(args.output.resolve())summary: dict[str, Any] = {- "arm": args.arm,+ "arm": group.binding["logical_role"] if group is not None else args.arm,"pair": args.pair,"passed": False,"shutdown_complete": False,"smoke": args.smoke,"pid": os.getpid(),}+ if group is not None:+ summary["group"] = group.binding+ summary["actual_arm"] = args.armos.environ.update({"SIE_TELEMETRY_DISABLED": "1",@@ -709,8 +751,12 @@ async def run(args: argparse.Namespace) -> dict[str, Any]:torch.set_num_threads(THREADS)torch.set_num_interop_threads(1)try:+ if group is not None:+ await group.grant("prepare")+ validate_source(group.binding, args.source, args.arm, args.pair)summary["environment"] = preflight(args, evidence)- async with asyncio.timeout(args.deadline_s):+ timeout = max(0, group.binding["work_deadline"] - time.monotonic()) if group is not None else args.deadline_s+ async with asyncio.timeout(timeout):await experiment(args, evidence, summary)except BaseException as error:summary["passed"] = False@@ -720,10 +766,12 @@ async def run(args: argparse.Namespace) -> dict[str, Any]:finally:atomic_json(evidence.directory / "trial.json", summary)evidence.emit("finished", passed=summary["passed"], shutdown_complete=summary["shutdown_complete"])+ if group is not None and summary["passed"] and summary["shutdown_complete"]:+ group.acknowledge(terminal_sha256=digest(evidence.directory / "trial.json"))return summary-def main() -> None:+def arguments(argv: list[str] | None = None) -> argparse.Namespace:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--source", type=Path, required=True)parser.add_argument("--fixtures", type=Path, required=True)@@ -733,12 +781,16 @@ def main() -> None:parser.add_argument("--pair", type=int, default=0)parser.add_argument("--deadline-s", type=float, default=MAX_TRIAL_SECONDS)parser.add_argument("--smoke", action="store_true")- args = parser.parse_args()+ args = parser.parse_args(argv)require(0 < args.deadline_s <= MAX_TRIAL_SECONDS,f"worker deadline must be in (0, {MAX_TRIAL_SECONDS}]",)- asyncio.run(run(args))+ return args+++def main() -> None:+ asyncio.run(run(arguments()))if __name__ == "__main__":