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): extend CrossEncoder qualification windows
svonava88c4053c3a9b
diff --git a/tools/benchmarks/cross_encoder_lora/README.md b/tools/benchmarks/cross_encoder_lora/README.mdindex eb0b40f3a..c46a0537c 100644--- a/tools/benchmarks/cross_encoder_lora/README.md+++ b/tools/benchmarks/cross_encoder_lora/README.md@@ -43,15 +43,21 @@ benchmark only inspects them and fails on a mismatch.```consolemise exec -- uv run --no-sync python -m tools.benchmarks.cross_encoder_lora.runner \--inputs /tmp/ce-sources --fixtures /tmp/ce-fixtures \- --output /tmp/ce-evidence --deadline-s 1740 --trial-deadline-s 120+ --output /tmp/ce-evidence --deadline-s 4200 --trial-deadline-s 270```Use a fresh output directory. Set the outer compute-session deadline beforelaunching, allowing bounded startup and cleanup. The runner owns and joins onlyits subprocesses; it cannot terminate an external GPU session. The operatormust stop that exact session and record cleanup. A failed or incomplete trial-stops the experiment and retains its evidence. Never change thresholds or drop-failed trials to obtain a pass.+stops the experiment and retains its evidence. Each new trial requires strictly+more than its 270-second limit plus 90 seconds for wait, termination and kill+grace (45/35/10). The proposed outer limits are 4,500 seconds for the operator+and 4,800 seconds from provider start, with a 300-second startup cutoff and an+additional absolute ceiling of application creation plus 5,100 seconds. The+operator must reserve export time before starting the runner; these settings+do not themselves authorize or allocate compute. Never change thresholds or+drop failed trials to obtain a pass, or retry the same failed protocol unchanged.## Frozen comparison@@ -61,11 +67,13 @@ N uses the candidate with no declared LoRA. R uses the candidate after A/Bactivity, with base selected and two adapters resident but disabled.Every arm uses the same password-reset query and four documents in `protocol.py`.-Each phase starts with 30 sequential warmup requests. C1 measures 200 sequential-requests; C4 and C16 each run a 12-second closed loop with one SDK client per+Each phase starts with 30 sequential warmup requests. C1 measures 2,000 sequential+requests; C4 and C16 each run a 60-second closed loop with one SDK client perlane. Throughput includes draining requests admitted before the deadline.Latencies use the nearest-rank p95. Neither warmup nor correctness calls enter-the primary statistics.+the primary statistics. Concurrent futures have a 120-second wait limit: the+60-second measurement, the existing 30-second request timeout, and 30 seconds+of scheduling margin. The worker and outer process limits still bound failures.All six metrics are required for **both** N/B and R/B: C1 mean and p95 latency,C4/C16 requests per second and p95 latency. The statistical unit is the six@@ -105,11 +113,13 @@ forward attribute lookup is restored: an original instance override is restoredexactly, or the temporary instance attribute is deleted to restore descriptorlookup. Production `score_pairs` and `set_active_lora` are bound directly.The harness checks the original forward target and that no observer activity-occurred, including restoration after an exceptional exit. Response-validation and header decoding happen after the phase clock stops; exactly one-successful HTTP response is required per warmup/measured SDK call, excluding-hidden retries. The timed client retains timer, result-list and raw-response-list-append overhead; this is an SDK workload measurement.+occurred, including restoration after an exceptional exit. Successful response+status and timing headers are captured as small metadata snapshots in the HTTP+observer, without retaining the successful HTTPX response. Error responses stay+available for deferred body and retry evidence. Validation happens after the+phase clock stops; exactly one successful HTTP response is required per+warmup/measured SDK call, excluding hidden retries. The timed client retains+timer, result-list and snapshot overhead; this is an SDK workload measurement.Actual timed C4/C16 batch shapes are **unknown**. Their raw four-score vectorsare compared diagnostically against complete preselection oracle vectors at@@ -132,11 +142,49 @@ live parameter allocation. The memory reference is captured after finitepreselection base and shape-oracle warmup, before any LoRA attachment, to keepone-time CUDA library initialization separate from adapter storage.-These observation changes are an explicit **preallocation protocol amendment**-to the original plan of observing every timed forward. All trial orders,-warmup/request counts, phase durations, numerical tolerances and statistical-gates remain unchanged. The original timed batch-attribution claim is withdrawn;-the observed untimed replays supply that evidence instead.+Removing timed forward observation was an earlier **preallocation protocol+amendment**. It preserved that version's trial order, workload and gates, and+withdrew its timed batch-attribution claim. Observed untimed replays supply that+evidence instead.++## Longer-window amendment++The original qualification used 200 C1 requests and 12-second C4/C16 phases.+Its failed full-run evidence and the failed baseline-only stability diagnostic+remain separate, with their original source and artifact hashes. Those outcomes+are not reinterpreted as passes. The diagnostic's longer warmup did not establish+stability, so qualification retains 30 sequential warmup requests.++The revised workload uses 2,000 C1 requests and 60-second concurrent phases to+observe longer intervals. The six balanced fresh-process triplets, checkpoint,+precision, dependencies, request payloads, numerical tolerances and all twelve+statistical gates stay fixed. Longer windows may reduce within-window sampling+variation; they do not guarantee comparability across fresh processes. There+are still only six independent paired units, not thousands of independent+latency samples for the t interval.++A model-free lifetime probe separately established that the old observer held+successful responses for the whole phase and kept its client alive through a+bound callback. Metadata snapshots and removal of the owned hook/history on+close address that benchmark-owned retention. Normal HTTPX response-stream and+SDK namespace cycles remain, with automatic GC enabled. This finding does not+identify the cause of earlier GPU timing variation. Snapshot capture adds timed+metadata work; its CPU cost must be recorded, without subtracting it from the+measurements or claiming zero overhead. Client and server still share a process,+so the result includes their normal GC and GIL interactions.++Freeze the reviewed source and operator bounds before one complete amended+18-process run. A separate baseline-readiness allocation is not required. Every+N/B and R/B gate and every correctness/lifecycle check must pass. If any fails,+retain all evidence and investigate before another method change; do not retry+unchanged, select favorable windows or pairs, waive N failures, or loosen gates.++The optional `stability` diagnostic keeps its original 200-request/12-second+windows and 90-second future wait through scoped settings that are restored on+success and failure. It records the current observer mode and worker source+hash. A new invocation uses this checkout's snapshot observer and is **not** a+byte-identical replay of the earlier diagnostic. Exact historical replay uses+commit `482b599224920a97bb2fce4a740317efb89351ab` and its original protocol.## Evidence and CPU checks@@ -145,6 +193,8 @@ gates 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-trialfiles instead of being copied into the growing summary. Final cross-processchecks reopen the complete records and verify their hashes and identities.+The runner records its monotonic start/deadline and every admission timestamp,+full cleanup reserve and remaining margin, including a refused admission.The summary also hashes the complete benchmark file manifest. Each trialcaptures the full installed-distribution manifest; its digest must remainidentical across arms. An optional `--environment-receipt` attaches a separatediff --git a/tools/benchmarks/cross_encoder_lora/protocol.py b/tools/benchmarks/cross_encoder_lora/protocol.pyindex 6a40f19bc..b1cd3b7f7 100644--- a/tools/benchmarks/cross_encoder_lora/protocol.py+++ b/tools/benchmarks/cross_encoder_lora/protocol.py@@ -1,4 +1,4 @@-"""Preregistered workload and paired non-inferiority gates (2026-10-16)."""+"""Pinned workload and paired gates; README records the longer-window amendment."""from __future__ import annotations@@ -25,13 +25,15 @@ EFFECT_FLOOR = 1e-5EFFECT_DRIFT_MULTIPLIER = 5ORDERS = ("BNR", "NRB", "RBN", "BRN", "RNB", "NBR")WARMUP = 30-SEQUENTIAL = 200-STEADY_SECONDS = 12+SEQUENTIAL = 2000+STEADY_SECONDS = 60CONCURRENCIES = (4, 16)THREADS = 4MAX_BATCH_ITEMS = 64-MAX_TRIAL_SECONDS = 300-MAX_EXPERIMENT_SECONDS = 3600+MAX_TRIAL_SECONDS = 270+MAX_EXPERIMENT_SECONDS = 4200+# Measured concurrent phase + request timeout + scheduling margin.+PERFORMANCE_FUTURE_TIMEOUT_S = 120EXPECTED_VERSIONS = {"torch": "2.9.1+cu129","transformers": "4.57.6",diff --git a/tools/benchmarks/cross_encoder_lora/runner.py b/tools/benchmarks/cross_encoder_lora/runner.pyindex bc8c078bb..bac07e12b 100644--- a/tools/benchmarks/cross_encoder_lora/runner.py+++ b/tools/benchmarks/cross_encoder_lora/runner.py@@ -193,9 +193,17 @@ def run(args: argparse.Namespace) -> dict[str, Any]:"smoke": args.smoke,"orders": ORDERS,"trials": [],+ "admissions": [],}summary_path = args.output / "summary.json"- absolute_deadline = time.monotonic() + args.deadline_s+ started = time.monotonic()+ absolute_deadline = started + args.deadline_s+ summary["runner_clock"] = {+ "monotonic_start_s": started,+ "wall_start_ns": time.time_ns(),+ "deadline_monotonic_s": absolute_deadline,+ "budget_s": args.deadline_s,+ }if args.environment_receipt is not None:summary["environment_preparation"] = {"sha256": digest(args.environment_receipt),@@ -204,15 +212,26 @@ def run(args: argparse.Namespace) -> dict[str, Any]:try:schedule = [(0, "R")] if args.smoke else [(pair, arm) for pair, order in enumerate(ORDERS) for arm in order]for pair, arm in schedule:- require(- time.monotonic()- + args.trial_deadline_s- + WAIT_GRACE_SECONDS- + TERMINATE_GRACE_SECONDS- + KILL_GRACE_SECONDS- < absolute_deadline,- "insufficient time for a complete bounded next trial and cleanup",+ admitted_at = time.monotonic()+ cleanup_deadline = (+ admitted_at + args.trial_deadline_s + WAIT_GRACE_SECONDS + TERMINATE_GRACE_SECONDS + KILL_GRACE_SECONDS+ )+ admitted = cleanup_deadline < absolute_deadline+ summary["admissions"].append(+ {+ "pair": pair,+ "arm": arm,+ "monotonic_s": admitted_at,+ "deadline_monotonic_s": absolute_deadline,+ "trial_limit_s": args.trial_deadline_s,+ "reserve_s": (+ args.trial_deadline_s + WAIT_GRACE_SECONDS + TERMINATE_GRACE_SECONDS + KILL_GRACE_SECONDS+ ),+ "margin_s": absolute_deadline - cleanup_deadline,+ "admitted": admitted,+ })+ require(admitted, "insufficient time for a complete bounded next trial and cleanup")directory = args.output / f"trial-{pair}-{arm}"source = (args.output / "sources" / ("B" if arm == "B" else "candidate")).resolve()command = [@@ -313,8 +332,8 @@ def main() -> None:help="Optional operator-owned JSON receipt of environment preparation (no secrets)",)parser.add_argument("--output", type=Path, required=True)- parser.add_argument("--deadline-s", type=float, default=2400)- parser.add_argument("--trial-deadline-s", type=float, default=120)+ parser.add_argument("--deadline-s", type=float, default=MAX_EXPERIMENT_SECONDS)+ parser.add_argument("--trial-deadline-s", type=float, default=MAX_TRIAL_SECONDS)parser.add_argument("--smoke", action="store_true")args = parser.parse_args()require(diff --git a/tools/benchmarks/cross_encoder_lora/stability.py b/tools/benchmarks/cross_encoder_lora/stability.pyindex a4d5f05c5..dc4bc1779 100644--- a/tools/benchmarks/cross_encoder_lora/stability.py+++ b/tools/benchmarks/cross_encoder_lora/stability.py@@ -2,9 +2,10 @@Run with --inputs, --fixtures and --output. Six fresh baseline processes eachexecute C1/C4/C16 with fixed S/L1/L2 windows: 30/200/200 sequential warmup-requests followed by the existing 200-request/12-second measurement. Later+requests followed by a fixed 200-request/12-second measurement. Laterwindow agreement is tested symmetrically; between-process dispersion remains-descriptive. The original timed methods and automatic GC behavior are reused.+descriptive. The current checkout's client observer and automatic GC are used;+exact historical replay requires the recorded original source commit."""# Only this checkout's Python worker runs; no shell or allocation.@@ -25,6 +26,8 @@ import statisticsimport subprocessimport sysimport time+from collections.abc import Iterator+from contextlib import contextmanagerfrom http import HTTPStatusfrom pathlib import Pathfrom typing import Any@@ -42,8 +45,6 @@ from tools.benchmarks.cross_encoder_lora.protocol import (MODEL,ORACLE_ATOL,RESTORE_ATOL,- SEQUENTIAL,- STEADY_SECONDS,THREADS,WEIGHTS_SHA256,paired_gate,@@ -64,6 +65,11 @@ from tools.benchmarks.cross_encoder_lora.runner import (PROCESSES = 6WINDOWS = (("S", 30), ("L1", 200), ("L2", 200))CONCURRENCIES = (1, 4, 16)+# Keep this diagnostic bounded independently of later qualification amendments.+SEQUENTIAL = 200+STEADY_SECONDS = 12+PERFORMANCE_FUTURE_TIMEOUT_S = 90+HISTORICAL_SOURCE_REVISION = "482b599224920a97bb2fce4a740317efb89351ab"METRICS = ((1, "mean_ms"), (1, "p95_ms"), (4, "rps"), (4, "p95_ms"), (16, "rps"), (16, "p95_ms"))RUNNER_LIMIT = 1200WORKER_LIMIT = 180@@ -87,6 +93,41 @@ class DiagnosticEvidence(Evidence):return super().emit(event, **fields)+def measurement_method() -> dict[str, Any]:+ return {+ "sequential_measured_requests": SEQUENTIAL,+ "concurrent_measured_seconds": STEADY_SECONDS,+ "future_wait_seconds": PERFORMANCE_FUTURE_TIMEOUT_S,+ "response_capture": getattr(worker, "RESPONSE_CAPTURE_MODE", "response-reference-retention"),+ "worker_source_sha256": digest(Path(worker.__file__)),+ "exact_historical_replay_commit": HISTORICAL_SOURCE_REVISION,+ "historical_byte_identity_claimed": False,+ }+++@contextmanager+def diagnostic_settings(warmups: int) -> Iterator[None]:+ """Pin the old workload without leaking settings into qualification calls."""+ values = {+ "WARMUP": warmups,+ "SEQUENTIAL": SEQUENTIAL,+ "STEADY_SECONDS": STEADY_SECONDS,+ "PERFORMANCE_FUTURE_TIMEOUT_S": PERFORMANCE_FUTURE_TIMEOUT_S,+ }+ missing = object()+ original = {name: getattr(worker, name, missing) for name in values}+ try:+ for name, value in values.items():+ setattr(worker, name, value)+ yield+ finally:+ for name, value in original.items():+ if value is missing:+ delattr(worker, name)+ else:+ setattr(worker, name, value)++def unified_cgroup(proc: Path = Path("/proc/self")) -> dict[str, Any]:"""Resolve the process's own namespace; never fall back to another cgroup."""try:@@ -406,18 +447,15 @@ def measure_window("concurrency": concurrency,"warmups": 2 if smoke else warmups,"smoke": smoke,+ "measurement_method": measurement_method(),}- original_warmups = worker.WARMUPtry:record["gpu_before"] = worker.telemetry()record["telemetry_before"] = snapshot()if continuity is not None:telemetry_delta(continuity, record["telemetry_before"])- worker.WARMUP = warmups # ty: ignore[invalid-assignment] -- scoped diagnostic value, always restored- try:+ with diagnostic_settings(warmups):measured = worker.performance(url, concurrency, evidence, smoke=smoke)- finally:- worker.WARMUP = original_warmupsrecord["telemetry_after"] = snapshot()record["gpu_after"] = worker.telemetry()record["telemetry_delta"] = telemetry_delta(record["telemetry_before"], record["telemetry_after"])@@ -439,7 +477,6 @@ def measure_window(record["error"] = worker.error_record(error)raisefinally:- worker.WARMUP = original_warmupsatomic_json(directory / "window.json", record)return {"qualification": False,@@ -579,6 +616,7 @@ async def child(args: argparse.Namespace) -> dict[str, Any]:"pid": os.getpid(),"source_commit": BASE_REVISION,"smoke": args.smoke,+ "measurement_method": measurement_method(),}os.environ.update({@@ -811,6 +849,7 @@ def run(args: argparse.Namespace) -> dict[str, Any]:"budget_s": args.deadline_s,}summary["methods"] = {+ **measurement_method(),"window_order": [{"name": name, "sequential_warmup_calls": count} for name, count in WINDOWS],"phase_order": list(CONCURRENCIES),"fresh_baseline_processes": PROCESSES,diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_runner_budget.py b/tools/benchmarks/cross_encoder_lora/tests/test_runner_budget.pyindex f755de8e1..f0ec56ca1 100644--- a/tools/benchmarks/cross_encoder_lora/tests/test_runner_budget.py+++ b/tools/benchmarks/cross_encoder_lora/tests/test_runner_budget.py@@ -6,6 +6,7 @@ import argparseimport jsonimport signalimport subprocess+import sysfrom pathlib import Pathfrom typing import Any@@ -14,7 +15,7 @@ import pytestfrom tools.benchmarks.cross_encoder_lora import runner-def arguments(tmp_path: Path, budget: float) -> argparse.Namespace:+def arguments(tmp_path: Path, budget: float, trial_limit: float = 120) -> argparse.Namespace:return argparse.Namespace(output=tmp_path / "evidence",inputs=tmp_path / "inputs",@@ -23,7 +24,7 @@ def arguments(tmp_path: Path, budget: float) -> argparse.Namespace:smoke=True,environment_receipt=None,deadline_s=budget,- trial_deadline_s=120,+ trial_deadline_s=trial_limit,)@@ -32,11 +33,13 @@ def setup_sources(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(runner, "harness_manifest", dict)[email protected](("budget", "admitted"), [(209.999, False), (210.0, False), (210.001, True)])[email protected]("trial_limit", [120, 270])[email protected](("margin", "admitted"), [(-0.001, False), (0.0, False), (0.001, True)])def test_trial_admission_reserves_full_cleanup(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,- budget: float,+ trial_limit: float,+ margin: float,admitted: bool,) -> None:setup_sources(monkeypatch)@@ -64,10 +67,10 @@ def test_trial_admission_reserves_full_cleanup(return CompletedProcess()monkeypatch.setattr(runner.subprocess, "Popen", start)- args = arguments(tmp_path, budget)+ args = arguments(tmp_path, trial_limit + 90 + margin, trial_limit)if admitted:assert runner.run(args)["passed"]- assert waits == [165]+ assert waits == [trial_limit + 45]else:with pytest.raises(AssertionError, match="insufficient time"):runner.run(args)@@ -75,11 +78,25 @@ def test_trial_admission_reserves_full_cleanup(assert not terminal["passed"]assert terminal["trials"] == []assert bool(started) is admitted--+ terminal = json.loads((args.output / "summary.json").read_text())+ assert terminal["runner_clock"]["monotonic_start_s"] == 100+ assert terminal["runner_clock"]["budget_s"] == args.deadline_s+ assert terminal["runner_clock"]["deadline_monotonic_s"] == 100 + args.deadline_s+ assert terminal["runner_clock"]["wall_start_ns"] > 0+ assert len(terminal["admissions"]) == 1+ admission = terminal["admissions"][0]+ assert (admission["pair"], admission["arm"], admission["monotonic_s"]) == (0, "R", 100)+ assert admission["trial_limit_s"] == trial_limit+ assert admission["reserve_s"] == trial_limit + 90+ assert admission["margin_s"] == pytest.approx(margin, abs=1e-9)+ assert admission["admitted"] is admitted++[email protected]("trial_limit", [120, 270])def test_full_timeout_cleanup_finishes_before_budget_and_retains_partial_trial(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,+ trial_limit: float,) -> None:setup_sources(monkeypatch)clock = [100.0]@@ -123,15 +140,43 @@ def test_full_timeout_cleanup_finishes_before_budget_and_retains_partial_trial(return HungProcess()monkeypatch.setattr(runner.subprocess, "Popen", start)- args = arguments(tmp_path, 211)+ args = arguments(tmp_path, trial_limit + 91, trial_limit)with pytest.raises(subprocess.TimeoutExpired):runner.run(args)- assert actions == [("wait", 165), ("signal", signal.SIGTERM), ("wait", 35), ("kill", None), ("wait", 10)]- assert clock[0] == 310+ assert actions == [+ ("wait", trial_limit + 45),+ ("signal", signal.SIGTERM),+ ("wait", 35),+ ("kill", None),+ ("wait", 10),+ ]+ assert clock[0] == 100 + trial_limit + 90assert clock[0] < 100 + args.deadline_sterminal = json.loads((args.output / "summary.json").read_text())assert not terminal["passed"]+ assert terminal["admissions"][0]["margin_s"] == 1+ assert terminal["admissions"][0]["admitted"]trial = terminal["trials"][0]assert trial["performance"]["1"]["count"] == 7assert trial["process_returncode"] == -9assert trial["runner_error"]["type"] == "TimeoutExpired"+++def test_default_cli_budget_matches_longer_qualification(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(sys, "argv", ["runner", "--inputs", "i", "--fixtures", "f", "--output", "o"])+ monkeypatch.setattr(runner.signal, "signal", lambda *_: None)+ captured = []+ monkeypatch.setattr(runner, "run", captured.append)+ runner.main()+ assert len(captured) == 1+ assert (captured[0].deadline_s, captured[0].trial_deadline_s) == (4200, 270)++[email protected](("flag", "value"), [("--deadline-s", "4200.001"), ("--trial-deadline-s", "270.001")])+def test_cli_rejects_limits_above_frozen_bounds(monkeypatch: pytest.MonkeyPatch, flag: str, value: str) -> None:+ monkeypatch.setattr(sys, "argv", ["runner", "--inputs", "i", "--fixtures", "f", "--output", "o", flag, value])+ started = []+ monkeypatch.setattr(runner, "run", started.append)+ with pytest.raises(AssertionError, match="deadline outside bounded protocol"):+ runner.main()+ assert not starteddiff --git a/tools/benchmarks/cross_encoder_lora/tests/test_stability.py b/tools/benchmarks/cross_encoder_lora/tests/test_stability.pyindex dc16e939b..c7230fc93 100644--- a/tools/benchmarks/cross_encoder_lora/tests/test_stability.py+++ b/tools/benchmarks/cross_encoder_lora/tests/test_stability.py@@ -20,7 +20,7 @@ from tools.benchmarks.cross_encoder_lora import stability as probefrom tools.benchmarks.cross_encoder_lora import workerfrom tools.benchmarks.cross_encoder_lora.evidence import digest, fingerprintfrom tools.benchmarks.cross_encoder_lora.fixtures import prepare-from tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISION, SEQUENTIAL+from tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISIONfrom tools.benchmarks.cross_encoder_lora.runner import ROOT, extract, source_environmentfrom tools.benchmarks.cross_encoder_lora.tests.test_probe import tiny_snapshot@@ -225,8 +225,8 @@ def response(label: str, index: int) -> dict[str, Any]:def stub_performance(_url: str, concurrency: int, evidence: probe.DiagnosticEvidence, *, smoke: bool) -> dict[str, Any]:warmups = [response(f"warm-{i}", i) for i in range(2 if smoke else worker.WARMUP)]- samples = [response(f"sample-{i}", i) for i in range(4 if smoke else SEQUENTIAL)]- elapsed = 0.2 if smoke else 12.0+ samples = [response(f"sample-{i}", i) for i in range(4 if smoke else worker.SEQUENTIAL)]+ elapsed = 0.2 if smoke else float(worker.STEADY_SECONDS)evidence.emit("performance_attempt",concurrency=concurrency,@@ -252,18 +252,28 @@ def install_stub(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(worker, "performance", stub_performance)-def test_raw_retention_reopen_and_warmup_restoration(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+def current_workload() -> tuple[Any, ...]:+ return tuple(+ getattr(worker, name, None)+ for name in ("WARMUP", "SEQUENTIAL", "STEADY_SECONDS", "PERFORMANCE_FUTURE_TIMEOUT_S")+ )+++def test_raw_retention_reopen_and_workload_restoration(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:install_stub(monkeypatch)- original = worker.WARMUP+ monkeypatch.setattr(worker, "PERFORMANCE_FUTURE_TIMEOUT_S", 120, raising=False)+ original = current_workload()continuity = observed(0)continuity["core"]["wall_ns"] = continuity["core"]["monotonic_ns"] = 1oracles = {"shape": {"copies": 1, "scores": [[4.0, 3.0, 2.0, 1.0][index] for index in worker.ORDER]}}compact = probe.measure_window("unused", 1, "L1", 200, tmp_path / "C1/L1", [4.0, 3.0, 2.0, 1.0], oracles, smoke=False, continuity=continuity)- assert original == worker.WARMUP+ assert original == current_workload()raw = probe.reopen_window(tmp_path, compact)assert len(raw["performance"]["samples"]) == 200+ assert raw["measurement_method"]["concurrent_measured_seconds"] == 12+ assert raw["measurement_method"]["future_wait_seconds"] == 90assert len(raw["chronological_quartiles"]) == 4assert continuity == raw["telemetry_after"]assert all(row["diagnostic_matching_oracle"]["workload_sha256"] == "shape" for row in raw["performance"]["samples"])@@ -280,12 +290,13 @@ def test_raw_retention_reopen_and_warmup_restoration(tmp_path: Path, monkeypatchprobe.reopen_window(tmp_path, compact)-def test_failed_window_keeps_partial_raw_and_restores_warmup(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+def test_failed_window_keeps_partial_raw_and_restores_workload(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:install_stub(monkeypatch)- original = worker.WARMUP+ monkeypatch.setattr(worker, "PERFORMANCE_FUTURE_TIMEOUT_S", 120, raising=False)+ original = current_workload()def failed(_url: str, _concurrency: int, evidence: probe.DiagnosticEvidence, *, smoke: bool) -> None:- assert worker.WARMUP == 200+ assert current_workload() == (200, 200, 12, 90)assert not smokeevidence.emit("performance_attempt", completed_samples=[{"error": "retained"}])raise RuntimeError("request failed")@@ -293,7 +304,7 @@ def test_failed_window_keeps_partial_raw_and_restores_warmup(tmp_path: Path, monmonkeypatch.setattr(worker, "performance", failed)with pytest.raises(RuntimeError, match="request failed"):probe.measure_window("unused", 1, "L2", 200, tmp_path / "C1/L2", [4.0, 3.0, 2.0, 1.0], {}, smoke=False)- assert original == worker.WARMUP+ assert original == current_workload()terminal = json.loads((tmp_path / "C1/L2/window.json").read_text())assert not terminal["qualification"]assert not terminal["completed"]@@ -301,6 +312,22 @@ def test_failed_window_keeps_partial_raw_and_restores_warmup(tmp_path: Path, monassert json.loads((tmp_path / "C1/L2/events.jsonl").read_text())["completed_samples"] == [{"error": "retained"}]+def test_diagnostic_settings_restore_absent_attribute(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delattr(worker, "PERFORMANCE_FUTURE_TIMEOUT_S", raising=False)+ with probe.diagnostic_settings(30):+ assert current_workload() == (30, 200, 12, 90)+ assert not hasattr(worker, "PERFORMANCE_FUTURE_TIMEOUT_S")+++def test_diagnostic_records_current_observer_and_exact_historical_source(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(worker, "RESPONSE_CAPTURE_MODE", "success-status-header-snapshots", raising=False)+ method = probe.measurement_method()+ assert method["response_capture"] == "success-status-header-snapshots"+ assert method["worker_source_sha256"] == digest(Path(worker.__file__))+ assert method["exact_historical_replay_commit"] == "482b599224920a97bb2fce4a740317efb89351ab"+ assert not method["historical_byte_identity_claimed"]++def test_full_cleanup_budget_is_strict() -> None:assert probe.admission(1, 272, 180)["reserve_s"] == 270with pytest.raises(AssertionError, match="insufficient"):@@ -320,7 +347,7 @@ def test_negative_raw_latency_cannot_hide_in_positive_aggregates() -> None:probe.metrics(phase)-def test_shared_timed_code_and_gc_are_unmodified() -> None:+def test_serving_observer_timed_loop_and_gc_are_unmodified() -> None:baseline = subprocess.run(["git", "show", "f06f414a:tools/benchmarks/cross_encoder_lora/worker.py"], # noqa: S607cwd=ROOT,@@ -330,11 +357,44 @@ def test_shared_timed_code_and_gc_are_unmodified() -> None:)if baseline.returncode:pytest.skip("timed-code invariant control requires its documented parent commit in git history")- names = {"performance", "Client", "unobserved"}+ # The Client capture lifecycle is intentionally amended. Preserve the+ # production observation boundary and actual timed loop, allowing only+ # the named wait limit that gained scheduling headroom for the longer run.+ names = {"performance", "unobserved"}++ class TimedCore(ast.NodeTransformer):+ def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:+ if node.name == "performance":+ timed = next(value for value in node.body if isinstance(value, ast.Try))+ end = next(+ index+ for index, value in enumerate(timed.body)+ if isinstance(value, ast.Assign)+ and any(isinstance(target, ast.Name) and target.id == "elapsed" for target in value.targets)+ )+ timed.body = timed.body[: end + 1]+ timed.finalbody = []+ self.generic_visit(node)+ return node++ def visit_Call(self, node: ast.Call) -> ast.Call:+ if (+ isinstance(node.func, ast.Attribute)+ and node.func.attr == "result"+ and isinstance(node.func.value, ast.Name)+ and node.func.value.id == "future"+ ):+ timeout = next(value for value in node.keywords if value.arg == "timeout")+ assert (isinstance(timeout.value, ast.Constant) and timeout.value.value == 90) or (+ isinstance(timeout.value, ast.Name) and timeout.value.id == "PERFORMANCE_FUTURE_TIMEOUT_S"+ )+ timeout.value = ast.Constant(value=90)+ self.generic_visit(node)+ return nodedef code(text: str) -> dict[str, str]:return {- node.name: ast.dump(node)+ node.name: ast.dump(TimedCore().visit(node))for node in ast.parse(text).bodyif isinstance(node, (ast.FunctionDef, ast.ClassDef)) and node.name in names}