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): run the published-benchmarks example against your own server (#889)
Shai Shmuel991540b0bfc7
diff --git a/examples/evaluations/published-benchmarks/README.md b/examples/evaluations/published-benchmarks/README.mdindex e1b24b016..71cdfa714 100644--- a/examples/evaluations/published-benchmarks/README.md+++ b/examples/evaluations/published-benchmarks/README.md@@ -27,7 +27,10 @@ never a verdict: no threshold, no pass, no fail.### Run it-Install the locked dependencies, then set the key the endpoint requires:+Install the locked dependencies, then set the key. The default endpoint+requires it; the key is sent only to the endpoint it is scoped to, so against+your own server see+[Run it against your own server](#run-it-against-your-own-server):```shuv sync --frozen@@ -59,6 +62,8 @@ required; `--output sparse|multivector` and `--items-per-request` are requiredfor the encode tasks and refused for `mteb/AskUbuntuDupQuestions`, which scoreseach query against its 20 task-native candidates.+When a result is not valid, the command prints each reason to stderr.+A completed run writes two files under `results/`, which git ignores; a runwith a failed request writes the result record alone and names the failurein `validity.reasons`:@@ -92,7 +97,11 @@ the example applies them to every run:- the whole `test` split of the pinned dataset revision; queries with norelevance judgement are dropped, as MTEB does;-- requests are sequential, one in flight, with no warmup;+- one readiness request on the first batch, not recorded, waits up to 300 s+ for the model to load; a failure writes `valid: false` with the reason and+ exits 1;+- requests are sequential, one in flight, with no warmup beyond that+ readiness request;- documents are encoded with `is_query=False` in batches of the reference'sitems per request, queries with `is_query=True`, and no instruction is sent;- sparse vectors are scored by the raw dot product, multivector outputs by@@ -121,11 +130,13 @@ sets `comparable: false` with the reason listed, and `comparison_basis` readsA run without a reference is also `comparable: false` and has no comparison:`comparison` is empty and `comparison_basis` is null.-Every response names the revision of the executed model bundle and-configuration. The run collects every distinct value into+Every response from the default endpoint names the revision of the executed+model bundle and configuration. The run collects every distinct value into`execution_revisions`; it is recorded, never compared with the reference'scheckpoint revision, and a change mid-run sets `comparable: false` with the-reason `execution revision changed`.+reason `execution revision changed`. A self-hosted sie-server reached+directly sends no revision, so `execution_revisions` stays empty and that+check cannot fire there.A delta is a number, not a result. The maintainers read a quality deltaagainst a 2% band when they decide whether a published number still holds;@@ -155,25 +166,30 @@ 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.+A run against the default endpoint needs `SIE_API_KEY` and spends credits;+against your own server the key is sent only when `SIE_BASE_URL` names that+server (see [Run it against your own server](#run-it-against-your-own-server)).+A run 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. When a result is+not valid, the command prints each reason to stderr. 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 sprovisioning 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;+ closed-loop warmup on that row (`--warmup 0` skips the closed-loop warmup;+ the readiness request and the 10 s settle still run, so it is not a cold+ start) and 10 s of idle settle;- deterministic arrivals: request `i` is due at `i / rate` seconds while thatis below the duration; a scheduler thread sleeps until each offset and handsthe request to a pool of `max_in_flight_per_process` threads, and when all@@ -255,6 +271,67 @@ invocation, the record's first level unless `--rate` is given, andwith the decimal point written as a hyphen. A change of execution revisionmid-run sets `comparable: false` and `valid: false`.+## Run it against your own server++Both commands run against the open-source sie-server as well. Start it with+the reference's model, here the Splade NFCorpus references:++```sh+pip install "sie-server[local]"+sie-server serve --host 127.0.0.1 -m prithivida/Splade_PP_en_v2+```++By default the server runs without a token, and `--host 127.0.0.1` keeps it+on this machine: leave `SIE_API_KEY` unset. A key in your shell is scoped to+the endpoint `SIE_BASE_URL` names, or to the default endpoint when it is+unset, which is the SDK's rule, so a key for the default endpoint is never+sent to your own server; the command says so on stderr when it holds one+back. With `SIE_AUTH_MODE=token` the server generates a token, saves it to a+file and prints where; export that value in `SIE_API_KEY` together with+`SIE_BASE_URL=http://localhost:8080`.++Then pass `--endpoint http://localhost:8080`. A quality smoke run:++```sh+uv run python run.py quality \+ --reference references/prod-web-fw-20260905-splade-nfcorpus-quality-02.json \+ --task "mteb/NFCorpus?limit=20" \+ --endpoint http://localhost:8080+```++A short performance run:++```sh+uv run python run.py performance \+ --reference references/prod-web-fw-20260905-splade-nfcorpus-perf-01.json \+ --rate 1 --duration 20 \+ --endpoint http://localhost:8080+```++What to expect:++- the first request loads the model; the readiness request waits for it up+ to 300 s, so a cold run is valid. A first download and load that takes+ longer than that fails the readiness request, the run says so and exits 1;+ send one request by hand, or run again once the server has loaded the model;+- every result is `comparable: false` with the reason+ `endpoint http://localhost:8080 != https://api.superlinked.com`, listed+ beside any other reason;+- a full quality run (the reference's task key, no `?limit`) against the+ same pinned model revision should land in the same band as the published+ numbers, within numeric precision;+- the smoke run above scores 20 queries, so its metrics are a check that the+ path works, not a comparison with the record;+- performance numbers describe your hardware and your network path and are+ not comparable with the record;+- `execution_revisions` stays empty, because a sie-server reached directly+ sends no revision header;+- `score.py` works the same on these results.++On an Apple Silicon laptop with the Splade NFCorpus quality smoke, the server+was ready in about half a minute, the cold model load took about 80 s, and a+20-query smoke took about 30 s once warm.+## Validation`validation/` holds the example's own output from 2026-11-03: three@@ -266,8 +343,9 @@ not evidence of record, and no value in the tables below is a pass thresholdor quality floor. The delta range is the smallest to the largest `delta` thethree result files carry (observed minus published); the spread is thelargest minus the smallest of the three observed values, computed before-rounding. Quality keeps the tool's five decimals; milliseconds and rates are-rounded to three here.+rounding. Quality keeps the tool's five decimals for ndcg, map, recall and+precision; mrr, which the tool and the record keep at full precision, is+rounded to five here. Milliseconds and rates are rounded to three here.### `prod-web-fw-20260905-splade-nfcorpus-quality-02`diff --git a/examples/evaluations/published-benchmarks/run.py b/examples/evaluations/published-benchmarks/run.pyindex 21f1c847e..385fab367 100644--- a/examples/evaluations/published-benchmarks/run.py+++ b/examples/evaluations/published-benchmarks/run.py@@ -7,6 +7,7 @@ import mathimport osimport platformimport re+import sysimport threadingimport timefrom collections.abc import Callable, Mapping, Sequence@@ -16,6 +17,7 @@ from datetime import UTC, datetimefrom fractions import Fractionfrom pathlib import Pathfrom typing import Any+from urllib.parse import urlsplitimport httpximport numpy as np@@ -166,6 +168,7 @@ class CallLog:sdk_retries: int = 0execution_revisions: list[str] = field(default_factory=list)failure: str | None = None+ readiness_failure: str | None = Nonedef record(self, client: Any) -> None:self.request_count += 1@@ -210,8 +213,64 @@ def plan_quality(args: argparse.Namespace) -> QualityPlan:return _plan_from_flags(args)+def _endpoint_key(url: str) -> tuple[str, str | None, int, str]:+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ try:+ port = parts.port+ except ValueError:+ raise ValueError("endpoint must be an http(s) URL") from None+ if port is None:+ port = 443 if scheme == "https" else 80+ elif port == 0:+ raise ValueError("endpoint must be an http(s) URL")+ return scheme, parts.hostname, port, parts.path.rstrip("/")+++def normalize_endpoint(url: str) -> str:+ scheme, hostname, port, path = _endpoint_key(url)+ if scheme not in {"http", "https"} or hostname is None:+ raise ValueError("endpoint must be an http(s) URL")+ default_port = 443 if scheme == "https" else 80+ host = f"[{hostname}]" if ":" in hostname else hostname+ suffix = "" if port == default_port else f":{port}"+ return f"{scheme}://{host}{suffix}{path}"+++def _key_scope() -> tuple[str, str]:+ key = os.environ.get("SIE_API_KEY", "").strip()+ scope = os.environ.get("SIE_BASE_URL", "").strip() or DEFAULT_ENDPOINT+ return key, scope+++def api_key_for(endpoint: str) -> str:+ """Return SIE_API_KEY only for the origin it is scoped to, as the SDK does; the path plays no part."""+ key, scope = _key_scope()+ try:+ scope = normalize_endpoint(scope)+ except ValueError:+ return ""+ return key if key and _endpoint_key(scope)[:3] == _endpoint_key(endpoint)[:3] else ""+++def _resolve_api_key(parser: argparse.ArgumentParser, endpoint: str) -> str:+ api_key = api_key_for(endpoint)+ if not api_key and endpoint == DEFAULT_ENDPOINT:+ parser.error(f"SIE_API_KEY must be set in the environment for {DEFAULT_ENDPOINT}")+ key, scope = _key_scope()+ if key and not api_key:+ print(+ f"note: SIE_API_KEY is scoped to {scope} and was not sent to {endpoint}; "+ "set SIE_BASE_URL to the endpoint to send it",+ file=sys.stderr,+ )+ return api_key++def _endpoint_reasons(endpoint: str) -> list[str]:- return [] if endpoint == DEFAULT_ENDPOINT else [f"endpoint {endpoint} != {DEFAULT_ENDPOINT}"]+ if _endpoint_key(endpoint) == _endpoint_key(DEFAULT_ENDPOINT):+ return []+ return [f"endpoint {endpoint} != {DEFAULT_ENDPOINT}"]def _check_limit(params: Mapping[str, str]) -> None:@@ -315,7 +374,7 @@ def _plan_from_reference(args: argparse.Namespace, reference: Mapping[str, Any])output_contract=reference["payload"]["output_contract"],items_per_request=reference["payload"]["items_per_request"],request_timeout_s=float(reference["timing"]["request_timeout_s"]),- endpoint=args.endpoint,+ endpoint=normalize_endpoint(args.endpoint),model_version=reference["model_version"],comparable_reasons=reasons,)@@ -346,7 +405,7 @@ def _plan_from_flags(args: argparse.Namespace) -> QualityPlan:output_contract=args.output if operation == "encode" else "scores",items_per_request=args.items_per_request,request_timeout_s=DEFAULT_TIMEOUT_S,- endpoint=args.endpoint,+ endpoint=normalize_endpoint(args.endpoint),model_version=None,comparable_reasons=reasons,)@@ -402,7 +461,7 @@ def _performance_plan_from_reference(args: argparse.Namespace, reference: Mappin),max_in_flight=int(timing["max_in_flight_per_process"]),lag_tolerance_ms=float(timing["scheduling_lag_tolerance_ms"]),- endpoint=args.endpoint,+ endpoint=normalize_endpoint(args.endpoint),model_version=reference["model_version"],comparable_reasons=reasons,)@@ -443,7 +502,7 @@ def _performance_plan_from_flags(args: argparse.Namespace) -> PerformancePlan:target_readiness_timeout_s=DEFAULT_READINESS_TIMEOUT_S,max_in_flight=max_in_flight,lag_tolerance_ms=DEFAULT_LAG_TOLERANCE_MS,- endpoint=args.endpoint,+ endpoint=normalize_endpoint(args.endpoint),model_version=None,comparable_reasons=["no reference", *_endpoint_reasons(args.endpoint)],)@@ -651,6 +710,33 @@ def warmup(client: Any, plan: PerformancePlan, data: PerformanceData) -> None:performance_call(client, plan, payload, wait_for_capacity=False, provision_timeout_s=plan.request_timeout_s)+def quality_readiness_request(client: Any, plan: QualityPlan, data: QualityData) -> None:+ if plan.operation == "score":+ query_id, text = next(iter(data.queries.items()))+ items = [+ {"id": doc_id, "text": document_text(data.corpus[doc_id])} for doc_id in (data.top_ranked or {})[query_id]+ ]+ client.score(+ plan.route,+ {"text": text},+ items,+ wait_for_capacity=True,+ provision_timeout_s=DEFAULT_READINESS_TIMEOUT_S,+ max_oom_retries=0,+ )+ return+ document_ids = list(data.corpus)[: plan.items_per_request]+ client.encode(+ plan.route,+ [{"id": doc_id, "text": document_text(data.corpus[doc_id])} for doc_id in document_ids],+ output_types=[plan.output_contract],+ is_query=False,+ wait_for_capacity=True,+ provision_timeout_s=DEFAULT_READINESS_TIMEOUT_S,+ max_oom_retries=0,+ )++def _call(log: CallLog, client: Any, method: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:try:result = method(*args, **kwargs)@@ -836,7 +922,11 @@ def build_record(if len(log.execution_revisions) > 1:reasons.append("execution revision changed")comparable = not reasons- validity_reasons = [f"sdk retries {log.sdk_retries}"] if log.sdk_retries else []+ validity_reasons: list[str] = []+ if log.readiness_failure is not None:+ validity_reasons.append(f"readiness request failed: {log.readiness_failure}")+ if log.sdk_retries:+ validity_reasons.append(f"sdk retries {log.sdk_retries}")if log.failure is not None:validity_reasons.append(f"request failed: {log.failure}")candidate_counts = [len(candidates) for candidates in (data.top_ranked or {}).values()]@@ -991,11 +1081,18 @@ def run_quality(log = CallLog()predictions: PredictionMap | None = Nonetry:- if plan.operation == "score":- predictions = rerank_predictions(client, plan, data, log)- else:- predictions = encode_predictions(client, plan, data, log)- except RequestFailed:+ try:+ quality_readiness_request(client, plan, data)+ except Exception as exc: # noqa: BLE001+ log.readiness_failure = f"{type(exc).__name__}: {exc}"+ if log.readiness_failure is None:+ if plan.operation == "score":+ predictions = rerank_predictions(client, plan, data, log)+ else:+ predictions = encode_predictions(client, plan, data, log)+ except (RequestFailed, ValueError, KeyError, TypeError) as exc:+ if not isinstance(exc, RequestFailed):+ log.failure = f"{type(exc).__name__}: {exc}"predictions = Nonefinished = clock()stem = f"{plan.reference_id or _slug(plan.route, plan.task_key)}-{started.strftime('%Y%m%dT%H%M%SZ')}"@@ -1046,32 +1143,39 @@ def run_performance(return record, result_path+def report_invalid(record: Mapping[str, Any]) -> None:+ if not record["validity"]["valid"]:+ for reason in record["validity"]["reasons"]:+ print(f"invalid: {reason}", file=sys.stderr)++def quality_command(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:try:plan = plan_quality(args)- except (ValueError, KeyError, OSError) as exc:+ except KeyError as exc:+ parser.error(f"reference {args.reference} is missing key {exc}")+ except (ValueError, 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")+ api_key = _resolve_api_key(parser, plan.endpoint)data = load_quality_data(plan)with SIEClient(plan.endpoint, api_key=api_key, timeout_s=plan.request_timeout_s) as client:record, result_path = run_quality(plan, data, client)print(result_path)for line in format_rows(record["metrics"], record["comparison"]):print(line)- if record["run"]["failure_count"]:+ report_invalid(record)+ if record["run"]["predictions_path"] is None:raise SystemExit(1)def performance_command(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:try:plan = plan_performance(args)- except (ValueError, KeyError, OSError) as exc:+ except KeyError as exc:+ parser.error(f"reference {args.reference} is missing key {exc}")+ except (ValueError, 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")+ api_key = _resolve_api_key(parser, plan.endpoint)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@@ -1080,6 +1184,7 @@ def performance_command(parser: argparse.ArgumentParser, args: argparse.Namespacprint(result_path)for line in format_rows(record["metrics"], record["comparison"]):print(line)+ report_invalid(record)if record["run"]["requests_path"] is None:raise SystemExit(1)diff --git a/examples/evaluations/published-benchmarks/tests/test_performance.py b/examples/evaluations/published-benchmarks/tests/test_performance.pyindex a05bf5dec..ad7e59caf 100644--- a/examples/evaluations/published-benchmarks/tests/test_performance.py+++ b/examples/evaluations/published-benchmarks/tests/test_performance.py@@ -375,6 +375,33 @@ class PlanTest(unittest.TestCase):self.assertEqual(plan.comparable_reasons, ["client processes 1 != 4"])self.assertEqual(plan.level_name, "fixed-50-rps")+ def test_endpoint_is_normalised_before_it_is_compared(self):+ same = plan_performance(parse("--reference", str(self.reference), "--endpoint", "HTTPS://API.superlinked.com/"))+ self.assertEqual((same.endpoint, same.comparable_reasons), (DEFAULT_ENDPOINT, ["client processes 1 != 4"]))+ local = plan_performance(parse("--reference", str(self.reference), "--endpoint", "http://localhost:8080/"))+ self.assertEqual(local.endpoint, "http://localhost:8080")+ self.assertEqual(+ local.comparable_reasons,+ [f"endpoint http://localhost:8080/ != {DEFAULT_ENDPOINT}", "client processes 1 != 4"],+ )+ with self.assertRaises(ValueError):+ plan_performance(parse("--reference", str(self.reference), "--endpoint", "localhost:8080"))++ def test_default_ports_are_normalised_away(self):+ same = plan_performance(+ parse("--reference", str(self.reference), "--endpoint", "https://api.superlinked.com:443/")+ )+ self.assertEqual((same.endpoint, same.comparable_reasons), (DEFAULT_ENDPOINT, ["client processes 1 != 4"]))+ plain = plan_performance(parse("--reference", str(self.reference), "--endpoint", "http://localhost:80/"))+ self.assertEqual(plain.endpoint, "http://localhost")+ local = plan_performance(parse("--reference", str(self.reference), "--endpoint", "http://localhost:8080"))+ self.assertEqual(local.endpoint, "http://localhost:8080")++ def test_an_endpoint_without_a_host_or_with_a_bad_port_is_rejected(self):+ for endpoint in ("http://:8080", "http://localhost:99999", "http://localhost:0"):+ with self.subTest(endpoint=endpoint), self.assertRaises(ValueError):+ plan_performance(parse("--reference", str(self.reference), "--endpoint", endpoint))+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"])@@ -843,6 +870,86 @@ class RunTest(unittest.TestCase):class CommandTest(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.reference = reference_file(self.temporary.name)++ def command(self, fake, *flags, environ=None):+ def measured(plan, data, client):+ return run_performance(plan, data, fake, results_dir=Path(self.temporary.name) / "results", now=clock)++ def loader(plan):+ return load_performance_data(plan, tiny_loaders())++ stderr = io.StringIO()+ code = None+ with (+ patch.dict("os.environ", environ or {}, clear=True),+ patch.object(run, "load_performance_data", side_effect=loader) as self.loader,+ patch.object(run, "run_performance", side_effect=measured),+ patch.object(run, "SIEClient") as client,+ contextlib.redirect_stdout(io.StringIO()),+ contextlib.redirect_stderr(stderr),+ ):+ try:+ run.main(["performance", "--reference", str(self.reference), *flags])+ except SystemExit as caught:+ code = caught.code+ return code, client, stderr.getvalue()++ def test_an_endpoint_without_a_host_or_with_a_bad_port_is_a_usage_error(self):+ for endpoint in ("localhost:8080", "http://:8080", "http://localhost:99999", "http://localhost:0"):+ with self.subTest(endpoint=endpoint):+ code, client, stderr = self.command(FakeClient(), "--endpoint", endpoint)+ self.assertEqual(code, 2)+ self.loader.assert_not_called()+ client.assert_not_called()+ self.assertIn("endpoint must be an http(s) URL", stderr)++ def test_a_local_endpoint_runs_without_a_key(self):+ code, client, stderr = self.command(FakeClient(), "--endpoint", "http://localhost:8080")+ self.assertIsNone(code)+ client.assert_called_once_with("http://localhost:8080", api_key="", timeout_s=5.0, max_connections=8)+ self.assertEqual(stderr, "")++ def test_a_cloud_key_is_not_sent_to_another_endpoint(self):+ code, client, stderr = self.command(+ FakeClient(), "--endpoint", "http://localhost:8080", environ={"SIE_API_KEY": "cloud-key"}+ )+ self.assertIsNone(code)+ client.assert_called_once_with("http://localhost:8080", api_key="", timeout_s=5.0, max_connections=8)+ self.assertIn(+ "note: SIE_API_KEY is scoped to https://api.superlinked.com and was not sent to http://localhost:8080",+ stderr,+ )++ def test_a_key_scoped_by_base_url_is_sent_to_that_endpoint(self):+ environ = {"SIE_BASE_URL": "http://localhost:8080/", "SIE_API_KEY": "local-token"}+ code, client, stderr = self.command(FakeClient(), "--endpoint", "http://localhost:8080", environ=environ)+ self.assertIsNone(code)+ client.assert_called_once_with("http://localhost:8080", api_key="local-token", timeout_s=5.0, max_connections=8)+ self.assertEqual(stderr, "")++ def test_a_failed_run_prints_its_reasons_and_exits_1(self):+ code, _, stderr = self.command(FakeClient(ready=False), "--endpoint", "http://localhost:8080")+ self.assertEqual(code, 1)+ self.assertEqual(stderr, "invalid: readiness request failed: ProvisioningError: no capacity\n")++ def test_an_invalid_run_with_retries_prints_the_reason_and_exits_0(self):+ code, _, stderr = self.command(FakeClient(retries={"2": 1}), "--endpoint", "http://localhost:8080")+ self.assertIsNone(code)+ self.assertEqual(stderr, "invalid: sdk retries 5\n")++ def test_a_missing_reference_key_is_named(self):+ broken = json.loads(self.reference.read_text(encoding="utf-8"))+ del broken["task_key"]+ self.reference.write_text(json.dumps(broken), encoding="utf-8")+ code, client, stderr = self.command(FakeClient(), "--endpoint", "http://localhost:8080")+ self.assertEqual(code, 2)+ client.assert_not_called()+ self.assertIn(f"reference {self.reference} is missing key 'task_key'", stderr)+def test_a_reference_run_without_a_key_fails_before_any_call(self):with tempfile.TemporaryDirectory() as temporary:reference = reference_file(temporary)diff --git a/examples/evaluations/published-benchmarks/tests/test_quality.py b/examples/evaluations/published-benchmarks/tests/test_quality.pyindex 91f59028f..8e97e59a4 100644--- a/examples/evaluations/published-benchmarks/tests/test_quality.py+++ b/examples/evaluations/published-benchmarks/tests/test_quality.py@@ -9,6 +9,7 @@ from unittest.mock import patchimport numpy as np+import runimport scorefrom run import (DEFAULT_ENDPOINT,@@ -120,6 +121,19 @@ class FakeClient:return {"model": model, "query_id": "", "scores": entries}+class ShortClient(FakeClient):+ def encode(self, model, items, **kwargs):+ return super().encode(model, items, **kwargs)[:-1]+++class NoneScoreClient(FakeClient):+ def score(self, model, query, items, **kwargs):+ result = super().score(model, query, items, **kwargs)+ if len(self.calls) > 1:+ result["scores"] = [{"item_id": items[0]["id"], "score": None, "rank": 0}]+ return result++def tiny_loaders():return Loaders(corpus=lambda name, revision: {doc_id: dict(doc) for doc_id, doc in CORPUS.items()},@@ -230,6 +244,35 @@ class PlanTest(unittest.TestCase):plan = plan_quality(parse("--reference", str(self.reference), "--endpoint", "http://localhost:8080"))self.assertEqual(plan.comparable_reasons, [f"endpoint http://localhost:8080 != {DEFAULT_ENDPOINT}"])+ def test_endpoint_is_normalised_before_it_is_compared(self):+ for endpoint in ("https://api.superlinked.com/", "HTTPS://API.superlinked.com"):+ with self.subTest(endpoint=endpoint):+ plan = plan_quality(parse("--reference", str(self.reference), "--endpoint", endpoint))+ self.assertEqual(plan.comparable_reasons, [])+ self.assertEqual(plan.endpoint, DEFAULT_ENDPOINT)+ local = plan_quality(parse("--reference", str(self.reference), "--endpoint", "http://localhost:8080/"))+ self.assertEqual(local.comparable_reasons, [f"endpoint http://localhost:8080/ != {DEFAULT_ENDPOINT}"])+ self.assertEqual(local.endpoint, "http://localhost:8080")+ flags = plan_quality(+ parse("--model", "m", "--task", "mteb/AskUbuntuDupQuestions", "--endpoint", "HTTP://LocalHost:8080/sie/")+ )+ self.assertEqual(flags.endpoint, "http://localhost:8080/sie")+ with self.assertRaises(ValueError):+ plan_quality(parse("--reference", str(self.reference), "--endpoint", "localhost:8080"))++ def test_default_ports_are_normalised_away(self):+ same = plan_quality(parse("--reference", str(self.reference), "--endpoint", "https://api.superlinked.com:443/"))+ self.assertEqual((same.endpoint, same.comparable_reasons), (DEFAULT_ENDPOINT, []))+ plain = plan_quality(parse("--reference", str(self.reference), "--endpoint", "http://localhost:80/"))+ self.assertEqual(plain.endpoint, "http://localhost")+ local = plan_quality(parse("--reference", str(self.reference), "--endpoint", "http://localhost:8080"))+ self.assertEqual(local.endpoint, "http://localhost:8080")++ def test_an_endpoint_without_a_host_or_with_a_bad_port_is_rejected(self):+ for endpoint in ("http://:8080", "http://localhost:99999", "http://localhost:0"):+ with self.subTest(endpoint=endpoint), self.assertRaises(ValueError):+ plan_quality(parse("--reference", str(self.reference), "--endpoint", endpoint))+def test_reference_kind_and_mode_are_checked(self):other = reference_file(self.temporary.name, evaluation_mode="isolated_performance")with self.assertRaises(ValueError):@@ -367,16 +410,17 @@ class EncodeRunTest(unittest.TestCase):def test_documents_then_queries_in_reference_batches(self):client = FakeClient()record, result_path = self.run_reference(client)- self.assertEqual([len(items) for _, _, items, _ in client.calls], [2, 2, 1, 2, 1])- self.assertEqual([kwargs["is_query"] for _, _, _, kwargs in client.calls], [False, False, False, True, True])- for _, model, _, kwargs in client.calls:+ measured = client.calls[1:]+ self.assertEqual([len(items) for _, _, items, _ in measured], [2, 2, 1, 2, 1])+ self.assertEqual([kwargs["is_query"] for _, _, _, kwargs in measured], [False, False, False, True, True])+ for _, model, _, kwargs in measured:self.assertEqual(model, "example/sparse-encoder")self.assertEqual(kwargs["output_types"], ["sparse"])self.assertFalse(kwargs["wait_for_capacity"])self.assertEqual(kwargs["provision_timeout_s"], 300.0)self.assertEqual(kwargs["max_oom_retries"], 0)self.assertNotIn("instruction", kwargs)- sent = [item for _, _, items, _ in client.calls[:3] for item in items]+ sent = [item for _, _, items, _ in measured[:3] for item in items]self.assertEqual([item["id"] for item in sent], ["d1", "d2", "d3", "d4", "d5"])self.assertEqual(sent[0]["text"], "Alpha alpha body")self.assertEqual(sent[2]["text"], "gamma body")@@ -447,19 +491,19 @@ class EncodeRunTest(unittest.TestCase):self.assertEqual(record["run"]["request_count"], 4)def test_sdk_retry_makes_the_run_invalid(self):- record, _ = self.run_reference(FakeClient(retries=(0, 1, 0, 2)))+ record, _ = self.run_reference(FakeClient(retries=(0, 0, 1, 0, 2)))self.assertEqual(record["validity"], {"valid": False, "reasons": ["sdk retries 3"], "sdk_retries": 3})self.assertTrue(record["comparable"])def test_execution_revision_change_is_collected_and_not_comparable(self):- record, _ = self.run_reference(FakeClient(revisions=("rev-a", "rev-b", "rev-a")))+ record, _ = self.run_reference(FakeClient(revisions=("rev-b", "rev-a", "rev-b")))self.assertEqual(record["execution_revisions"], ["rev-a", "rev-b"])self.assertFalse(record["comparable"])self.assertEqual(record["comparable_reasons"], ["execution revision changed"])self.assertTrue(record["validity"]["valid"])def test_failed_request_stops_the_run_and_is_recorded(self):- record, result_path = self.run_reference(FakeClient(fail_at=2))+ record, result_path = self.run_reference(FakeClient(fail_at=3))self.assertTrue(result_path.exists())self.assertEqual((record["run"]["request_count"], record["run"]["failure_count"]), (3, 0 + 1))self.assertIsNone(record["run"]["predictions_path"])@@ -469,12 +513,51 @@ class EncodeRunTest(unittest.TestCase):self.assertEqual(record["validity"]["reasons"], ["request failed: RuntimeError: boom"])def test_retries_before_a_failed_request_are_recorded(self):- record, _ = self.run_reference(FakeClient(retries=(0, 1, 2), fail_at=2))+ record, _ = self.run_reference(FakeClient(retries=(0, 0, 1, 2), fail_at=3))self.assertEqual(record["validity"]["sdk_retries"], 3)self.assertEqual(record["validity"]["reasons"], ["sdk retries 3", "request failed: RuntimeError: boom"])+ def test_readiness_request_is_the_first_call_and_is_not_counted(self):+ client = FakeClient()+ record, _ = self.run_reference(client)+ kind, model, items, kwargs = client.calls[0]+ self.assertEqual((kind, model), ("encode", "example/sparse-encoder"))+ self.assertEqual([item["id"] for item in items], ["d1", "d2"])+ self.assertEqual(items, client.calls[1][2])+ self.assertTrue(kwargs["wait_for_capacity"])+ self.assertEqual(kwargs["provision_timeout_s"], 300.0)+ self.assertEqual(+ (kwargs["max_oom_retries"], kwargs["is_query"], kwargs["output_types"]), (0, False, ["sparse"])+ )+ self.assertEqual(len(client.calls), 6)+ self.assertEqual(record["run"]["request_count"], 5)++ def test_readiness_failure_skips_the_measured_phase(self):+ client = FakeClient(fail_at=0)+ record, result_path = self.run_reference(client)+ self.assertTrue(result_path.exists())+ self.assertEqual(len(client.calls), 1)+ self.assertFalse(record["validity"]["valid"])+ self.assertEqual(record["validity"]["reasons"], ["readiness request failed: RuntimeError: boom"])+ self.assertEqual((record["run"]["request_count"], record["run"]["failure_count"]), (0, 0))+ self.assertIsNone(record["run"]["predictions_path"])+ self.assertEqual((record["metrics"], record["comparison"]), ([], []))++ def test_retries_on_the_readiness_request_are_not_counted(self):+ record, _ = self.run_reference(FakeClient(retries=(4,)))+ self.assertEqual(record["validity"], {"valid": True, "reasons": [], "sdk_retries": 0})++ def test_a_malformed_response_is_recorded_as_a_failed_run(self):+ record, result_path = self.run_reference(ShortClient())+ self.assertTrue(result_path.exists())+ self.assertIsNone(record["run"]["predictions_path"])+ self.assertEqual((record["run"]["request_count"], record["run"]["failure_count"]), (1, 0))+ self.assertFalse(record["validity"]["valid"])+ (reason,) = record["validity"]["reasons"]+ self.assertTrue(reason.startswith("request failed: ValueError: "), reason)+def test_multivector_run_without_reference(self):- client = FakeClient(revisions=("r1", "r2"))+ client = FakeClient(revisions=("r2", "r1"))plan = plan_quality(parse("--model", "m/colbert", "--task", "mteb/SciFact", "--output", "multivector", "--items-per-request", "3"@@ -483,7 +566,7 @@ class EncodeRunTest(unittest.TestCase):record, _ = run_quality(plan, load_quality_data(plan, tiny_loaders()), client, results_dir=self.results, now=clock)- self.assertEqual([len(items) for _, _, items, _ in client.calls], [3, 2, 3])+ self.assertEqual([len(items) for _, _, items, _ in client.calls[1:]], [3, 2, 3])self.assertEqual({kwargs["output_types"][0] for _, _, _, kwargs in client.calls}, {"multivector"})predictions = json.loads(Path(record["run"]["predictions_path"]).read_text(encoding="utf-8"))self.assertEqual(list(predictions["q1"]), ["d2", "d3", "d1", "d4", "d5"])@@ -504,15 +587,19 @@ class RerankRunTest(unittest.TestCase):data = load_quality_data(plan, tiny_loaders())record, _ = run_quality(plan, data, client, results_dir=Path(temporary) / "results", now=clock)predictions = json.loads(Path(record["run"]["predictions_path"]).read_text(encoding="utf-8"))- self.assertEqual([kind for kind, _, _, _ in client.calls], ["score", "score", "score"])- queries = [query for _, _, (query, _), _ in client.calls]+ self.assertEqual([kind for kind, _, _, _ in client.calls], ["score", "score", "score", "score"])+ self.assertEqual(client.calls[0][2], client.calls[1][2])+ self.assertTrue(client.calls[0][3]["wait_for_capacity"])+ measured = client.calls[1:]+ queries = [query for _, _, (query, _), _ in measured]self.assertEqual(queries, [{"text": "first query"}, {"text": "second query"}, {"text": "third query"}])- items = [items for _, _, (_, items), _ in client.calls]+ items = [items for _, _, (_, items), _ in measured]self.assertEqual([[item["id"] for item in batch] for batch in items], [["d2", "d1"], ["d3", "d5"], ["d4", "d2"]])self.assertEqual(items[0][1]["text"], "Alpha alpha body")- for _, _, _, kwargs in client.calls:+ self.assertEqual(record["run"]["request_count"], 3)+ for _, _, _, kwargs in measured:self.assertFalse(kwargs["wait_for_capacity"])self.assertEqual(kwargs["provision_timeout_s"], 300.0)self.assertEqual(kwargs["max_oom_retries"], 0)@@ -526,6 +613,144 @@ class RerankRunTest(unittest.TestCase):self.assertEqual(main["value"], map_1000["value"])+class CommandTest(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.reference = reference_file(self.temporary.name)++ def command(self, fake, *flags, environ=None):+ def measured(plan, data, client):+ return run_quality(plan, data, fake, results_dir=Path(self.temporary.name) / "results", now=clock)++ def loader(plan):+ return load_quality_data(plan, tiny_loaders())++ stdout, stderr = io.StringIO(), io.StringIO()+ code = None+ with (+ patch.dict("os.environ", environ or {}, clear=True),+ patch.object(run, "load_quality_data", side_effect=loader) as self.loader,+ patch.object(run, "run_quality", side_effect=measured),+ patch.object(run, "SIEClient") as client,+ contextlib.redirect_stdout(stdout),+ contextlib.redirect_stderr(stderr),+ ):+ try:+ run.main(["quality", "--reference", str(self.reference), *flags])+ except SystemExit as caught:+ code = caught.code+ return code, client, stderr.getvalue()++ def test_a_reference_run_without_a_key_fails_before_any_call(self):+ code, client, stderr = self.command(FakeClient())+ self.assertEqual(code, 2)+ client.assert_not_called()+ self.assertIn(f"SIE_API_KEY must be set in the environment for {DEFAULT_ENDPOINT}", stderr)++ def test_a_local_endpoint_runs_without_a_key(self):+ code, client, stderr = self.command(FakeClient(), "--endpoint", "http://localhost:8080")+ self.assertIsNone(code)+ client.assert_called_once_with("http://localhost:8080", api_key="", timeout_s=300.0)+ self.assertEqual(stderr, "")++ def test_a_key_is_passed_as_is(self):+ code, client, _ = self.command(FakeClient(), environ={"SIE_API_KEY": "test-key"})+ self.assertIsNone(code)+ client.assert_called_once_with(DEFAULT_ENDPOINT, api_key="test-key", timeout_s=300.0)++ def test_a_cloud_key_is_not_sent_to_another_endpoint(self):+ code, client, stderr = self.command(+ FakeClient(), "--endpoint", "http://localhost:8080", environ={"SIE_API_KEY": "cloud-key"}+ )+ self.assertIsNone(code)+ client.assert_called_once_with("http://localhost:8080", api_key="", timeout_s=300.0)+ self.assertIn(+ "note: SIE_API_KEY is scoped to https://api.superlinked.com and was not sent to http://localhost:8080",+ stderr,+ )++ def test_a_key_scoped_by_base_url_is_sent_to_that_endpoint(self):+ environ = {"SIE_BASE_URL": "http://localhost:8080/", "SIE_API_KEY": "local-token"}+ code, client, stderr = self.command(FakeClient(), "--endpoint", "http://localhost:8080", environ=environ)+ self.assertIsNone(code)+ client.assert_called_once_with("http://localhost:8080", api_key="local-token", timeout_s=300.0)+ self.assertEqual(stderr, "")++ def test_a_key_scope_is_an_origin_so_a_path_on_the_endpoint_still_matches(self):+ environ = {"SIE_BASE_URL": "http://localhost:8080", "SIE_API_KEY": "local-token"}+ code, client, stderr = self.command(FakeClient(), "--endpoint", "http://localhost:8080/sie/", environ=environ)+ self.assertIsNone(code)+ client.assert_called_once_with("http://localhost:8080/sie", api_key="local-token", timeout_s=300.0)+ self.assertEqual(stderr, "")++ def test_a_key_scoped_elsewhere_fails_on_the_default_endpoint(self):+ environ = {"SIE_BASE_URL": "http://localhost:8080", "SIE_API_KEY": "local-token"}+ code, client, stderr = self.command(FakeClient(), environ=environ)+ self.assertEqual(code, 2)+ client.assert_not_called()+ self.assertIn(f"SIE_API_KEY must be set in the environment for {DEFAULT_ENDPOINT}", stderr)++ def test_a_failed_run_prints_its_reasons_and_exits_1(self):+ for fake, reason in (+ (FakeClient(fail_at=0), "readiness request failed: RuntimeError: boom"),+ (FakeClient(fail_at=1), "request failed: RuntimeError: boom"),+ (ShortClient(), "request failed: ValueError: encode returned a different number of results"),+ ):+ with self.subTest(reason=reason):+ code, _, stderr = self.command(fake, "--endpoint", "http://localhost:8080")+ self.assertEqual(code, 1)+ self.assertTrue(stderr.startswith(f"invalid: {reason}"), stderr)+ self.assertNotIn("Traceback", stderr)++ def test_an_invalid_run_with_retries_prints_the_reason_and_exits_0(self):+ code, _, stderr = self.command(FakeClient(retries=(0, 2)), "--endpoint", "http://localhost:8080")+ self.assertIsNone(code)+ self.assertEqual(stderr, "invalid: sdk retries 2\n")++ def test_a_missing_reference_key_is_named(self):+ broken = json.loads(self.reference.read_text(encoding="utf-8"))+ del broken["task_key"]+ self.reference.write_text(json.dumps(broken), encoding="utf-8")+ code, client, stderr = self.command(FakeClient(), "--endpoint", "http://localhost:8080")+ self.assertEqual(code, 2)+ client.assert_not_called()+ self.assertIn(f"reference {self.reference} is missing key 'task_key'", stderr)++ def test_an_endpoint_without_a_scheme_is_a_usage_error(self):+ code, client, stderr = self.command(FakeClient(), "--endpoint", "localhost:8080")+ self.assertEqual(code, 2)+ client.assert_not_called()+ self.assertIn("endpoint must be an http(s) URL", stderr)++ def test_an_endpoint_without_a_host_or_with_a_bad_port_is_a_usage_error(self):+ for endpoint in ("http://:8080", "http://localhost:99999", "http://localhost:0"):+ with self.subTest(endpoint=endpoint):+ code, client, stderr = self.command(FakeClient(), "--endpoint", endpoint)+ self.assertEqual(code, 2)+ self.loader.assert_not_called()+ client.assert_not_called()+ self.assertIn("endpoint must be an http(s) URL", stderr)++ def test_a_score_without_a_value_is_recorded_as_a_failed_run(self):+ self.reference = reference_file(+ self.temporary.name,+ model="Qwen/Qwen3-Reranker-0.6B",+ operation="score",+ task_key="mteb/AskUbuntuDupQuestions",+ dataset={"name": "mteb/AskUbuntuDupQuestions", "revision": REVISION, "subset": "test", "parameters": []},+ payload={"items_per_request": 2, "output_contract": "scores", "parameters": []},+ )+ code, _, stderr = self.command(NoneScoreClient(), "--endpoint", "http://localhost:8080")+ self.assertEqual(code, 1)+ (result_path,) = (Path(self.temporary.name) / "results").glob("*-????????T??????Z.json")+ record = json.loads(result_path.read_text(encoding="utf-8"))+ self.assertIsNone(record["run"]["predictions_path"])+ (reason,) = record["validity"]["reasons"]+ self.assertTrue(reason.startswith("request failed: TypeError"), reason)+ self.assertTrue(stderr.startswith("invalid: request failed: TypeError"), stderr)++class ScoringTest(unittest.TestCase):def test_two_query_hand_computed_case(self):qrels = {"q1": {"a": 1}, "q2": {"c": 1}}