Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(examples): replay the published fixed-rate performance records from one client (#881)
Shai Shmuel31ecf76155d1
diff --git a/examples/README.md b/examples/README.mdindex b59f61f1b..983c4f830 100644--- a/examples/README.md+++ b/examples/README.md@@ -38,7 +38,7 @@ to a separately maintained repository (clone and run there).| [Answer several triage questions about one record, each with a probability](./typed-decisions) | Asking CVE descriptions typed pick-one and yes-or-no questions against NVD analyst gold, with a fast, a smart and an LLM lane, and the questions no model passed reported rather than shown | `extract`, `chat/completions` | Self-hosted SIE with GLiFormer, GLiClass, Laya, GLiNER2, GLiNER2.5-Decide and Qwen3 4B; `fetch.py` pulls the recorded run, `score.py` reproduces the figures with no key | Runnable recorded example || [Screen harmful prompts before your model sees them](./guardrails) | Scoring SIE's Qwen3Guard 4B and GLiGuard against three LLM judges and OpenAI Moderation on 4,768 human-labelled ToxicChat and Aegis 2.0 prompts, with a paired bootstrap and the pre-registered bars | `chat/completions`, `extract` | SIE Cloud with GLiGuard, an SIE server for Qwen3Guard; `fetch.py` pulls the recorded run and both sets, `score.py` reproduces every figure with no key | Runnable recorded example || [Expand a query into matchable terms](./sparse) | Comparing SPLADE, which adds terms the text never used, with bge-m3 sparse, which does not | `encode` | SIE Cloud with SPLADE++ and bge-m3; `fetch.py` pulls the recorded vectors, `score.py` reproduces the figures with no key | Runnable recorded example |-| [Repeat the published benchmark numbers](./evaluations/published-benchmarks) | Repeating the quality method behind the six published Cloud quality benchmark records, SPLADE++ and bge-m3 sparse on NFCorpus, GTE-ModernColBERT and bge-m3 multivector on SciFact, Qwen3 Reranker 0.6B and 4B on AskUbuntuDupQuestions, from one client process, and reading the delta against every published metric | `encode`, `score` | SIE Cloud with an SIE API key for a run, which spends credits; `score.py` recomputes the metrics from a run's predictions and the pinned qrels with no key | Runnable |+| [Repeat the published benchmark numbers](./evaluations/published-benchmarks) | Repeating the method behind the twelve published Cloud benchmark records, six quality and six fixed-rate performance, for SPLADE++ and bge-m3 sparse on NFCorpus, GTE-ModernColBERT and bge-m3 multivector on SciFact, Qwen3 Reranker 0.6B and 4B on AskUbuntuDupQuestions, from one client process, and reading the delta against every published metric | `encode`, `score` | SIE Cloud with an SIE API key for a run, which spends credits; `score.py` recomputes quality metrics from a run's predictions and the pinned qrels, and performance metrics from its requests file, with no key | Runnable || [Mask personal data before it reaches a log, a prompt or a vendor](./redact) | Composing two PII models and scoring coverage recall on 660 documents against Presidio, OpenAI Privacy Filter and two LLM prompts, with the price of each | `extract` | SIE Cloud with GLiNER PII and NuNER Zero; `fetch.py` pulls the recorded run, `score.py` reproduces the figures with no key | Runnable recorded example || [Read a full app screenshot into typed fields](./screenshot-fields) | Reproducing all 26 original field checks from one complete Kanboard task screenshot and a strict schema | `chat/completions` | SIE endpoint with Gemma 4 31B; pinned evidence and offline scoring need no API key | Runnable recorded example || [Read the numbers off a dashboard that has no API](./screenshot-mining) | Reading twelve Superset, Argo CD, Airflow, Kubernetes, GitLab and Jaeger screens into schema-valid JSON | `generate` | SIE Cloud with Qwen3.8 27B; `fetch.py` pulls the recorded run and the screenshots, `score.py` reproduces 328 of 335 with no key | Runnable recorded example |diff --git a/examples/evaluations/published-benchmarks/README.md b/examples/evaluations/published-benchmarks/README.mdindex fdbb0d044..e15f3c80e 100644--- a/examples/evaluations/published-benchmarks/README.md+++ b/examples/evaluations/published-benchmarks/README.md@@ -1,15 +1,20 @@# Repeat the published benchmark numbers-This example repeats the method behind the six quality numbers published on-the SIE website, from one client process on your machine. Each-`references/<id>.json` is a projection of one published benchmark record: the-model and profile, the task key, the pinned dataset revision, the request shape-and the published metrics. `run.py quality` sends the same requests through+This example repeats the method behind the benchmark numbers published on the+SIE website, six quality records and six fixed-rate performance records, from+one client process on your machine. Each `references/<id>.json` is a+projection of one published benchmark record: the model and profile, the task+key, the pinned dataset revision, the request shape, the timing constants and+the published metrics. `run.py quality` sends the same requests through`sie_sdk.SIEClient`, ranks in the client, scores the ranking with `pytrec_eval`and writes one record-shaped result with the delta against every published-metric. It prints deltas and never a verdict: no threshold, no pass, no fail.+metric. `run.py performance` sends a record's requests at its published rate+and aggregates their timing the way the record did. Both print deltas and+never a verdict: no threshold, no pass, no fail.-## The six references+## Quality++### The six references| Reference | Model | Profile | Task | Published main score || --- | --- | --- | --- | ---: |@@ -20,7 +25,7 @@ metric. It prints deltas and never a verdict: no threshold, no pass, no fail.| `prod-web-fw-20260905-qwen3-reranker-0-6b-askubuntu-quality-10` | `Qwen/Qwen3-Reranker-0.6B` | default | `mteb/AskUbuntuDupQuestions` | map_at_1000 0.59526 || `prod-web-fw-20260905-qwen3-reranker-4b-askubuntu-quality-12` | `Qwen/Qwen3-Reranker-4B` | default | `mteb/AskUbuntuDupQuestions` | map_at_1000 0.64484 |-## Run it+### Run itInstall the locked dependencies, then set the key the endpoint requires:@@ -67,7 +72,7 @@ in `validity.reasons`:1000 documents with their scores, or the reranker's 20 candidates per query.Every metric is recomputed from this file.-## Recompute offline+### Recompute offline```shuv run python score.py results/<id>-<utc>.json@@ -80,7 +85,7 @@ Face cache), recomputes every metric and prints each one beside the publishedvalue and the delta. It rewrites nothing unless you pass `--write`, whichupdates `metrics` and `comparison` in the result in place.-## What is fixed by the method+### What is fixed by the methodThese are not flags. They are the method behind the published numbers, andthe example applies them to every run:@@ -103,7 +108,7 @@ the example applies them to every run:record). After every call the SDK's retry count is read and recorded; anyretry sets `valid: false`, as does any failed request.-## What the comparison means+### What the comparison means`comparable: true` means the run's identity and parameters equal thereference's: model, profile, task key, output contract, items per request,@@ -126,6 +131,129 @@ against a 2% band when they decide whether a published number still holds;that band is their reading policy, and this tool never prints it, nor any passthreshold or quality floor.+## Performance++### The six performance references++| Reference | Model | Profile | Request | Level | p50 ms | p95 ms | p99 ms | Achieved rps |+| --- | --- | --- | --- | --- | ---: | ---: | ---: | ---: |+| `prod-web-fw-20260905-splade-nfcorpus-perf-01` | `prithivida/Splade_PP_en_v2` | default | one of 256 NFCorpus documents, sparse | `fixed-10-rps` | 144.4 | 241.6 | 491.5 | 9.98 |+| `prod-web-fw-20260905-bge-m3-sparse-nfcorpus-perf-03` | `BAAI/bge-m3` | sparse | one of 256 NFCorpus documents, sparse | `fixed-10-rps` | 172.7 | 217.8 | 387.0 | 9.98 |+| `prod-web-fw-20260905-gte-moderncolbert-scifact-perf-v2-r1` | `lightonai/GTE-ModernColBERT-v1` | default | one of 256 SciFact documents, multivector | `fixed-1-rps` | 178.8 | 198.8 | 285.0 | 1.0 |+| `prod-web-fw-20260905-bge-m3-multivector-scifact-perf-v2-r1` | `BAAI/bge-m3` | multivector | one of 256 SciFact documents, multivector | `fixed-1-rps` | 353.7 | 1164.3 | 1407.2 | 1.0 |+| `prod-web-fw-20260905-qwen3-reranker-0-6b-askubuntu-perf-09` | `Qwen/Qwen3-Reranker-0.6B` | default | one of 64 AskUbuntu queries with its 20 candidates, scores | `fixed-0-25-rps` | 210.5 | 230.2 | 230.2 | 0.25 |+| `prod-web-fw-20260905-qwen3-reranker-4b-askubuntu-perf-11` | `Qwen/Qwen3-Reranker-4B` | default | one of 64 AskUbuntu queries with its 20 candidates, scores | `fixed-0-25-rps` | 489.5 | 579.4 | 579.4 | 0.25 |++Published values of each record's first load level, latencies rounded to one+decimal, rates to two; the reference file carries every metric of that level.++### Run it++```sh+uv run python run.py performance \+ --reference references/prod-web-fw-20260905-gte-moderncolbert-scifact-perf-v2-r1.json+```++A run needs `SIE_API_KEY`, spends credits and takes about two minutes: one+readiness request, 30 s of warmup, 10 s of settle, 60 s of scheduled requests+and up to 10 s of drain. With `--reference`, model, profile, task, output+contract, items per request, timeout, in-flight cap, settle, drain and lag+tolerance come from the file; `--rate` defaults to the record's published+level, `--duration` to 60 and `--warmup` to 30, `--endpoint` is accepted as+for quality, and any value that differs from the reference adds a+`comparable_reasons` entry. Without a reference, `--model`, `--task` and+`--rate` are required, `--output` and `--items-per-request` are required for+the encode tasks and refused for the score task, and the timeout and cap are+30 s and 64 for encode, 300 s and 128 for score. No other flags exist.++### What is fixed by the method++- a readiness request on the first row, `wait_for_capacity=True` with a 300 s+ provisioning timeout, before the measurement; a failure writes+ `valid: false` with the reason and exits 1; then 30 s of unrecorded+ closed-loop warmup on that row (`--warmup 0` measures cold) and 10 s of+ idle settle;+- deterministic arrivals: request `i` is due at `i / rate` seconds while that+ is below the duration; a scheduler thread sleeps until each offset and hands+ the request to a pool of `max_in_flight_per_process` threads, and when all+ are busy the request waits and its scheduling lag grows; after the last+ offset, up to 10 s of drain, then a wait for any request still running to+ finish or time out, so every request has a final status;+- one attempt per request, no backoff, `wait_for_capacity=False`,+ `provision_timeout_s` equal to the request timeout, `max_oom_retries=0` and+ a connection pool twice the cap; after every call the SDK's retry count is+ read and written on the request's row;+- selection by the task key: `filter=nonempty` drops rows whose text is empty+ after stripping whitespace; `role=corpus` takes the documents, queries+ otherwise; the remaining rows are ordered by source id compared as strings+ and `limit=N` keeps the first N; for AskUbuntu, `limit=64` keeps the first+ 64 queries in that order and `candidates-k=20` each query's 20 task-native+ candidates in source order; the chosen ids go to `dataset.selected_ids` in+ that order;+- rows cycle: encode request `s` takes documents `s × n` to `s × n + n − 1`+ of the selection, modulo its size, with `n` the items per request (1 in+ every record); score request `s` takes query `s` modulo the selection+ size (64 in the records);+- a document is sent as its title, a newline and its text, an empty title+ left out; encode items carry `is_query=False` and the reference's output+ type; a score request is the query text with its 20 candidates, without+ the `max_tokens_per_doc` the reranker references list, which bounded the+ published runs' inputs and was not part of their requests; responses are+ not scored, only their timing is kept.++### What the run writes++Beside the quality envelope, the result carries `load_level_name`, `schedule`+with the one level that ran, `timing` as in the reference, `run.requests_path`+and `validity`. The metrics use the record's names and aggregations:+`offered_requests_per_second` is the level rate; `achieved_requests_per_second`+counts successes completed inside the duration window (60 s in the records)+and `eventual_achieved_requests_per_second` all successes, each divided by+the duration, so a completion during drain counts only in the latter; the+four success rates are over the scheduled count, retry-free meaning one+attempt and a zero SDK retry count; the latency percentiles are nearest-rank+over successful requests of completed minus sent on the monotonic clock;+`scheduling_lag_p99_ms` is the nearest-rank p99 of actual send minus due+offset over every request, floored at zero. `validity.valid` is false after+any SDK retry, a lag p99 above the 20 ms tolerance, a failed readiness+request or an in-flight peak above the cap; `validity` also lists+`lag_max_ms`, `in_flight_peak`, `timeouts` and `sdk_retries`. A failed or+timed-out request does not invalidate the run; it lowers the success rates.++`results/<id>-<utc>.requests.jsonl` has one row per scheduled request:+`sequence`, `level_name`, `offset_s` (when it was due), `actual_send_offset_ns`+and `completed_offset_ns` (monotonic, from the schedule start),+`scheduling_lag_ms`, `status` (`success`, `timeout` when the SDK's request+timeout expired, or `error:<ExceptionType>`), `attempt` (always 1),+`client_retry_count` and `in_flight_at_send`. Every metric is recomputed from+this file:+`score.py results/<id>-<utc>.json`, as for quality, detects the mode, re-reads+the rows, re-aggregates every metric through the same function the run used,+`performance_metrics(rows, rate, duration_s)`, and prints each one beside the+published value and the delta, with no key, no network and no dataset;+`--write` updates `metrics` and `comparison` in place.++### What the comparison means++Same method, different client. The encode records ran two workers of two+processes and the reranker records one worker of two; this tool runs one+process, so every performance run is `comparable: false` with the reason+`client processes 1 != 4` or `1 != 2`, listed after any flag that differs,+and `comparison_basis` reads `same method, different parameters: <reasons>`.+The schedule is the union of the record's per-process partitions, so the+offered load is the same, but one process carries a 4× or 2× higher+per-process rate, and the in-flight cap and the 20 ms lag gate bind sooner.+At 0.25 rps for 60 s there are 15 requests, so p95 = p99 = max, in the+records and here; `run.request_count` shows it. The records' client ran in+the same cloud region as the endpoint; from anywhere else the latencies+include the network path and the response size (a multivector response is+hundreds of kilobytes), so read the rate and success metrics first and the+latency deltas as a property of where the run was made. One level runs per+invocation, the record's first level unless `--rate` is given, and+`load_level_name` is derived from the effective rate as `fixed-<rate>-rps`+with the decimal point written as a hyphen. A change of execution revision+mid-run sets `comparable: false` and `valid: false`.+## Verify```sh@@ -143,7 +271,8 @@ network.records, and no floor, target, threshold or gate;- no `mteb` dependency, no nAUC or cv_recall metrics, and no match of thescorer's implementation digest;-- no multi-process client, load ladder or candidate generation;+- no multi-process client, load ladder, Poisson arrivals, clock calibration+ or candidate generation;- no cost, price or accounting fields;- no recorded-evidence download: the inputs are the six reference files andthe pinned public datasets;diff --git a/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-bge-m3-multivector-scifact-perf-v2-r1.json b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-bge-m3-multivector-scifact-perf-v2-r1.jsonnew file mode 100644index 000000000..d84c9c4ce--- /dev/null+++ b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-bge-m3-multivector-scifact-perf-v2-r1.json@@ -0,0 +1,152 @@+{+ "accepted_at": "2026-09-05T05:18:13.478090Z",+ "client": {+ "processes_per_worker": 2,+ "worker_count": 2+ },+ "dataset": {+ "name": "mteb/SciFact",+ "parameters": [+ {+ "name": "limit",+ "value": 256+ },+ {+ "name": "role",+ "value": "corpus"+ },+ {+ "name": "filter",+ "value": "nonempty"+ }+ ],+ "revision": "d56462d0e63a25450459c4f213e49ffdb866f7f9",+ "subset": "test"+ },+ "evaluation_mode": "isolated_performance",+ "kind": "published-benchmark-reference",+ "load_level_name": "fixed-1-rps",+ "measurement_started_at": "2026-09-05T05:00:33.700016Z",+ "metrics": [+ {+ "aggregation": "campaign_global",+ "name": "offered_requests_per_second",+ "unit": "requests_per_second",+ "value": 1.0+ },+ {+ "aggregation": "common_window",+ "name": "achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 1.0+ },+ {+ "aggregation": "including_drain",+ "name": "eventual_achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "p99",+ "name": "scheduling_lag_p99_ms",+ "unit": "milliseconds",+ "value": 5.869+ },+ {+ "aggregation": "p50",+ "name": "latency_p50_ms",+ "unit": "milliseconds",+ "value": 353.7+ },+ {+ "aggregation": "p95",+ "name": "latency_p95_ms",+ "unit": "milliseconds",+ "value": 1164.307+ },+ {+ "aggregation": "p99",+ "name": "latency_p99_ms",+ "unit": "milliseconds",+ "value": 1407.226+ }+ ],+ "model": "BAAI/bge-m3",+ "model_version": "5617a9f61b028005a4858fdac845db406aefb181",+ "operation": "encode",+ "payload": {+ "items_per_request": 1,+ "output_contract": "multivector",+ "parameters": [+ {+ "name": "is_query",+ "value": false+ }+ ]+ },+ "profile": "multivector",+ "reference_id": "prod-web-fw-20260905-bge-m3-multivector-scifact-perf-v2-r1",+ "schedule": {+ "arrival": "deterministic",+ "levels": [+ {+ "duration_s": 60.0,+ "name": "fixed-1-rps",+ "rate": 1.0+ },+ {+ "duration_s": 60.0,+ "name": "fixed-3-rps",+ "rate": 3.0+ },+ {+ "duration_s": 60.0,+ "name": "fixed-5-rps",+ "rate": 5.0+ }+ ],+ "seed": 0,+ "unit": "requests_per_second"+ },+ "schema_version": 1,+ "scorer": null,+ "task_key": "mteb/SciFact?split=test&role=corpus&limit=256&filter=nonempty",+ "timing": {+ "drain_s": 10.0,+ "max_in_flight_per_process": 64,+ "request_timeout_s": 30.0,+ "retry": {+ "backoff": "none",+ "max_attempts": 1,+ "record_attempts": true+ },+ "scheduling_lag_tolerance_ms": 20.0,+ "settle_s": 10.0,+ "target_readiness_timeout_s": 300.0,+ "warmup_s": 30.0+ }+}diff --git a/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-bge-m3-sparse-nfcorpus-perf-03.json b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-bge-m3-sparse-nfcorpus-perf-03.jsonnew file mode 100644index 000000000..c46bc6b28--- /dev/null+++ b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-bge-m3-sparse-nfcorpus-perf-03.json@@ -0,0 +1,152 @@+{+ "accepted_at": "2026-09-05T05:18:05.630618Z",+ "client": {+ "processes_per_worker": 2,+ "worker_count": 2+ },+ "dataset": {+ "name": "mteb/NFCorpus",+ "parameters": [+ {+ "name": "limit",+ "value": 256+ },+ {+ "name": "role",+ "value": "corpus"+ },+ {+ "name": "filter",+ "value": "nonempty"+ }+ ],+ "revision": "ec0fa4fe99da2ff19ca1214b7966684033a58814",+ "subset": "test"+ },+ "evaluation_mode": "isolated_performance",+ "kind": "published-benchmark-reference",+ "load_level_name": "fixed-10-rps",+ "measurement_started_at": "2026-09-05T01:49:57.556820Z",+ "metrics": [+ {+ "aggregation": "campaign_global",+ "name": "offered_requests_per_second",+ "unit": "requests_per_second",+ "value": 10.0+ },+ {+ "aggregation": "common_window",+ "name": "achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 9.983333333333333+ },+ {+ "aggregation": "including_drain",+ "name": "eventual_achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 10.0+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_success_rate",+ "unit": "ratio",+ "value": 0.9983333333333333+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_retry_free_success_rate",+ "unit": "ratio",+ "value": 0.9983333333333333+ },+ {+ "aggregation": "campaign_global",+ "name": "success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "p99",+ "name": "scheduling_lag_p99_ms",+ "unit": "milliseconds",+ "value": 2.451+ },+ {+ "aggregation": "p50",+ "name": "latency_p50_ms",+ "unit": "milliseconds",+ "value": 172.685+ },+ {+ "aggregation": "p95",+ "name": "latency_p95_ms",+ "unit": "milliseconds",+ "value": 217.758+ },+ {+ "aggregation": "p99",+ "name": "latency_p99_ms",+ "unit": "milliseconds",+ "value": 386.963+ }+ ],+ "model": "BAAI/bge-m3",+ "model_version": "5617a9f61b028005a4858fdac845db406aefb181",+ "operation": "encode",+ "payload": {+ "items_per_request": 1,+ "output_contract": "sparse",+ "parameters": [+ {+ "name": "is_query",+ "value": false+ }+ ]+ },+ "profile": "sparse",+ "reference_id": "prod-web-fw-20260905-bge-m3-sparse-nfcorpus-perf-03",+ "schedule": {+ "arrival": "deterministic",+ "levels": [+ {+ "duration_s": 60.0,+ "name": "fixed-10-rps",+ "rate": 10.0+ },+ {+ "duration_s": 60.0,+ "name": "fixed-20-rps",+ "rate": 20.0+ },+ {+ "duration_s": 60.0,+ "name": "fixed-25-rps",+ "rate": 25.0+ }+ ],+ "seed": 0,+ "unit": "requests_per_second"+ },+ "schema_version": 1,+ "scorer": null,+ "task_key": "mteb/NFCorpus?split=test&role=corpus&limit=256&filter=nonempty",+ "timing": {+ "drain_s": 10.0,+ "max_in_flight_per_process": 64,+ "request_timeout_s": 30.0,+ "retry": {+ "backoff": "none",+ "max_attempts": 1,+ "record_attempts": true+ },+ "scheduling_lag_tolerance_ms": 20.0,+ "settle_s": 10.0,+ "target_readiness_timeout_s": 300.0,+ "warmup_s": 30.0+ }+}diff --git a/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-gte-moderncolbert-scifact-perf-v2-r1.json b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-gte-moderncolbert-scifact-perf-v2-r1.jsonnew file mode 100644index 000000000..eef6769be--- /dev/null+++ b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-gte-moderncolbert-scifact-perf-v2-r1.json@@ -0,0 +1,152 @@+{+ "accepted_at": "2026-09-05T05:18:11.531679Z",+ "client": {+ "processes_per_worker": 2,+ "worker_count": 2+ },+ "dataset": {+ "name": "mteb/SciFact",+ "parameters": [+ {+ "name": "limit",+ "value": 256+ },+ {+ "name": "role",+ "value": "corpus"+ },+ {+ "name": "filter",+ "value": "nonempty"+ }+ ],+ "revision": "d56462d0e63a25450459c4f213e49ffdb866f7f9",+ "subset": "test"+ },+ "evaluation_mode": "isolated_performance",+ "kind": "published-benchmark-reference",+ "load_level_name": "fixed-1-rps",+ "measurement_started_at": "2026-09-05T04:47:35.842475Z",+ "metrics": [+ {+ "aggregation": "campaign_global",+ "name": "offered_requests_per_second",+ "unit": "requests_per_second",+ "value": 1.0+ },+ {+ "aggregation": "common_window",+ "name": "achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 1.0+ },+ {+ "aggregation": "including_drain",+ "name": "eventual_achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "p99",+ "name": "scheduling_lag_p99_ms",+ "unit": "milliseconds",+ "value": 5.886+ },+ {+ "aggregation": "p50",+ "name": "latency_p50_ms",+ "unit": "milliseconds",+ "value": 178.81900000000002+ },+ {+ "aggregation": "p95",+ "name": "latency_p95_ms",+ "unit": "milliseconds",+ "value": 198.75799999999998+ },+ {+ "aggregation": "p99",+ "name": "latency_p99_ms",+ "unit": "milliseconds",+ "value": 285.029+ }+ ],+ "model": "lightonai/GTE-ModernColBERT-v1",+ "model_version": "cbbe53366e564450558f5e639dd499171f127538",+ "operation": "encode",+ "payload": {+ "items_per_request": 1,+ "output_contract": "multivector",+ "parameters": [+ {+ "name": "is_query",+ "value": false+ }+ ]+ },+ "profile": "default",+ "reference_id": "prod-web-fw-20260905-gte-moderncolbert-scifact-perf-v2-r1",+ "schedule": {+ "arrival": "deterministic",+ "levels": [+ {+ "duration_s": 60.0,+ "name": "fixed-1-rps",+ "rate": 1.0+ },+ {+ "duration_s": 60.0,+ "name": "fixed-3-rps",+ "rate": 3.0+ },+ {+ "duration_s": 60.0,+ "name": "fixed-5-rps",+ "rate": 5.0+ }+ ],+ "seed": 0,+ "unit": "requests_per_second"+ },+ "schema_version": 1,+ "scorer": null,+ "task_key": "mteb/SciFact?split=test&role=corpus&limit=256&filter=nonempty",+ "timing": {+ "drain_s": 10.0,+ "max_in_flight_per_process": 64,+ "request_timeout_s": 30.0,+ "retry": {+ "backoff": "none",+ "max_attempts": 1,+ "record_attempts": true+ },+ "scheduling_lag_tolerance_ms": 20.0,+ "settle_s": 10.0,+ "target_readiness_timeout_s": 300.0,+ "warmup_s": 30.0+ }+}diff --git a/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-qwen3-reranker-0-6b-askubuntu-perf-09.json b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-qwen3-reranker-0-6b-askubuntu-perf-09.jsonnew file mode 100644index 000000000..1a87030cb--- /dev/null+++ b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-qwen3-reranker-0-6b-askubuntu-perf-09.json@@ -0,0 +1,148 @@+{+ "accepted_at": "2026-09-05T05:18:10.659367Z",+ "client": {+ "processes_per_worker": 2,+ "worker_count": 1+ },+ "dataset": {+ "name": "mteb/AskUbuntuDupQuestions",+ "parameters": [+ {+ "name": "limit",+ "value": 64+ },+ {+ "name": "candidate_count",+ "value": 20+ }+ ],+ "revision": "c5691e3c48741d5f83b5cc8e630653d7a8cfc048",+ "subset": "test"+ },+ "evaluation_mode": "isolated_performance",+ "kind": "published-benchmark-reference",+ "load_level_name": "fixed-0-25-rps",+ "measurement_started_at": "2026-09-05T04:02:57.223664Z",+ "metrics": [+ {+ "aggregation": "campaign_global",+ "name": "offered_requests_per_second",+ "unit": "requests_per_second",+ "value": 0.25+ },+ {+ "aggregation": "common_window",+ "name": "achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 0.25+ },+ {+ "aggregation": "including_drain",+ "name": "eventual_achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 0.25+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "p99",+ "name": "scheduling_lag_p99_ms",+ "unit": "milliseconds",+ "value": 9.863999999999999+ },+ {+ "aggregation": "p50",+ "name": "latency_p50_ms",+ "unit": "milliseconds",+ "value": 210.527+ },+ {+ "aggregation": "p95",+ "name": "latency_p95_ms",+ "unit": "milliseconds",+ "value": 230.207+ },+ {+ "aggregation": "p99",+ "name": "latency_p99_ms",+ "unit": "milliseconds",+ "value": 230.207+ }+ ],+ "model": "Qwen/Qwen3-Reranker-0.6B",+ "model_version": "e61197ed45024b0ed8a2d74b80b4d909f1255473",+ "operation": "score",+ "payload": {+ "items_per_request": 20,+ "output_contract": "scores",+ "parameters": [+ {+ "name": "max_tokens_per_doc",+ "value": 1000+ }+ ]+ },+ "profile": "default",+ "reference_id": "prod-web-fw-20260905-qwen3-reranker-0-6b-askubuntu-perf-09",+ "schedule": {+ "arrival": "deterministic",+ "levels": [+ {+ "duration_s": 60.0,+ "name": "fixed-0-25-rps",+ "rate": 0.25+ },+ {+ "duration_s": 60.0,+ "name": "fixed-0-5-rps",+ "rate": 0.5+ },+ {+ "duration_s": 60.0,+ "name": "fixed-1-rps",+ "rate": 1.0+ }+ ],+ "seed": 0,+ "unit": "requests_per_second"+ },+ "schema_version": 1,+ "scorer": null,+ "task_key": "mteb/AskUbuntuDupQuestions?split=test&limit=64&candidates-k=20",+ "timing": {+ "drain_s": 10.0,+ "max_in_flight_per_process": 128,+ "request_timeout_s": 300.0,+ "retry": {+ "backoff": "none",+ "max_attempts": 1,+ "record_attempts": true+ },+ "scheduling_lag_tolerance_ms": 20.0,+ "settle_s": 10.0,+ "target_readiness_timeout_s": 300.0,+ "warmup_s": 30.0+ }+}diff --git a/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-qwen3-reranker-4b-askubuntu-perf-11.json b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-qwen3-reranker-4b-askubuntu-perf-11.jsonnew file mode 100644index 000000000..8f56e2498--- /dev/null+++ b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-qwen3-reranker-4b-askubuntu-perf-11.json@@ -0,0 +1,148 @@+{+ "accepted_at": "2026-09-05T05:18:08.949342Z",+ "client": {+ "processes_per_worker": 2,+ "worker_count": 1+ },+ "dataset": {+ "name": "mteb/AskUbuntuDupQuestions",+ "parameters": [+ {+ "name": "limit",+ "value": 64+ },+ {+ "name": "candidate_count",+ "value": 20+ }+ ],+ "revision": "c5691e3c48741d5f83b5cc8e630653d7a8cfc048",+ "subset": "test"+ },+ "evaluation_mode": "isolated_performance",+ "kind": "published-benchmark-reference",+ "load_level_name": "fixed-0-25-rps",+ "measurement_started_at": "2026-09-05T04:24:10.417651Z",+ "metrics": [+ {+ "aggregation": "campaign_global",+ "name": "offered_requests_per_second",+ "unit": "requests_per_second",+ "value": 0.25+ },+ {+ "aggregation": "common_window",+ "name": "achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 0.25+ },+ {+ "aggregation": "including_drain",+ "name": "eventual_achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 0.25+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "p99",+ "name": "scheduling_lag_p99_ms",+ "unit": "milliseconds",+ "value": 9.841000000000001+ },+ {+ "aggregation": "p50",+ "name": "latency_p50_ms",+ "unit": "milliseconds",+ "value": 489.513+ },+ {+ "aggregation": "p95",+ "name": "latency_p95_ms",+ "unit": "milliseconds",+ "value": 579.444+ },+ {+ "aggregation": "p99",+ "name": "latency_p99_ms",+ "unit": "milliseconds",+ "value": 579.444+ }+ ],+ "model": "Qwen/Qwen3-Reranker-4B",+ "model_version": "22e683669bc0f0bd69640a1354a6d0aebcfeede5",+ "operation": "score",+ "payload": {+ "items_per_request": 20,+ "output_contract": "scores",+ "parameters": [+ {+ "name": "max_tokens_per_doc",+ "value": 1000+ }+ ]+ },+ "profile": "default",+ "reference_id": "prod-web-fw-20260905-qwen3-reranker-4b-askubuntu-perf-11",+ "schedule": {+ "arrival": "deterministic",+ "levels": [+ {+ "duration_s": 60.0,+ "name": "fixed-0-25-rps",+ "rate": 0.25+ },+ {+ "duration_s": 60.0,+ "name": "fixed-0-5-rps",+ "rate": 0.5+ },+ {+ "duration_s": 60.0,+ "name": "fixed-1-rps",+ "rate": 1.0+ }+ ],+ "seed": 0,+ "unit": "requests_per_second"+ },+ "schema_version": 1,+ "scorer": null,+ "task_key": "mteb/AskUbuntuDupQuestions?split=test&limit=64&candidates-k=20",+ "timing": {+ "drain_s": 10.0,+ "max_in_flight_per_process": 128,+ "request_timeout_s": 300.0,+ "retry": {+ "backoff": "none",+ "max_attempts": 1,+ "record_attempts": true+ },+ "scheduling_lag_tolerance_ms": 20.0,+ "settle_s": 10.0,+ "target_readiness_timeout_s": 300.0,+ "warmup_s": 30.0+ }+}diff --git a/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-splade-nfcorpus-perf-01.json b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-splade-nfcorpus-perf-01.jsonnew file mode 100644index 000000000..22eb4854f--- /dev/null+++ b/examples/evaluations/published-benchmarks/references/prod-web-fw-20260905-splade-nfcorpus-perf-01.json@@ -0,0 +1,152 @@+{+ "accepted_at": "2026-09-05T05:17:30.631561Z",+ "client": {+ "processes_per_worker": 2,+ "worker_count": 2+ },+ "dataset": {+ "name": "mteb/NFCorpus",+ "parameters": [+ {+ "name": "limit",+ "value": 256+ },+ {+ "name": "role",+ "value": "corpus"+ },+ {+ "name": "filter",+ "value": "nonempty"+ }+ ],+ "revision": "ec0fa4fe99da2ff19ca1214b7966684033a58814",+ "subset": "test"+ },+ "evaluation_mode": "isolated_performance",+ "kind": "published-benchmark-reference",+ "load_level_name": "fixed-10-rps",+ "measurement_started_at": "2026-09-05T01:29:44.032382Z",+ "metrics": [+ {+ "aggregation": "campaign_global",+ "name": "offered_requests_per_second",+ "unit": "requests_per_second",+ "value": 10.0+ },+ {+ "aggregation": "common_window",+ "name": "achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 9.983333333333333+ },+ {+ "aggregation": "including_drain",+ "name": "eventual_achieved_requests_per_second",+ "unit": "requests_per_second",+ "value": 10.0+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_success_rate",+ "unit": "ratio",+ "value": 0.9983333333333333+ },+ {+ "aggregation": "campaign_global",+ "name": "in_window_retry_free_success_rate",+ "unit": "ratio",+ "value": 0.9983333333333333+ },+ {+ "aggregation": "campaign_global",+ "name": "success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "campaign_global",+ "name": "retry_free_success_rate",+ "unit": "ratio",+ "value": 1.0+ },+ {+ "aggregation": "p99",+ "name": "scheduling_lag_p99_ms",+ "unit": "milliseconds",+ "value": 2.297+ },+ {+ "aggregation": "p50",+ "name": "latency_p50_ms",+ "unit": "milliseconds",+ "value": 144.41799999999998+ },+ {+ "aggregation": "p95",+ "name": "latency_p95_ms",+ "unit": "milliseconds",+ "value": 241.596+ },+ {+ "aggregation": "p99",+ "name": "latency_p99_ms",+ "unit": "milliseconds",+ "value": 491.514+ }+ ],+ "model": "prithivida/Splade_PP_en_v2",+ "model_version": "f0d4aa214dcb60c274052a52c0497535e3aec64c",+ "operation": "encode",+ "payload": {+ "items_per_request": 1,+ "output_contract": "sparse",+ "parameters": [+ {+ "name": "is_query",+ "value": false+ }+ ]+ },+ "profile": "default",+ "reference_id": "prod-web-fw-20260905-splade-nfcorpus-perf-01",+ "schedule": {+ "arrival": "deterministic",+ "levels": [+ {+ "duration_s": 60.0,+ "name": "fixed-10-rps",+ "rate": 10.0+ },+ {+ "duration_s": 60.0,+ "name": "fixed-20-rps",+ "rate": 20.0+ },+ {+ "duration_s": 60.0,+ "name": "fixed-25-rps",+ "rate": 25.0+ }+ ],+ "seed": 0,+ "unit": "requests_per_second"+ },+ "schema_version": 1,+ "scorer": null,+ "task_key": "mteb/NFCorpus?split=test&role=corpus&limit=256&filter=nonempty",+ "timing": {+ "drain_s": 10.0,+ "max_in_flight_per_process": 64,+ "request_timeout_s": 30.0,+ "retry": {+ "backoff": "none",+ "max_attempts": 1,+ "record_attempts": true+ },+ "scheduling_lag_tolerance_ms": 20.0,+ "settle_s": 10.0,+ "target_readiness_timeout_s": 300.0,+ "warmup_s": 30.0+ }+}diff --git a/examples/evaluations/published-benchmarks/run.py b/examples/evaluations/published-benchmarks/run.pyindex 63229bc8d..21f1c847e 100644--- a/examples/evaluations/published-benchmarks/run.py+++ b/examples/evaluations/published-benchmarks/run.py@@ -1,16 +1,23 @@"""Repeat the method behind the published benchmark numbers from one client process."""import argparse+import contextlibimport json+import mathimport osimport platformimport re+import threading+import timefrom collections.abc import Callable, Mapping, Sequence+from concurrent.futures import ThreadPoolExecutor, waitfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime+from fractions import Fractionfrom pathlib import Pathfrom typing import Any+import httpximport numpy as npimport sie_sdkfrom scipy.sparse import csr_matrix@@ -18,8 +25,12 @@ from sie_sdk import SIEClientfrom score import (HF_DATASETS,+ NS_PER_MS,+ NS_PER_S,+ PERFORMANCE_MODE,SCORER_ID,Qrels,+ Rows,compare,format_rows,load_corpus,@@ -27,10 +38,14 @@ from score import (load_queries,load_top_ranked,metric_rows,+ nanoseconds,parse_task_key,+ performance_metric_rows,+ performance_metrics,scorer_version,task_metrics,write_json,+ write_jsonl,)DEFAULT_ENDPOINT = "https://api.superlinked.com"@@ -43,11 +58,21 @@ SCORE_TASKS = frozenset({"mteb/AskUbuntuDupQuestions"})ENCODE_OUTPUTS = ("sparse", "multivector")REFERENCE_KIND = "published-benchmark-reference"RESULT_KIND = "published-benchmark-reproduction"+PERFORMANCE_LIMITS = {"encode": (30.0, 64), "score": (300.0, 128)}+DEFAULT_DURATION_S = 60.0+DEFAULT_WARMUP_S = 30.0+DEFAULT_SETTLE_S = 10.0+DEFAULT_DRAIN_S = 10.0+DEFAULT_READINESS_TIMEOUT_S = 300.0+DEFAULT_LAG_TOLERANCE_MS = 20.0+RETRY_POLICY = {"backoff": "none", "max_attempts": 1, "record_attempts": True}+ROLES = ("queries", "corpus")Corpus = dict[str, dict[str, str]]Queries = dict[str, str]TopRanked = dict[str, list[str]]PredictionMap = dict[str, dict[str, float]]+ScoreRequest = tuple[dict[str, str], list[dict[str, str]]]class RequestFailed(Exception):@@ -77,6 +102,41 @@ class QualityPlan:return self.model if self.profile == "default" else f"{self.model}:{self.profile}"+@dataclass(frozen=True)+class PerformancePlan:+ reference_id: str | None+ reference_metrics: list[dict[str, Any]]+ model: str+ profile: str+ operation: str+ task_key: str+ task_name: str+ task_params: dict[str, str]+ revision: str+ output_contract: str+ items_per_request: int | None+ rate: float+ duration_s: float+ warmup_s: float+ settle_s: float+ drain_s: float+ request_timeout_s: float+ target_readiness_timeout_s: float+ max_in_flight: int+ lag_tolerance_ms: float+ endpoint: str+ model_version: str | None+ comparable_reasons: list[str]++ @property+ def route(self) -> str:+ return self.model if self.profile == "default" else f"{self.model}:{self.profile}"++ @property+ def level_name(self) -> str:+ return load_level_name(self.rate)++@dataclass(frozen=True)class Loaders:corpus: Callable[[str, str], Corpus] = load_corpus@@ -93,6 +153,12 @@ class QualityData:top_ranked: TopRanked | None+@dataclass(frozen=True)+class PerformanceData:+ selected_ids: list[str]+ payloads: list[dict[str, str]] | list[ScoreRequest]++@dataclassclass CallLog:request_count: int = 0@@ -115,16 +181,25 @@ class CallLog:self.failure = f"{type(exc).__name__}: {exc}"+def _add_shared_arguments(command: argparse.ArgumentParser) -> None:+ command.add_argument("--reference", type=Path, help="A references/<id>.json file")+ command.add_argument("--model", help="Model route, model[:profile]")+ command.add_argument("--task", help="Task key, for example mteb/SciFact")+ command.add_argument("--output", choices=ENCODE_OUTPUTS, help="Output contract of an encode task")+ command.add_argument("--items-per-request", type=int, help="Items per encode request")+ command.add_argument("--endpoint", default=DEFAULT_ENDPOINT, help="SIE endpoint URL")++def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description=__doc__)commands = parser.add_subparsers(dest="command", required=True)quality = commands.add_parser("quality", help="Repeat a published quality measurement")- quality.add_argument("--reference", type=Path, help="A references/<id>.json file")- quality.add_argument("--model", help="Model route, model[:profile]")- quality.add_argument("--task", help="Task key, for example mteb/SciFact")- quality.add_argument("--output", choices=ENCODE_OUTPUTS, help="Output contract of an encode task")- quality.add_argument("--items-per-request", type=int, help="Items per encode request")- quality.add_argument("--endpoint", default=DEFAULT_ENDPOINT, help="SIE endpoint URL")+ _add_shared_arguments(quality)+ performance = commands.add_parser("performance", help="Repeat a published fixed-rate performance measurement")+ _add_shared_arguments(performance)+ performance.add_argument("--rate", type=float, help="Requests per second; the reference's published level")+ performance.add_argument("--duration", type=float, help="Seconds of scheduled arrivals (default 60)")+ performance.add_argument("--warmup", type=float, help="Seconds of unrecorded warmup (default 30; 0 skips it)")return parser@@ -144,9 +219,35 @@ def _check_limit(params: Mapping[str, str]) -> None:raise ValueError("limit must be a positive integer")-def _plan_from_reference(args: argparse.Namespace, reference: Mapping[str, Any]) -> QualityPlan:- if reference.get("kind") != REFERENCE_KIND or reference.get("evaluation_mode") != "quality":- raise ValueError("--reference must name a quality published-benchmark-reference file")+def _check_positive_integer(params: Mapping[str, str], name: str) -> None:+ if name in params and (not params[name].isdigit() or int(params[name]) < 1):+ raise ValueError(f"{name} must be a positive integer")+++def _check_performance_params(params: Mapping[str, str], operation: str) -> None:+ _check_limit(params)+ _check_positive_integer(params, "candidates-k")+ if params.get("split", "test") != "test":+ raise ValueError("only split=test is available")+ if params.get("filter", "nonempty") != "nonempty":+ raise ValueError("filter must be nonempty")+ role = params.get("role", "queries")+ if role not in ROLES:+ raise ValueError("role must be queries or corpus")+ if operation == "score" and role != "queries":+ raise ValueError("the score task sends queries; role=corpus is not available")+++def _check_timing(rate: float, duration_s: float, warmup_s: float) -> None:+ if not math.isfinite(rate) or rate <= 0:+ raise ValueError("--rate must be a positive finite number")+ if not math.isfinite(duration_s) or duration_s <= 0:+ raise ValueError("--duration must be a positive finite number")+ if not math.isfinite(warmup_s) or warmup_s < 0:+ raise ValueError("--warmup must be a finite number that is not negative")+++def _refuse_fixed_flags(args: argparse.Namespace) -> None:for flag, value in (("--model", args.model),("--output", args.output),@@ -154,9 +255,41 @@ def _plan_from_reference(args: argparse.Namespace, reference: Mapping[str, Any])):if value is not None:raise ValueError(f"{flag} cannot be combined with --reference; the reference fixes it")+++def _plain_reference_id(reference: Mapping[str, Any]) -> str:reference_id = reference["reference_id"]if not reference_id or Path(reference_id).name != reference_id or reference_id in {".", ".."}:raise ValueError(f"reference_id {reference_id!r} is not a plain file name")+ return reference_id+++def _client_processes_reasons(reference: Mapping[str, Any]) -> list[str]:+ processes = reference["client"]["worker_count"] * reference["client"]["processes_per_worker"]+ return [] if processes == 1 else [f"client processes 1 != {processes}"]+++def _check_output_flags(args: argparse.Namespace, operation: str) -> None:+ if operation == "encode" and (args.output is None or args.items_per_request is None):+ raise ValueError("--output and --items-per-request are required for encode tasks")+ if operation == "score" and (args.output is not None or args.items_per_request is not None):+ raise ValueError("--output and --items-per-request are not accepted for the score task")+ if args.items_per_request is not None and args.items_per_request < 1:+ raise ValueError("--items-per-request must be a positive integer")+++def _override(value: float | None, fixed: float, label: str, reasons: list[str]) -> float:+ if value is None or value == fixed:+ return fixed+ reasons.append(f"{label} {value:g} != {fixed:g}")+ return value+++def _plan_from_reference(args: argparse.Namespace, reference: Mapping[str, Any]) -> QualityPlan:+ if reference.get("kind") != REFERENCE_KIND or reference.get("evaluation_mode") != "quality":+ raise ValueError("--reference must name a quality published-benchmark-reference file")+ _refuse_fixed_flags(args)+ reference_id = _plain_reference_id(reference)task_key = reference["task_key"]task_name, params = parse_task_key(task_key)reasons: list[str] = []@@ -168,9 +301,7 @@ def _plan_from_reference(args: argparse.Namespace, reference: Mapping[str, Any])reasons.append(f"smoke key {task_key}")_check_limit(params)reasons.extend(_endpoint_reasons(args.endpoint))- processes = reference["client"]["worker_count"] * reference["client"]["processes_per_worker"]- if processes != 1:- reasons.append(f"client processes 1 != {processes}")+ reasons.extend(_client_processes_reasons(reference))return QualityPlan(reference_id=reference_id,reference_metrics=list(reference["metrics"]),@@ -197,12 +328,7 @@ def _plan_from_flags(args: argparse.Namespace) -> QualityPlan:_check_limit(params)model, _, profile = args.model.partition(":")operation = "score" if task_name in SCORE_TASKS else "encode"- if operation == "encode" and (args.output is None or args.items_per_request is None):- raise ValueError("--output and --items-per-request are required for encode tasks")- if operation == "score" and (args.output is not None or args.items_per_request is not None):- raise ValueError("--output and --items-per-request are not accepted for the score task")- if args.items_per_request is not None and args.items_per_request < 1:- raise ValueError("--items-per-request must be a positive integer")+ _check_output_flags(args, operation)reasons = ["no reference"]if "limit" in params:reasons.append(f"smoke key {args.task}")@@ -226,6 +352,103 @@ def _plan_from_flags(args: argparse.Namespace) -> QualityPlan:)+def plan_performance(args: argparse.Namespace) -> PerformancePlan:+ if args.reference is not None:+ reference = json.loads(Path(args.reference).read_text(encoding="utf-8"))+ return _performance_plan_from_reference(args, reference)+ return _performance_plan_from_flags(args)+++def _performance_plan_from_reference(args: argparse.Namespace, reference: Mapping[str, Any]) -> PerformancePlan:+ if reference.get("kind") != REFERENCE_KIND or reference.get("evaluation_mode") != PERFORMANCE_MODE:+ raise ValueError("--reference must name a performance published-benchmark-reference file")+ _refuse_fixed_flags(args)+ reference_id = _plain_reference_id(reference)+ task_key = reference["task_key"]+ if args.task is not None and args.task != task_key:+ raise ValueError(f"--task must equal the reference task_key {task_key!r}")+ task_name, params = parse_task_key(task_key)+ operation = reference["operation"]+ _check_performance_params(params, operation)+ level, timing = reference["schedule"]["levels"][0], reference["timing"]+ reasons: list[str] = []+ rate = _override(args.rate, float(level["rate"]), "rate", reasons)+ duration_s = _override(args.duration, float(level["duration_s"]), "duration", reasons)+ warmup_s = _override(args.warmup, float(timing["warmup_s"]), "warmup", reasons)+ _check_timing(rate, duration_s, warmup_s)+ reasons.extend(_endpoint_reasons(args.endpoint))+ reasons.extend(_client_processes_reasons(reference))+ readiness_timeout_s = timing["target_readiness_timeout_s"]+ return PerformancePlan(+ reference_id=reference_id,+ reference_metrics=list(reference["metrics"]),+ model=reference["model"],+ profile=reference["profile"],+ operation=operation,+ task_key=task_key,+ task_name=task_name,+ task_params=params,+ revision=reference["dataset"]["revision"],+ output_contract=reference["payload"]["output_contract"],+ items_per_request=reference["payload"]["items_per_request"],+ rate=rate,+ duration_s=duration_s,+ warmup_s=warmup_s,+ settle_s=float(timing["settle_s"]),+ drain_s=float(timing["drain_s"]),+ request_timeout_s=float(timing["request_timeout_s"]),+ target_readiness_timeout_s=(+ DEFAULT_READINESS_TIMEOUT_S if readiness_timeout_s is None else float(readiness_timeout_s)+ ),+ max_in_flight=int(timing["max_in_flight_per_process"]),+ lag_tolerance_ms=float(timing["scheduling_lag_tolerance_ms"]),+ endpoint=args.endpoint,+ model_version=reference["model_version"],+ comparable_reasons=reasons,+ )+++def _performance_plan_from_flags(args: argparse.Namespace) -> PerformancePlan:+ if args.model is None or args.task is None:+ raise ValueError("--model and --task are required without --reference")+ if args.rate is None:+ raise ValueError("--rate is required without --reference")+ task_name, params = parse_task_key(args.task)+ model, _, profile = args.model.partition(":")+ operation = "score" if task_name in SCORE_TASKS else "encode"+ _check_performance_params(params, operation)+ _check_output_flags(args, operation)+ duration_s = DEFAULT_DURATION_S if args.duration is None else args.duration+ warmup_s = DEFAULT_WARMUP_S if args.warmup is None else args.warmup+ _check_timing(args.rate, duration_s, warmup_s)+ request_timeout_s, max_in_flight = PERFORMANCE_LIMITS[operation]+ return PerformancePlan(+ reference_id=None,+ reference_metrics=[],+ model=model,+ profile=profile or "default",+ operation=operation,+ task_key=args.task,+ task_name=task_name,+ task_params=params,+ revision=HF_DATASETS[task_name][1],+ output_contract=args.output if operation == "encode" else "scores",+ items_per_request=args.items_per_request,+ rate=args.rate,+ duration_s=duration_s,+ warmup_s=warmup_s,+ settle_s=DEFAULT_SETTLE_S,+ drain_s=DEFAULT_DRAIN_S,+ request_timeout_s=request_timeout_s,+ target_readiness_timeout_s=DEFAULT_READINESS_TIMEOUT_S,+ max_in_flight=max_in_flight,+ lag_tolerance_ms=DEFAULT_LAG_TOLERANCE_MS,+ endpoint=args.endpoint,+ model_version=None,+ comparable_reasons=["no reference", *_endpoint_reasons(args.endpoint)],+ )++def select_queries(queries: Queries, qrels: Qrels, params: Mapping[str, str]) -> Queries:selected = {query_id: text for query_id, text in queries.items() if qrels.get(query_id)}if "limit" not in params:@@ -255,6 +478,179 @@ def document_text(document: Mapping[str, str]) -> str:return f"{title} {document['text']}".strip() if title else document["text"].strip()+def performance_text(document: Mapping[str, str]) -> str:+ title = document.get("title") or ""+ return f"{title}\n{document['text']}" if title else document["text"]+++def select_ids(texts: Mapping[str, str], params: Mapping[str, str]) -> list[str]:+ nonempty = params.get("filter") == "nonempty"+ selected = sorted(item_id for item_id, text in texts.items() if not nonempty or text.strip())+ return selected[: int(params["limit"])] if "limit" in params else selected+++def load_performance_data(plan: PerformancePlan, loaders: Loaders | None = None) -> PerformanceData:+ loaders = loaders or Loaders()+ params = plan.task_params+ if plan.operation == "score":+ queries = loaders.queries(plan.task_name, plan.revision)+ corpus = loaders.corpus(plan.task_name, plan.revision)+ top_ranked = loaders.top_ranked(plan.task_name, plan.revision)+ selected = select_ids(queries, params)+ k = int(params["candidates-k"]) if "candidates-k" in params else None+ requests: list[ScoreRequest] = [+ (+ {"text": queries[query_id]},+ [{"id": doc_id, "text": performance_text(corpus[doc_id])} for doc_id in top_ranked[query_id][:k]],+ )+ for query_id in selected+ ]+ return PerformanceData(selected, requests)+ if params.get("role", "queries") == "corpus":+ corpus = loaders.corpus(plan.task_name, plan.revision)+ selected = select_ids({doc_id: document["text"] for doc_id, document in corpus.items()}, params)+ return PerformanceData(+ selected, [{"id": doc_id, "text": performance_text(corpus[doc_id])} for doc_id in selected]+ )+ queries = loaders.queries(plan.task_name, plan.revision)+ selected = select_ids(queries, params)+ return PerformanceData(selected, [{"id": query_id, "text": queries[query_id]} for query_id in selected])+++def load_level_name(rate: float) -> str:+ return f"fixed-{rate:g}-rps".replace(".", "-")+++def schedule_offsets(rate: float, duration_s: float) -> list[Fraction]:+ exact_rate, exact_duration = Fraction(str(rate)), Fraction(str(duration_s))+ return [Fraction(index) / exact_rate for index in range(math.ceil(exact_rate * exact_duration))]+++def request_rows(sequence: int, items_per_request: int, length: int) -> list[int]:+ return [(sequence * items_per_request + position) % length for position in range(items_per_request)]+++def request_payload(plan: PerformancePlan, data: PerformanceData, sequence: int) -> Any:+ if not data.payloads:+ raise ValueError(f"the task key {plan.task_key!r} selects no rows")+ if plan.operation == "score":+ return data.payloads[sequence % len(data.payloads)]+ return [data.payloads[row] for row in request_rows(sequence, plan.items_per_request or 1, len(data.payloads))]+++def performance_call(+ client: Any, plan: PerformancePlan, payload: Any, *, wait_for_capacity: bool, provision_timeout_s: float+) -> Any:+ if plan.operation == "score":+ query, items = payload+ return client.score(+ plan.route,+ query,+ items,+ wait_for_capacity=wait_for_capacity,+ provision_timeout_s=provision_timeout_s,+ max_oom_retries=0,+ )+ return client.encode(+ plan.route,+ payload,+ output_types=[plan.output_contract],+ is_query=False,+ wait_for_capacity=wait_for_capacity,+ provision_timeout_s=provision_timeout_s,+ max_oom_retries=0,+ )+++def request_status(exc: BaseException) -> str:+ cause: BaseException | None = exc+ while cause is not None:+ if isinstance(cause, httpx.TimeoutException):+ return "timeout"+ cause = cause.__cause__+ return f"error:{type(exc).__name__}"+++@dataclass+class Dispatcher:+ plan: PerformancePlan+ data: PerformanceData+ client: Any+ log: CallLog = field(default_factory=CallLog)+ rows: list[dict[str, Any]] = field(default_factory=list)+ readiness_failure: str | None = None+ in_flight_peak: int = 0+ _in_flight: int = 0+ _origin_ns: int = 0+ _lock: threading.Lock = field(default_factory=threading.Lock)++ def send(self, sequence: int, offset: Fraction) -> dict[str, Any]:+ payload = request_payload(self.plan, self.data, sequence)+ with self._lock:+ in_flight_at_send = self._in_flight+ self._in_flight += 1+ self.in_flight_peak = max(self.in_flight_peak, self._in_flight)+ failure: Exception | None = None+ sent_ns = time.perf_counter_ns() - self._origin_ns+ try:+ performance_call(+ self.client,+ self.plan,+ payload,+ wait_for_capacity=False,+ provision_timeout_s=self.plan.request_timeout_s,+ )+ except Exception as exc: # noqa: BLE001+ failure = exc+ completed_ns = time.perf_counter_ns() - self._origin_ns+ retry_count = int(self.client.last_retry_count)+ with self._lock:+ self._in_flight -= 1+ if failure is None:+ self.log.record(self.client)+ else:+ self.log.fail(self.client, failure)+ return {+ "sequence": sequence,+ "level_name": self.plan.level_name,+ "offset_s": float(offset),+ "actual_send_offset_ns": sent_ns,+ "completed_offset_ns": completed_ns,+ "scheduling_lag_ms": max(0.0, (sent_ns - nanoseconds(offset)) / NS_PER_MS),+ "status": "success" if failure is None else request_status(failure),+ "attempt": 1,+ "client_retry_count": retry_count,+ "in_flight_at_send": in_flight_at_send,+ }++ def run(self) -> None:+ offsets = schedule_offsets(self.plan.rate, self.plan.duration_s)+ with ThreadPoolExecutor(max_workers=self.plan.max_in_flight) as pool:+ self._origin_ns = time.perf_counter_ns()+ futures = []+ for sequence, offset in enumerate(offsets):+ remaining_ns = self._origin_ns + nanoseconds(offset) - time.perf_counter_ns()+ if remaining_ns > 0:+ time.sleep(remaining_ns / NS_PER_S)+ futures.append(pool.submit(self.send, sequence, offset))+ _, pending = wait(futures, timeout=self.plan.drain_s)+ wait(pending)+ self.rows = [future.result() for future in futures]+++def readiness_request(client: Any, plan: PerformancePlan, data: PerformanceData) -> None:+ payload = request_payload(plan, data, 0)+ performance_call(client, plan, payload, wait_for_capacity=True, provision_timeout_s=plan.target_readiness_timeout_s)+++def warmup(client: Any, plan: PerformancePlan, data: PerformanceData) -> None:+ payload = request_payload(plan, data, 0)+ deadline = time.monotonic() + plan.warmup_s+ while time.monotonic() < deadline:+ with contextlib.suppress(Exception):+ performance_call(client, plan, payload, wait_for_capacity=False, provision_timeout_s=plan.request_timeout_s)++def _call(log: CallLog, client: Any, method: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:try:result = method(*args, **kwargs)@@ -415,12 +811,12 @@ def _timestamp(moment: datetime) -> str:return moment.strftime("%Y-%m-%dT%H:%M:%SZ")-def _slug(plan: QualityPlan) -> str:- return re.sub(r"[^A-Za-z0-9._-]+", "-", f"{plan.route}-{plan.task_key}").strip("-")+def _slug(route: str, task_key: str) -> str:+ return re.sub(r"[^A-Za-z0-9._-]+", "-", f"{route}-{task_key}").strip("-")-def comparison_basis(plan: QualityPlan, comparable: bool, reasons: Sequence[str]) -> str | None:- if plan.reference_id is None:+def comparison_basis(reference_id: str | None, comparable: bool, reasons: Sequence[str]) -> str | None:+ if reference_id is None:return Noneif comparable:return "same parameters"@@ -482,7 +878,103 @@ def build_record("validity": {"valid": not validity_reasons, "reasons": validity_reasons, "sdk_retries": log.sdk_retries},"metrics": rows,"comparison": compare(rows, plan.reference_metrics) if plan.reference_id is not None else [],- "comparison_basis": comparison_basis(plan, comparable, reasons),+ "comparison_basis": comparison_basis(plan.reference_id, comparable, reasons),+ }+++def performance_validity(plan: PerformancePlan, dispatcher: Dispatcher, metrics: Mapping[str, float]) -> dict[str, Any]:+ log = dispatcher.log+ reasons: list[str] = []+ if dispatcher.readiness_failure is not None:+ reasons.append(f"readiness request failed: {dispatcher.readiness_failure}")+ if log.sdk_retries:+ reasons.append(f"sdk retries {log.sdk_retries}")+ lag_p99_ms = metrics.get("scheduling_lag_p99_ms")+ if lag_p99_ms is not None and lag_p99_ms > plan.lag_tolerance_ms:+ reasons.append(f"scheduling lag p99 {lag_p99_ms:.3f} ms > {plan.lag_tolerance_ms:g} ms")+ if dispatcher.in_flight_peak > plan.max_in_flight:+ reasons.append(f"in-flight peak {dispatcher.in_flight_peak} > {plan.max_in_flight}")+ if len(log.execution_revisions) > 1:+ reasons.append("execution revision changed")+ return {+ "valid": not reasons,+ "reasons": reasons,+ "lag_max_ms": max((row["scheduling_lag_ms"] for row in dispatcher.rows), default=0.0),+ "in_flight_peak": dispatcher.in_flight_peak,+ "timeouts": sum(row["status"] == "timeout" for row in dispatcher.rows),+ "sdk_retries": log.sdk_retries,+ }+++def build_performance_record(+ plan: PerformancePlan,+ data: PerformanceData,+ dispatcher: Dispatcher,+ started: datetime,+ finished: datetime,+ requests_path: Path | None,+ rows: Rows,+) -> dict[str, Any]:+ log = dispatcher.log+ reasons = list(plan.comparable_reasons)+ if len(log.execution_revisions) > 1:+ reasons.append("execution revision changed")+ comparable = not reasons+ candidate_counts = [len(items) for _, items in data.payloads] if plan.operation == "score" else []+ return {+ "kind": RESULT_KIND,+ "schema_version": 1,+ "reference_id": plan.reference_id,+ "comparable": comparable,+ "comparable_reasons": reasons,+ "evaluation_mode": PERFORMANCE_MODE,+ "model": plan.model,+ "profile": plan.profile,+ "operation": plan.operation,+ "model_version": plan.model_version,+ "execution_revisions": list(log.execution_revisions),+ "ingress": {"url": plan.endpoint},+ "task_key": plan.task_key,+ "dataset": {+ "name": plan.task_name,+ "revision": plan.revision,+ "subset": "test",+ "parameters": [{"name": name, "value": value} for name, value in plan.task_params.items()],+ "selected_ids": list(data.selected_ids),+ },+ "payload": {+ "items_per_request": plan.items_per_request or max(candidate_counts, default=0),+ "output_contract": plan.output_contract,+ "parameters": [{"name": "is_query", "value": False}] if plan.operation == "encode" else [],+ },+ "client": {"description": client_description(), "worker_count": 1, "processes_per_worker": 1},+ "load_level_name": plan.level_name,+ "schedule": {+ "arrival": "deterministic",+ "levels": [{"name": plan.level_name, "rate": plan.rate, "duration_s": plan.duration_s}],+ },+ "timing": {+ "warmup_s": plan.warmup_s,+ "settle_s": plan.settle_s,+ "drain_s": plan.drain_s,+ "request_timeout_s": plan.request_timeout_s,+ "target_readiness_timeout_s": plan.target_readiness_timeout_s,+ "max_in_flight_per_process": plan.max_in_flight,+ "scheduling_lag_tolerance_ms": plan.lag_tolerance_ms,+ "retry": dict(RETRY_POLICY),+ },+ "run": {+ "started_at": _timestamp(started),+ "finished_at": _timestamp(finished),+ "endpoint": plan.endpoint,+ "request_count": log.request_count,+ "failure_count": log.failure_count,+ "requests_path": str(requests_path) if requests_path is not None else None,+ },+ "validity": performance_validity(plan, dispatcher, {row["name"]: row["value"] for row in rows}),+ "metrics": rows,+ "comparison": compare(rows, plan.reference_metrics) if plan.reference_id is not None else [],+ "comparison_basis": comparison_basis(plan.reference_id, comparable, reasons),}@@ -506,7 +998,7 @@ def run_quality(except RequestFailed:predictions = Nonefinished = clock()- stem = f"{plan.reference_id or _slug(plan)}-{started.strftime('%Y%m%dT%H%M%SZ')}"+ stem = f"{plan.reference_id or _slug(plan.route, plan.task_key)}-{started.strftime('%Y%m%dT%H%M%SZ')}"results_dir.mkdir(parents=True, exist_ok=True)result_path = results_dir / f"{stem}.json"predictions_path = None@@ -520,6 +1012,40 @@ def run_quality(return record, result_path+def run_performance(+ plan: PerformancePlan,+ data: PerformanceData,+ client: Any,+ *,+ results_dir: Path = RESULTS_DIR,+ now: Callable[[], datetime] | None = None,+) -> tuple[dict[str, Any], Path]:+ clock = now or (lambda: datetime.now(UTC))+ started = clock()+ dispatcher = Dispatcher(plan, data, client)+ try:+ readiness_request(client, plan, data)+ except Exception as exc: # noqa: BLE001+ dispatcher.readiness_failure = f"{type(exc).__name__}: {exc}"+ if dispatcher.readiness_failure is None:+ warmup(client, plan, data)+ time.sleep(plan.settle_s)+ dispatcher.run()+ finished = clock()+ stem = f"{plan.reference_id or _slug(plan.route, plan.task_key)}-{started.strftime('%Y%m%dT%H%M%SZ')}"+ results_dir.mkdir(parents=True, exist_ok=True)+ result_path = results_dir / f"{stem}.json"+ requests_path = None+ rows: Rows = []+ if dispatcher.rows:+ requests_path = results_dir / f"{stem}.requests.jsonl"+ write_jsonl(requests_path, dispatcher.rows)+ rows = performance_metric_rows(performance_metrics(dispatcher.rows, plan.rate, plan.duration_s))+ record = build_performance_record(plan, data, dispatcher, started, finished, requests_path, rows)+ write_json(result_path, record)+ return record, result_path++def quality_command(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:try:plan = plan_quality(args)@@ -538,11 +1064,33 @@ def quality_command(parser: argparse.ArgumentParser, args: argparse.Namespace) -raise SystemExit(1)+def performance_command(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:+ try:+ plan = plan_performance(args)+ except (ValueError, KeyError, OSError) as exc:+ parser.error(str(exc))+ api_key = os.environ.get("SIE_API_KEY")+ if not api_key:+ parser.error("SIE_API_KEY must be set in the environment")+ data = load_performance_data(plan)+ with SIEClient(+ plan.endpoint, api_key=api_key, timeout_s=plan.request_timeout_s, max_connections=2 * plan.max_in_flight+ ) as client:+ record, result_path = run_performance(plan, data, client)+ print(result_path)+ for line in format_rows(record["metrics"], record["comparison"]):+ print(line)+ if record["run"]["requests_path"] is None:+ raise SystemExit(1)++def main(argv: Sequence[str] | None = None) -> None:parser = build_parser()args = parser.parse_args(argv)if args.command == "quality":quality_command(parser, args)+ elif args.command == "performance":+ performance_command(parser, args)if __name__ == "__main__":diff --git a/examples/evaluations/published-benchmarks/score.py b/examples/evaluations/published-benchmarks/score.pyindex 6d3c9f6e0..7842c2d63 100644--- a/examples/evaluations/published-benchmarks/score.py+++ b/examples/evaluations/published-benchmarks/score.py@@ -1,9 +1,11 @@-"""Recompute the published quality metrics from a result's predictions file and print the deltas."""+"""Recompute the published metrics from a result's predictions or requests file and print the deltas."""import argparseimport importlib.metadataimport json+import mathfrom collections.abc import Mapping, Sequence+from fractions import Fractionfrom pathlib import Pathfrom typing import Anyfrom urllib.parse import parse_qsl@@ -31,6 +33,23 @@ METRIC_UNIT = "ratio"AGGREGATION = "task_native"SCORER_ID = "pytrec-eval"SCORER_DISTRIBUTION = "pytrec-eval-terrier"+PERFORMANCE_MODE = "isolated_performance"+PERFORMANCE_METRICS = {+ "offered_requests_per_second": ("requests_per_second", "campaign_global"),+ "achieved_requests_per_second": ("requests_per_second", "common_window"),+ "eventual_achieved_requests_per_second": ("requests_per_second", "including_drain"),+ "in_window_success_rate": ("ratio", "campaign_global"),+ "in_window_retry_free_success_rate": ("ratio", "campaign_global"),+ "success_rate": ("ratio", "campaign_global"),+ "retry_free_success_rate": ("ratio", "campaign_global"),+ "scheduling_lag_p99_ms": ("milliseconds", "p99"),+ "latency_p50_ms": ("milliseconds", "p50"),+ "latency_p95_ms": ("milliseconds", "p95"),+ "latency_p99_ms": ("milliseconds", "p99"),+}+LATENCY_PERCENTILES = (50, 95, 99)+NS_PER_S = 1_000_000_000+NS_PER_MS = 1_000_000Qrels = dict[str, dict[str, int]]Predictions = Mapping[str, Mapping[str, float]]@@ -134,6 +153,53 @@ def metric_rows(metrics: Mapping[str, float]) -> Rows:]+def nanoseconds(seconds: float | Fraction) -> int:+ return int(Fraction(str(seconds)) * NS_PER_S)+++def nearest_rank(values: Sequence[float], percent: int) -> float:+ if not values:+ raise ValueError("a percentile needs at least one value")+ ordered = sorted(values)+ return ordered[max(0, math.ceil(Fraction(percent * len(ordered), 100)) - 1)]+++def _retry_free(row: Mapping[str, Any]) -> bool:+ return row["attempt"] == 1 and row["client_retry_count"] == 0+++def performance_metrics(rows: Sequence[Mapping[str, Any]], rate: float, duration_s: float) -> dict[str, float]:+ count = len(rows)+ if count == 0:+ raise ValueError("performance metrics need at least one scheduled request")+ window_ns = nanoseconds(duration_s)+ successes = [row for row in rows if row["status"] == "success"]+ in_window = [row for row in successes if row["completed_offset_ns"] < window_ns]+ metrics = {+ "offered_requests_per_second": float(rate),+ "achieved_requests_per_second": len(in_window) / duration_s,+ "eventual_achieved_requests_per_second": len(successes) / duration_s,+ "in_window_success_rate": len(in_window) / count,+ "in_window_retry_free_success_rate": sum(_retry_free(row) for row in in_window) / count,+ "success_rate": len(successes) / count,+ "retry_free_success_rate": sum(_retry_free(row) for row in successes) / count,+ "scheduling_lag_p99_ms": nearest_rank([row["scheduling_lag_ms"] for row in rows], 99),+ }+ if successes:+ latencies = [(row["completed_offset_ns"] - row["actual_send_offset_ns"]) / NS_PER_MS for row in successes]+ for percent in LATENCY_PERCENTILES:+ metrics[f"latency_p{percent}_ms"] = nearest_rank(latencies, percent)+ return metrics+++def performance_metric_rows(metrics: Mapping[str, float]) -> Rows:+ return [+ {"name": name, "unit": unit, "aggregation": aggregation, "value": metrics[name]}+ for name, (unit, aggregation) in PERFORMANCE_METRICS.items()+ if name in metrics+ ]++def compare(rows: Sequence[Mapping[str, Any]], reference_rows: Sequence[Mapping[str, Any]]) -> Rows:reference = {(row["name"], row["aggregation"]): row["value"] for row in reference_rows}comparison: Rows = []@@ -155,9 +221,10 @@ def compare(rows: Sequence[Mapping[str, Any]], reference_rows: Sequence[Mapping[def format_rows(rows: Sequence[Mapping[str, Any]], comparison: Sequence[Mapping[str, Any]]) -> list[str]:matched = {(row["name"], row["aggregation"]): row for row in comparison}+ width = max([20, *(len(row["name"]) for row in rows)])lines = []for row in rows:- line = f"{row['name']:<20} {row['value']:.5f}"+ line = f"{row['name']:<{width}} {row['value']:.5f}"entry = matched.get((row["name"], row["aggregation"]))if entry is not None:line += f" reference {entry['reference_value']:.5f} delta {entry['delta']:+.5f}"@@ -176,17 +243,42 @@ def write_json(path: Path, payload: Any, *, compact: bool = False) -> None:path.write_text(text + "\n", encoding="utf-8")-def rescore(result_path: Path) -> tuple[dict[str, Any], Rows, Rows]:- record = json.loads(result_path.read_text(encoding="utf-8"))- predictions_name = record["run"]["predictions_path"]- if predictions_name is None:- raise ValueError(f"{result_path} has no predictions file; its run did not complete")- predictions_path = result_path.parent / Path(predictions_name).name+def write_jsonl(path: Path, rows: Sequence[Mapping[str, Any]]) -> None:+ path.write_text("".join(json.dumps(row, separators=(",", ":")) + "\n" for row in rows), encoding="utf-8")+++def read_jsonl(path: Path) -> list[dict[str, Any]]:+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]+++def _sibling(result_path: Path, record: Mapping[str, Any], key: str, label: str) -> Path:+ name = record["run"][key]+ if name is None:+ raise ValueError(f"{result_path} has no {label} file; its run did not complete")+ return result_path.parent / Path(name).name+++def _quality_rows(result_path: Path, record: Mapping[str, Any]) -> Rows:+ predictions_path = _sibling(result_path, record, "predictions_path", "predictions")predictions = json.loads(predictions_path.read_text(encoding="utf-8"))task_name, params = parse_task_key(record["task_key"])dataset = record["dataset"]qrels = scoped_qrels(load_qrels(task_name, dataset["revision"], dataset["subset"]), predictions, params)- rows = metric_rows(task_metrics(predictions, qrels, task_name))+ return metric_rows(task_metrics(predictions, qrels, task_name))+++def _performance_rows(result_path: Path, record: Mapping[str, Any]) -> Rows:+ requests = read_jsonl(_sibling(result_path, record, "requests_path", "requests"))+ level = record["schedule"]["levels"][0]+ return performance_metric_rows(performance_metrics(requests, level["rate"], level["duration_s"]))+++def rescore(result_path: Path) -> tuple[dict[str, Any], Rows, Rows]:+ record = json.loads(result_path.read_text(encoding="utf-8"))+ if record.get("evaluation_mode") == PERFORMANCE_MODE:+ rows = _performance_rows(result_path, record)+ else:+ rows = _quality_rows(result_path, record)reference_rows = [{"name": row["name"], "aggregation": row["aggregation"], "value": row["reference_value"]}for row in record.get("comparison", [])diff --git a/examples/evaluations/published-benchmarks/tests/test_performance.py b/examples/evaluations/published-benchmarks/tests/test_performance.pynew file mode 100644index 000000000..a05bf5dec--- /dev/null+++ b/examples/evaluations/published-benchmarks/tests/test_performance.py@@ -0,0 +1,863 @@+import contextlib+import io+import json+import tempfile+import threading+import time+import unittest+from collections import Counter+from datetime import UTC, datetime+from fractions import Fraction+from pathlib import Path+from unittest.mock import patch++import httpx+from sie_sdk import ProvisioningError, ServerError, SIEConnectionError++import run+import score+from run import (+ DEFAULT_ENDPOINT,+ Dispatcher,+ Loaders,+ PerformanceData,+ build_parser,+ load_level_name,+ load_performance_data,+ performance_text,+ performance_validity,+ plan_performance,+ request_payload,+ request_rows,+ request_status,+ run_performance,+ schedule_offsets,+ select_ids,+)+from score import (+ PERFORMANCE_METRICS,+ nearest_rank,+ parse_task_key,+ performance_metric_rows,+ performance_metrics,+)++REFERENCE_ID = "example-reference-performance-01"+REVISION = "d56462d0e63a25450459c4f213e49ffdb866f7f9"+CORPUS_KEY = "mteb/SciFact?split=test&role=corpus&limit=4&filter=nonempty"+SCORE_KEY = "mteb/AskUbuntuDupQuestions?split=test&limit=2&candidates-k=2"+CORPUS = {+ "10": {"title": "Ten", "text": "ten body"},+ "9": {"title": "", "text": "nine body"},+ "100": {"title": "Hundred", "text": " "},+ "2": {"text": "two body"},+ "33": {"title": "T", "text": "thirty-three body"},+}+SELECTED = ["10", "2", "33", "9"]+QUERIES = {"q2": "second query", "q1": "first query", "q10": "tenth query"}+TOP_RANKED = {"q1": ["10", "9", "2"], "q2": ["2", "33"], "q10": ["9"]}+RESULT_KEYS = {+ "kind",+ "schema_version",+ "reference_id",+ "comparable",+ "comparable_reasons",+ "evaluation_mode",+ "model",+ "profile",+ "operation",+ "model_version",+ "execution_revisions",+ "ingress",+ "task_key",+ "dataset",+ "payload",+ "client",+ "load_level_name",+ "schedule",+ "timing",+ "run",+ "validity",+ "metrics",+ "comparison",+ "comparison_basis",+}+++def timeout_error():+ error = SIEConnectionError("Request timed out")+ error.__cause__ = httpx.ReadTimeout("read timed out")+ return error+++class FakeClient:+ def __init__(self, *, delay_s=0.005, failures=None, retries=None, revisions=("rev-a",), ready=True):+ self.calls = []+ self.delay_s = delay_s+ self.failures = dict(failures or {})+ self.retries = dict(retries or {})+ self.revisions = list(revisions)+ self.ready = ready+ self._lock = threading.Lock()+ self._state = threading.local()++ @property+ def last_retry_count(self):+ return getattr(self._state, "retry_count", 0)++ @property+ def last_model_revision(self):+ return getattr(self._state, "revision", None)++ def _observe(self, call, key, kwargs):+ with self._lock:+ self.calls.append(call)+ index = len(self.calls) - 1+ if kwargs.get("wait_for_capacity") and not self.ready:+ raise ProvisioningError("no capacity")+ time.sleep(self.delay_s)+ self._state.retry_count = self.retries.get(key, 0)+ self._state.revision = None+ failure = self.failures.get(key)+ if failure is not None:+ raise failure+ self._state.revision = self.revisions[index % len(self.revisions)]++ def encode(self, model, items, **kwargs):+ self._observe(("encode", model, items, kwargs), items[0]["id"], kwargs)+ return [{"id": item["id"], "sparse": {"indices": [0], "values": [1.0]}} for item in items]++ def score(self, model, query, items, **kwargs):+ self._observe(("score", model, (query, items), kwargs), query["text"], kwargs)+ return {"model": model, "query_id": "", "scores": [{"item_id": item["id"], "score": 1.0} for item in items]}+++def tiny_loaders():+ return Loaders(+ corpus=lambda name, revision: {doc_id: dict(doc) for doc_id, doc in CORPUS.items()},+ queries=lambda name, revision: dict(QUERIES),+ qrels=lambda name, revision: {},+ top_ranked=lambda name, revision: {query_id: list(docs) for query_id, docs in TOP_RANKED.items()},+ )+++def reference_file(directory, **overrides):+ reference = {+ "kind": "published-benchmark-reference",+ "schema_version": 1,+ "reference_id": REFERENCE_ID,+ "evaluation_mode": "isolated_performance",+ "model": "example/sparse-encoder",+ "model_version": "0" * 40,+ "profile": "default",+ "operation": "encode",+ "task_key": CORPUS_KEY,+ "dataset": {+ "name": "mteb/SciFact",+ "revision": REVISION,+ "subset": "test",+ "parameters": [+ {"name": "limit", "value": 4},+ {"name": "role", "value": "corpus"},+ {"name": "filter", "value": "nonempty"},+ ],+ },+ "payload": {+ "items_per_request": 1,+ "output_contract": "sparse",+ "parameters": [{"name": "is_query", "value": False}],+ },+ "load_level_name": "fixed-50-rps",+ "schedule": {+ "arrival": "deterministic",+ "levels": [{"name": "fixed-50-rps", "rate": 50.0, "duration_s": 0.4}],+ "seed": 0,+ "unit": "requests_per_second",+ },+ "timing": {+ "warmup_s": 0.0,+ "settle_s": 0.0,+ "drain_s": 0.0,+ "request_timeout_s": 5.0,+ "target_readiness_timeout_s": 30.0,+ "max_in_flight_per_process": 4,+ "scheduling_lag_tolerance_ms": 20.0,+ "retry": {"backoff": "none", "max_attempts": 1, "record_attempts": True},+ },+ "client": {"worker_count": 2, "processes_per_worker": 2},+ "scorer": None,+ "metrics": [+ {+ "name": "offered_requests_per_second",+ "unit": "requests_per_second",+ "aggregation": "campaign_global",+ "value": 50.0,+ },+ {"name": "success_rate", "unit": "ratio", "aggregation": "campaign_global", "value": 1.0},+ {"name": "latency_p50_ms", "unit": "milliseconds", "aggregation": "p50", "value": 10.0},+ ],+ "accepted_at": "2026-09-05T05:18:08Z",+ "measurement_started_at": "2026-09-05T04:47:35Z",+ }+ reference.update(overrides)+ path = Path(directory) / f"{REFERENCE_ID}.json"+ path.write_text(json.dumps(reference), encoding="utf-8")+ return path+++def parse(*argv):+ return build_parser().parse_args(["performance", *argv])+++def clock():+ return datetime(2026, 11, 2, 12, 0, 0, tzinfo=UTC)+++def request_row(sequence, lag_ms, latency_ms, status="success", retries=0):+ offset_ns = sequence * 1_000_000_000+ sent_ns = offset_ns + int(lag_ms * 1_000_000)+ return {+ "sequence": sequence,+ "level_name": "fixed-1-rps",+ "offset_s": float(sequence),+ "actual_send_offset_ns": sent_ns,+ "completed_offset_ns": sent_ns + int(latency_ms * 1_000_000),+ "scheduling_lag_ms": lag_ms,+ "status": status,+ "attempt": 1,+ "client_retry_count": retries,+ "in_flight_at_send": 0,+ }+++LEVEL_ROWS = [+ request_row(0, 1.0, 100.0),+ request_row(1, 2.0, 200.0),+ request_row(2, 0.0, 300.0),+ request_row(3, 3.0, 30000.0, status="timeout"),+ request_row(4, 0.5, 400.0),+ request_row(5, 1.0, 500.0, retries=1),+ request_row(6, 25.0, 600.0),+ request_row(7, 0.0, 10.0, status="error:RuntimeError"),+ request_row(8, 0.0, 2600.0),+ request_row(9, 4.0, 700.0),+]+++class ScheduleTest(unittest.TestCase):+ def test_offsets_are_exact_fractions_below_the_duration(self):+ for rate, count in ((0.25, 15), (1.0, 60), (10.0, 600)):+ with self.subTest(rate=rate):+ offsets = schedule_offsets(rate, 60.0)+ self.assertEqual(len(offsets), count)+ self.assertEqual(offsets, [Fraction(index) / Fraction(str(rate)) for index in range(count)])+ self.assertLess(offsets[-1], 60)+ self.assertEqual(schedule_offsets(50.0, 0.4), [Fraction(index, 50) for index in range(20)])+ self.assertEqual(schedule_offsets(3.0, 1.0), [Fraction(0), Fraction(1, 3), Fraction(2, 3)])++ def test_level_name_writes_the_decimal_point_as_a_hyphen(self):+ self.assertEqual(load_level_name(0.25), "fixed-0-25-rps")+ self.assertEqual(load_level_name(1.0), "fixed-1-rps")+ self.assertEqual(load_level_name(10.0), "fixed-10-rps")+ self.assertEqual(load_level_name(2.5), "fixed-2-5-rps")+++class RowAssignmentTest(unittest.TestCase):+ def test_encode_rows_wrap_modulo_the_dataset_length(self):+ self.assertEqual([request_rows(sequence, 1, 4) for sequence in range(6)], [[0], [1], [2], [3], [0], [1]])+ self.assertEqual(request_rows(0, 3, 5), [0, 1, 2])+ self.assertEqual(request_rows(1, 3, 5), [3, 4, 0])+ self.assertEqual(request_rows(2, 3, 5), [1, 2, 3])++ def test_payloads_follow_the_selected_list(self):+ encode = plan_performance(+ parse("--model", "m", "--task", CORPUS_KEY, "--output", "sparse", "--items-per-request", "3", "--rate", "1")+ )+ data = load_performance_data(encode, tiny_loaders())+ self.assertEqual([item["id"] for item in request_payload(encode, data, 1)], ["9", "10", "2"])+ rerank = plan_performance(parse("--model", "m", "--task", SCORE_KEY, "--rate", "1"))+ data = load_performance_data(rerank, tiny_loaders())+ self.assertEqual(request_payload(rerank, data, 0), request_payload(rerank, data, 2))+ self.assertEqual(request_payload(rerank, data, 3)[0], {"text": "tenth query"})+ with self.assertRaises(ValueError):+ request_payload(rerank, PerformanceData([], []), 0)+++class SelectionTest(unittest.TestCase):+ def test_nonempty_filter_then_string_sorted_ids_then_first_n(self):+ texts = {doc_id: doc["text"] for doc_id, doc in CORPUS.items()}+ self.assertEqual(select_ids(texts, {"filter": "nonempty", "limit": "2"}), ["10", "2"])+ self.assertEqual(select_ids(texts, {"filter": "nonempty"}), SELECTED)+ self.assertEqual(select_ids(texts, {"limit": "3"}), ["10", "100", "2"])++ def test_corpus_role_sends_title_newline_text(self):+ plan = plan_performance(+ parse("--model", "m", "--task", CORPUS_KEY, "--output", "sparse", "--items-per-request", "1", "--rate", "1")+ )+ data = load_performance_data(plan, tiny_loaders())+ self.assertEqual(data.selected_ids, SELECTED)+ self.assertEqual(+ data.payloads,+ [+ {"id": "10", "text": "Ten\nten body"},+ {"id": "2", "text": "two body"},+ {"id": "33", "text": "T\nthirty-three body"},+ {"id": "9", "text": "nine body"},+ ],+ )+ self.assertEqual(performance_text({"title": "", "text": " beta "}), " beta ")++ def test_queries_role_by_default(self):+ plan = plan_performance(+ parse(+ "--model",+ "m",+ "--task",+ "mteb/SciFact?limit=2",+ "--output",+ "sparse",+ "--items-per-request",+ "1",+ "--rate",+ "1",+ )+ )+ data = load_performance_data(plan, tiny_loaders())+ self.assertEqual(data.selected_ids, ["q1", "q10"])+ self.assertEqual(data.payloads, [{"id": "q1", "text": "first query"}, {"id": "q10", "text": "tenth query"}])++ def test_score_task_keeps_each_query_candidates_in_source_order(self):+ plan = plan_performance(parse("--model", "m", "--task", SCORE_KEY, "--rate", "1"))+ data = load_performance_data(plan, tiny_loaders())+ self.assertEqual(data.selected_ids, ["q1", "q10"])+ self.assertEqual(+ data.payloads,+ [+ ({"text": "first query"}, [{"id": "10", "text": "Ten\nten body"}, {"id": "9", "text": "nine body"}]),+ ({"text": "tenth query"}, [{"id": "9", "text": "nine body"}]),+ ],+ )+ whole = plan_performance(parse("--model", "m", "--task", "mteb/AskUbuntuDupQuestions", "--rate", "1"))+ data = load_performance_data(whole, tiny_loaders())+ self.assertEqual(data.selected_ids, ["q1", "q10", "q2"])+ self.assertEqual([doc["id"] for doc in data.payloads[0][1]], ["10", "9", "2"])++ def test_parse_task_key_keeps_every_performance_parameter(self):+ self.assertEqual(+ parse_task_key("mteb/NFCorpus?split=test&role=corpus&limit=256&filter=nonempty"),+ ("mteb/NFCorpus", {"split": "test", "role": "corpus", "limit": "256", "filter": "nonempty"}),+ )+ self.assertEqual(+ parse_task_key("mteb/AskUbuntuDupQuestions?split=test&limit=64&candidates-k=20"),+ ("mteb/AskUbuntuDupQuestions", {"split": "test", "limit": "64", "candidates-k": "20"}),+ )+++class PlanTest(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.reference = reference_file(self.temporary.name)++ def test_reference_values_are_taken_from_the_file(self):+ plan = plan_performance(parse("--reference", str(self.reference)))+ self.assertEqual(+ (plan.reference_id, plan.model, plan.profile, plan.route),+ (REFERENCE_ID, "example/sparse-encoder", "default", "example/sparse-encoder"),+ )+ self.assertEqual((plan.operation, plan.output_contract, plan.items_per_request), ("encode", "sparse", 1))+ self.assertEqual((plan.rate, plan.duration_s, plan.warmup_s), (50.0, 0.4, 0.0))+ self.assertEqual((plan.settle_s, plan.drain_s, plan.request_timeout_s), (0.0, 0.0, 5.0))+ self.assertEqual((plan.target_readiness_timeout_s, plan.max_in_flight, plan.lag_tolerance_ms), (30.0, 4, 20.0))+ self.assertEqual((plan.task_key, plan.task_name), (CORPUS_KEY, "mteb/SciFact"))+ self.assertEqual(plan.task_params, {"split": "test", "role": "corpus", "limit": "4", "filter": "nonempty"})+ self.assertEqual((plan.revision, plan.model_version, plan.endpoint), (REVISION, "0" * 40, DEFAULT_ENDPOINT))+ self.assertEqual(plan.comparable_reasons, ["client processes 1 != 4"])+ self.assertEqual(plan.level_name, "fixed-50-rps")++ def test_overrides_are_comparable_reasons(self):+ plan = plan_performance(parse("--reference", str(self.reference), "--rate", "100"))+ self.assertEqual(plan.comparable_reasons, ["rate 100 != 50", "client processes 1 != 4"])+ self.assertEqual((plan.rate, plan.level_name), (100.0, "fixed-100-rps"))+ plan = plan_performance(+ parse("--reference", str(self.reference), "--rate", "50", "--duration", "1", "--warmup", "2")+ )+ self.assertEqual(plan.comparable_reasons, ["duration 1 != 0.4", "warmup 2 != 0", "client processes 1 != 4"])+ plan = plan_performance(parse("--reference", str(self.reference), "--endpoint", "http://localhost:8080"))+ self.assertEqual(+ plan.comparable_reasons,+ [f"endpoint http://localhost:8080 != {DEFAULT_ENDPOINT}", "client processes 1 != 4"],+ )++ def test_reference_fixes_model_output_items_and_task(self):+ for flags in (+ ["--model", "x"],+ ["--output", "sparse"],+ ["--items-per-request", "4"],+ ["--task", "mteb/SciFact"],+ ):+ with self.subTest(flags=flags), self.assertRaises(ValueError):+ plan_performance(parse("--reference", str(self.reference), *flags))+ same = plan_performance(parse("--reference", str(self.reference), "--task", CORPUS_KEY))+ self.assertEqual(same.comparable_reasons, ["client processes 1 != 4"])++ def test_reference_kind_mode_and_id_are_checked(self):+ quality = reference_file(self.temporary.name, evaluation_mode="quality")+ with self.assertRaises(ValueError):+ plan_performance(parse("--reference", str(quality)))+ escaped = reference_file(self.temporary.name, reference_id="../escape")+ with self.assertRaises(ValueError):+ plan_performance(parse("--reference", str(escaped)))++ def test_timing_values_must_be_sane(self):+ for flags in (+ ["--rate", "0"],+ ["--rate", "-1"],+ ["--rate", "nan"],+ ["--rate", "inf"],+ ["--duration", "0"],+ ["--duration", "inf"],+ ["--warmup", "-1"],+ ["--warmup", "nan"],+ ["--warmup", "inf"],+ ):+ with self.subTest(flags=flags), self.assertRaises(ValueError):+ plan_performance(parse("--reference", str(self.reference), *flags))++ def test_flags_without_reference(self):+ with self.assertRaises(ValueError):+ plan_performance(+ parse("--model", "m", "--task", CORPUS_KEY, "--output", "sparse", "--items-per-request", "1")+ )+ with self.assertRaises(ValueError):+ plan_performance(parse("--model", "m", "--task", CORPUS_KEY, "--rate", "1"))+ with self.assertRaises(ValueError):+ plan_performance(parse("--model", "m", "--task", SCORE_KEY, "--output", "sparse", "--rate", "1"))+ with self.assertRaises(ValueError):+ plan_performance(parse("--model", "m", "--task", SCORE_KEY, "--items-per-request", "20", "--rate", "1"))+ encode = plan_performance(+ parse(+ "--model",+ "BAAI/bge-m3:sparse",+ "--task",+ CORPUS_KEY,+ "--output",+ "sparse",+ "--items-per-request",+ "2",+ "--rate",+ "10",+ )+ )+ self.assertEqual((encode.model, encode.profile, encode.route), ("BAAI/bge-m3", "sparse", "BAAI/bge-m3:sparse"))+ self.assertEqual((encode.operation, encode.output_contract, encode.items_per_request), ("encode", "sparse", 2))+ self.assertEqual((encode.rate, encode.duration_s, encode.warmup_s), (10.0, 60.0, 30.0))+ self.assertEqual((encode.settle_s, encode.drain_s, encode.target_readiness_timeout_s), (10.0, 10.0, 300.0))+ self.assertEqual((encode.request_timeout_s, encode.max_in_flight, encode.lag_tolerance_ms), (30.0, 64, 20.0))+ self.assertEqual(encode.comparable_reasons, ["no reference"])+ self.assertIsNone(encode.reference_id)+ self.assertEqual(encode.revision, score.HF_DATASETS["mteb/SciFact"][1])+ rerank = plan_performance(+ parse("--model", "Qwen/Qwen3-Reranker-0.6B", "--task", SCORE_KEY, "--rate", "0.25", "--warmup", "0")+ )+ self.assertEqual(+ (rerank.operation, rerank.output_contract, rerank.items_per_request), ("score", "scores", None)+ )+ self.assertEqual((rerank.request_timeout_s, rerank.max_in_flight, rerank.warmup_s), (300.0, 128, 0.0))+ self.assertEqual(rerank.level_name, "fixed-0-25-rps")++ def test_key_parameters_are_checked(self):+ for key in (+ "mteb/SciFact?split=train&role=corpus",+ "mteb/SciFact?role=documents",+ "mteb/SciFact?filter=all",+ "mteb/SciFact?limit=0",+ "mteb/AskUbuntuDupQuestions?candidates-k=0",+ "mteb/AskUbuntuDupQuestions?role=corpus",+ ):+ flags = [] if key.startswith("mteb/AskUbuntu") else ["--output", "sparse", "--items-per-request", "1"]+ with self.subTest(key=key), self.assertRaises(ValueError):+ plan_performance(parse("--model", "m", "--task", key, "--rate", "1", *flags))+++class AggregationTest(unittest.TestCase):+ def test_every_metric_of_a_hand_built_level(self):+ metrics = performance_metrics(LEVEL_ROWS, 1.0, 10.0)+ self.assertEqual(+ metrics,+ {+ "offered_requests_per_second": 1.0,+ "achieved_requests_per_second": 0.7,+ "eventual_achieved_requests_per_second": 0.8,+ "in_window_success_rate": 0.7,+ "in_window_retry_free_success_rate": 0.6,+ "success_rate": 0.8,+ "retry_free_success_rate": 0.7,+ "scheduling_lag_p99_ms": 25.0,+ "latency_p50_ms": 400.0,+ "latency_p95_ms": 2600.0,+ "latency_p99_ms": 2600.0,+ },+ )+ rows = performance_metric_rows(metrics)+ self.assertEqual([row["name"] for row in rows], list(PERFORMANCE_METRICS))+ self.assertEqual(+ rows[1],+ {+ "name": "achieved_requests_per_second",+ "unit": "requests_per_second",+ "aggregation": "common_window",+ "value": 0.7,+ },+ )+ self.assertEqual(rows[-1]["aggregation"], "p99")+ lines = score.format_rows(rows, [])+ self.assertEqual(lines[2], "eventual_achieved_requests_per_second 0.80000")++ def test_nearest_rank_percentiles(self):+ fifteen = list(range(1, 16))+ self.assertEqual((nearest_rank(fifteen, 50), nearest_rank(fifteen, 95), nearest_rank(fifteen, 99)), (8, 15, 15))+ hundred = list(range(100, 0, -1))+ self.assertEqual(+ (nearest_rank(hundred, 50), nearest_rank(hundred, 95), nearest_rank(hundred, 99)), (50, 95, 99)+ )+ self.assertEqual(nearest_rank([7.0], 99), 7.0)+ with self.assertRaises(ValueError):+ nearest_rank([], 50)++ def test_no_success_leaves_the_latency_metrics_out(self):+ rows = [request_row(sequence, 0.0, 100.0, status="timeout") for sequence in range(3)]+ metrics = performance_metrics(rows, 1.0, 3.0)+ self.assertEqual(metrics["success_rate"], 0.0)+ self.assertEqual(metrics["achieved_requests_per_second"], 0.0)+ self.assertNotIn("latency_p50_ms", metrics)+ self.assertEqual(len(performance_metric_rows(metrics)), 8)+ with self.assertRaises(ValueError):+ performance_metrics([], 1.0, 3.0)++ def test_request_status_classification(self):+ self.assertEqual(request_status(timeout_error()), "timeout")+ self.assertEqual(request_status(httpx.ConnectTimeout("slow")), "timeout")+ self.assertEqual(request_status(SIEConnectionError("refused")), "error:SIEConnectionError")+ self.assertEqual(request_status(ServerError("boom", status_code=503)), "error:ServerError")+ self.assertEqual(request_status(KeyError("scores")), "error:KeyError")+++class ValidityTest(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.plan = plan_performance(parse("--reference", str(reference_file(self.temporary.name))))++ def dispatcher(self):+ return Dispatcher(self.plan, PerformanceData([], []), None)++ def test_clean_run_is_valid(self):+ validity = performance_validity(self.plan, self.dispatcher(), {"scheduling_lag_p99_ms": 20.0})+ self.assertEqual(+ validity,+ {"valid": True, "reasons": [], "lag_max_ms": 0.0, "in_flight_peak": 0, "timeouts": 0, "sdk_retries": 0},+ )++ def test_each_rule_names_its_reason(self):+ dispatcher = self.dispatcher()+ dispatcher.log.sdk_retries = 2+ self.assertEqual(performance_validity(self.plan, dispatcher, {})["reasons"], ["sdk retries 2"])+ validity = performance_validity(self.plan, self.dispatcher(), {"scheduling_lag_p99_ms": 20.5})+ self.assertEqual(validity["reasons"], ["scheduling lag p99 20.500 ms > 20 ms"])+ dispatcher = self.dispatcher()+ dispatcher.in_flight_peak = 5+ self.assertEqual(performance_validity(self.plan, dispatcher, {})["reasons"], ["in-flight peak 5 > 4"])+ dispatcher = self.dispatcher()+ dispatcher.readiness_failure = "ProvisioningError: no capacity"+ self.assertEqual(+ performance_validity(self.plan, dispatcher, {})["reasons"],+ ["readiness request failed: ProvisioningError: no capacity"],+ )+ dispatcher = self.dispatcher()+ dispatcher.log.execution_revisions = ["rev-a", "rev-b"]+ self.assertEqual(performance_validity(self.plan, dispatcher, {})["reasons"], ["execution revision changed"])++ def test_counts_come_from_the_rows(self):+ dispatcher = self.dispatcher()+ dispatcher.rows = [request_row(0, 1.5, 10.0), request_row(1, 0.0, 10.0, status="timeout")]+ validity = performance_validity(self.plan, dispatcher, {"scheduling_lag_p99_ms": 1.5})+ self.assertEqual((validity["valid"], validity["lag_max_ms"], validity["timeouts"]), (True, 1.5, 1))+++class RunTest(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.results = Path(self.temporary.name) / "results"+ self.reference = reference_file(self.temporary.name)++ def run_reference(self, client, *flags, reference=None):+ plan = plan_performance(parse("--reference", str(reference or self.reference), *flags))+ data = load_performance_data(plan, tiny_loaders())+ return run_performance(plan, data, client, results_dir=self.results, now=clock)++ def test_timed_fixed_rate_run(self):+ client = FakeClient()+ record, result_path = self.run_reference(client)+ self.assertEqual(result_path, self.results / f"{REFERENCE_ID}-20261102T120000Z.json")+ self.assertEqual(json.loads(result_path.read_text(encoding="utf-8")), record)+ readiness, *scheduled = client.calls+ self.assertEqual(len(scheduled), 20)+ self.assertEqual(readiness[0], "encode")+ self.assertEqual([item["id"] for item in readiness[2]], ["10"])+ self.assertTrue(readiness[3]["wait_for_capacity"])+ self.assertEqual(readiness[3]["provision_timeout_s"], 30.0)+ for kind, model, items, kwargs in scheduled:+ self.assertEqual((kind, model, len(items)), ("encode", "example/sparse-encoder", 1))+ self.assertEqual(kwargs["output_types"], ["sparse"])+ self.assertFalse(kwargs["is_query"])+ self.assertFalse(kwargs["wait_for_capacity"])+ self.assertEqual(kwargs["provision_timeout_s"], 5.0)+ self.assertEqual(kwargs["max_oom_retries"], 0)+ self.assertNotIn("instruction", kwargs)+ self.assertEqual(+ Counter(items[0]["id"] for _, _, items, _ in scheduled), Counter({"10": 5, "2": 5, "33": 5, "9": 5})+ )+ self.assertEqual(+ {items[0]["text"] for _, _, items, _ in scheduled if items[0]["id"] == "10"}, {"Ten\nten body"}+ )+ requests_path = Path(record["run"]["requests_path"])+ self.assertEqual(requests_path, self.results / f"{REFERENCE_ID}-20261102T120000Z.requests.jsonl")+ rows = score.read_jsonl(requests_path)+ self.assertEqual([row["sequence"] for row in rows], list(range(20)))+ for row in rows:+ self.assertEqual(row["offset_s"], row["sequence"] / 50)+ self.assertEqual(row["level_name"], "fixed-50-rps")+ self.assertEqual(row["status"], "success")+ self.assertEqual((row["attempt"], row["client_retry_count"]), (1, 0))+ self.assertLessEqual(row["sequence"] * 20_000_000, row["actual_send_offset_ns"])+ self.assertLessEqual(row["actual_send_offset_ns"], row["completed_offset_ns"])+ self.assertGreaterEqual(row["scheduling_lag_ms"], 0.0)+ self.assertGreaterEqual(row["in_flight_at_send"], 0)+ self.assertEqual(+ list(row),+ [+ "sequence",+ "level_name",+ "offset_s",+ "actual_send_offset_ns",+ "completed_offset_ns",+ "scheduling_lag_ms",+ "status",+ "attempt",+ "client_retry_count",+ "in_flight_at_send",+ ],+ )+ self.assertEqual(set(record), RESULT_KEYS)+ self.assertEqual((record["kind"], record["schema_version"]), ("published-benchmark-reproduction", 1))+ self.assertEqual(record["evaluation_mode"], "isolated_performance")+ self.assertFalse(record["comparable"])+ self.assertEqual(record["comparable_reasons"], ["client processes 1 != 4"])+ self.assertEqual(record["comparison_basis"], "same method, different parameters: client processes 1 != 4")+ self.assertEqual(record["execution_revisions"], ["rev-a"])+ self.assertEqual(record["dataset"]["selected_ids"], SELECTED)+ self.assertEqual(+ record["dataset"]["parameters"],+ [+ {"name": "split", "value": "test"},+ {"name": "role", "value": "corpus"},+ {"name": "limit", "value": "4"},+ {"name": "filter", "value": "nonempty"},+ ],+ )+ self.assertEqual(+ record["payload"],+ {"items_per_request": 1, "output_contract": "sparse", "parameters": [{"name": "is_query", "value": False}]},+ )+ self.assertEqual(record["load_level_name"], "fixed-50-rps")+ self.assertEqual(+ record["schedule"],+ {"arrival": "deterministic", "levels": [{"name": "fixed-50-rps", "rate": 50.0, "duration_s": 0.4}]},+ )+ self.assertEqual(record["timing"]["max_in_flight_per_process"], 4)+ self.assertEqual(record["timing"]["retry"], {"backoff": "none", "max_attempts": 1, "record_attempts": True})+ self.assertEqual((record["run"]["request_count"], record["run"]["failure_count"]), (20, 0))+ self.assertEqual(record["run"]["started_at"], "2026-11-02T12:00:00Z")+ self.assertEqual(+ list(record["validity"]), ["valid", "reasons", "lag_max_ms", "in_flight_peak", "timeouts", "sdk_retries"]+ )+ self.assertEqual((record["validity"]["timeouts"], record["validity"]["sdk_retries"]), (0, 0))+ self.assertGreaterEqual(record["validity"]["in_flight_peak"], 1)+ self.assertLessEqual(record["validity"]["in_flight_peak"], 4)+ metrics = {row["name"]: row["value"] for row in record["metrics"]}+ self.assertEqual(set(metrics), set(PERFORMANCE_METRICS))+ self.assertEqual(metrics["offered_requests_per_second"], 50.0)+ self.assertEqual(metrics["success_rate"], 1.0)+ self.assertEqual(metrics["eventual_achieved_requests_per_second"], 50.0)+ self.assertGreaterEqual(metrics["latency_p50_ms"], 5.0)+ self.assertEqual(+ [row["name"] for row in record["comparison"]],+ ["offered_requests_per_second", "success_rate", "latency_p50_ms"],+ )+ self.assertEqual(record["comparison"][0]["delta"], 0.0)+ self.assertNotIn("scorer", record)++ def test_requests_file_re_aggregates_to_the_same_metrics(self):+ record, result_path = self.run_reference(FakeClient())+ again, rows, comparison = score.rescore(result_path)+ self.assertEqual(again, record)+ self.assertEqual(rows, record["metrics"])+ self.assertEqual(comparison, record["comparison"])+ output = io.StringIO()+ with contextlib.redirect_stdout(output):+ score.main([str(result_path), "--write"])+ self.assertEqual(output.getvalue().splitlines(), score.format_rows(rows, comparison))+ self.assertEqual(json.loads(result_path.read_text(encoding="utf-8")), record)++ def test_timeouts_and_errors_lower_the_success_rates(self):+ failures = {"2": timeout_error(), "33": ServerError("boom", status_code=503), "9": RuntimeError("malformed")}+ record, result_path = self.run_reference(FakeClient(failures=failures))+ rows = score.read_jsonl(Path(record["run"]["requests_path"]))+ expected = {1: "timeout", 2: "error:ServerError", 3: "error:RuntimeError"}+ self.assertEqual(+ [row["status"] for row in rows], [expected.get(row["sequence"] % 4, "success") for row in rows]+ )+ self.assertEqual((record["run"]["request_count"], record["run"]["failure_count"]), (20, 15))+ self.assertEqual(record["validity"]["timeouts"], 5)+ metrics = {row["name"]: row["value"] for row in record["metrics"]}+ self.assertEqual((metrics["success_rate"], metrics["eventual_achieved_requests_per_second"]), (0.25, 12.5))+ self.assertEqual([r for r in record["validity"]["reasons"] if not r.startswith("scheduling lag")], [])+ self.assertEqual(score.rescore(result_path)[1], record["metrics"])++ def test_sdk_retries_invalidate_and_lower_the_retry_free_rates(self):+ record, _ = self.run_reference(FakeClient(retries={"9": 1}))+ rows = score.read_jsonl(Path(record["run"]["requests_path"]))+ self.assertEqual(+ [row["client_retry_count"] for row in rows], [1 if row["sequence"] % 4 == 3 else 0 for row in rows]+ )+ self.assertEqual(record["validity"]["sdk_retries"], 5)+ self.assertIn("sdk retries 5", record["validity"]["reasons"])+ self.assertFalse(record["validity"]["valid"])+ metrics = {row["name"]: row["value"] for row in record["metrics"]}+ self.assertEqual((metrics["success_rate"], metrics["retry_free_success_rate"]), (1.0, 0.75))+ self.assertLessEqual(metrics["in_window_retry_free_success_rate"], 0.75)++ def test_execution_revision_change_is_not_comparable_and_not_valid(self):+ record, _ = self.run_reference(FakeClient(revisions=("rev-a", "rev-b")))+ self.assertEqual(set(record["execution_revisions"]), {"rev-a", "rev-b"})+ self.assertEqual(record["comparable_reasons"], ["client processes 1 != 4", "execution revision changed"])+ self.assertIn("execution revision changed", record["validity"]["reasons"])+ self.assertFalse(record["validity"]["valid"])++ def test_readiness_failure_writes_the_result_and_sends_nothing_else(self):+ client = FakeClient(ready=False)+ record, result_path = self.run_reference(client)+ self.assertTrue(result_path.exists())+ self.assertEqual(len(client.calls), 1)+ self.assertIsNone(record["run"]["requests_path"])+ self.assertEqual((record["run"]["request_count"], record["run"]["failure_count"]), (0, 0))+ self.assertEqual((record["metrics"], record["comparison"]), ([], []))+ self.assertEqual(+ record["validity"],+ {+ "valid": False,+ "reasons": ["readiness request failed: ProvisioningError: no capacity"],+ "lag_max_ms": 0.0,+ "in_flight_peak": 0,+ "timeouts": 0,+ "sdk_retries": 0,+ },+ )+ with self.assertRaises(ValueError):+ score.rescore(result_path)+ client = FakeClient(failures={"10": RuntimeError("malformed")})+ record, _ = self.run_reference(client)+ self.assertEqual(len(client.calls), 1)+ self.assertEqual(record["validity"]["reasons"], ["readiness request failed: RuntimeError: malformed"])++ def test_warmup_is_a_closed_loop_on_row_zero_that_is_not_recorded(self):+ client = FakeClient()+ record, _ = self.run_reference(client, "--warmup", "0.05")+ self.assertEqual(record["comparable_reasons"], ["warmup 0.05 != 0", "client processes 1 != 4"])+ self.assertEqual(record["timing"]["warmup_s"], 0.05)+ warm = client.calls[1 : len(client.calls) - 20]+ self.assertGreaterEqual(len(warm), 2)+ self.assertEqual({items[0]["id"] for _, _, items, _ in warm}, {"10"})+ self.assertEqual({kwargs["wait_for_capacity"] for _, _, _, kwargs in warm}, {False})+ self.assertEqual(record["run"]["request_count"], 20)++ def test_the_pool_bounds_in_flight_requests_and_the_lag_gate_binds(self):+ reference = Path(self.temporary.name) / "bounded.json"+ payload = json.loads(self.reference.read_text(encoding="utf-8"))+ payload["schedule"]["levels"] = [{"name": "fixed-100-rps", "rate": 100.0, "duration_s": 0.1}]+ payload["timing"]["max_in_flight_per_process"] = 2+ reference.write_text(json.dumps(payload), encoding="utf-8")+ record, _ = self.run_reference(FakeClient(delay_s=0.05), reference=reference)+ rows = score.read_jsonl(Path(record["run"]["requests_path"]))+ self.assertEqual(len(rows), 10)+ self.assertEqual(record["validity"]["in_flight_peak"], 2)+ self.assertLessEqual(max(row["in_flight_at_send"] for row in rows), 1)+ self.assertFalse(record["validity"]["valid"])+ self.assertTrue(record["validity"]["reasons"][0].startswith("scheduling lag p99 "))+ self.assertTrue(record["validity"]["reasons"][0].endswith(" ms > 20 ms"))+ metrics = {row["name"]: row["value"] for row in record["metrics"]}+ self.assertGreater(metrics["scheduling_lag_p99_ms"], 20.0)+ self.assertEqual(metrics["success_rate"], 1.0)+ self.assertLess(metrics["achieved_requests_per_second"], metrics["eventual_achieved_requests_per_second"])++ def test_score_run_sends_one_query_with_its_candidates(self):+ payload = json.loads(self.reference.read_text(encoding="utf-8"))+ payload.update(+ {+ "model": "Qwen/Qwen3-Reranker-0.6B",+ "operation": "score",+ "task_key": SCORE_KEY,+ "dataset": {+ "name": "mteb/AskUbuntuDupQuestions",+ "revision": REVISION,+ "subset": "test",+ "parameters": [],+ },+ "payload": {"items_per_request": 2, "output_contract": "scores", "parameters": []},+ "client": {"worker_count": 1, "processes_per_worker": 2},+ }+ )+ reference = Path(self.temporary.name) / "score.json"+ reference.write_text(json.dumps(payload), encoding="utf-8")+ client = FakeClient()+ record, _ = self.run_reference(client, reference=reference)+ readiness, *scheduled = client.calls+ self.assertEqual(+ readiness[2],+ ({"text": "first query"}, [{"id": "10", "text": "Ten\nten body"}, {"id": "9", "text": "nine body"}]),+ )+ self.assertEqual(+ Counter(query["text"] for _, _, (query, _), _ in scheduled), Counter({"first query": 10, "tenth query": 10})+ )+ for kind, model, _, kwargs in scheduled:+ self.assertEqual((kind, model), ("score", "Qwen/Qwen3-Reranker-0.6B"))+ self.assertFalse(kwargs["wait_for_capacity"])+ self.assertEqual((kwargs["provision_timeout_s"], kwargs["max_oom_retries"]), (5.0, 0))+ self.assertNotIn("output_types", kwargs)+ self.assertEqual(record["operation"], "score")+ self.assertEqual(record["payload"], {"items_per_request": 2, "output_contract": "scores", "parameters": []})+ self.assertEqual(record["dataset"]["selected_ids"], ["q1", "q10"])+ self.assertEqual(record["comparable_reasons"], ["client processes 1 != 2"])+++class CommandTest(unittest.TestCase):+ def test_a_reference_run_without_a_key_fails_before_any_call(self):+ with tempfile.TemporaryDirectory() as temporary:+ reference = reference_file(temporary)+ with (+ patch.dict("os.environ", {}, clear=True),+ patch.object(run, "load_performance_data") as loader,+ patch.object(run, "SIEClient") as client,+ contextlib.redirect_stderr(io.StringIO()),+ self.assertRaises(SystemExit) as caught,+ ):+ run.main(["performance", "--reference", str(reference)])+ self.assertEqual(caught.exception.code, 2)+ loader.assert_not_called()+ client.assert_not_called()+++if __name__ == "__main__":+ unittest.main()