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: observe cross-encoder GC only at phase boundaries
svonava4eb6a0daae90
diff --git a/tools/benchmarks/cross_encoder_lora/README.md b/tools/benchmarks/cross_encoder_lora/README.mdindex 87392d700..e2ae7b911 100644--- a/tools/benchmarks/cross_encoder_lora/README.md+++ b/tools/benchmarks/cross_encoder_lora/README.md@@ -43,7 +43,7 @@ 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 4200 --trial-deadline-s 270+ --output /tmp/ce-evidence --deadline-s 3900 --trial-deadline-s 270```Use a fresh output directory. Set the outer compute-session deadline before@@ -55,8 +55,11 @@ more than its 270-second limit plus 90 seconds for wait, termination and killgrace (45/35/10). The proposed outer limits are 4,500 seconds for the operatorand 4,800 seconds from provider start, with a 300-second startup cutoff and anadditional 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+operator reserves 300 seconds for export and requires strictly more than 4,255+seconds remaining before starting the 3,900-second runner (plus 45 seconds wait+and 10 seconds cleanup). The public runner's 4,200-second ceiling remains+available, but is not this operator preset. These settings do not themselves+authorize or allocate compute. Never change thresholds ordrop failed trials to obtain a pass, or retry the same failed protocol unchanged.## Frozen comparison@@ -215,24 +218,42 @@ created. Cancellation, malformed protocol and child errors fail the trial andtrigger bounded termination/reaping. SIGKILL or immediate parent-death exit canlose the interrupted phase; prior completed atomic phase files remain evidence.-Each PID records preallocated numeric GC events and self-duration. The combined-server-plus-client estimated callback cost must be at most **0.1%** of each-measured interval, including a fixed 10-microsecond allowance per intersecting-callback. A bounded local calibration must be retained before hardware use;-it checks the allowance rather than changing it after outcomes. This estimate-cannot prove zero scheduling or GC perturbation. Overflow, missing event pairs,-clock contradictions, callback-list changes or the cost limit fail qualification.-Run the public local calibration once from the frozen checkout and retain its-full JSON, including failures and outliers:+### Boundary-only observation amendment++The first isolated run at `250bd9a91c8f465aafe69de94aee98aad6ac3298` completed+the first baseline trial's three SDK phases, then failed its prospective+combined GC-callback cost limit. Its C16 estimate was **0.183546%** against+**0.1%**: measured inner callback self-time contributed **0.055258%** and the+fixed 10-microsecond allowance contributed **0.128287%**. That failed run remains+failed; no candidate trials or paired performance gates were qualified. The+allowance was not reduced after observing the result.++The qualification harness now adds **no per-event GC callbacks** in either+PID; pre-existing callbacks are preserved. Outside-clock snapshots retain normal GC enable state, thresholds,+collection counters and ordered callback identities. The original callback+objects stay referenced through both boundaries, and changes to their identities+or GC configuration fail the phase. These checks cannot detect an intervening+change undone before the next snapshot. No automatic collection is disabled,+and no forced collection is added during timing.++Actual GC pause intervals and callback self-time/cost are explicitly **unavailable**+(`null`), not measured zero; the absent observer's cost gate is `not_applicable`,+not passed. Boundary snapshots still have overhead outside the request clocks;+this is not a zero-overhead claim. The SDK process separation, workload,+statistical gates, numerical and memory limits, wire checks and process cleanup+remain unchanged. The historical recorder and calibration remain standalone+diagnostics and are not prerequisites for a run that does not install callbacks.+To run that optional diagnostic from a frozen checkout, retain its full JSON,+including failures and outliers:```consolemise exec -- uv run --no-sync python -m tools.benchmarks.cross_encoder_lora.calibrate_gc --output /tmp/ce-gc-calibration.json```-It estimates local mean cost, not worst-case event cost or another host's cost.-Short CPU smoke applies integrity checks but does not qualify performance or-apply a meaningful wall-time cost budget. No automatic collection is disabled,-and no forced collection is added during timing.+It estimates local mean callback cost, not worst-case event cost or another+host's cost. Exact replay of the instrumented method requires its recorded+`250bd9a9` checkout. Short CPU smoke checks evidence integrity but does not+qualify performance.CPU/context-switch/cgroup snapshots bracket the actual shared monotonic interval;they include boundary work and are not exact request-level or GPU-only timers.diff --git a/tools/benchmarks/cross_encoder_lora/isolation.py b/tools/benchmarks/cross_encoder_lora/isolation.pyindex 3524b7270..4cadc6031 100644--- a/tools/benchmarks/cross_encoder_lora/isolation.py+++ b/tools/benchmarks/cross_encoder_lora/isolation.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import gcimport jsonimport mathimport os@@ -15,7 +16,12 @@ from typing import Any, Selffrom tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digestfrom tools.benchmarks.cross_encoder_lora.loadgen import CONTROL_LIMIT, CONTROL_TIMEOUT_S, PHASES-from tools.benchmarks.cross_encoder_lora.process_metrics import MAX_CALLBACK_FRACTION, GCRecorder, bracket, snapshot+from tools.benchmarks.cross_encoder_lora.process_metrics import (+ boundary_gc_report,+ bracket,+ snapshot,+ validate_boundary_gc,+)from tools.benchmarks.cross_encoder_lora.protocol import PERFORMANCE_FUTURE_TIMEOUT_S, require@@ -115,12 +121,11 @@ class IsolatedLoadgen:len(self.records) < len(PHASES) and concurrency == PHASES[len(self.records)],"duplicate or reordered measured phase",)- monitor = GCRecorder()observation: dict[str, Any] = {"server_pid": os.getpid(), "client_identity": self.receipt["identity"]}try:await self._send("phase", concurrency)await self._read("ready", concurrency)- monitor.start()+ callbacks = tuple(gc.callbacks)observation["before"] = snapshot()await self._send("go", concurrency)measured = await self._read("measured", concurrency, wait_s=PERFORMANCE_FUTURE_TIMEOUT_S)@@ -135,8 +140,7 @@ class IsolatedLoadgen:)observation["clock"] = clockobservation["after"] = snapshot()- monitor.close()- observation["gc"] = monitor.report(clock["start"], clock["end"])+ observation["gc"] = boundary_gc_report(observation["before"], observation["after"], callbacks)observation["resources"] = bracket(observation["before"], observation["after"], clock)await self._send("observed", concurrency)complete = await self._read("phase_complete", concurrency)@@ -159,7 +163,6 @@ class IsolatedLoadgen:)return recordfinally:- monitor.close()primary_error = sys.exception()try:atomic_json(self.evidence.directory / f"server-C{concurrency}-observations.json", observation)@@ -279,24 +282,11 @@ class IsolatedLoadgen:require(client["gc"]["pid"] == identity["pid"], "client GC observation PID differs")require(server["gc"]["pid"] == os.getpid(), "server GC observation PID differs")for observation in (client, server):- gc_report = observation["gc"]- require(- gc_report["window_start_ns"] == round(server["clock"]["start"] * 1e9)- and gc_report["window_end_ns"] == round(server["clock"]["end"] * 1e9),- "GC observation window differs",- )- require(gc_report["integrity_passed"] is True, "GC observer integrity gate failed")- cost = gc_report["estimated_observer_fraction"]- require(type(cost) in (int, float) and math.isfinite(cost) and cost >= 0, "invalid observer cost")- combined = server["gc"]["estimated_observer_fraction"] + client["gc"]["estimated_observer_fraction"]- # Tiny CPU smoke has no performance qualification. It still must prove- # evidence integrity; the unchanged prospective cost gate is mandatory- # for every real measurement window on the qualifying allocation.- if not self.smoke:- require(combined <= MAX_CALLBACK_FRACTION, "combined observer cost gate failed")+ validate_boundary_gc(observation)value["server_observation"] = server- value["combined_estimated_observer_fraction"] = combined- value["observer_cost_gate_applied"] = not self.smoke+ value["combined_estimated_observer_fraction"] = None+ value["observer_cost_gate_applied"] = False+ value["observer_cost_gate_status"] = "not_applicable"return valuedef results(self) -> dict[str, dict[str, Any]]:diff --git a/tools/benchmarks/cross_encoder_lora/loadgen.py b/tools/benchmarks/cross_encoder_lora/loadgen.pyindex eb1fdae7a..f1fb26dd8 100644--- a/tools/benchmarks/cross_encoder_lora/loadgen.py+++ b/tools/benchmarks/cross_encoder_lora/loadgen.py@@ -3,6 +3,7 @@from __future__ import annotationsimport argparse+import gcimport inspectimport jsonimport os@@ -19,7 +20,12 @@ from sie_sdk import SIEClientfrom tools.benchmarks.cross_encoder_lora.client import performancefrom tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digest-from tools.benchmarks.cross_encoder_lora.process_metrics import GCRecorder, bracket, snapshot+from tools.benchmarks.cross_encoder_lora.process_metrics import (+ boundary_gc_report,+ bracket,+ snapshot,+ validate_boundary_gc,+)from tools.benchmarks.cross_encoder_lora.protocol import requireCONTROL_LIMIT = 65_536@@ -133,11 +139,12 @@ def run(args: argparse.Namespace) -> None:for concurrency in PHASES:control.receive("phase", concurrency)require_sdk_only()- monitor = GCRecorder()- monitor.start()+ callbacks: tuple[Any, ...] = ()observations: dict[str, Any] = {}def before_measure() -> None:+ nonlocal callbacks+ callbacks = tuple(gc.callbacks)observations["before"] = snapshot()control.send("ready", concurrency)control.receive("go", concurrency)@@ -145,7 +152,7 @@ def run(args: argparse.Namespace) -> None:def after_measure(clock: dict[str, float]) -> None:observations["clock"] = clockobservations["after"] = snapshot()- monitor.close()+ observations["gc"] = boundary_gc_report(observations["before"], observations["after"], callbacks)control.send("measured", concurrency, clock=clock)control.receive("observed", concurrency)@@ -159,15 +166,16 @@ def run(args: argparse.Namespace) -> None:after_measure=after_measure,)finally:- monitor.close()- if "clock" in observations:- observations["gc"] = monitor.report(observations["clock"]["start"], observations["clock"]["end"])- atomic_json(evidence.directory / f"phase-C{concurrency}-observations.json", observations)- require(observations["gc"]["integrity_passed"], "client GC observation integrity failed")- if not args.smoke:- require(- observations["gc"]["cost_budget_passed"], "client GC observation exceeded its prospective cost gate"- )+ primary_error = sys.exception()+ try:+ atomic_json(evidence.directory / f"phase-C{concurrency}-observations.json", observations)+ except BaseException as write_error:+ if primary_error is None:+ raise+ primary_error.add_note(+ f"Secondary client observation write failure: {type(write_error).__name__}: {write_error}"+ )+ validate_boundary_gc(observations)observations["resources"] = bracket(observations["before"], observations["after"], result["measurement_clock"])diff --git a/tools/benchmarks/cross_encoder_lora/process_metrics.py b/tools/benchmarks/cross_encoder_lora/process_metrics.pyindex 2cde82443..ee19fe7fb 100644--- a/tools/benchmarks/cross_encoder_lora/process_metrics.py+++ b/tools/benchmarks/cross_encoder_lora/process_metrics.py@@ -137,6 +137,7 @@ def snapshot() -> dict[str, Any]:"rusage": {key: getattr(usage, key) for key in RUSAGE_FIELDS},"gc_enabled": gc.isenabled(),"gc_thresholds": list(gc.get_threshold()),+ "gc_callback_ids": [id(callback) for callback in gc.callbacks],"gc_count": list(gc.get_count()),"gc_stats": gc.get_stats(),}@@ -244,7 +245,72 @@ def telemetry_delta(before: dict[str, Any], after: dict[str, Any]) -> dict[str,}-# Prospective observation limits, independent of the performance gates.+def _boundary_gc_projection(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:+ first, last = before["core"], after["core"]+ errors = []+ for core in (first, last):+ require(+ isinstance(core["gc_callback_ids"], list)+ and all(type(value) is int and value > 0 for value in core["gc_callback_ids"]),+ "invalid boundary GC callback identities",+ )+ require(+ len(core["gc_thresholds"]) == GC_GENERATIONS+ and all(type(value) is int and value >= 0 for value in core["gc_thresholds"]),+ "invalid boundary GC thresholds",+ )+ if first["pid"] != last["pid"]:+ errors.append("GC boundary process identity changed")+ if first["gc_callback_ids"] != last["gc_callback_ids"]:+ errors.append("pre-existing GC callback identities changed")+ if first["gc_enabled"] is not True or last["gc_enabled"] is not True:+ errors.append("ordinary automatic GC must remain enabled")+ if first["gc_thresholds"] != last["gc_thresholds"] or first["gc_thresholds"][0] <= 0:+ errors.append("GC thresholds changed or disabled automatic collection")+ return {+ "mode": "boundary-only",+ "pid": first["pid"],+ "scope": "Boundary state only; intervening changes and GC pauses are unobserved.",+ "integrity_passed": not errors,+ "errors": errors,+ "records": None,+ "intervals": None,+ "callback_self_ns": None,+ "estimated_observer_fraction": None,+ "cost_budget_passed": None,+ "unavailable_reason": "No per-event GC callbacks are installed by the qualification harness.",+ }+++def boundary_gc_report(before: dict[str, Any], after: dict[str, Any], callbacks: tuple[Any, ...]) -> dict[str, Any]:+ """Check outside-clock state without installing callbacks or changing GC.++ Holding the original objects through both snapshots prevents identity reuse.+ This cannot observe an intervening change that is undone before the boundary.+ """+ result = _boundary_gc_projection(before, after)+ if (+ before["core"]["gc_callback_ids"] != [id(callback) for callback in callbacks]+ or len(gc.callbacks) != len(callbacks)+ or any(current is not prior for current, prior in zip(gc.callbacks, callbacks, strict=False))+ ):+ result["errors"].append("retained GC callback identity differs at a boundary")+ result["integrity_passed"] = False+ return result+++def validate_boundary_gc(observation: dict[str, Any]) -> None:+ """Reject measured-event claims or contradictory raw boundary evidence."""+ expected = _boundary_gc_projection(observation["before"], observation["after"])+ require(+ expected["integrity_passed"] is True+ and observation["gc"]["integrity_passed"] is True+ and observation["gc"] == expected,+ "boundary-only GC state or unavailable observation fields differ",+ )+++# Historical per-event diagnostic limits; qualification does not install this recorder.MAX_CALLBACK_FRACTION = 0.001CALLBACK_TAIL_ALLOWANCE_NS = 10_000GC_RECORD_CAPACITY = 65_536@@ -391,7 +457,7 @@ class GCRecorder:def bracket(before: dict[str, Any], after: dict[str, Any], clock: dict[str, float]) -> dict[str, Any]:- """Attribute exact GC intervals separately from enclosing CPU/cgroup deltas."""+ """Keep enclosing GC/CPU/cgroup deltas distinct from request-level timing."""require(before["core"]["pid"] == after["core"]["pid"], "process identity changed")begin, end = clock["start"], clock["end"]require(diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_isolation.py b/tools/benchmarks/cross_encoder_lora/tests/test_isolation.pyindex 05fb7311e..1afdbc43b 100644--- a/tools/benchmarks/cross_encoder_lora/tests/test_isolation.py+++ b/tools/benchmarks/cross_encoder_lora/tests/test_isolation.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport astimport asyncioimport copy+import gcimport jsonimport osimport subprocess@@ -18,6 +19,7 @@ from typing import Any, castimport pytestfrom sie_sdk._msgpack import packb, unpackb+from tools.benchmarks.cross_encoder_lora import isolation, loadgen, process_metricsfrom tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digestfrom tools.benchmarks.cross_encoder_lora.isolation import IsolatedLoadgenfrom tools.benchmarks.cross_encoder_lora.loadgen import PHASES@@ -67,7 +69,32 @@ def sdk_server(monkeypatch: pytest.MonkeyPatch) -> Iterator[str]:@pytest.mark.asyncio-async def test_one_sdk_only_exec_pid_reused_across_all_phases_and_reaped(sdk_server: str, tmp_path: Path) -> None:+async def test_one_sdk_only_exec_pid_reused_across_all_phases_and_reaped(+ sdk_server: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ def forbidden(*_args: Any, **_kwargs: Any) -> None:+ raise AssertionError("qualification must not construct a GCRecorder")++ # Exercise both real qualification paths with the historical recorder+ # constructor made fatal. The SDK-only exec still uses its ordinary CLI.+ monkeypatch.setattr(isolation, "GCRecorder", forbidden, raising=False)+ monkeypatch.setattr(process_metrics, "GCRecorder", forbidden)+ original_exec = asyncio.create_subprocess_exec++ async def guarded_exec(*args: Any, **kwargs: Any) -> asyncio.subprocess.Process:+ assert args[1:3] == ("-m", "tools.benchmarks.cross_encoder_lora.loadgen")+ bootstrap = (+ "from tools.benchmarks.cross_encoder_lora import process_metrics, loadgen\n"+ "def forbidden(*args, **kwargs):\n"+ " raise AssertionError('qualification must not construct a GCRecorder')\n"+ "process_metrics.GCRecorder = forbidden\n"+ "loadgen.GCRecorder = forbidden\n"+ "loadgen.main()\n"+ )+ return await original_exec(args[0], "-c", bootstrap, *args[3:], **kwargs)++ monkeypatch.setattr(asyncio, "create_subprocess_exec", guarded_exec)+ callbacks, thresholds = tuple(gc.callbacks), gc.get_threshold()evidence = Evidence(tmp_path / "out")async with IsolatedLoadgen(sdk_server, ROOT, evidence, smoke=True) as owner:assert owner.process is not None@@ -94,8 +121,21 @@ async def test_one_sdk_only_exec_pid_reused_across_all_phases_and_reaped(sdk_serassert phase["client_observation"]["gc"]["integrity_passed"]assert phase["server_observation"]["gc"]["integrity_passed"]assert phase["measurement_clock"] == phase["server_observation"]["clock"]- assert phase["observer_cost_gate_applied"] is False # CPU smoke never qualifies performance.+ assert phase["combined_estimated_observer_fraction"] is None+ assert phase["observer_cost_gate_applied"] is False+ assert phase["observer_cost_gate_status"] == "not_applicable"+ for observation in (phase["client_observation"], phase["server_observation"]):+ assert observation["gc"]["mode"] == "boundary-only"+ assert observation["gc"]["records"] is None+ assert observation["gc"]["intervals"] is None+ assert observation["gc"]["callback_self_ns"] is None+ assert observation["gc"]["estimated_observer_fraction"] is None+ assert observation["gc"]["cost_budget_passed"] is Noneassert all(len(row["responses"]) == 1 for row in phase["samples"])+ assert len(gc.callbacks) == len(callbacks)+ assert all(current is prior for current, prior in zip(gc.callbacks, callbacks, strict=True))+ assert gc.isenabled()+ assert gc.get_threshold() == thresholdsterminal = json.loads((evidence.directory / "loadgen/terminal.json").read_text())assert terminal["phases"] == owner.recordswith pytest.raises(ProcessLookupError):@@ -109,18 +149,13 @@ def synthetic_owner(tmp_path: Path) -> tuple[IsolatedLoadgen, dict[str, Any], diclock = {"start": 1.0, "deadline": 61.0, "end": 61.1}def observation(pid: int) -> dict[str, Any]:- return {- "before": {"core": {"pid": pid}},- "after": {"core": {"pid": pid}},+ value = {+ "before": {"core": {"pid": pid, "gc_enabled": True, "gc_thresholds": [700, 10, 10], "gc_callback_ids": []}},+ "after": {"core": {"pid": pid, "gc_enabled": True, "gc_thresholds": [700, 10, 10], "gc_callback_ids": []}},"clock": clock,- "gc": {- "pid": pid,- "integrity_passed": True,- "window_start_ns": 1_000_000_000,- "window_end_ns": 61_100_000_000,- "estimated_observer_fraction": 0.0001,- },}+ value["gc"] = process_metrics._boundary_gc_projection(value["before"], value["after"])+ return valueowner.observations[1] = observation(os.getpid())record = {"concurrency": 1}@@ -142,16 +177,21 @@ def synthetic_owner(tmp_path: Path) -> tuple[IsolatedLoadgen, dict[str, Any], di"observation_clock","identity","pid",- "window",+ "mode",+ "callbacks",+ "thresholds",+ "disabled","cost_nan",- "combined_budget",+ "zero_cost",+ "empty_events",+ "false_gate","integrity",],)-def test_phase_payload_must_match_observed_ipc_provenance_and_combined_budget(tmp_path: Path, mutation: str) -> None:+def test_phase_payload_must_match_observed_ipc_provenance_and_boundary_state(tmp_path: Path, mutation: str) -> None:owner, record, original = synthetic_owner(tmp_path)value = copy.deepcopy(original)- assert owner._validate_phase(record, copy.deepcopy(original))["observer_cost_gate_applied"]+ assert owner._validate_phase(record, copy.deepcopy(original))["observer_cost_gate_applied"] is Falseif mutation == "swapped_phase":value["concurrency"] = 4elif mutation == "clock":@@ -162,19 +202,71 @@ def test_phase_payload_must_match_observed_ipc_provenance_and_combined_budget(tmvalue["identity"]["source"] = "/wrong"elif mutation == "pid":value["client_observation"]["after"]["core"]["pid"] += 1- elif mutation == "window":- value["client_observation"]["gc"]["window_start_ns"] += 1+ elif mutation == "mode":+ value["client_observation"]["gc"]["mode"] = "per-event"+ elif mutation == "callbacks":+ value["client_observation"]["after"]["core"]["gc_callback_ids"] = [123]+ elif mutation == "thresholds":+ value["client_observation"]["after"]["core"]["gc_thresholds"][0] += 1+ elif mutation == "disabled":+ value["client_observation"]["after"]["core"]["gc_enabled"] = Falseelif mutation == "cost_nan":value["client_observation"]["gc"]["estimated_observer_fraction"] = float("nan")- elif mutation == "combined_budget":- owner.observations[1]["gc"]["estimated_observer_fraction"] = 0.0006- value["client_observation"]["gc"]["estimated_observer_fraction"] = 0.0006+ elif mutation == "zero_cost":+ value["client_observation"]["gc"]["estimated_observer_fraction"] = 0+ elif mutation == "empty_events":+ value["client_observation"]["gc"]["records"] = []+ elif mutation == "false_gate":+ value["client_observation"]["gc"]["cost_budget_passed"] = Falseelse:value["client_observation"]["gc"]["integrity_passed"] = Falsewith pytest.raises(AssertionError):owner._validate_phase(record, value)+def test_child_observation_write_failure_cannot_replace_primary_phase_failure(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import argparse++ class Control:+ def __init__(self, _token: str) -> None:+ pass++ def send(self, *_args: Any, **_kwargs: Any) -> None:+ pass++ def receive(self, *_args: Any) -> None:+ pass++ def close(self) -> None:+ pass++ def failed_performance(*_args: Any, before_measure: Any, **_kwargs: Any) -> None:+ before_measure()+ raise ValueError("primary SDK failure")++ original_write = loadgen.atomic_json++ def failed_write(path: Path, value: Any) -> None:+ if path.name.endswith("-observations.json"):+ raise OSError("observation write failed")+ original_write(path, value)++ monkeypatch.setattr(loadgen, "Control", Control)+ monkeypatch.setattr(loadgen, "identity", lambda _source: {"pid": os.getpid()})+ monkeypatch.setattr(loadgen, "require_sdk_only", lambda: None)+ monkeypatch.setattr(loadgen, "performance", failed_performance)+ monkeypatch.setattr(loadgen, "atomic_json", failed_write)+ args = argparse.Namespace(output=tmp_path / "child", source=ROOT, token=str(os.getpid()), smoke=True, url="unused")+ with pytest.raises(ValueError, match="primary SDK failure") as caught:+ loadgen.run(args)+ assert any("observation write failed" in note for note in caught.value.__notes__)+ terminal = json.loads((args.output / "terminal.json").read_text())+ assert terminal["error"]["type"] == "ValueError"+ assert terminal["passed"] is False++@pytest.mark.asyncio@pytest.mark.parametrize("mutation", ["failed", "identity", "schedule", "smoke"])async def test_valid_terminal_hash_cannot_mask_wrong_terminal_payload(diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_process_metrics.py b/tools/benchmarks/cross_encoder_lora/tests/test_process_metrics.pyindex bbbf35f80..0bd0fe6ee 100644--- a/tools/benchmarks/cross_encoder_lora/tests/test_process_metrics.py+++ b/tools/benchmarks/cross_encoder_lora/tests/test_process_metrics.py@@ -2,6 +2,7 @@from __future__ import annotations+import copyimport gcimport timefrom array import array@@ -13,6 +14,79 @@ import pytestfrom tools.benchmarks.cross_encoder_lora import process_metrics as metrics+def test_boundary_observation_preserves_gc_without_measuring_events() -> None:+ callbacks, thresholds = tuple(gc.callbacks), gc.get_threshold()+ before = metrics.snapshot()+ after = metrics.snapshot()+ value = metrics.boundary_gc_report(before, after, callbacks)+ metrics.validate_boundary_gc({"before": before, "after": after, "gc": value})+ assert value["mode"] == "boundary-only"+ assert value["integrity_passed"]+ assert all(+ value[key] is None+ for key in ("records", "intervals", "callback_self_ns", "estimated_observer_fraction", "cost_budget_passed")+ )+ assert "unobserved" in value["scope"]+ assert before["core"]["gc_callback_ids"] == after["core"]["gc_callback_ids"] == [id(item) for item in callbacks]+ assert len(gc.callbacks) == len(callbacks)+ assert all(current is prior for current, prior in zip(gc.callbacks, callbacks, strict=True))+ assert gc.isenabled()+ assert gc.get_threshold() == thresholds+++def test_boundary_callback_identity_check_does_not_use_callable_equality() -> None:+ class Permissive:+ def __call__(self, _phase: str, _info: dict[str, Any]) -> None:+ pass++ def __eq__(self, _other: object) -> bool:+ return True++ def __hash__(self) -> int:+ return 0++ original, replacement = Permissive(), Permissive()+ previous = tuple(gc.callbacks)+ gc.callbacks.append(original)+ callbacks = tuple(gc.callbacks)+ try:+ before = metrics.snapshot()+ gc.callbacks[-1] = replacement+ after = metrics.snapshot()+ value = metrics.boundary_gc_report(before, after, callbacks)+ assert not value["integrity_passed"]+ with pytest.raises(AssertionError, match="boundary-only"):+ metrics.validate_boundary_gc({"before": before, "after": after, "gc": value})+ # Even forged matching snapshot IDs cannot hide a changed live object+ # from the local retained-reference check.+ after["core"]["gc_callback_ids"] = before["core"]["gc_callback_ids"]+ assert not metrics.boundary_gc_report(before, after, callbacks)["integrity_passed"]+ finally:+ gc.callbacks[:] = previous+++def test_boundary_threshold_mutation_and_disabled_gc_fail_without_restoring_them_silently() -> None:+ thresholds = gc.get_threshold()+ callbacks = tuple(gc.callbacks)+ before = metrics.snapshot()+ try:+ gc.set_threshold(thresholds[0] + 1, *thresholds[1:])+ after = metrics.snapshot()+ value = metrics.boundary_gc_report(before, after, callbacks)+ assert not value["integrity_passed"]+ assert gc.get_threshold()[0] == thresholds[0] + 1+ gc.disable()+ with pytest.raises(AssertionError, match="GC state"):+ metrics.snapshot()+ after = copy.deepcopy(before)+ after["core"]["gc_enabled"] = False+ assert not metrics.boundary_gc_report(before, after, callbacks)["integrity_passed"]+ assert not gc.isenabled()+ finally:+ gc.set_threshold(*thresholds)+ gc.enable()++def report(rows: list[list[int]], start: float = 1.0, end: float = 2.0) -> dict[str, Any]:recorder = metrics.GCRecorder(capacity=max(1, len(rows)))recorder.start()