Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

test: isolate cross-encoder benchmark load generation

svonava250bd9a91c8f
diff --git a/tools/benchmarks/cross_encoder_lora/README.md b/tools/benchmarks/cross_encoder_lora/README.md
index c46a0537c..87392d700 100644
--- a/tools/benchmarks/cross_encoder_lora/README.md
+++ b/tools/benchmarks/cross_encoder_lora/README.md
@@ -170,8 +170,9 @@ 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.
+measurements or claiming zero overhead. That version shared one client/server process and included their normal GC and
+GIL interactions; the subsequent isolation amendment below preserves its failed
+result rather than reclassifying it.
Freeze the reviewed source and operator bounds before one complete amended
18-process run. A separate baseline-readiness allocation is not required. Every
@@ -186,6 +187,68 @@ 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.
+## SDK process isolation amendment
+
+The complete longer-window run at `a2932d81ef0894d3270a26350a2cd0703fa66a82`
+failed five of twelve upper-confidence gates. Its point estimates did not
+establish a serving slowdown, but they also did not satisfy the fixed precision
+requirement. No source defect or physical cause was established. The original
+records and criteria remain unchanged.
+
+Qualification now starts one fresh Python **exec** load generator per server
+trial and reuses it across C1/C4/C16. It imports only the selected archive's SDK
+and benchmark client/telemetry helpers, never Torch, PEFT or the serving model.
+The server retains its original process, CPU allocation, affinity and model
+state. The SDK, HTTP, serving work, normal GC and every fixed workload/gate
+remain included. Separation removes direct client/server interpreter and GIL
+coupling; it does not remove shared CPU competition or guarantee precise results.
+The historical `stability` command retains its in-process diagnostic method.
+
+Client startup, warmup, boundary handshakes, process shutdown and evidence serialization
+are outside the request timers. The same lane loop releases a barrier after
+recording its start and drains every admitted request before the end timestamp.
+The parent waits asynchronously so the server event loop continues. A single
+stdin reader monitors parent lifetime; unexpected EOF ends the owned child.
+Normal shutdown wakes and joins that reader, writes final terminal evidence,
+then reports completion; the parent reaps the child before closing stdin. No new process group or detached session is
+created. Cancellation, malformed protocol and child errors fail the trial and
+trigger bounded termination/reaping. SIGKILL or immediate parent-death exit can
+lose 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:
+
+```console
+mise 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.
+
+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.
+Shared cgroup observations are labeled and must never be summed across PIDs.
+Missing optional counters remain unavailable. Existing server correctness
+histories are retained and counted; the pre-timing memory checkpoint keeps its
+existing explicit GC and CUDA synchronization. No speculative history cleanup
+or heap normalization is introduced. The child retains its request histories
+until all phases end. The server ingests them only after the child is reaped.
+
+Phase payloads, observed IPC clocks, PID/source identities, ordered terminal
+records, lengths and hashes must agree. Raw requests, wire attempts and all
+existing numerical checks remain available. Child observations and phase files
+live under each trial's `loadgen/` directory, with a separate process receipt and
+server boundary snapshots. Keep those files in the full durable archive.
+
## Evidence and CPU checks
`summary.json` schema 2 retains trial outcomes, aggregate metrics, statistical
@@ -214,7 +277,7 @@ Store the evidence directory on durable storage and verify the full archive
hash after retrieval; stdout is unsuitable for transferring large artifacts.
```console
-mise run test -- tools/benchmarks/cross_encoder_lora/tests/test_probe.py
+mise run test -- tools/benchmarks/cross_encoder_lora/tests
mise run typecheck -- tools/benchmarks/cross_encoder_lora
```
diff --git a/tools/benchmarks/cross_encoder_lora/calibrate_gc.py b/tools/benchmarks/cross_encoder_lora/calibrate_gc.py
new file mode 100644
index 000000000..77770cc49
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/calibrate_gc.py
@@ -0,0 +1,195 @@
+"""Bounded model-free calibration of the fixed GC observer allowance, not serving performance."""
+
+from __future__ import annotations
+
+import argparse
+import gc
+import math
+import platform
+import statistics
+import sys
+import time
+from array import array
+from pathlib import Path
+from typing import Any
+
+from tools.benchmarks.cross_encoder_lora.evidence import atomic_json, digest
+from tools.benchmarks.cross_encoder_lora.process_metrics import CALLBACK_TAIL_ALLOWANCE_NS, GCRecorder
+from tools.benchmarks.cross_encoder_lora.protocol import percentile, require
+
+BLOCKS = 6
+COLLECTIONS = 10_000
+DIRECT_PAIRS = 500
+T95_DF5 = 2.0150483733330233
+
+
+def bound(values: list[float]) -> dict[str, Any]:
+ require(
+ len(values) == BLOCKS and all(math.isfinite(value) for value in values), "six finite calibration units required"
+ )
+ mean = statistics.mean(values)
+ upper = mean + T95_DF5 * statistics.stdev(values) / math.sqrt(BLOCKS)
+ return {
+ "block_mean_residual_ns": values,
+ "mean_ns": mean,
+ "one_sided_95_upper_ns": upper,
+ "allowance_ns": CALLBACK_TAIL_ALLOWANCE_NS,
+ "passed": max(values) <= CALLBACK_TAIL_ALLOWANCE_NS and upper <= CALLBACK_TAIL_ALLOWANCE_NS,
+ }
+
+
+def collect_arm(observed: bool, count: int, record: dict[str, Any] | None = None) -> dict[str, Any]:
+ if record is None:
+ record = {}
+ record.update(observed=observed, passed=False, completed=0)
+ durations = array("Q", [0]) * count
+ collected = array("Q", [0]) * count
+ recorder = GCRecorder(capacity=2 * count + 64)
+ thresholds, prior = gc.get_threshold(), tuple(gc.callbacks)
+ require(gc.isenabled(), "normal GC must remain enabled")
+ if observed:
+ recorder.start()
+ try:
+ for index in range(count):
+ started = time.perf_counter_ns()
+ collected[index] = gc.collect(0)
+ durations[index] = time.perf_counter_ns() - started
+ record["completed"] = index + 1
+ finally:
+ try:
+ if observed:
+ recorder.close()
+ finally:
+ rows = [list(recorder.buffer[i * 6 : (i + 1) * 6]) for i in range(recorder.count)]
+ record.update(
+ duration_ns=list(durations),
+ collected=list(collected),
+ records=rows,
+ recorder_errors=recorder.lifecycle_errors,
+ invalid=recorder.invalid,
+ overflow=recorder.overflow,
+ )
+ require(gc.isenabled() and gc.get_threshold() == thresholds, "GC configuration changed")
+ require(
+ len(gc.callbacks) == len(prior) and all(a is b for a, b in zip(gc.callbacks, prior, strict=True)),
+ "GC callback identities changed",
+ )
+ if observed:
+ require(
+ not recorder.lifecycle_errors and not recorder.invalid and not recorder.overflow,
+ "invalid calibration observer",
+ )
+ require(len(rows) == 2 * count, "unexpected extra/missing calibration GC callbacks")
+ require(
+ all(row[1] == index % 2 and row[2] == 0 for index, row in enumerate(rows)), "calibration GC pairing differs"
+ )
+ record["passed"] = True
+ return record
+
+
+def direct(generation: int, pairs: int) -> dict[str, Any]:
+ # This is a diagnostic direct call, not an installed GC callback. It covers
+ # all field paths while the real-dispatch pairs above exercise CPython GC.
+ recorder = GCRecorder(capacity=2 * pairs)
+ durations = array("Q", [0]) * (2 * pairs)
+ info = {"generation": generation, "collected": 101, "uncollectable": 3}
+ callback = recorder._record
+ for index in range(2 * pairs):
+ phase = "start" if index % 2 == 0 else "stop"
+ started = time.perf_counter_ns()
+ callback(phase, info)
+ durations[index] = time.perf_counter_ns() - started
+ self_ns = [recorder.buffer[index * 6 + 5] for index in range(2 * pairs)]
+ residual: list[float] = [elapsed - cost for elapsed, cost in zip(durations, self_ns, strict=True)]
+ return {
+ "generation": generation,
+ "info": info,
+ "external_ns": list(durations),
+ "self_ns": self_ns,
+ "residual_ns": residual,
+ "mean_residual_ns": statistics.mean(residual),
+ "p99_residual_ns": percentile(residual, 0.99),
+ "maximum_residual_ns": max(residual),
+ }
+
+
+def run(result: dict[str, Any]) -> None:
+ prior, thresholds = tuple(gc.callbacks), gc.get_threshold()
+ require(gc.isenabled(), "normal GC must remain enabled")
+ blocks: list[dict[str, Any]] = []
+ result["blocks"] = blocks
+ for index in range(BLOCKS):
+ order = (False, True) if index % 2 == 0 else (True, False)
+ block: dict[str, Any] = {"block": index, "order": list(order), "arms": {}, "direct": []}
+ blocks.append(block)
+ arms = block["arms"]
+ for observed in order:
+ arms[str(observed)] = {}
+ collect_arm(observed, COLLECTIONS, arms[str(observed)])
+ baseline, observed = arms["False"], arms["True"]
+ self_mean = statistics.mean(row[5] for row in observed["records"])
+ # Pair means are the independent units. The baseline cost, including
+ # the identical loop/timer/storage, is subtracted only in this diagnostic.
+ # Signed residuals are retained; none are clipped or selected away.
+ residual = (statistics.mean(observed["duration_ns"]) - statistics.mean(baseline["duration_ns"])) / 2 - self_mean
+ unsubtracted = [
+ (elapsed - observed["records"][2 * j][5] - observed["records"][2 * j + 1][5]) / 2
+ for j, elapsed in enumerate(observed["duration_ns"])
+ ]
+ block.update(
+ {
+ "residual_ns_per_callback": residual,
+ "unsubtracted_residual_p99_ns": percentile(unsubtracted, 0.99),
+ "unsubtracted_residual_maximum_ns": max(unsubtracted),
+ "direct": [direct(generation, DIRECT_PAIRS) for generation in range(3)],
+ }
+ )
+ gates = {"actual_gc_dispatch": bound([row["residual_ns_per_callback"] for row in blocks])}
+ for generation in range(3):
+ gates[f"direct_gen{generation}"] = bound([row["direct"][generation]["mean_residual_ns"] for row in blocks])
+ require(gc.isenabled() and gc.get_threshold() == thresholds, "GC configuration changed")
+ require(
+ len(gc.callbacks) == len(prior) and all(a is b for a, b in zip(gc.callbacks, prior, strict=True)),
+ "GC callback identities changed",
+ )
+ result.update(
+ {
+ "qualification": False,
+ "passed": all(value["passed"] for value in gates.values()),
+ "python": sys.version,
+ "platform": platform.platform(),
+ "gc_thresholds": list(thresholds),
+ "source_sha256": digest(Path(__file__)),
+ "observer_sha256": digest(Path(__file__).with_name("process_metrics.py")),
+ "blocks": blocks,
+ "gates": gates,
+ "interpretation": "Local mean-overhead estimator calibration only. The fixed10us allowance is not a worst-case event bound or a guarantee for another host. All samples/outliers retained; no benchmark subtraction or threshold adjustment.",
+ "runtime_budget": "Combined server+client estimated observer cost<=0.001 in every real measured phase, unchanged.",
+ }
+ )
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ require(not args.output.exists(), "calibration output must be new")
+ result: dict[str, Any] = {
+ "qualification": False,
+ "passed": False,
+ "source_sha256": digest(Path(__file__)),
+ "observer_sha256": digest(Path(__file__).with_name("process_metrics.py")),
+ }
+ try:
+ run(result)
+ except BaseException as error:
+ result["error"] = {"type": type(error).__name__, "message": str(error)}
+ raise
+ finally:
+ atomic_json(args.output, result)
+ print({"passed": result["passed"], "qualification": False, "output_sha256": digest(args.output)}, flush=True)
+ require(result["passed"], "fixed GC allowance calibration failed; retain evidence and investigate")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/benchmarks/cross_encoder_lora/client.py b/tools/benchmarks/cross_encoder_lora/client.py
new file mode 100644
index 000000000..5891a723a
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/client.py
@@ -0,0 +1,299 @@
+"""SDK-only request capture and load loop, shared by local and isolated drivers."""
+
+from __future__ import annotations
+
+import math
+import statistics
+import threading
+import time
+from collections.abc import Callable
+from concurrent.futures import ThreadPoolExecutor
+from http import HTTPStatus
+from typing import Any
+
+import httpx
+from sie_sdk import SIEClient
+from sie_sdk._msgpack import unpackb
+from sie_sdk.client.errors import ServerError
+
+from tools.benchmarks.cross_encoder_lora.evidence import Evidence
+from tools.benchmarks.cross_encoder_lora.protocol import (
+ DOCUMENTS,
+ MODEL,
+ PERFORMANCE_FUTURE_TIMEOUT_S,
+ QUERY,
+ SEQUENTIAL,
+ STEADY_SECONDS,
+ WARMUP,
+ percentile,
+ require,
+)
+
+MAX_LOADING_RETRIES = 10
+MAX_LOADING_DELAY = 5
+REQUEST_ITEMS = len(DOCUMENTS)
+RESPONSE_CAPTURE_MODE = "success-status-header-snapshots"
+
+
+class Client:
+ def __init__(self, url: str) -> None:
+ self.responses: list[dict[str, Any] | httpx.Response] = []
+ http = httpx.Client(base_url=url, timeout=30, event_hooks={"response": [self.observe]})
+ self._http = http
+ self.sdk = SIEClient(url, timeout_s=30, http_client=http)
+
+ def observe(self, response: httpx.Response) -> None:
+ # Keep successful wire evidence without retaining its Response/Request/
+ # stream graph for the whole phase. Failure bodies are decoded later.
+ self.responses.append(describe_response(response) if response.status_code == HTTPStatus.OK else response)
+
+ def score(self, selection: str | None, label: str, *, cold: bool = False, timed: bool = False) -> dict[str, Any]:
+ started = time.perf_counter_ns()
+ wall_started = time.time_ns()
+ first = len(self.responses)
+ # score() currently does not retry LORA_LOADING. These are explicitly
+ # fresh SDK calls for this pre-execution status, never transport retries.
+ for attempt in range(MAX_LOADING_RETRIES + 1):
+ try:
+ result = self.sdk.score(
+ MODEL,
+ {"text": QUERY["text"]},
+ [{"id": f"{label}:{index}", "text": text} for index, text in enumerate(DOCUMENTS)],
+ options={"lora": selection},
+ wait_for_capacity=False,
+ max_oom_retries=0,
+ provision_timeout_s=30,
+ )
+ break
+ except ServerError as error:
+ if (
+ not cold
+ or error.status_code != HTTPStatus.SERVICE_UNAVAILABLE
+ or error.code != "LORA_LOADING"
+ or attempt == MAX_LOADING_RETRIES
+ ):
+ raise
+ delay = error.retry_after if error.retry_after is not None else 0.2
+ require(0 <= delay <= MAX_LOADING_DELAY, "unexpected loading retry delay")
+ time.sleep(delay)
+ elapsed = (time.perf_counter_ns() - started) / 1e6
+ row = {
+ "label": label,
+ "selection": selection,
+ "latency_ms": elapsed,
+ "start_ns": wall_started,
+ "end_ns": time.time_ns(),
+ "result": result,
+ "responses": self.responses[first:],
+ }
+ if not timed:
+ validate_response(row, allow_loading=cold)
+ return row
+
+ def close(self) -> None:
+ try:
+ self.sdk.close()
+ finally:
+ # Callers serialize their evidence before closing. Preserve unrelated
+ # hooks, and break only the observer/history this benchmark owns.
+ hooks = self._http.event_hooks["response"]
+ hooks[:] = [
+ hook
+ for hook in hooks
+ if not (
+ getattr(hook, "__self__", None) is self and getattr(hook, "__func__", None) is type(self).observe
+ )
+ ]
+ self.responses.clear()
+
+
+def describe_response(response: httpx.Response | dict[str, Any]) -> dict[str, Any]:
+ if not isinstance(response, httpx.Response):
+ return response
+ row: dict[str, Any] = {
+ "status": response.status_code,
+ "timing_headers": {
+ name: response.headers[name]
+ for name in (
+ "x-queue-time",
+ "x-tokenization-time",
+ "x-inference-time",
+ "x-postprocessing-time",
+ "x-total-time",
+ )
+ if name in response.headers
+ },
+ }
+ if response.status_code >= HTTPStatus.BAD_REQUEST:
+ row["content_type"] = response.headers.get("content-type")
+ row["retry_after"] = response.headers.get("retry-after")
+ try:
+ response.read()
+ except (httpx.StreamError, httpx.HTTPError) as error:
+ # A partially read error stream can already have failed in the SDK.
+ # Preserve that original failure and its wire metadata; diagnostic
+ # re-reading must not replace it or discard earlier attempts.
+ row.update(body_unavailable=True, body_read_error=type(error).__name__, code=None)
+ return row
+ row["body_hex"] = response.content.hex()
+ try:
+ body = (
+ unpackb(response.content, numeric_arrays=False)
+ if "msgpack" in response.headers.get("content-type", "")
+ else response.json()
+ )
+ except ValueError as error:
+ row["body_decode_error"] = type(error).__name__
+ body = None
+ error = body.get("error", body.get("detail", body)) if isinstance(body, dict) else None
+ row["code"] = error.get("code") if isinstance(error, dict) else None
+ return row
+
+
+def serialize_responses(row: dict[str, Any]) -> None:
+ row["responses"] = [
+ describe_response(value) if isinstance(value, httpx.Response) else value for value in row["responses"]
+ ]
+
+
+def validate_response(row: dict[str, Any], *, allow_loading: bool = False) -> None:
+ serialize_responses(row)
+ statuses = row["responses"]
+ require(statuses and statuses[-1]["status"] == HTTPStatus.OK, "missing successful HTTP response")
+ if allow_loading:
+ require(
+ all(
+ value["status"] == HTTPStatus.SERVICE_UNAVAILABLE and value.get("code") == "LORA_LOADING"
+ for value in statuses[:-1]
+ ),
+ "unexpected retry during cold adapter request",
+ )
+ else:
+ require(len(statuses) == 1, "hidden SDK retry disqualifies this request")
+ scores = row["result"]["scores"]
+ expected_ids = [f"{row['label']}:{i}" for i in range(REQUEST_ITEMS)]
+ by_id = {item["item_id"]: item["score"] for item in scores}
+ require(len(scores) == REQUEST_ITEMS and set(by_id) == set(expected_ids), "score result lost or changed item IDs")
+ require([item["rank"] for item in scores] == list(range(REQUEST_ITEMS)), "score ranks changed")
+ values = [by_id[key] for key in expected_ids]
+ row["scores"] = values
+ require(all(math.isfinite(value) for value in values), "nonfinite SDK score")
+ require([item["score"] for item in scores] == sorted(values, reverse=True), "score ranks are unordered")
+
+
+def performance(
+ url: str,
+ concurrency: int,
+ evidence: Evidence,
+ *,
+ smoke: bool,
+ warmup: int = WARMUP,
+ sequential: int = SEQUENTIAL,
+ steady_seconds: float = STEADY_SECONDS,
+ future_timeout: float = PERFORMANCE_FUTURE_TIMEOUT_S,
+ before_measure: Callable[[], None] | None = None,
+ after_measure: Callable[[dict[str, float]], None] | None = None,
+) -> dict[str, Any]:
+ clients: list[Client] = []
+ samples: list[dict[str, Any]] = []
+ warmups: list[dict[str, Any]] = []
+ lock = threading.Lock()
+ clock: dict[str, float] = {}
+ measurement_notified = False
+ primary_error: BaseException | None = None
+
+ def notify_measurement_end() -> None:
+ nonlocal measurement_notified
+ if "start" in clock and not measurement_notified:
+ clock.setdefault("end", time.perf_counter())
+ measurement_notified = True
+ if after_measure is not None:
+ after_measure(dict(clock))
+
+ try:
+ for _ in range(concurrency):
+ clients.append(Client(url))
+ for i in range(2 if smoke else warmup):
+ warmups.append(clients[0].score(None, f"warm-C{concurrency}-{i}", timed=True))
+ barrier = threading.Barrier(concurrency + 1)
+
+ def lane(index: int) -> None:
+ barrier.wait(timeout=30)
+ counter = 0
+ while (
+ counter < (4 if smoke else sequential) if concurrency == 1 else time.perf_counter() < clock["deadline"]
+ ):
+ row = clients[index].score(None, f"C{concurrency}-lane{index}-{counter}", timed=True)
+ with lock:
+ samples.append(row)
+ counter += 1
+
+ with ThreadPoolExecutor(max_workers=concurrency) as executor:
+ futures = [executor.submit(lane, i) for i in range(concurrency)]
+ try:
+ if before_measure is not None:
+ before_measure()
+ except BaseException:
+ barrier.abort()
+ raise
+ clock["start"] = time.perf_counter()
+ clock["deadline"] = clock["start"] + (0.15 if smoke else steady_seconds)
+ barrier.wait(timeout=30)
+ for future in futures:
+ future.result(timeout=future_timeout)
+ clock["end"] = time.perf_counter()
+ elapsed = clock["end"] - clock["start"]
+ notify_measurement_end()
+ for row in [*warmups, *samples]:
+ validate_response(row)
+ latencies = [row["latency_ms"] for row in samples]
+ return {
+ "concurrency": concurrency,
+ "count": len(samples),
+ "elapsed_s": elapsed,
+ "mean_ms": statistics.mean(latencies),
+ "p95_ms": percentile(latencies, 0.95),
+ "rps": len(samples) / elapsed,
+ "samples": samples,
+ "measurement_clock": dict(clock),
+ }
+ except BaseException as error:
+ primary_error = error
+ raise
+ finally:
+ # Finalize each owned responsibility independently. A broken telemetry
+ # handshake must not replace an SDK failure or erase its wire attempts.
+ finalization_errors: list[BaseException] = []
+
+ def finalize(action: Callable[[], None]) -> None:
+ try:
+ action()
+ except BaseException as error: # noqa: BLE001 -- finalize all owned resources, then re-raise
+ finalization_errors.append(error)
+
+ finalize(notify_measurement_end)
+ for row in [*warmups, *samples]:
+ finalize(lambda row=row: serialize_responses(row))
+ finalize(
+ lambda: evidence.emit(
+ "performance_attempt",
+ concurrency=concurrency,
+ completed_samples=samples,
+ warmups=warmups,
+ wire_responses=[describe_response(response) for client in clients for response in client.responses],
+ primary_error=None
+ if primary_error is None
+ else {"type": type(primary_error).__name__, "message": str(primary_error)},
+ finalization_errors=[
+ {"type": type(error).__name__, "message": str(error)} for error in finalization_errors
+ ],
+ )
+ )
+ for client in clients:
+ finalize(client.close)
+ if finalization_errors:
+ if primary_error is not None:
+ for error in finalization_errors:
+ primary_error.add_note(f"Secondary benchmark finalization failure: {type(error).__name__}: {error}")
+ else:
+ raise finalization_errors[0]
diff --git a/tools/benchmarks/cross_encoder_lora/isolation.py b/tools/benchmarks/cross_encoder_lora/isolation.py
new file mode 100644
index 000000000..3524b7270
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/isolation.py
@@ -0,0 +1,316 @@
+"""Async parent ownership of one exec-only SDK child; no compute provisioning."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import math
+import os
+import sys
+import time
+import uuid
+from pathlib import Path
+from types import TracebackType
+from typing import Any, Self
+
+from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digest
+from 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.protocol import PERFORMANCE_FUTURE_TIMEOUT_S, require
+
+
+class IsolatedLoadgen:
+ """Leave uvicorn running while awaiting a bounded, same-group SDK child."""
+
+ def __init__(self, url: str, source: Path, evidence: Evidence, *, smoke: bool) -> None:
+ self.url, self.source, self.evidence, self.smoke = url, source.resolve(), evidence, smoke
+ self.token = uuid.uuid4().hex
+ self.process: asyncio.subprocess.Process | None = None
+ self.log: Any = None
+ self.records: list[dict[str, Any]] = []
+ self.observations: dict[int, dict[str, Any]] = {}
+ self.receipt: dict[str, Any] = {"passed": False, "reaped": False, "phases": self.records}
+
+ async def _send(self, command: str, concurrency: int | None = None) -> None:
+ assert self.process is not None
+ assert self.process.stdin is not None
+ value = {"token": self.token, "command": command, "concurrency": concurrency}
+ self.process.stdin.write((json.dumps(value) + "\n").encode())
+ await asyncio.wait_for(self.process.stdin.drain(), timeout=5)
+
+ async def _read(
+ self, event: str, concurrency: int | None = None, *, wait_s: float = CONTROL_TIMEOUT_S
+ ) -> dict[str, Any]:
+ assert self.process is not None
+ assert self.process.stdout is not None
+ line = await asyncio.wait_for(self.process.stdout.readline(), timeout=wait_s)
+ require(
+ bool(line) and len(line) <= CONTROL_LIMIT and line.endswith(b"\n"), "missing or oversized loadgen message"
+ )
+ value = json.loads(line)
+ require(isinstance(value, dict), "invalid loadgen control object")
+ require(value.get("token") == self.token and value.get("event") == event, "unexpected loadgen event")
+ require(value.get("concurrency") == concurrency, "loadgen phase identity differs")
+ return value
+
+ async def __aenter__(self) -> Self:
+ command = [
+ sys.executable,
+ "-m",
+ "tools.benchmarks.cross_encoder_lora.loadgen",
+ "--source",
+ str(self.source),
+ "--output",
+ str(self.evidence.directory / "loadgen"),
+ "--url",
+ self.url,
+ "--token",
+ self.token,
+ ]
+ if self.smoke:
+ command.append("--smoke")
+ self.log = (self.evidence.directory / "loadgen.log").open("wb")
+ try:
+ self.process = await asyncio.create_subprocess_exec(
+ *command,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=self.log,
+ close_fds=True,
+ limit=CONTROL_LIMIT,
+ )
+ hello = await self._read("hello")
+ identity = hello["identity"]
+ require(identity["pid"] == self.process.pid and identity["pid"] != os.getpid(), "loadgen PID differs")
+ require(
+ identity["ppid"] == os.getpid() and identity["process_group"] == os.getpgrp(),
+ "loadgen ownership/group differs",
+ )
+ require(
+ identity["source"] == str(self.source) and identity["forbidden_imports_present"] is False,
+ "loadgen source/import preflight failed",
+ )
+ sdk_path = Path(identity["sdk_path"])
+ require(
+ sdk_path.is_relative_to(self.source / "packages/sie_sdk/src"), "loadgen SDK source escaped its archive"
+ )
+ require(digest(sdk_path) == identity["sdk_sha256"], "loadgen SDK implementation hash differs")
+ clock = time.get_clock_info("perf_counter")
+ require(
+ identity["clock"]["implementation"] == clock.implementation,
+ "client/server monotonic clock implementations differ",
+ )
+ self.receipt["identity"] = identity
+ self.evidence.emit("loadgen_started", **identity)
+ return self
+ except BaseException as error:
+ try:
+ await self._cleanup(False)
+ except BaseException as cleanup_error: # noqa: BLE001 -- retain primary startup failure
+ error.add_note(f"Loadgen startup cleanup failed: {type(cleanup_error).__name__}: {cleanup_error}")
+ raise
+
+ async def phase(self, concurrency: int) -> dict[str, Any]:
+ require(
+ 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()
+ observation["before"] = snapshot()
+ await self._send("go", concurrency)
+ measured = await self._read("measured", concurrency, wait_s=PERFORMANCE_FUTURE_TIMEOUT_S)
+ clock = measured["clock"]
+ require(
+ set(clock) == {"start", "deadline", "end"}
+ and all(type(v) in (int, float) and math.isfinite(v) for v in clock.values()),
+ "invalid loadgen measurement clock",
+ )
+ require(
+ 0 < clock["start"] < clock["end"] and clock["deadline"] > clock["start"], "loadgen clock order differs"
+ )
+ observation["clock"] = clock
+ observation["after"] = snapshot()
+ monitor.close()
+ observation["gc"] = monitor.report(clock["start"], clock["end"])
+ observation["resources"] = bracket(observation["before"], observation["after"], clock)
+ await self._send("observed", concurrency)
+ complete = await self._read("phase_complete", concurrency)
+ record = complete["record"]
+ require(
+ type(record["concurrency"]) is int
+ and record["concurrency"] == concurrency
+ and record["path"] == f"phase-C{concurrency}.json",
+ "loadgen record identity differs",
+ )
+ path = self.evidence.directory / "loadgen" / record["path"]
+ require(
+ path.is_file() and path.stat().st_size == record["bytes"] and digest(path) == record["sha256"],
+ "loadgen phase record is incomplete or corrupt",
+ )
+ self.records.append(record)
+ self.observations[concurrency] = observation
+ self.evidence.emit(
+ "loadgen_phase_complete", concurrency=concurrency, record=record, server_observation=observation
+ )
+ return record
+ finally:
+ monitor.close()
+ primary_error = sys.exception()
+ try:
+ atomic_json(self.evidence.directory / f"server-C{concurrency}-observations.json", observation)
+ except BaseException as write_error:
+ if primary_error is None:
+ raise
+ primary_error.add_note(
+ f"Secondary server observation write failure: {type(write_error).__name__}: {write_error}"
+ )
+
+ async def _cleanup(self, successful: bool) -> None:
+ try:
+ if self.process is not None:
+ try:
+ if successful:
+ require(len(self.records) == len(PHASES), "loadgen did not complete every phase")
+ await self._send("finish")
+ finished = await self._read("finished")
+ await asyncio.wait_for(self.process.wait(), timeout=10)
+ require(self.process.returncode == 0, "loadgen failed after final evidence")
+ terminal = self.evidence.directory / "loadgen/terminal.json"
+ require(digest(terminal) == finished["terminal_sha256"], "loadgen terminal record differs")
+ self._validate_terminal(json.loads(terminal.read_text()))
+ self.receipt["terminal_sha256"] = finished["terminal_sha256"]
+ self.receipt["passed"] = True
+ finally:
+ if self.process.returncode is None:
+ try:
+ self.process.terminate()
+ except ProcessLookupError:
+ self.receipt["termination_raced_exit"] = True
+ try:
+ await asyncio.wait_for(self.process.wait(), timeout=3)
+ except TimeoutError:
+ try:
+ self.process.kill()
+ except ProcessLookupError:
+ self.receipt["kill_raced_exit"] = True
+ await asyncio.wait_for(self.process.wait(), timeout=2)
+ self.receipt["returncode"] = self.process.returncode
+ self.receipt["reaped"] = self.process.returncode is not None
+ if self.process.stdin is not None:
+ self.process.stdin.close()
+ else:
+ self.receipt["reaped"] = True
+ finally:
+ if self.log is not None:
+ self.log.close()
+ atomic_json(self.evidence.directory / "loadgen-process.json", self.receipt)
+
+ async def __aexit__(
+ self, error_type: type[BaseException] | None, error: BaseException | None, traceback: TracebackType | None
+ ) -> None:
+ task = asyncio.create_task(self._cleanup(error_type is None))
+ try:
+ await asyncio.shield(task)
+ except asyncio.CancelledError as cancelled:
+ # Cancellation may arrive while the successful finish handshake is
+ # waiting for a silent child. Cancel that wait, join its bounded
+ # teardown, then explicitly reap even if it never started running.
+ task.cancel()
+ try:
+ await asyncio.shield(task)
+ except asyncio.CancelledError:
+ pass
+ except BaseException as cleanup_error: # noqa: BLE001 -- cancellation remains primary
+ self.receipt["cancelled_cleanup_error"] = {
+ "type": type(cleanup_error).__name__,
+ "message": str(cleanup_error),
+ }
+ try:
+ await asyncio.shield(asyncio.create_task(self._cleanup(False)))
+ except BaseException as cleanup_error: # noqa: BLE001 -- preserve cancellation after bounded reaping
+ cancelled.add_note(
+ f"Secondary cancelled cleanup failure: {type(cleanup_error).__name__}: {cleanup_error}"
+ )
+ raise
+ except BaseException as cleanup_error:
+ if error is None:
+ raise
+ error.add_note(f"Secondary loadgen cleanup failure: {type(cleanup_error).__name__}: {cleanup_error}")
+ self.receipt["cleanup_error"] = {"type": type(cleanup_error).__name__, "message": str(cleanup_error)}
+ try:
+ atomic_json(self.evidence.directory / "loadgen-process.json", self.receipt)
+ except BaseException as write_error: # noqa: BLE001 -- original phase failure remains primary
+ error.add_note(f"Secondary cleanup receipt write failure: {type(write_error).__name__}: {write_error}")
+
+ def _validate_terminal(self, terminal: dict[str, Any]) -> None:
+ 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("phases") == self.records, "loadgen terminal phase records differ")
+ require(tuple(record["concurrency"] for record in self.records) == PHASES, "loadgen terminal schedule differs")
+ require(
+ type(terminal.get("finished_ns")) is int and terminal["finished_ns"] > 0,
+ "loadgen terminal clock is missing",
+ )
+
+ def _validate_phase(self, record: dict[str, Any], value: dict[str, Any]) -> dict[str, Any]:
+ concurrency = record["concurrency"]
+ server = self.observations[concurrency]
+ identity = self.receipt["identity"]
+ require(
+ type(value.get("concurrency")) is int and value["concurrency"] == concurrency,
+ "phase payload concurrency differs",
+ )
+ require(
+ value.get("identity") == identity and value.get("smoke") is self.smoke, "phase payload provenance differs"
+ )
+ require(value.get("measurement_clock") == server["clock"], "phase payload differs from observed IPC clock")
+ client = value["client_observation"]
+ require(client.get("clock") == server["clock"], "client observation clock differs")
+ require(
+ all(client[key]["core"]["pid"] == identity["pid"] for key in ("before", "after")),
+ "phase observation PID differs",
+ )
+ 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")
+ value["server_observation"] = server
+ value["combined_estimated_observer_fraction"] = combined
+ value["observer_cost_gate_applied"] = not self.smoke
+ return value
+
+ def results(self) -> dict[str, dict[str, Any]]:
+ require(
+ self.receipt["passed"] and self.receipt["reaped"],
+ "loadgen must finish and be reaped before ingesting raw rows",
+ )
+ values = {}
+ for record in self.records:
+ path = self.evidence.directory / "loadgen" / record["path"]
+ require(
+ path.stat().st_size == record["bytes"] and digest(path) == record["sha256"],
+ "completed loadgen evidence changed",
+ )
+ value = self._validate_phase(record, json.loads(path.read_text()))
+ values[str(record["concurrency"])] = value
+ return values
diff --git a/tools/benchmarks/cross_encoder_lora/loadgen.py b/tools/benchmarks/cross_encoder_lora/loadgen.py
new file mode 100644
index 000000000..eb1fdae7a
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/loadgen.py
@@ -0,0 +1,217 @@
+"""One SDK-only exec child, reused across a trial's three measured phases."""
+
+from __future__ import annotations
+
+import argparse
+import inspect
+import json
+import os
+import queue
+import select
+import signal
+import sys
+import threading
+import time
+from pathlib import Path
+from typing import Any
+
+from sie_sdk import SIEClient
+
+from tools.benchmarks.cross_encoder_lora.client import performance
+from 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.protocol import require
+
+CONTROL_LIMIT = 65_536
+CONTROL_TIMEOUT_S = 30
+PHASES = (1, 4, 16)
+FORBIDDEN_IMPORTS = ("torch", "transformers", "peft", "sie_server")
+
+
+def require_sdk_only() -> None:
+ require(
+ not any(name.split(".", 1)[0] in FORBIDDEN_IMPORTS for name in sys.modules),
+ "load generator imported serving or CUDA model libraries",
+ )
+
+
+class Control:
+ """One stdin reader; loss of its sole parent writer ends this owned child."""
+
+ def __init__(self, token: str) -> None:
+ self.token = token
+ self.messages: queue.Queue[dict[str, Any]] = queue.Queue(maxsize=8)
+ self.normal_exit = False
+ self.stop_read, self.stop_write = os.pipe()
+ self.reader = threading.Thread(target=self._read, name="loadgen-parent-pipe", daemon=True)
+ self.reader.start()
+
+ def _read(self) -> None:
+ pending = bytearray()
+ try:
+ while True:
+ readable, _, _ = select.select([sys.stdin.fileno(), self.stop_read], [], [])
+ if self.stop_read in readable:
+ return
+ data = os.read(sys.stdin.fileno(), 4096)
+ if not data:
+ if not self.normal_exit:
+ # A hard-killed parent cannot finalize current samples.
+ # Previously completed atomic files remain the evidence.
+ os.kill(os.getpid(), signal.SIGTERM)
+ return
+ pending.extend(data)
+ while b"\n" in pending:
+ end = pending.index(b"\n") + 1
+ line = bytes(pending[:end])
+ del pending[:end]
+ try:
+ require(len(line) <= CONTROL_LIMIT, "invalid control line length")
+ value = json.loads(line)
+ require(isinstance(value, dict), "invalid control object")
+ except (ValueError, AssertionError) as error:
+ value = {"reader_error": type(error).__name__}
+ # Malformed input does not disable the sole EOF monitor.
+ # A flooded queue fails closed without blocking this reader.
+ self.messages.put_nowait(value)
+ require(len(pending) <= CONTROL_LIMIT, "unterminated control line is too large")
+ except BaseException: # noqa: BLE001 -- losing the lifetime monitor must terminate this owned child
+ if not self.normal_exit:
+ os.kill(os.getpid(), signal.SIGTERM)
+
+ def close(self) -> None:
+ # Raw-fd reads avoid a daemon holding Python's buffered stdin lock at
+ # interpreter shutdown. Wake and join it explicitly before normal exit.
+ self.normal_exit = True
+ os.write(self.stop_write, b"x")
+ self.reader.join(timeout=2)
+ require(not self.reader.is_alive(), "parent-pipe monitor failed to stop")
+ 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)
+ 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")
+ return value
+
+ def send(self, event: str, concurrency: int | None = None, **fields: Any) -> None:
+ value = {"token": self.token, "event": event, "concurrency": concurrency, **fields}
+ line = json.dumps(value, allow_nan=False)
+ require(len(line.encode()) < CONTROL_LIMIT, "control output exceeds bounded protocol")
+ print(line, flush=True)
+
+
+def identity(source: Path) -> dict[str, Any]:
+ require_sdk_only()
+ implementation = Path(inspect.getfile(SIEClient)).resolve()
+ expected = source.resolve() / "packages/sie_sdk/src"
+ require(implementation.is_relative_to(expected), "load generator SDK did not come from the selected source archive")
+ clock = time.get_clock_info("perf_counter")
+ require(clock.monotonic and not clock.adjustable, "load generator requires a monotonic performance clock")
+ return {
+ "pid": os.getpid(),
+ "ppid": os.getppid(),
+ "process_group": os.getpgrp(),
+ "sdk_path": str(implementation),
+ "sdk_sha256": digest(implementation),
+ "python": sys.executable,
+ "source": str(source.resolve()),
+ "clock": {name: getattr(clock, name) for name in ("implementation", "resolution", "monotonic", "adjustable")},
+ "forbidden_imports_present": False,
+ }
+
+
+def run(args: argparse.Namespace) -> None:
+ evidence = Evidence(args.output.resolve())
+ 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"])
+ try:
+ for concurrency in PHASES:
+ control.receive("phase", concurrency)
+ require_sdk_only()
+ monitor = GCRecorder()
+ monitor.start()
+ observations: dict[str, Any] = {}
+
+ def before_measure() -> None:
+ observations["before"] = snapshot()
+ control.send("ready", concurrency)
+ control.receive("go", concurrency)
+
+ def after_measure(clock: dict[str, float]) -> None:
+ observations["clock"] = clock
+ observations["after"] = snapshot()
+ monitor.close()
+ control.send("measured", concurrency, clock=clock)
+ control.receive("observed", concurrency)
+
+ try:
+ result = performance(
+ args.url,
+ concurrency,
+ evidence,
+ smoke=args.smoke,
+ before_measure=before_measure,
+ 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"
+ )
+ observations["resources"] = bracket(
+ observations["before"], observations["after"], result["measurement_clock"]
+ )
+ result["client_observation"] = observations
+ result["identity"] = terminal["identity"]
+ result["smoke"] = args.smoke
+ require_sdk_only()
+ path = evidence.directory / f"phase-C{concurrency}.json"
+ atomic_json(path, result)
+ record = {
+ "concurrency": concurrency,
+ "path": path.name,
+ "sha256": digest(path),
+ "bytes": path.stat().st_size,
+ }
+ terminal["phases"].append(record)
+ atomic_json(evidence.directory / "terminal.json", terminal)
+ # Preserve the historical request-history lifetime, but only in the
+ # load generator's heap. The serving process never ingests these
+ # rows until every timed phase is complete.
+ retained_results.append(result)
+ control.send("phase_complete", concurrency, record=record)
+ control.receive("finish")
+ terminal["passed"] = True
+ except BaseException as error:
+ terminal["error"] = {"type": type(error).__name__, "message": str(error)}
+ raise
+ finally:
+ control.close()
+ terminal["finished_ns"] = time.time_ns()
+ atomic_json(evidence.directory / "terminal.json", terminal)
+ if terminal["passed"]:
+ control.send("finished", terminal_sha256=digest(evidence.directory / "terminal.json"))
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", type=Path, required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--url", required=True)
+ parser.add_argument("--token", required=True)
+ parser.add_argument("--smoke", action="store_true")
+ run(parser.parse_args())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/benchmarks/cross_encoder_lora/process_metrics.py b/tools/benchmarks/cross_encoder_lora/process_metrics.py
new file mode 100644
index 000000000..2cde82443
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/process_metrics.py
@@ -0,0 +1,406 @@
+"""Process-local observations; filesystem reads occur only outside timed work."""
+
+from __future__ import annotations
+
+import gc
+import math
+import os
+import resource
+import time
+from array import array
+from pathlib import Path
+from typing import Any
+
+from tools.benchmarks.cross_encoder_lora.protocol import require
+
+GC_FIELDS = ("collections", "collected", "uncollectable")
+
+RUSAGE_FIELDS = ("ru_utime", "ru_stime", "ru_minflt", "ru_majflt", "ru_nvcsw", "ru_nivcsw")
+
+OPTIONAL_FILES = ("cpu.stat", "cpu.stat.local", "cpu.pressure", "cpu.max", "cpu.weight", "cpuset.cpus.effective")
+
+COUNTER_FILES = ("cpu.stat", "cpu.stat.local")
+
+CONTROL_FILES = ("cpu.max", "cpu.weight", "cpuset.cpus.effective")
+
+GC_GENERATIONS = 3
+
+PSI_FIELDS = ("avg10", "avg60", "avg300", "total")
+
+MAX_PERCENT = 100
+
+MAX_CPU_WEIGHT = 10000
+
+
+def unified_cgroup(proc: Path = Path("/proc/self")) -> dict[str, Any]:
+ """Resolve the process's own namespace; never fall back to another cgroup."""
+ try:
+ rows = (proc / "cgroup").read_text().splitlines()
+ membership = [row[3:] for row in rows if row.startswith("0::")]
+ require(len(membership) == 1, "unified cgroup membership is unavailable or ambiguous")
+ group = Path(membership[0])
+ require(group.is_absolute() and ".." not in group.parts, "invalid cgroup membership")
+ matches = []
+ for row in (proc / "mountinfo").read_text().splitlines():
+ left, right = row.split(" - ", 1)
+ if right.split()[0] != "cgroup2":
+ continue
+ fields = left.split()
+ root = Path(fields[3].replace("\\040", " ").replace("\\134", "\\"))
+ mount = Path(fields[4].replace("\\040", " ").replace("\\134", "\\"))
+ if group.is_relative_to(root):
+ matches.append(mount / group.relative_to(root))
+ require(len(matches) == 1, "cgroup mount cannot be resolved uniquely")
+ path = matches[0]
+ info = path.stat()
+ return {"path": str(path), "device": info.st_dev, "inode": info.st_ino, "error": None}
+ except (OSError, ValueError, IndexError, AssertionError) as error:
+ return {"path": None, "error": f"{type(error).__name__}: {error}"}
+
+
+def flat_counters(text: str) -> dict[str, int]:
+ result = {}
+ for row in text.splitlines():
+ key, value = row.split()
+ require(key not in result, "duplicate telemetry counter")
+ result[key] = int(value)
+ require(result[key] >= 0, "negative telemetry counter")
+ require(bool(result), "empty exposed telemetry counter file")
+ return result
+
+
+def pressure(text: str) -> dict[str, dict[str, float | int]]:
+ result = {}
+ for row in text.splitlines():
+ name, *parts = row.split()
+ require(name in {"some", "full"} and name not in result, "invalid PSI row")
+ values = dict(part.split("=", 1) for part in parts)
+ require(len(parts) == len(PSI_FIELDS) and set(values) == set(PSI_FIELDS), "invalid PSI fields")
+ parsed = {key: int(value) if key == "total" else float(value) for key, value in values.items()}
+ require(all(math.isfinite(value) and value >= 0 for value in parsed.values()), "invalid PSI value")
+ require(all(parsed[key] <= MAX_PERCENT for key in PSI_FIELDS[:-1]), "invalid PSI percentage")
+ result[name] = parsed
+ require("some" in result, "missing exposed PSI some row")
+ return result
+
+
+def validate_core(core: dict[str, Any]) -> None:
+ require(
+ all(isinstance(core[key], int) and core[key] > 0 for key in ("wall_ns", "monotonic_ns"))
+ and core["gc_enabled"] is True,
+ "invalid required clock/GC state",
+ )
+ require(
+ set(core["rusage"]) == set(RUSAGE_FIELDS)
+ and all(math.isfinite(value) and value >= 0 for value in core["rusage"].values()),
+ "invalid required rusage",
+ )
+ for key in ("gc_thresholds", "gc_count"):
+ require(
+ len(core[key]) == GC_GENERATIONS and all(type(value) is int and value >= 0 for value in core[key]),
+ "invalid required GC counts/thresholds",
+ )
+ require(core["gc_thresholds"][0] > 0, "automatic GC is disabled by its threshold")
+ require(len(core["gc_stats"]) == GC_GENERATIONS, "missing required GC generations")
+ require(
+ all(
+ set(row) == set(GC_FIELDS) and all(type(row[key]) is int and row[key] >= 0 for key in GC_FIELDS)
+ for row in core["gc_stats"]
+ ),
+ "invalid required GC statistics",
+ )
+
+
+def control_value(name: str, text: str) -> str:
+ if name == "cpu.max":
+ quota, period = text.split()
+ require((quota == "max" or int(quota) > 0) and int(period) > 0, "invalid exposed cpu.max")
+ elif name == "cpu.weight":
+ require(1 <= int(text) <= MAX_CPU_WEIGHT, "invalid exposed cpu.weight")
+ else:
+ for item in text.split(","):
+ bounds = [int(value) for value in item.split("-")]
+ require(len(bounds) in {1, 2} and bounds[0] >= 0 and bounds[-1] >= bounds[0], "invalid exposed cpuset")
+ return text
+
+
+def snapshot() -> dict[str, Any]:
+ """Only called outside performance(), including all filesystem reads."""
+ started = time.monotonic_ns()
+ usage = resource.getrusage(resource.RUSAGE_SELF)
+ core = {
+ "wall_ns": time.time_ns(),
+ "monotonic_ns": started,
+ "perf_counter_ns": time.perf_counter_ns(),
+ "pid": os.getpid(),
+ "ppid": os.getppid(),
+ "rusage": {key: getattr(usage, key) for key in RUSAGE_FIELDS},
+ "gc_enabled": gc.isenabled(),
+ "gc_thresholds": list(gc.get_threshold()),
+ "gc_count": list(gc.get_count()),
+ "gc_stats": gc.get_stats(),
+ }
+ validate_core(core)
+ group = unified_cgroup()
+ files: dict[str, Any] = {}
+ errors = {}
+ if group["path"] is not None:
+ for name in OPTIONAL_FILES:
+ try:
+ text = (Path(group["path"]) / name).read_text().strip()
+ except OSError as error:
+ files[name] = None
+ errors[name] = f"{type(error).__name__}: {error}"
+ continue
+ # Missing optional files are unavailability, but malformed exposed
+ # counters must not be mistaken for trustworthy zero deltas.
+ files[name] = (
+ flat_counters(text)
+ if name in COUNTER_FILES
+ else pressure(text)
+ if name == "cpu.pressure"
+ else control_value(name, text)
+ )
+ else:
+ files = dict.fromkeys(OPTIONAL_FILES)
+ errors["cgroup"] = group["error"]
+ affinity = None
+ try:
+ if hasattr(os, "sched_getaffinity"):
+ affinity = sorted(os.sched_getaffinity(0))
+ require(bool(affinity), "empty exposed affinity")
+ else:
+ errors["affinity"] = "sched_getaffinity unavailable on this platform"
+ except OSError as error:
+ errors["affinity"] = f"{type(error).__name__}: {error}"
+ return {
+ "qualification": False,
+ "core": core,
+ "cgroup": group,
+ "cgroup_files": files,
+ "optional_errors": errors,
+ "affinity": affinity,
+ "snapshot_read_ns": time.monotonic_ns() - started,
+ }
+
+
+def counter_delta(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
+ require(set(before) == set(after), "counter fields changed within a window")
+ result = {key: after[key] - value for key, value in before.items()}
+ require(all(math.isfinite(value) and value >= 0 for value in result.values()), "telemetry counter reset")
+ return result
+
+
+def telemetry_delta(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
+ first, last = before["core"], after["core"]
+ validate_core(first)
+ validate_core(last)
+ require(
+ last["wall_ns"] > first["wall_ns"] and last["monotonic_ns"] > first["monotonic_ns"],
+ "required clock did not advance",
+ )
+ require(
+ first["gc_enabled"] and last["gc_enabled"] and first["gc_thresholds"] == last["gc_thresholds"],
+ "GC configuration changed",
+ )
+ group_before, group_after = before["cgroup"], after["cgroup"]
+ require(
+ all(group_before.get(key) == group_after.get(key) for key in ("path", "device", "inode")),
+ "cgroup path or identity changed within a window",
+ )
+ require(before["affinity"] == after["affinity"], "process affinity changed within a window")
+ for name in CONTROL_FILES:
+ require(
+ before["cgroup_files"].get(name) == after["cgroup_files"].get(name),
+ "cgroup quota/weight/cpuset changed within a window",
+ )
+ optional = {}
+ for name in COUNTER_FILES:
+ a, b = before["cgroup_files"].get(name), after["cgroup_files"].get(name)
+ optional[name] = counter_delta(a, b) if a is not None and b is not None else None
+ a, b = before["cgroup_files"].get("cpu.pressure"), after["cgroup_files"].get("cpu.pressure")
+ optional["cpu.pressure"] = (
+ counter_delta({k: v["total"] for k, v in a.items()}, {k: v["total"] for k, v in b.items()})
+ if a is not None and b is not None
+ else None
+ )
+ return {
+ "qualification": False,
+ "scope": "Whole performance call, including sequential warmup, measurement, drain, validation and raw emission",
+ "wall_s": (last["wall_ns"] - first["wall_ns"]) / 1e9,
+ "monotonic_s": (last["monotonic_ns"] - first["monotonic_ns"]) / 1e9,
+ "rusage": counter_delta(first["rusage"], last["rusage"]),
+ "gc_stats": [counter_delta(a, b) for a, b in zip(first["gc_stats"], last["gc_stats"], strict=True)],
+ "optional_cgroup": optional,
+ "cpu_pressure_counters_available": all(optional.get(name) is not None for name in ("cpu.stat", "cpu.pressure")),
+ "resource_telemetry_complete": before["affinity"] is not None
+ and after["affinity"] is not None
+ and all(
+ before["cgroup_files"].get(name) is not None and after["cgroup_files"].get(name) is not None
+ for name in OPTIONAL_FILES
+ ),
+ "optional_errors_before": before["optional_errors"],
+ "optional_errors_after": after["optional_errors"],
+ }
+
+
+# Prospective observation limits, independent of the performance gates.
+MAX_CALLBACK_FRACTION = 0.001
+CALLBACK_TAIL_ALLOWANCE_NS = 10_000
+GC_RECORD_CAPACITY = 65_536
+GC_RECORD_WIDTH = 6
+
+
+class GCRecorder:
+ """Bounded numeric records, with no I/O, locks or growing collections in callbacks.
+
+ Python still creates transient scalar objects. The reported cost includes
+ measured callback self time plus a fixed per-call tail allowance; it is an
+ estimate with a conservative allowance, not proof of zero perturbation.
+ """
+
+ def __init__(self, capacity: int = GC_RECORD_CAPACITY) -> None:
+ require(type(capacity) is int and capacity > 0, "invalid GC recorder capacity")
+ self.capacity = capacity
+ self.buffer = array("Q", [0]) * (capacity * GC_RECORD_WIDTH)
+ self.count = 0
+ self.overflow = False
+ self.invalid = False
+ self._hook: Any = None
+ self._prior: tuple[Any, ...] = ()
+ self._thresholds: tuple[int, ...] = ()
+ self._closed = False
+ self.lifecycle_errors: list[str] = []
+
+ def _record(self, phase: str, info: dict[str, Any]) -> None:
+ entered = time.perf_counter_ns()
+ generation = info.get("generation")
+ if phase not in ("start", "stop") or type(generation) is not int or not 0 <= generation < GC_GENERATIONS:
+ self.invalid = True
+ return
+ if self.count >= self.capacity:
+ self.overflow = True
+ return
+ collected, uncollectable = info.get("collected", 0), info.get("uncollectable", 0)
+ if type(collected) is not int or type(uncollectable) is not int or collected < 0 or uncollectable < 0:
+ self.invalid = True
+ return
+ offset = self.count * GC_RECORD_WIDTH
+ self.buffer[offset] = entered
+ self.buffer[offset + 1] = int(phase == "stop")
+ self.buffer[offset + 2] = generation
+ self.buffer[offset + 3] = collected
+ self.buffer[offset + 4] = uncollectable
+ self.count += 1
+ self.buffer[offset + 5] = time.perf_counter_ns() - entered
+
+ def start(self) -> None:
+ require(self._hook is None and not self._closed, "GC recorder cannot be restarted")
+ require(gc.isenabled() and gc.get_threshold()[0] > 0, "ordinary automatic GC must remain enabled")
+ self._prior = tuple(gc.callbacks)
+ self._thresholds = gc.get_threshold()
+ self._hook = self._record
+ gc.callbacks.append(self._hook)
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ hook, self._hook = self._hook, None
+ if hook is None:
+ self.lifecycle_errors.append("GC recorder was never installed")
+ else:
+ matches = [index for index, item in enumerate(gc.callbacks) if item is hook]
+ if len(matches) != 1:
+ self.lifecycle_errors.append("owned GC callback identity changed")
+ for index in reversed(matches):
+ gc.callbacks.pop(index)
+ if len(gc.callbacks) != len(self._prior) or any(
+ current is not prior for current, prior in zip(gc.callbacks, self._prior, strict=False)
+ ):
+ self.lifecycle_errors.append("pre-existing GC callbacks changed")
+ if not gc.isenabled() or gc.get_threshold() != self._thresholds:
+ self.lifecycle_errors.append("GC enable state or thresholds changed")
+ self._closed = True
+
+ def report(self, start_s: float, end_s: float) -> dict[str, Any]:
+ require(self._closed, "GC recorder must close before materializing evidence")
+ require(math.isfinite(start_s) and math.isfinite(end_s) and 0 < start_s < end_s, "invalid GC measurement clock")
+ begin, end = round(start_s * 1e9), round(end_s * 1e9)
+ rows = [
+ list(self.buffer[index * GC_RECORD_WIDTH : (index + 1) * GC_RECORD_WIDTH]) for index in range(self.count)
+ ]
+ pending: dict[int, int] = {}
+ intervals = []
+ pair_errors = []
+ for stamp, stopped, generation, collected, uncollectable, _cost in rows:
+ if not stopped:
+ if generation in pending:
+ pair_errors.append("duplicate GC start")
+ pending[generation] = stamp
+ elif generation not in pending:
+ pair_errors.append("GC stop has no observed start")
+ else:
+ first = pending.pop(generation)
+ if stamp < first:
+ pair_errors.append("GC event clock reversed")
+ intervals.append(
+ {
+ "generation": generation,
+ "start_ns": first,
+ "end_ns": stamp,
+ "collected": collected,
+ "uncollectable": uncollectable,
+ "overlap_ns": max(0, min(end, stamp) - max(begin, first)),
+ }
+ )
+ if pending:
+ pair_errors.append("GC start has no observed stop")
+ relevant = [row for row in rows if row[0] <= end and row[0] + row[5] + CALLBACK_TAIL_ALLOWANCE_NS >= begin]
+ self_ns = sum(row[5] for row in relevant)
+ allowance_ns = len(relevant) * CALLBACK_TAIL_ALLOWANCE_NS
+ estimated_fraction = (self_ns + allowance_ns) / (end - begin)
+ errors = [*self.lifecycle_errors, *pair_errors]
+ if self.overflow:
+ errors.append("GC recorder overflow")
+ if self.invalid:
+ errors.append("invalid GC callback event")
+ integrity_passed = not errors
+ cost_passed = estimated_fraction <= MAX_CALLBACK_FRACTION
+ if not cost_passed:
+ errors.append("GC observer cost exceeds prospective window budget")
+ return {
+ "pid": os.getpid(),
+ "clock": "perf_counter_ns, verified against child/server handshake bounds",
+ "columns": ["timestamp_ns", "stop", "generation", "collected", "uncollectable", "callback_self_ns"],
+ "records": rows,
+ "intervals": intervals,
+ "window_start_ns": begin,
+ "window_end_ns": end,
+ "callback_count_intersecting_window": len(relevant),
+ "callback_count_entered_in_window": sum(begin <= row[0] <= end for row in rows),
+ "callback_self_ns": self_ns,
+ "per_event_tail_allowance_ns": CALLBACK_TAIL_ALLOWANCE_NS,
+ "estimated_observer_fraction": estimated_fraction,
+ "maximum_observer_fraction": MAX_CALLBACK_FRACTION,
+ "uncertainty": "Includes a fixed 10us/call tail allowance requiring a recorded preflight calibration; timing cost does not bound every scheduling/GC perturbation.",
+ "integrity_passed": integrity_passed,
+ "cost_budget_passed": cost_passed,
+ "passed": not errors,
+ "errors": errors,
+ }
+
+
+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."""
+ require(before["core"]["pid"] == after["core"]["pid"], "process identity changed")
+ begin, end = clock["start"], clock["end"]
+ require(
+ before["core"]["perf_counter_ns"] / 1e9 <= begin < end <= after["core"]["perf_counter_ns"] / 1e9,
+ "process telemetry does not bracket the measured monotonic interval",
+ )
+ delta = telemetry_delta(before, after)
+ delta["scope"] = (
+ "Enclosing process interval around the load-generator timer; includes boundary handshake/observation overhead, not exact per-request CPU time"
+ )
+ delta["cgroup_scope"] = "Shared container counters; never sum client and server observations"
+ return {"before": before, "after": after, "delta": delta}
diff --git a/tools/benchmarks/cross_encoder_lora/stability.py b/tools/benchmarks/cross_encoder_lora/stability.py
index dc4bc1779..479900b66 100644
--- a/tools/benchmarks/cross_encoder_lora/stability.py
+++ b/tools/benchmarks/cross_encoder_lora/stability.py
@@ -15,11 +15,9 @@ from __future__ import annotations
import argparse
import asyncio
-import gc
import json
import math
import os
-import resource
import signal
import socket
import statistics
@@ -34,10 +32,13 @@ from typing import Any
import torch
import uvicorn
+from sie_sdk import SIEClient
from tools.benchmarks.cross_encoder_lora import worker
from tools.benchmarks.cross_encoder_lora.adapter import require_forward_selection
+from tools.benchmarks.cross_encoder_lora.client import validate_response
from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digest, fingerprint, vector_delta
+from tools.benchmarks.cross_encoder_lora.process_metrics import CONTROL_FILES, snapshot, telemetry_delta
from tools.benchmarks.cross_encoder_lora.protocol import (
BASE_REVISION,
CPU_ORACLE,
@@ -73,16 +74,7 @@ HISTORICAL_SOURCE_REVISION = "482b599224920a97bb2fce4a740317efb89351ab"
METRICS = ((1, "mean_ms"), (1, "p95_ms"), (4, "rps"), (4, "p95_ms"), (16, "rps"), (16, "p95_ms"))
RUNNER_LIMIT = 1200
WORKER_LIMIT = 180
-GC_FIELDS = ("collections", "collected", "uncollectable")
-RUSAGE_FIELDS = ("ru_utime", "ru_stime", "ru_minflt", "ru_majflt", "ru_nvcsw", "ru_nivcsw")
-OPTIONAL_FILES = ("cpu.stat", "cpu.stat.local", "cpu.pressure", "cpu.max", "cpu.weight", "cpuset.cpus.effective")
-COUNTER_FILES = ("cpu.stat", "cpu.stat.local")
-CONTROL_FILES = ("cpu.max", "cpu.weight", "cpuset.cpus.effective")
-GC_GENERATIONS = 3
QUARTILES = 4
-PSI_FIELDS = ("avg10", "avg60", "avg300", "total")
-MAX_PERCENT = 100
-MAX_CPU_WEIGHT = 10000
class DiagnosticEvidence(Evidence):
@@ -128,215 +120,6 @@ def diagnostic_settings(warmups: int) -> Iterator[None]:
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:
- rows = (proc / "cgroup").read_text().splitlines()
- membership = [row[3:] for row in rows if row.startswith("0::")]
- require(len(membership) == 1, "unified cgroup membership is unavailable or ambiguous")
- group = Path(membership[0])
- require(group.is_absolute() and ".." not in group.parts, "invalid cgroup membership")
- matches = []
- for row in (proc / "mountinfo").read_text().splitlines():
- left, right = row.split(" - ", 1)
- if right.split()[0] != "cgroup2":
- continue
- fields = left.split()
- root = Path(fields[3].replace("\\040", " ").replace("\\134", "\\"))
- mount = Path(fields[4].replace("\\040", " ").replace("\\134", "\\"))
- if group.is_relative_to(root):
- matches.append(mount / group.relative_to(root))
- require(len(matches) == 1, "cgroup mount cannot be resolved uniquely")
- path = matches[0]
- info = path.stat()
- return {"path": str(path), "device": info.st_dev, "inode": info.st_ino, "error": None}
- except (OSError, ValueError, IndexError, AssertionError) as error:
- return {"path": None, "error": f"{type(error).__name__}: {error}"}
-
-
-def flat_counters(text: str) -> dict[str, int]:
- result = {}
- for row in text.splitlines():
- key, value = row.split()
- require(key not in result, "duplicate telemetry counter")
- result[key] = int(value)
- require(result[key] >= 0, "negative telemetry counter")
- require(bool(result), "empty exposed telemetry counter file")
- return result
-
-
-def pressure(text: str) -> dict[str, dict[str, float | int]]:
- result = {}
- for row in text.splitlines():
- name, *parts = row.split()
- require(name in {"some", "full"} and name not in result, "invalid PSI row")
- values = dict(part.split("=", 1) for part in parts)
- require(len(parts) == len(PSI_FIELDS) and set(values) == set(PSI_FIELDS), "invalid PSI fields")
- parsed = {key: int(value) if key == "total" else float(value) for key, value in values.items()}
- require(all(math.isfinite(value) and value >= 0 for value in parsed.values()), "invalid PSI value")
- require(all(parsed[key] <= MAX_PERCENT for key in PSI_FIELDS[:-1]), "invalid PSI percentage")
- result[name] = parsed
- require("some" in result, "missing exposed PSI some row")
- return result
-
-
-def validate_core(core: dict[str, Any]) -> None:
- require(
- all(isinstance(core[key], int) and core[key] > 0 for key in ("wall_ns", "monotonic_ns"))
- and core["gc_enabled"] is True,
- "invalid required clock/GC state",
- )
- require(
- set(core["rusage"]) == set(RUSAGE_FIELDS)
- and all(math.isfinite(value) and value >= 0 for value in core["rusage"].values()),
- "invalid required rusage",
- )
- for key in ("gc_thresholds", "gc_count"):
- require(
- len(core[key]) == GC_GENERATIONS and all(type(value) is int and value >= 0 for value in core[key]),
- "invalid required GC counts/thresholds",
- )
- require(core["gc_thresholds"][0] > 0, "automatic GC is disabled by its threshold")
- require(len(core["gc_stats"]) == GC_GENERATIONS, "missing required GC generations")
- require(
- all(
- set(row) == set(GC_FIELDS) and all(type(row[key]) is int and row[key] >= 0 for key in GC_FIELDS)
- for row in core["gc_stats"]
- ),
- "invalid required GC statistics",
- )
-
-
-def control_value(name: str, text: str) -> str:
- if name == "cpu.max":
- quota, period = text.split()
- require((quota == "max" or int(quota) > 0) and int(period) > 0, "invalid exposed cpu.max")
- elif name == "cpu.weight":
- require(1 <= int(text) <= MAX_CPU_WEIGHT, "invalid exposed cpu.weight")
- else:
- for item in text.split(","):
- bounds = [int(value) for value in item.split("-")]
- require(len(bounds) in {1, 2} and bounds[0] >= 0 and bounds[-1] >= bounds[0], "invalid exposed cpuset")
- return text
-
-
-def snapshot() -> dict[str, Any]:
- """Only called outside performance(), including all filesystem reads."""
- started = time.monotonic_ns()
- usage = resource.getrusage(resource.RUSAGE_SELF)
- core = {
- "wall_ns": time.time_ns(),
- "monotonic_ns": started,
- "rusage": {key: getattr(usage, key) for key in RUSAGE_FIELDS},
- "gc_enabled": gc.isenabled(),
- "gc_thresholds": list(gc.get_threshold()),
- "gc_count": list(gc.get_count()),
- "gc_stats": gc.get_stats(),
- }
- validate_core(core)
- group = unified_cgroup()
- files: dict[str, Any] = {}
- errors = {}
- if group["path"] is not None:
- for name in OPTIONAL_FILES:
- try:
- text = (Path(group["path"]) / name).read_text().strip()
- except OSError as error:
- files[name] = None
- errors[name] = f"{type(error).__name__}: {error}"
- continue
- # Missing optional files are unavailability, but malformed exposed
- # counters must not be mistaken for trustworthy zero deltas.
- files[name] = (
- flat_counters(text)
- if name in COUNTER_FILES
- else pressure(text)
- if name == "cpu.pressure"
- else control_value(name, text)
- )
- else:
- files = dict.fromkeys(OPTIONAL_FILES)
- errors["cgroup"] = group["error"]
- affinity = None
- try:
- if hasattr(os, "sched_getaffinity"):
- affinity = sorted(os.sched_getaffinity(0))
- require(bool(affinity), "empty exposed affinity")
- else:
- errors["affinity"] = "sched_getaffinity unavailable on this platform"
- except OSError as error:
- errors["affinity"] = f"{type(error).__name__}: {error}"
- return {
- "qualification": False,
- "core": core,
- "cgroup": group,
- "cgroup_files": files,
- "optional_errors": errors,
- "affinity": affinity,
- "snapshot_read_ns": time.monotonic_ns() - started,
- }
-
-
-def counter_delta(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
- require(set(before) == set(after), "counter fields changed within a window")
- result = {key: after[key] - value for key, value in before.items()}
- require(all(math.isfinite(value) and value >= 0 for value in result.values()), "telemetry counter reset")
- return result
-
-
-def telemetry_delta(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
- first, last = before["core"], after["core"]
- validate_core(first)
- validate_core(last)
- require(
- last["wall_ns"] > first["wall_ns"] and last["monotonic_ns"] > first["monotonic_ns"],
- "required clock did not advance",
- )
- require(
- first["gc_enabled"] and last["gc_enabled"] and first["gc_thresholds"] == last["gc_thresholds"],
- "GC configuration changed",
- )
- group_before, group_after = before["cgroup"], after["cgroup"]
- require(
- all(group_before.get(key) == group_after.get(key) for key in ("path", "device", "inode")),
- "cgroup path or identity changed within a window",
- )
- require(before["affinity"] == after["affinity"], "process affinity changed within a window")
- for name in CONTROL_FILES:
- require(
- before["cgroup_files"].get(name) == after["cgroup_files"].get(name),
- "cgroup quota/weight/cpuset changed within a window",
- )
- optional = {}
- for name in COUNTER_FILES:
- a, b = before["cgroup_files"].get(name), after["cgroup_files"].get(name)
- optional[name] = counter_delta(a, b) if a is not None and b is not None else None
- a, b = before["cgroup_files"].get("cpu.pressure"), after["cgroup_files"].get("cpu.pressure")
- optional["cpu.pressure"] = (
- counter_delta({k: v["total"] for k, v in a.items()}, {k: v["total"] for k, v in b.items()})
- if a is not None and b is not None
- else None
- )
- return {
- "qualification": False,
- "scope": "Whole performance call, including sequential warmup, measurement, drain, validation and raw emission",
- "wall_s": (last["wall_ns"] - first["wall_ns"]) / 1e9,
- "monotonic_s": (last["monotonic_ns"] - first["monotonic_ns"]) / 1e9,
- "rusage": counter_delta(first["rusage"], last["rusage"]),
- "gc_stats": [counter_delta(a, b) for a, b in zip(first["gc_stats"], last["gc_stats"], strict=True)],
- "optional_cgroup": optional,
- "cpu_pressure_counters_available": all(optional.get(name) is not None for name in ("cpu.stat", "cpu.pressure")),
- "resource_telemetry_complete": before["affinity"] is not None
- and after["affinity"] is not None
- and all(
- before["cgroup_files"].get(name) is not None and after["cgroup_files"].get(name) is not None
- for name in OPTIONAL_FILES
- ),
- "optional_errors_before": before["optional_errors"],
- "optional_errors_after": after["optional_errors"],
- }
-
-
def metrics(phase: dict[str, Any]) -> dict[str, Any]:
samples = phase["samples"]
latencies = [row["latency_ms"] for row in samples]
@@ -418,7 +201,7 @@ def verify_attempt(path: Path, record: dict[str, Any]) -> None:
)
for row in rows:
saved = row["scores"][:]
- worker.validate_response(row)
+ validate_response(row)
require(saved == row["scores"] and row["selection"] is None, "baseline scores/selection differ")
require(row["end_ns"] >= row["start_ns"] > 0, "invalid request timestamps")
if record["concurrency"] == 1:
@@ -635,7 +418,7 @@ async def child(args: argparse.Namespace) -> dict[str, Any]:
environment["hardware_preflight_only"] = environment.pop("qualification")
environment["qualification"] = False
environment["source_imports"] = {}
- for name, target in (("sdk", worker.SIEClient), ("server", worker.AppFactory)):
+ for name, target in (("sdk", SIEClient), ("server", worker.AppFactory)):
module_file = sys.modules[target.__module__].__file__
assert module_file is not None, "source module has no file"
source_file = Path(module_file).resolve() # noqa: ASYNC240 -- preflight before model/server starts
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_client_lifecycle.py b/tools/benchmarks/cross_encoder_lora/tests/test_client_lifecycle.py
index 93d899001..23e6c12c6 100644
--- a/tools/benchmarks/cross_encoder_lora/tests/test_client_lifecycle.py
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_client_lifecycle.py
@@ -15,7 +15,7 @@ import pytest
from sie_sdk._msgpack import packb, unpackb
from sie_sdk.client.errors import ServerError, SIEConnectionError
-from tools.benchmarks.cross_encoder_lora import worker
+from tools.benchmarks.cross_encoder_lora import client as worker
from tools.benchmarks.cross_encoder_lora.evidence import Evidence
HTTP_CLIENT = httpx.Client
@@ -369,3 +369,47 @@ def test_performance_evidence_failure_still_closes_all_clients(monkeypatch: pyte
worker.performance(URL, 4, evidence, smoke=True)
assert closed == [True] * 4
assert gc.isenabled() == gc_enabled
+
+
+def test_primary_sdk_error_survives_observer_failure_with_all_wire_attempts(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ attempts = 0
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal attempts
+ attempts += 1
+ if attempts == 4: # two warmups, one completed timed request, one failure
+ return httpx.Response(500, json={"error": {"code": "INTERNAL_ERROR", "message": "primary SDK failure"}})
+ return success(request)
+
+ def after(_clock: dict[str, float]) -> None:
+ raise BrokenPipeError("secondary observer failed")
+
+ install_transport(monkeypatch, handler)
+ evidence = Evidence(tmp_path / "out")
+ with pytest.raises(ServerError) as failure:
+ worker.performance(URL, 1, evidence, smoke=True, after_measure=after)
+ assert "secondary observer failed" in " ".join(failure.value.__notes__)
+ row = json.loads((evidence.directory / "events.jsonl").read_text())
+ assert len(row["completed_samples"]) == 1
+ assert [value["status"] for value in row["wire_responses"]] == [200, 200, 200, 500]
+ assert row["primary_error"]["type"] == "ServerError"
+ assert row["finalization_errors"] == [{"type": "BrokenPipeError", "message": "secondary observer failed"}]
+
+
+def test_before_measure_failure_aborts_waiting_threads_and_preserves_warmups(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ install_transport(monkeypatch, success)
+
+ def before() -> None:
+ raise OSError("boundary failed before timer")
+
+ evidence = Evidence(tmp_path / "out")
+ with pytest.raises(OSError, match="boundary failed"):
+ worker.performance(URL, 4, evidence, smoke=True, before_measure=before)
+ row = json.loads((evidence.directory / "events.jsonl").read_text())
+ assert len(row["warmups"]) == 2
+ assert row["completed_samples"] == []
+ assert len(row["wire_responses"]) == 2
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_isolation.py b/tools/benchmarks/cross_encoder_lora/tests/test_isolation.py
new file mode 100644
index 000000000..05fb7311e
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_isolation.py
@@ -0,0 +1,352 @@
+"""Real SDK-only child protocol, identity, clock and owned-process controls."""
+
+from __future__ import annotations
+
+import ast
+import asyncio
+import copy
+import json
+import os
+import subprocess
+import sys
+import threading
+from collections.abc import Iterator
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any, cast
+
+import pytest
+from sie_sdk._msgpack import packb, unpackb
+
+from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digest
+from tools.benchmarks.cross_encoder_lora.isolation import IsolatedLoadgen
+from tools.benchmarks.cross_encoder_lora.loadgen import PHASES
+from tools.benchmarks.cross_encoder_lora.protocol import MODEL
+from tools.benchmarks.cross_encoder_lora.runner import ROOT, source_environment
+
+
+def sdk_server(monkeypatch: pytest.MonkeyPatch) -> Iterator[str]:
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self) -> None:
+ body = unpackb(self.rfile.read(int(self.headers["content-length"])), numeric_arrays=False)
+ content = packb(
+ {
+ "model": MODEL,
+ "scores": [
+ {"item_id": item["id"], "score": float(4 - index), "rank": index}
+ for index, item in enumerate(body["items"])
+ ],
+ "usage": {"input_tokens": 17},
+ }
+ )
+ self.send_response(200)
+ self.send_header("Content-Type", "application/msgpack")
+ self.send_header("Content-Length", str(len(content)))
+ self.send_header("X-Total-Time", "0.01")
+ self.end_headers()
+ self.wfile.write(content)
+ self.wfile.flush()
+
+ def log_message(self, format: str, *args: Any) -> None:
+ pass
+
+ monkeypatch.setenv("PYTHONPATH", source_environment(ROOT)["PYTHONPATH"])
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_port}"
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+ assert not thread.is_alive()
+
+
+async def test_one_sdk_only_exec_pid_reused_across_all_phases_and_reaped(sdk_server: str, tmp_path: Path) -> None:
+ evidence = Evidence(tmp_path / "out")
+ async with IsolatedLoadgen(sdk_server, ROOT, evidence, smoke=True) as owner:
+ assert owner.process is not None
+ pid = owner.process.pid
+ assert pid != os.getpid()
+ for concurrency in PHASES:
+ await owner.phase(concurrency)
+ assert owner.process.pid == pid
+ with pytest.raises(AssertionError, match="reaped"):
+ owner.results()
+ assert owner.receipt["passed"]
+ assert owner.receipt["reaped"]
+ assert owner.receipt["returncode"] == 0
+ identity = owner.receipt["identity"]
+ assert identity["forbidden_imports_present"] is False
+ assert identity["process_group"] == os.getpgrp()
+ assert identity["ppid"] == os.getpid()
+ assert Path(identity["sdk_path"]).is_relative_to(ROOT / "packages/sie_sdk/src")
+ results = owner.results()
+ assert list(results) == ["1", "4", "16"]
+ assert results["1"]["count"] == 4
+ for phase in results.values():
+ assert phase["identity"] == identity
+ assert 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 all(len(row["responses"]) == 1 for row in phase["samples"])
+ terminal = json.loads((evidence.directory / "loadgen/terminal.json").read_text())
+ assert terminal["phases"] == owner.records
+ with pytest.raises(ProcessLookupError):
+ os.kill(pid, 0)
+
+
+def synthetic_owner(tmp_path: Path) -> tuple[IsolatedLoadgen, dict[str, Any], dict[str, Any]]:
+ owner = IsolatedLoadgen("http://unused.invalid", ROOT, Evidence(tmp_path / "out"), smoke=False)
+ identity = {"pid": 999999, "source": str(ROOT)}
+ owner.receipt["identity"] = identity
+ clock = {"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}},
+ "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,
+ },
+ }
+
+ owner.observations[1] = observation(os.getpid())
+ record = {"concurrency": 1}
+ value = {
+ "concurrency": 1,
+ "smoke": False,
+ "identity": identity,
+ "measurement_clock": clock,
+ "client_observation": observation(identity["pid"]),
+ }
+ return owner, record, value
+
+
+ "mutation",
+ [
+ "swapped_phase",
+ "clock",
+ "observation_clock",
+ "identity",
+ "pid",
+ "window",
+ "cost_nan",
+ "combined_budget",
+ "integrity",
+ ],
+)
+def test_phase_payload_must_match_observed_ipc_provenance_and_combined_budget(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"]
+ if mutation == "swapped_phase":
+ value["concurrency"] = 4
+ elif mutation == "clock":
+ value["measurement_clock"]["end"] += 1
+ elif mutation == "observation_clock":
+ value["client_observation"]["clock"] = {"start": 2.0, "deadline": 62.0, "end": 62.1}
+ elif mutation == "identity":
+ value["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 == "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
+ else:
+ value["client_observation"]["gc"]["integrity_passed"] = False
+ with pytest.raises(AssertionError):
+ owner._validate_phase(record, value)
+
+
[email protected]("mutation", ["failed", "identity", "schedule", "smoke"])
+async def test_valid_terminal_hash_cannot_mask_wrong_terminal_payload(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mutation: str
+) -> None:
+ owner, _, _ = synthetic_owner(tmp_path)
+ owner.records.extend({"concurrency": c} for c in PHASES)
+ terminal: dict[str, Any] = {
+ "passed": True,
+ "identity": owner.receipt["identity"],
+ "phases": owner.records,
+ "smoke": False,
+ "finished_ns": 1,
+ }
+ terminal = copy.deepcopy(terminal)
+ if mutation == "failed":
+ terminal["passed"] = False
+ elif mutation == "identity":
+ terminal["identity"]["pid"] += 1
+ elif mutation == "schedule":
+ terminal["phases"].reverse()
+ else:
+ terminal["smoke"] = True
+ path = owner.evidence.directory / "loadgen/terminal.json"
+ path.parent.mkdir()
+ atomic_json(path, terminal)
+
+ class Exited:
+ returncode = 0
+ stdin = None
+
+ async def wait(self) -> int:
+ return 0
+
+ async def send(*_args: Any) -> None:
+ pass
+
+ async def read(*_args: Any, **_kwargs: Any) -> dict[str, Any]:
+ return {"terminal_sha256": digest(path)}
+
+ owner.process = cast("asyncio.subprocess.Process", Exited())
+ monkeypatch.setattr(owner, "_send", send)
+ monkeypatch.setattr(owner, "_read", read)
+ with pytest.raises(AssertionError, match="terminal"):
+ await owner._cleanup(True)
+ assert owner.receipt["passed"] is False
+ assert owner.receipt["reaped"] is True
+
+
+async def test_cancel_during_finish_handshake_reaps_silent_real_child(tmp_path: Path) -> None:
+ owner = IsolatedLoadgen("http://unused.invalid", ROOT, Evidence(tmp_path / "out"), smoke=True)
+ owner.process = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-c",
+ "import time; time.sleep(60)",
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.DEVNULL,
+ close_fds=True,
+ )
+ owner.records.extend({"concurrency": c} for c in PHASES)
+ task = asyncio.create_task(owner.__aexit__(None, None, None))
+ await asyncio.sleep(0.05)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, timeout=8)
+ assert owner.receipt["reaped"]
+ assert owner.process is not None
+ assert owner.process.returncode is not None
+
+
+async def test_child_crash_and_parent_phase_cancellation_reap(sdk_server: str, tmp_path: Path) -> None:
+ owner = IsolatedLoadgen(sdk_server, ROOT, Evidence(tmp_path / "out"), smoke=True)
+ with pytest.raises(AssertionError, match="missing"):
+ async with owner:
+ assert owner.process is not None
+ owner.process.kill()
+ await owner.process.wait()
+ await owner._read("ready", 1)
+ assert owner.receipt["reaped"]
+ assert owner.process is not None
+ assert owner.process.returncode is not None
+
+
+async def test_termination_exit_race_preserves_original_failure(tmp_path: Path) -> None:
+ owner = IsolatedLoadgen("http://unused.invalid", ROOT, Evidence(tmp_path / "out"), smoke=True)
+
+ class RacedExit:
+ returncode = None
+ stdin = None
+
+ def terminate(self) -> None:
+ raise ProcessLookupError("already exited")
+
+ async def wait(self) -> int:
+ self.returncode = 1
+ return 1
+
+ owner.process = cast("asyncio.subprocess.Process", RacedExit())
+ original = ValueError("primary phase failure")
+ await owner.__aexit__(ValueError, original, None)
+ assert owner.receipt["termination_raced_exit"]
+ assert owner.receipt["reaped"]
+ assert owner.receipt["returncode"] == 1
+
+
+async def test_cleanup_write_failure_never_masks_primary_phase_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from tools.benchmarks.cross_encoder_lora import isolation
+
+ owner = IsolatedLoadgen("http://unused.invalid", ROOT, Evidence(tmp_path / "out"), smoke=True)
+
+ def fail(*_args: Any) -> None:
+ raise OSError("injected receipt write failure")
+
+ monkeypatch.setattr(isolation, "atomic_json", fail)
+ original = ValueError("original phase error")
+ await owner.__aexit__(ValueError, original, None)
+ assert any("receipt write failure" in note for note in original.__notes__)
+ assert owner.receipt["reaped"]
+
+
+def test_sdk_calls_lanes_and_measured_executor_core_match_recorded_harness() -> None:
+ from tools.benchmarks.cross_encoder_lora import client
+
+ baseline = subprocess.run(
+ ["git", "show", "a2932d81:tools/benchmarks/cross_encoder_lora/worker.py"], # noqa: S607
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if baseline.returncode:
+ pytest.skip("source invariant requires the recorded parent commit in git history")
+ old, new = ast.parse(baseline.stdout), ast.parse(Path(client.__file__).read_text())
+
+ def definition(tree: ast.AST, name: str) -> ast.AST:
+ return next(
+ node for node in ast.walk(tree) if isinstance(node, (ast.FunctionDef, ast.ClassDef)) and node.name == name
+ )
+
+ class Names(ast.NodeTransformer):
+ def visit_Name(self, node: ast.Name) -> ast.Name:
+ names = {
+ "sequential": "SEQUENTIAL",
+ "steady_seconds": "STEADY_SECONDS",
+ "future_timeout": "PERFORMANCE_FUTURE_TIMEOUT_S",
+ }
+ return ast.Name(id=names.get(node.id, node.id), ctx=node.ctx)
+
+ assert ast.dump(definition(old, "Client")) == ast.dump(definition(new, "Client"))
+ assert ast.dump(definition(old, "lane")) == ast.dump(Names().visit(definition(new, "lane")))
+
+ def executor(tree: ast.AST) -> ast.With:
+ return next(
+ node
+ for node in ast.walk(definition(tree, "performance"))
+ if isinstance(node, ast.With)
+ and any(
+ isinstance(item.context_expr, ast.Call)
+ and getattr(item.context_expr.func, "id", None) == "ThreadPoolExecutor"
+ for item in node.items
+ )
+ )
+
+ new_executor = executor(new)
+ # Only the pre-clock readiness hook is new. It aborts the barrier on failure.
+ assert isinstance(new_executor.body[1], ast.Try)
+ new_executor.body.pop(1)
+ assert ast.dump(executor(old)) == ast.dump(Names().visit(new_executor))
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_probe.py b/tools/benchmarks/cross_encoder_lora/tests/test_probe.py
index 8864463da..339efbc0c 100644
--- a/tools/benchmarks/cross_encoder_lora/tests/test_probe.py
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_probe.py
@@ -18,11 +18,12 @@ from transformers import BertConfig, BertForSequenceClassification, BertTokenize
from tools.benchmarks.cross_encoder_lora import prepare as source_preparer
from tools.benchmarks.cross_encoder_lora.adapter import require_forward_coverage
+from tools.benchmarks.cross_encoder_lora.client import describe_response, validate_response
from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, vector_delta
from tools.benchmarks.cross_encoder_lora.fixtures import prepare
from tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISION, ORDERS, compare, paired_gate, percentile
from tools.benchmarks.cross_encoder_lora.runner import ROOT, extract, source_environment
-from tools.benchmarks.cross_encoder_lora.worker import ORDER, describe_response, matching_vector, validate_response
+from tools.benchmarks.cross_encoder_lora.worker import ORDER, matching_vector
def tiny_snapshot(directory: Path) -> Path:
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_process_metrics.py b/tools/benchmarks/cross_encoder_lora/tests/test_process_metrics.py
new file mode 100644
index 000000000..bbbf35f80
--- /dev/null
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_process_metrics.py
@@ -0,0 +1,210 @@
+"""GC recording is bounded and diagnostic counters keep their actual scope."""
+
+from __future__ import annotations
+
+import gc
+import time
+from array import array
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from tools.benchmarks.cross_encoder_lora import process_metrics as metrics
+
+
+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()
+ recorder.close()
+ recorder.count = len(rows)
+ recorder.buffer = array("Q", [value for row in rows for value in row])
+ return recorder.report(start, end)
+
+
+def test_actual_gc_records_preserve_callbacks_thresholds_and_pairing() -> None:
+ callbacks = tuple(gc.callbacks)
+ thresholds = gc.get_threshold()
+ recorder = metrics.GCRecorder()
+ before = metrics.snapshot()
+ recorder.start()
+ started = time.perf_counter()
+ cycle = []
+ cycle.append(cycle)
+ del cycle
+ gc.collect()
+ ended = time.perf_counter()
+ recorder.close()
+ after = metrics.snapshot()
+ value = recorder.report(started, ended)
+ assert value["integrity_passed"]
+ assert value["records"]
+ assert any(interval["generation"] == 2 and interval["collected"] >= 1 for interval in value["intervals"])
+ assert tuple(gc.callbacks) == callbacks
+ assert gc.get_threshold() == thresholds
+ assert gc.isenabled()
+ assert recorder._hook is None
+ bracket = metrics.bracket(before, after, {"start": started, "end": ended})
+ assert "Enclosing process interval" in bracket["delta"]["scope"]
+ assert "never sum" in bracket["delta"]["cgroup_scope"]
+
+
+def test_callback_straddling_start_is_charged_and_collection_overlap_reported() -> None:
+ value = report([[999_999_000, 0, 0, 0, 0, 500], [1_100_000_000, 1, 0, 4, 0, 500]])
+ assert value["passed"]
+ assert value["callback_count_entered_in_window"] == 1
+ assert value["callback_count_intersecting_window"] == 2
+ assert value["callback_self_ns"] == 1000
+ assert value["intervals"][0]["overlap_ns"] == 100_000_000
+ assert value["estimated_observer_fraction"] == 0.000021
+
+
+ "rows",
+ [
+ [[1_100_000_000, 0, 0, 0, 0, 1]],
+ [[1_100_000_000, 1, 0, 0, 0, 1]],
+ [[1_200_000_000, 0, 0, 0, 0, 1], [1_100_000_000, 1, 0, 0, 0, 1]],
+ [[1_100_000_000, 0, 0, 0, 0, 1], [1_200_000_000, 0, 0, 0, 0, 1]],
+ ],
+)
+def test_incomplete_or_reversed_gc_events_fail_integrity(rows: list[list[int]]) -> None:
+ assert not report(rows)["integrity_passed"]
+
+
+def test_overflow_and_invalid_events_fail_without_unbounded_growth() -> None:
+ recorder = metrics.GCRecorder(capacity=1)
+ recorder.start()
+ recorder._record("start", {"generation": 0})
+ recorder._record("stop", {"generation": 0})
+ recorder._record("bad", {"generation": 0})
+ recorder.close()
+ value = recorder.report(1.0, time.perf_counter())
+ assert len(recorder.buffer) == metrics.GC_RECORD_WIDTH
+ assert not value["integrity_passed"]
+ assert "GC recorder overflow" in value["errors"]
+ assert "invalid GC callback event" in value["errors"]
+
+
+def test_prior_callbacks_are_preserved_and_foreign_change_rejects() -> None:
+ def prior(_phase: str, _info: dict[str, Any]) -> None:
+ pass
+
+ def unexpected(_phase: str, _info: dict[str, Any]) -> None:
+ pass
+
+ gc.callbacks.append(prior)
+ recorder = metrics.GCRecorder()
+ try:
+ recorder.start()
+ gc.callbacks.append(unexpected)
+ recorder.close()
+ assert prior in gc.callbacks
+ assert unexpected in gc.callbacks
+ assert "pre-existing GC callbacks changed" in recorder.report(1.0, 2.0)["errors"]
+ finally:
+ recorder.close()
+ gc.callbacks.remove(prior)
+ gc.callbacks.remove(unexpected)
+
+
+def test_cost_limit_never_changes_performance_gates() -> None:
+ value = report([[1_100_000_000, 0, 0, 0, 0, 600_000], [1_200_000_000, 1, 0, 0, 0, 600_000]])
+ assert value["integrity_passed"]
+ assert not value["cost_budget_passed"]
+ assert not value["passed"]
+ assert value["maximum_observer_fraction"] == 0.001
+
+
[email protected](("started", "ended"), [(2.0, 1.0), (1.0, 1.0), (float("nan"), 2.0)])
+def test_invalid_measurement_clock_rejected(started: float, ended: float) -> None:
+ with pytest.raises(AssertionError, match="clock"):
+ report([], started, ended)
+
+
+def test_callable_equality_cannot_hide_changed_callback_identity() -> 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()
+ gc.callbacks.append(original)
+ recorder = metrics.GCRecorder()
+ try:
+ recorder.start()
+ index = next(index for index, value in enumerate(gc.callbacks) if value is original)
+ gc.callbacks[index] = replacement
+ recorder.close()
+ assert "pre-existing GC callbacks changed" in recorder.report(1.0, 2.0)["errors"]
+ finally:
+ recorder.close()
+ gc.callbacks[:] = [value for value in gc.callbacks if value is not original and value is not replacement]
+
+
+def test_calibration_uses_six_units_fixed_allowance_and_signed_residuals() -> None:
+ from tools.benchmarks.cross_encoder_lora.calibrate_gc import bound
+
+ assert bound([-100.0] * 6)["mean_ns"] == -100.0
+ assert bound([10_000.0] * 6)["passed"]
+ assert not bound([10_000.1] * 6)["passed"]
+ uncertain = bound([0, 0, 0, 10_000, 10_000, 10_000])
+ assert uncertain["one_sided_95_upper_ns"] > uncertain["mean_ns"]
+ with pytest.raises(AssertionError, match="six"):
+ bound([1.0] * 5)
+
+
+def test_calibration_preserves_gc_and_exercises_nonzero_fields() -> None:
+ from tools.benchmarks.cross_encoder_lora.calibrate_gc import collect_arm, direct
+
+ prior = tuple(gc.callbacks)
+ thresholds = gc.get_threshold()
+ for observed in (False, True):
+ value = collect_arm(observed, 5)
+ assert len(value["duration_ns"]) == 5
+ assert len(value["records"]) == (10 if observed else 0)
+ for generation in range(3):
+ value = direct(generation, 5)
+ assert value["info"]["collected"] > 0
+ assert value["info"]["uncollectable"] > 0
+ assert len(value["residual_ns"]) == 10
+ assert tuple(gc.callbacks) == prior
+ assert gc.get_threshold() == thresholds
+ assert gc.isenabled()
+
+
+def test_calibration_failure_writes_partial_raw_arms_before_reraising(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import json
+ import sys
+
+ from tools.benchmarks.cross_encoder_lora import calibrate_gc
+
+ class ExtraStop(metrics.GCRecorder):
+ def _record(self, phase: str, info: dict[str, Any]) -> None:
+ super()._record(phase, info)
+ if phase == "stop":
+ super()._record(phase, info)
+
+ monkeypatch.setattr(calibrate_gc, "GCRecorder", ExtraStop)
+ monkeypatch.setattr(calibrate_gc, "COLLECTIONS", 3)
+ output = tmp_path / "failed-calibration.json"
+ monkeypatch.setattr(sys, "argv", ["calibrate_gc", "--output", str(output)])
+ with pytest.raises(AssertionError, match="extra/missing"):
+ calibrate_gc.main()
+ value = json.loads(output.read_text())
+ assert value["passed"] is False
+ assert value["qualification"] is False
+ assert value["error"]["type"] == "AssertionError"
+ assert value["blocks"][0]["arms"]["False"]["passed"]
+ observed = value["blocks"][0]["arms"]["True"]
+ assert not observed["passed"]
+ assert observed["completed"] == 3
+ assert len(observed["duration_ns"]) == 3
+ assert len(observed["records"]) == 9
diff --git a/tools/benchmarks/cross_encoder_lora/tests/test_stability.py b/tools/benchmarks/cross_encoder_lora/tests/test_stability.py
index c7230fc93..f0973a6e8 100644
--- a/tools/benchmarks/cross_encoder_lora/tests/test_stability.py
+++ b/tools/benchmarks/cross_encoder_lora/tests/test_stability.py
@@ -16,8 +16,8 @@ from typing import Any
import pytest
from tools.benchmarks.cross_encoder_lora import prepare as source_preparer
+from tools.benchmarks.cross_encoder_lora import process_metrics, worker
from tools.benchmarks.cross_encoder_lora import stability as probe
-from tools.benchmarks.cross_encoder_lora import worker
from tools.benchmarks.cross_encoder_lora.evidence import digest, fingerprint
from tools.benchmarks.cross_encoder_lora.fixtures import prepare
from tools.benchmarks.cross_encoder_lora.protocol import BASE_REVISION
@@ -31,14 +31,14 @@ def observed(tick: int = 1) -> dict[str, Any]:
"core": {
"wall_ns": tick * 1000000000,
"monotonic_ns": tick * 1000000000,
- "rusage": dict.fromkeys(probe.RUSAGE_FIELDS, tick),
+ "rusage": dict.fromkeys(process_metrics.RUSAGE_FIELDS, tick),
"gc_enabled": True,
"gc_thresholds": [700, 10, 10],
"gc_count": [tick, 0, 0],
- "gc_stats": [dict.fromkeys(probe.GC_FIELDS, tick) for _ in range(3)],
+ "gc_stats": [dict.fromkeys(process_metrics.GC_FIELDS, tick) for _ in range(3)],
},
"cgroup": {"path": None, "error": "unavailable"},
- "cgroup_files": dict.fromkeys(probe.OPTIONAL_FILES),
+ "cgroup_files": dict.fromkeys(process_metrics.OPTIONAL_FILES),
"optional_errors": {"cgroup": "unavailable"},
"affinity": None,
"snapshot_read_ns": 1,
@@ -116,10 +116,10 @@ def test_all_fixed_process_units_and_positive_metrics_required(failure: str) ->
def test_optional_cgroup_unavailable_is_explicit_not_zero(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(probe, "unified_cgroup", lambda: {"path": None, "error": "not exposed"})
+ monkeypatch.setattr(process_metrics, "unified_cgroup", lambda: {"path": None, "error": "not exposed"})
first, last = probe.snapshot(), probe.snapshot()
delta = probe.telemetry_delta(first, last)
- assert set(first["cgroup_files"]) == set(probe.OPTIONAL_FILES)
+ assert set(first["cgroup_files"]) == set(process_metrics.OPTIONAL_FILES)
assert all(value is None for value in first["cgroup_files"].values())
assert delta["optional_cgroup"]["cpu.stat"] is None
assert not delta["resource_telemetry_complete"]
@@ -140,7 +140,7 @@ def test_required_telemetry_validation(failure: str) -> None:
else:
core["gc_enabled"] = False
with pytest.raises(AssertionError):
- probe.validate_core(core)
+ process_metrics.validate_core(core)
def test_own_cgroup_resolution_and_no_namespace_fallback(tmp_path: Path) -> None:
@@ -152,20 +152,22 @@ def test_own_cgroup_resolution_and_no_namespace_fallback(tmp_path: Path) -> None
(proc / "cgroup").write_text("0::/namespace/child\n")
line = f"1 0 0:1 /namespace {mount} rw - cgroup2 cgroup rw\n"
(proc / "mountinfo").write_text(line)
- assert probe.unified_cgroup(proc)["path"] == str(owned)
+ assert process_metrics.unified_cgroup(proc)["path"] == str(owned)
(proc / "mountinfo").write_text(line + line)
- assert probe.unified_cgroup(proc)["path"] is None
+ assert process_metrics.unified_cgroup(proc)["path"] is None
(proc / "cgroup").write_text("0::/other/child\n")
(proc / "mountinfo").write_text(line)
- assert probe.unified_cgroup(proc)["path"] is None
+ assert process_metrics.unified_cgroup(proc)["path"] is None
def test_exposed_counters_and_gauges_have_distinct_semantics() -> None:
first, last = observed(1), observed(2)
for record, ticks, avg in ((first, 100, 90), (last, 120, 1)):
record["cgroup"] = {"path": "/owned", "device": 1, "inode": 2, "error": None}
- record["cgroup_files"]["cpu.stat"] = probe.flat_counters(f"usage_usec {ticks}\nnr_throttled 1\n")
- record["cgroup_files"]["cpu.pressure"] = probe.pressure(f"some avg10={avg} avg60=0 avg300=0 total={ticks}\n")
+ record["cgroup_files"]["cpu.stat"] = process_metrics.flat_counters(f"usage_usec {ticks}\nnr_throttled 1\n")
+ record["cgroup_files"]["cpu.pressure"] = process_metrics.pressure(
+ f"some avg10={avg} avg60=0 avg300=0 total={ticks}\n"
+ )
last["core"]["gc_count"] = [0, 0, 0] # Automatic GC resets this gauge normally.
delta = probe.telemetry_delta(first, last)
assert delta["cpu_pressure_counters_available"]
@@ -177,9 +179,9 @@ def test_exposed_counters_and_gauges_have_distinct_semantics() -> None:
probe.telemetry_delta(first, last)
for text in ("usage_usec -1", "usage_usec 0\nusage_usec 1", ""):
with pytest.raises((AssertionError, ValueError)):
- probe.flat_counters(text)
+ process_metrics.flat_counters(text)
with pytest.raises(AssertionError, match="PSI"):
- probe.pressure("some avg10=nan avg60=0 avg300=0 total=1")
+ process_metrics.pressure("some avg10=nan avg60=0 avg300=0 total=1")
@pytest.mark.parametrize(
@@ -347,59 +349,28 @@ def test_negative_raw_latency_cannot_hide_in_positive_aggregates() -> None:
probe.metrics(phase)
-def test_serving_observer_timed_loop_and_gc_are_unmodified() -> None:
+def test_serving_observer_and_gc_are_unmodified() -> None:
baseline = subprocess.run(
- ["git", "show", "f06f414a:tools/benchmarks/cross_encoder_lora/worker.py"], # noqa: S607
+ ["git", "show", "a2932d81:tools/benchmarks/cross_encoder_lora/worker.py"], # noqa: S607
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
if baseline.returncode:
- pytest.skip("timed-code invariant control requires its documented parent commit in git history")
- # 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 node
+ pytest.skip("invariant control requires its documented parent commit in git history")
def code(text: str) -> dict[str, str]:
return {
- node.name: ast.dump(TimedCore().visit(node))
+ node.name: ast.dump(node)
for node in ast.parse(text).body
- if isinstance(node, (ast.FunctionDef, ast.ClassDef)) and node.name in names
+ if isinstance(node, ast.FunctionDef) and node.name in {"unobserved", "memory"}
}
assert code(Path(worker.__file__).read_text()) == code(baseline.stdout)
+ # Historical diagnostic timing still uses the in-process wrapper and does
+ # not force GC. The new qualification load loop has its own extraction and
+ # clock-boundary tests; exact historical replay remains pinned to 482b.
tree = ast.parse(Path(probe.__file__).read_text())
assert not any(
isinstance(node, ast.Call)
diff --git a/tools/benchmarks/cross_encoder_lora/worker.py b/tools/benchmarks/cross_encoder_lora/worker.py
index 110fd52d3..01c56d044 100644
--- a/tools/benchmarks/cross_encoder_lora/worker.py
+++ b/tools/benchmarks/cross_encoder_lora/worker.py
@@ -12,7 +12,6 @@ import math
import os
import resource
import socket
-import statistics
import subprocess
import sys
import threading
@@ -20,26 +19,30 @@ import time
import weakref
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
-from contextlib import ExitStack, contextmanager
+from contextlib import contextmanager
from http import HTTPStatus
from pathlib import Path
from typing import Any
-import httpx
import torch
import uvicorn
import yaml
-from sie_sdk import SIEClient
-from sie_sdk._msgpack import unpackb
-from sie_sdk.client.errors import RequestError, ServerError
+from sie_sdk.client.errors import RequestError
from sie_server.adapters.cross_encoder import CrossEncoderAdapter
from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin
from sie_server.app.app_factory import AppFactory
from sie_server.app.app_state_config import AppStateConfig
from sie_server.types.inputs import Item
+from tools.benchmarks.cross_encoder_lora import client as client_workload
from tools.benchmarks.cross_encoder_lora.adapter import require_forward_selection
+from tools.benchmarks.cross_encoder_lora.client import (
+ REQUEST_ITEMS,
+ Client,
+ describe_response,
+)
from tools.benchmarks.cross_encoder_lora.evidence import Evidence, atomic_json, digest, fingerprint, vector_delta
+from tools.benchmarks.cross_encoder_lora.isolation import IsolatedLoadgen
from tools.benchmarks.cross_encoder_lora.protocol import (
CONCURRENCIES,
CPU_ORACLE,
@@ -59,17 +62,13 @@ from tools.benchmarks.cross_encoder_lora.protocol import (
THREADS,
WARMUP,
WEIGHTS_SHA256,
- percentile,
require,
)
+RESPONSE_CAPTURE_MODE = client_workload.RESPONSE_CAPTURE_MODE
HERE = Path(__file__).resolve().parent
ORDER = sorted(range(len(DOCUMENTS)), key=lambda index: len(DOCUMENTS[index]))
-MAX_LOADING_RETRIES = 10
-MAX_LOADING_DELAY = 5
RESIDENT_CAPACITY = 2
-REQUEST_ITEMS = len(DOCUMENTS)
-RESPONSE_CAPTURE_MODE = "success-status-header-snapshots"
def error_record(error: BaseException) -> dict[str, Any]:
@@ -204,152 +203,6 @@ def adapter_storage(adapter: Any) -> dict[str, int]:
}
-class Client:
- def __init__(self, url: str) -> None:
- self.responses: list[dict[str, Any] | httpx.Response] = []
- http = httpx.Client(base_url=url, timeout=30, event_hooks={"response": [self.observe]})
- self._http = http
- self.sdk = SIEClient(url, timeout_s=30, http_client=http)
-
- def observe(self, response: httpx.Response) -> None:
- # Keep successful wire evidence without retaining its Response/Request/
- # stream graph for the whole phase. Failure bodies are decoded later.
- self.responses.append(describe_response(response) if response.status_code == HTTPStatus.OK else response)
-
- def score(self, selection: str | None, label: str, *, cold: bool = False, timed: bool = False) -> dict[str, Any]:
- started = time.perf_counter_ns()
- wall_started = time.time_ns()
- first = len(self.responses)
- # score() currently does not retry LORA_LOADING. These are explicitly
- # fresh SDK calls for this pre-execution status, never transport retries.
- for attempt in range(MAX_LOADING_RETRIES + 1):
- try:
- result = self.sdk.score(
- MODEL,
- {"text": QUERY["text"]},
- [{"id": f"{label}:{index}", "text": text} for index, text in enumerate(DOCUMENTS)],
- options={"lora": selection},
- wait_for_capacity=False,
- max_oom_retries=0,
- provision_timeout_s=30,
- )
- break
- except ServerError as error:
- if (
- not cold
- or error.status_code != HTTPStatus.SERVICE_UNAVAILABLE
- or error.code != "LORA_LOADING"
- or attempt == MAX_LOADING_RETRIES
- ):
- raise
- delay = error.retry_after if error.retry_after is not None else 0.2
- require(0 <= delay <= MAX_LOADING_DELAY, "unexpected loading retry delay")
- time.sleep(delay)
- elapsed = (time.perf_counter_ns() - started) / 1e6
- row = {
- "label": label,
- "selection": selection,
- "latency_ms": elapsed,
- "start_ns": wall_started,
- "end_ns": time.time_ns(),
- "result": result,
- "responses": self.responses[first:],
- }
- if not timed:
- validate_response(row, allow_loading=cold)
- return row
-
- def close(self) -> None:
- try:
- self.sdk.close()
- finally:
- # Callers serialize their evidence before closing. Preserve unrelated
- # hooks, and break only the observer/history this benchmark owns.
- hooks = self._http.event_hooks["response"]
- hooks[:] = [
- hook
- for hook in hooks
- if not (
- getattr(hook, "__self__", None) is self and getattr(hook, "__func__", None) is type(self).observe
- )
- ]
- self.responses.clear()
-
-
-def describe_response(response: httpx.Response | dict[str, Any]) -> dict[str, Any]:
- if not isinstance(response, httpx.Response):
- return response
- row: dict[str, Any] = {
- "status": response.status_code,
- "timing_headers": {
- name: response.headers[name]
- for name in (
- "x-queue-time",
- "x-tokenization-time",
- "x-inference-time",
- "x-postprocessing-time",
- "x-total-time",
- )
- if name in response.headers
- },
- }
- if response.status_code >= HTTPStatus.BAD_REQUEST:
- row["content_type"] = response.headers.get("content-type")
- row["retry_after"] = response.headers.get("retry-after")
- try:
- response.read()
- except (httpx.StreamError, httpx.HTTPError) as error:
- # A partially read error stream can already have failed in the SDK.
- # Preserve that original failure and its wire metadata; diagnostic
- # re-reading must not replace it or discard earlier attempts.
- row.update(body_unavailable=True, body_read_error=type(error).__name__, code=None)
- return row
- row["body_hex"] = response.content.hex()
- try:
- body = (
- unpackb(response.content, numeric_arrays=False)
- if "msgpack" in response.headers.get("content-type", "")
- else response.json()
- )
- except ValueError as error:
- row["body_decode_error"] = type(error).__name__
- body = None
- error = body.get("error", body.get("detail", body)) if isinstance(body, dict) else None
- row["code"] = error.get("code") if isinstance(error, dict) else None
- return row
-
-
-def serialize_responses(row: dict[str, Any]) -> None:
- row["responses"] = [
- describe_response(value) if isinstance(value, httpx.Response) else value for value in row["responses"]
- ]
-
-
-def validate_response(row: dict[str, Any], *, allow_loading: bool = False) -> None:
- serialize_responses(row)
- statuses = row["responses"]
- require(statuses and statuses[-1]["status"] == HTTPStatus.OK, "missing successful HTTP response")
- if allow_loading:
- require(
- all(
- value["status"] == HTTPStatus.SERVICE_UNAVAILABLE and value.get("code") == "LORA_LOADING"
- for value in statuses[:-1]
- ),
- "unexpected retry during cold adapter request",
- )
- else:
- require(len(statuses) == 1, "hidden SDK retry disqualifies this request")
- scores = row["result"]["scores"]
- expected_ids = [f"{row['label']}:{i}" for i in range(REQUEST_ITEMS)]
- by_id = {item["item_id"]: item["score"] for item in scores}
- require(len(scores) == REQUEST_ITEMS and set(by_id) == set(expected_ids), "score result lost or changed item IDs")
- require([item["rank"] for item in scores] == list(range(REQUEST_ITEMS)), "score ranks changed")
- values = [by_id[key] for key in expected_ids]
- row["scores"] = values
- require(all(math.isfinite(value) for value in values), "nonfinite SDK score")
- require([item["score"] for item in scores] == sorted(values, reverse=True), "score ranks are unordered")
-
-
@contextmanager
def unobserved(adapter: Any) -> Iterator[None]:
"""Time production methods with the original forward attribute lookup restored."""
@@ -395,60 +248,17 @@ def matching_vector(scores: list[float], oracles: dict[str, Any]) -> dict[str, A
def performance(url: str, concurrency: int, evidence: Evidence, *, smoke: bool) -> dict[str, Any]:
- clients = [Client(url) for _ in range(concurrency)]
- samples: list[dict[str, Any]] = []
- warmups: list[dict[str, Any]] = []
- lock = threading.Lock()
- try:
- for i in range(2 if smoke else WARMUP):
- warmups.append(clients[0].score(None, f"warm-C{concurrency}-{i}", timed=True))
- barrier = threading.Barrier(concurrency + 1)
- clock: dict[str, float] = {}
-
- def lane(index: int) -> None:
- barrier.wait(timeout=30)
- counter = 0
- while (
- counter < (4 if smoke else SEQUENTIAL) if concurrency == 1 else time.perf_counter() < clock["deadline"]
- ):
- row = clients[index].score(None, f"C{concurrency}-lane{index}-{counter}", timed=True)
- with lock:
- samples.append(row)
- counter += 1
-
- with ThreadPoolExecutor(max_workers=concurrency) as executor:
- futures = [executor.submit(lane, i) for i in range(concurrency)]
- clock["start"] = time.perf_counter()
- clock["deadline"] = clock["start"] + (0.15 if smoke else STEADY_SECONDS)
- barrier.wait(timeout=30)
- for future in futures:
- future.result(timeout=PERFORMANCE_FUTURE_TIMEOUT_S)
- elapsed = time.perf_counter() - clock["start"]
- for row in [*warmups, *samples]:
- validate_response(row)
- latencies = [row["latency_ms"] for row in samples]
- return {
- "concurrency": concurrency,
- "count": len(samples),
- "elapsed_s": elapsed,
- "mean_ms": statistics.mean(latencies),
- "p95_ms": percentile(latencies, 0.95),
- "rps": len(samples) / elapsed,
- "samples": samples,
- }
- finally:
- with ExitStack() as cleanup:
- for client in clients:
- cleanup.callback(client.close)
- for row in [*warmups, *samples]:
- serialize_responses(row)
- evidence.emit(
- "performance_attempt",
- concurrency=concurrency,
- completed_samples=samples,
- warmups=warmups,
- wire_responses=[describe_response(response) for client in clients for response in client.responses],
- )
+ """Retain the historical in-process diagnostic with its explicit settings."""
+ return client_workload.performance(
+ url,
+ concurrency,
+ evidence,
+ smoke=smoke,
+ warmup=WARMUP,
+ sequential=SEQUENTIAL,
+ steady_seconds=STEADY_SECONDS,
+ future_timeout=PERFORMANCE_FUTURE_TIMEOUT_S,
+ )
def validate_usage(rows: list[dict[str, Any]], batches: list[dict[str, Any]]) -> None:
@@ -766,29 +576,43 @@ async def experiment(args: argparse.Namespace, evidence: Evidence, summary: dict
)
summary["resident_memory"] = memory()
summary["performance"] = {}
+ summary["pre_timing_history"] = {
+ "batches": len(adapter.batch_observations),
+ "selections": len(adapter.selection_observations),
+ "fetches": len(adapter.fetch_observations),
+ "main_client_wire_attempts": len(client.responses),
+ "retained_untimed_replays": sum(len(value["requests"]) for value in summary["untimed_replays"].values()),
+ "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):
- for concurrency in (1, *CONCURRENCIES):
- phase = f"performance-C{concurrency}"
- evidence.emit("gpu_before_phase", phase=phase, telemetry=telemetry())
- measured = await asyncio.to_thread(performance, url, concurrency, evidence, smoke=args.smoke)
- summary["performance"][str(concurrency)] = measured
- evidence.emit("performance", phase=phase, **measured)
- atomic_json(evidence.directory / "trial.json", summary)
- for row in measured["samples"]:
- require(row["result"]["usage"] == bases[0]["result"]["usage"], "timed SDK usage differs")
- if concurrency == 1:
- require(vector_delta(row["scores"], baseline) <= RESTORE_ATOL, "timed C1 base output differs")
- row["diagnostic_matching_oracle"] = matching_vector(row["scores"], summary["shape_oracles"])
- measured["actual_timed_batch_shape"] = "unobserved"
- evidence.emit(
- "timed_output_diagnostics",
- concurrency=concurrency,
- witnesses=[
- {"label": row["label"], "match": row["diagnostic_matching_oracle"]}
- for row in measured["samples"]
- ],
- )
- evidence.emit("gpu_after_phase", phase=phase, telemetry=telemetry())
+ async with IsolatedLoadgen(url, args.source, evidence, smoke=args.smoke) as loadgen:
+ for concurrency in (1, *CONCURRENCIES):
+ phase = f"performance-C{concurrency}"
+ evidence.emit("gpu_before_phase", phase=phase, telemetry=telemetry())
+ await loadgen.phase(concurrency)
+ evidence.emit("gpu_after_phase", phase=phase, telemetry=telemetry())
+ # 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.
+ summary["loadgen"] = loadgen.receipt
+ summary["performance"] = loadgen.results()
+ for concurrency in (1, *CONCURRENCIES):
+ measured = summary["performance"][str(concurrency)]
+ evidence.emit("performance", phase=f"performance-C{concurrency}", **measured)
+ atomic_json(evidence.directory / "trial.json", summary)
+ for row in measured["samples"]:
+ require(row["result"]["usage"] == bases[0]["result"]["usage"], "timed SDK usage differs")
+ if concurrency == 1:
+ require(vector_delta(row["scores"], baseline) <= RESTORE_ATOL, "timed C1 base output differs")
+ row["diagnostic_matching_oracle"] = matching_vector(row["scores"], summary["shape_oracles"])
+ measured["actual_timed_batch_shape"] = "unobserved"
+ evidence.emit(
+ "timed_output_diagnostics",
+ concurrency=concurrency,
+ witnesses=[
+ {"label": row["label"], "match": row["diagnostic_matching_oracle"]} for row in measured["samples"]
+ ],
+ )
adapter.observation_phase = "lifecycle"
if args.arm == "R":
previous = set(registry.loaded_lora_names(MODEL))