From c2c47826ba256bfaf91a036cfae328af179f3b59 Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Wed, 25 Nov 2026 15:08:21 +0100 Subject: [PATCH 01/11] feat(benchmarks): add pysweep, a declarative sweep runner for the ChatQnA benchmark pysweep runs benchmark.py across a declared grid of configurations and records, per run, the configuration that was observed on the deployment, not just the one that was asked for. Each deployment knob is a Property that reads the live value, applies a desired one and verifies it; client knobs are benchmark.py's own options. Deployment combinations are the outer loop (applied and verified once), client combinations the inner loop, and every run adds a row to one summary CSV (knobs, TTFT/TPOT mean and p90). This first part ships the framework with every client knob and one deployment knob, llms.max_new_tokens (Runtime-API plane, through the system_fingerprint API). retriever.k and reranker.top_n follow in a stacked PR; the llms.model swap is designed (DESIGN.md) but not included. - benchmark.py: parse_args(argv) and run_benchmark() split out of main(), so pysweep can run one load test per combination in-process. Running it as a script is unchanged. - The benchmark's tokenizer (-m) is derived from the model the pipeline is observed to serve, mapped to its HF repo id through the model catalog (models-rag.yaml first, then models.yaml). - Keycloak user tokens are minted per worker and re-minted before every run; for the sweep the UI client's access-token lifespan is set to 1h (an arbitrary value that only has to outlast one run) and restored afterwards. - Preflight: question files are checked before anything is applied. - tox env pysweep_unit_tests, now also in the unit-test CI matrix. Ported from intel-innersource/applications.ai.enterprise.ai-erag#143 and adapted to this repo (config.erag.yaml, env lookup from the installer layout instead of /root/ai-solutions). Signed-off-by: Kurzacz, Kamil --- .github/workflows/val-unit-tests.yml | 1 + src/tests/e2e/benchmarks/chatqna/benchmark.py | 38 +- .../e2e/benchmarks/chatqna/pysweep/DESIGN.md | 514 ++++++++ .../e2e/benchmarks/chatqna/pysweep/README.md | 460 +++++++ .../benchmarks/chatqna/pysweep/__init__.py | 8 + .../chatqna/pysweep/authentication.py | 386 ++++++ .../e2e/benchmarks/chatqna/pysweep/base.py | 88 ++ .../benchmarks/chatqna/pysweep/client_args.py | 299 +++++ .../e2e/benchmarks/chatqna/pysweep/config.py | 503 ++++++++ .../chatqna/pysweep/examples/config.yaml | 20 + .../chatqna/pysweep/examples/sweep.yaml | 86 ++ .../chatqna/pysweep/model_catalog.py | 178 +++ .../e2e/benchmarks/chatqna/pysweep/paths.py | 48 + .../chatqna/pysweep/properties/__init__.py | 8 + .../chatqna/pysweep/properties/max_tokens.py | 74 ++ .../chatqna/pysweep/pysweep_bench.py | 812 ++++++++++++ .../e2e/benchmarks/chatqna/pysweep/results.py | 415 ++++++ .../benchmarks/chatqna/pysweep/runtime_api.py | 253 ++++ .../chatqna/pysweep/served_model.py | 160 +++ src/tests/e2e/validation/pysweep/conftest.py | 94 ++ .../validation/pysweep/test_config_unit.py | 448 +++++++ .../e2e/validation/pysweep/test_max_tokens.py | 74 ++ .../pysweep/test_max_tokens_unit.py | 124 ++ .../pysweep/test_model_catalog_unit.py | 237 ++++ .../e2e/validation/pysweep/test_paths_unit.py | 91 ++ .../pysweep/test_pysweep_bench_unit.py | 1134 +++++++++++++++++ .../validation/pysweep/test_results_unit.py | 397 ++++++ .../validation/pysweep/test_served_model.py | 93 ++ .../pysweep/test_served_model_unit.py | 188 +++ .../pysweep/test_token_lifespan_unit.py | 135 ++ src/tests/e2e/validation/requirements.txt | 1 + src/tox.ini | 27 + 32 files changed, 7386 insertions(+), 8 deletions(-) create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/README.md create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/__init__.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/base.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/config.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/paths.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/results.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py create mode 100644 src/tests/e2e/validation/pysweep/conftest.py create mode 100644 src/tests/e2e/validation/pysweep/test_config_unit.py create mode 100644 src/tests/e2e/validation/pysweep/test_max_tokens.py create mode 100644 src/tests/e2e/validation/pysweep/test_max_tokens_unit.py create mode 100644 src/tests/e2e/validation/pysweep/test_model_catalog_unit.py create mode 100644 src/tests/e2e/validation/pysweep/test_paths_unit.py create mode 100644 src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py create mode 100644 src/tests/e2e/validation/pysweep/test_results_unit.py create mode 100644 src/tests/e2e/validation/pysweep/test_served_model.py create mode 100644 src/tests/e2e/validation/pysweep/test_served_model_unit.py create mode 100644 src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py diff --git a/.github/workflows/val-unit-tests.yml b/.github/workflows/val-unit-tests.yml index 730bdb21..807879da 100644 --- a/.github/workflows/val-unit-tests.yml +++ b/.github/workflows/val-unit-tests.yml @@ -49,6 +49,7 @@ jobs: - llm_guard_output_guardrail_unit_tests - llms_unit_tests - prompt_template_unit_tests + - pysweep_unit_tests - reranks_unit_tests - retrievers_unit_tests - system_fingerprint_unit_tests diff --git a/src/tests/e2e/benchmarks/chatqna/benchmark.py b/src/tests/e2e/benchmarks/chatqna/benchmark.py index eb75b9ca..e817af92 100644 --- a/src/tests/e2e/benchmarks/chatqna/benchmark.py +++ b/src/tests/e2e/benchmarks/chatqna/benchmark.py @@ -18,7 +18,6 @@ from queue import Empty, Queue import requests import urllib3 -from transformers import AutoTokenizer class QueryPool: def __init__(self, file_path, n_tokens, tokenizer): @@ -79,7 +78,14 @@ def __init__(self): self.err = None self.code = 0 -def parse_args(): +def parse_args(argv=None): + """Parse the load-test options. + + ``argv`` defaults to the process's arguments, so running this as a script is + unchanged. Passing a list is what lets an in-process caller (pysweep) drive + one load test per sweep combination without re-implementing the CLI or + shelling out. + """ parser = argparse.ArgumentParser(description="Load testing tool.") parser.add_argument("-f", type=str, help="Question File Location") parser.add_argument("-s", type=str, default="https://solutions.ai/api/v1/chatqna", help="Server Address format") @@ -91,7 +97,7 @@ def parse_args(): parser.add_argument("-b", type=str, default="uat.txt", help="Path to file with UAT") parser.add_argument("-x", type=int, default=0, help="Fix length of input query to X tokens (0 means no fixing)") parser.add_argument("-w", type=int, default=1, help="Warmup request per thread to skip") - return parser.parse_args() + return parser.parse_args(argv) def duration_to_seconds(duration_str): units = {"s": 1, "m": 60, "h": 3600} @@ -182,13 +188,21 @@ def call_chatqna(url, question, wid, tokenizer, bearer): def signal_handler(var, signal, frame): var[0] = var[0] + 1 -def main(): - args = parse_args() +def run_benchmark(args, output_file=None): + """Run one load test and return ``(error, output_file)``. + + Split out of ``main`` so a caller can run several load tests in one process + and know where each wrote its rows: ``main`` still exits on ``error``, but + pysweep needs the exit code *and* the CSV path per sweep combination, and it + passes ``output_file`` so results land under the combination's own name. + """ print(' \n'.join(f'{k}: {v}' for k, v in vars(args).items())) + # Local import due to heavy library + from transformers import AutoTokenizer + tokenizer = AutoTokenizer.from_pretrained(args.m) - logging.basicConfig(stream=sys.stderr, level=logging.INFO) stop_event = threading.Event() signal.signal(signal.SIGINT, lambda s, f: stop_event.set()) @@ -196,7 +210,8 @@ def main(): num_workers = args.c duration = duration_to_seconds(args.d) delay_unit = duration_to_seconds(args.u) - output_file = f"./bench_{time.strftime('%m%d-%H%M')}_c-{num_workers}_d-{args.u}.result.csv" + if output_file is None: + output_file = f"./bench_{time.strftime('%m%d-%H%M')}_c-{num_workers}_d-{args.u}.result.csv" result_queue = Queue() failures_allowed = args.e @@ -231,7 +246,14 @@ def main(): future.result() collector_thread.join() - sys.exit(error) + + return error, output_file + +def main(): + args = parse_args() + logging.basicConfig(stream=sys.stderr, level=logging.INFO) + error, _ = run_benchmark(args) + sys.exit(error) if __name__ == "__main__": main() diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md b/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md new file mode 100644 index 00000000..d22c9f5c --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md @@ -0,0 +1,514 @@ + + +# pysweep — Declarative Configuration Sweeps for ChatQNA Benchmarks + +> **Status.** This document covers both config planes. On the Runtime-API plane +> `llms.max_new_tokens` is implemented; `retriever.k` and `reranker.top_n` are +> designed and land next. The K8s-spec plane's one designed knob, `llms.model` +> (`LlmModel`: model-manager + `gmc-config`), is **not implemented yet**; the +> sections on it describe the design it will follow. Until then the runner only *reads* the served model, +> to derive the benchmark's tokenizer (`served_model.py`). + +## Problem + +Benchmarking the ChatQNA microservice app requires running the same workload +against many different app configurations (resource allocation, retriever/reranker +knobs, model-server env vars, ...). Today this is done with a set of bash scripts: + +- `prepare_change_*.sh` — **setters** that mutate one knob each, split across two + different mechanisms (Kubernetes and a runtime REST API). +- `preflight_checks/run.bash` — a **checker** with the expected values hardcoded + inline, mixing auth, side effects, and `kubectl get` reads. + +The result: **it is hard to know what configuration was actually tested** in a +given run. Expectations live in one script, setters in another, and nothing ties +a declared desired state to the state the system was actually in when the +benchmark ran. + +## Goals + +1. **Declare** the desired configuration (or a sweep of configurations) in one + place — a YAML file — decoupled from *how* each knob is applied. +2. **Apply** the desired state idempotently before each benchmark iteration. +3. **Verify** that the system actually reached the desired state before the + benchmark runs — reading *observed* state, not just the value we wrote. Kept + distinct from **preflight**, which checks config-level preconditions that + belong to no property (see "Execution flow"). +4. **Record** the observed, resolved configuration alongside each run's results, + so "what was tested" is never in doubt. +5. **Scale**: adding a new knob = adding one small, self-contained Python class. +6. **Stay in sync with the deployment.** Every property class has an accompanying + **e2e test** that exercises its `read()` / `apply()` / `wait_until_ready()` + against a real (or realistic) deployment. These tests are the contract that + proves pysweep still matches the actual deployment modules — if a plane's + mechanism drifts (e.g. gmc-config keys renamed, the runtime API path changes, + a workload's kind/label changes), the property's e2e test fails **before** a + benchmark run silently tests the wrong configuration. New knob = new property + class **and** its e2e test. + +## Non-goals (initial version) + +- ~~Running the benchmark itself~~ — since implemented: `pysweep_bench.py` drives + the load too, reusing `benchmark.py` unchanged rather than replacing it. The + reason is provenance: only the runner knows which configuration produced which + result CSV, so only it can write the summary row (see "Execution flow"). +- More than the two planes described below (env-var / helm-values knobs are + deferred — see "Future: a third plane"). +- Automatic teardown / restore of a baseline between runs (noted as a risk; + not implemented initially). + +## Core concepts + +### Property + +A **Property** owns exactly one configuration knob. It knows: + +- how to **read** the knob's *observed* value from the live system, +- whether an observed value **satisfies** a desired value, +- how to **apply** a desired value (write only when not already satisfied — + idempotent), +- how to **wait** until the applied change has actually converged. + +Interface (conceptual): + +```python +class Property: + plane: Plane + + def read(self) -> Any: ... # observed state, NOT the spec we wrote + def is_satisfied(self, desired) -> bool: ... + def apply(self, desired) -> None: ... # no-op if already satisfied + def wait_until_ready(self, timeout) -> None: ... +``` + +Each concrete property (e.g. `MaxNewTokens`, `RetrieverK`, `LlmModel`, +`RerankerTopN`) is a small class bound to a config leaf via +`Annotated[..., PropertyBinding(SomeProperty)]`, so the YAML references it by +that leaf's dotted path rather than by a registered name. + +### Plane + +A **Plane** is *the channel through which a knob's value lives and is changed*. +The planes differ in set mechanism, propagation semantics, how convergence is +detected, and what "read" should return. A property delegates the mechanics to +its plane. + +We support **two planes** in the initial version: + +| | **K8s spec plane** | **Runtime API plane** | +|---|---|---| +| Example knobs | the served LLM model | reranker `top_n`, retriever `k`, `max_new_tokens` | +| Where value lives | `gmc-config` ConfigMap (`system` ns), which the GMC operator renders onto the pipeline's workloads | inside the running app | +| Set mechanism | delegate serving to the `model-manager` CLI, then patch the knob inside `gmc-config` so the operator repoints the pipeline | authenticated HTTP POST to `system_fingerprint/change_arguments` | +| Client library | `kr8s` (native ConfigMap + workload access), plus a subprocess for `model-manager` | `httpx`/`requests` | +| Propagation | **async** — the ConfigMap write returns instantly; the operator re-renders and the pods have to be replaced, over minutes to hours | ~synchronous — live once the call returns 200 | +| `wait_until_ready` | poll observed state until the property holds the desired value | typically a no-op | +| `read()` returns | **observed/actual** (the env of the live pods' processes + serving status), **not** the ConfigMap and **not** `.spec` | GET the value back from the API | +| Drift source | direct edits of the operator's *rendered* output are reverted on its next reconcile — so we don't do them; `gmc-config` is the durable source | value is in-process; lost on pod restart | +| Auth | kubeconfig | Keycloak user access token | + +**The set/verify split is the crux of the design.** Setting a K8s knob returns +immediately, but the system has not converged until GMC has reconciled and the +new pods are `Ready`. Verifying against the value we just wrote — whether the +ConfigMap or the workload `.spec` — would falsely pass. Therefore getters read +*observed* state (live workload + pod status), and `wait_until_ready()` gates +verification. + +**Why not patch the pipeline's workloads directly?** They are **GMC-owned**: the +operator `Update`s them from the `gmc-config` templates on every reconcile, and it +reconciles on *any* ConfigMap change in the namespaces it watches. A direct +`kr8s`/`kubectl` patch — of the workload, or of a ConfigMap the operator renders — +is therefore reverted, the classic silent mid-sweep rollback. `gmc-config` is the +value GMC itself reads, so writing it is durable, and the write is itself the +reconcile trigger. See the K8s-plane source-of-truth decision below. + +**And why not create the serving workloads either?** Getting a model served is not +one field: it is an `LLMInferenceService`, a weight download, CPU/NUMA and balloon +sizing, engine args, and a gateway route, all coupled per model. The deployment +team owns that as the `model-manager` CLI — the tool this cluster was built with — +so the K8s plane **delegates** it instead of reimplementing it. See the decision +below. + +### Sweep config (YAML) + +Declares the knobs and the value(s) to test. A single value = one setting; a +list = multiple settings to sweep. The existing `config.yaml` already uses this +list-of-values shape. + +**Combination strategy: `product` (decided).** The sweep is the cartesian +product of every property's declared values: + +- A property given a **single value** is fixed across all combinations. +- A property given a **list** contributes one dimension to the product; every + one of its values appears in combinations paired with every combination of the + other list-valued properties. +- The total number of combinations is the product of the list lengths (properties + with a single value contribute a factor of 1). This blows up fast — and each + K8s-plane change is a multi-minute rollout — so keep the number of list-valued + properties (and their lengths) small. + +Considered and deferred: `zip`/paired (lists advanced together) and `scenarios` +(an explicit list of named, fully-specified combinations). Not implemented in the +initial version. + +The sweep is **ordered so expensive K8s-plane changes are the outer loop and +cheap runtime-API changes are the inner loop**, minimizing rollouts across the +product. + +#### Client knobs: sweep dimensions with no plane + +The load generator's own parameters (concurrency, input token count, duration, +warmup, …) are sweep knobs in the sense that matters: each distinct value is a +different test scenario, and they expand into the product like anything else. But +they have **no plane**, and modelling them as a third one was considered and +rejected. A `Plane` exists to describe *how a value lives in the running system +and how a change propagates to it*; a client parameter has no such existence. +Concretely, all three `Property` methods would be vacuous: + +- `apply()` — nothing to mutate; the value is an argument to a process pysweep is + about to start. +- `wait_until_ready()` — nothing to propagate. +- `read()` — nothing to observe. It could only echo the value the harness already + holds, which is exactly the spec-read that "getters read observed state, never + the spec we wrote" forbids. The preflight for such a property would be + tautological, and its snapshot entry would be a claim with nothing behind it. + +Since the invariant is what makes "what was tested" trustworthy for the knobs +that *do* have observable state, the client knobs get a separate adapter +(`client_args.py`) that mirrors `benchmark.py`'s options and renders resolved +values back into its CLI. They keep everything a knob needs — schema validation, +product expansion, result-file naming, a recorded snapshot — and stay out of the +apply/converge/verify machinery entirely. `ClientSetting` is deliberately a +different type from `PropertySetting`, so a client knob cannot reach that path by +accident. + +**Two nested products, not one.** Client knobs expand into their own product, +which the runner nests inside the deployment one (see "Execution flow"). The +nesting is the ordering: deployment combinations vary in the outer loop because +each costs a rollout, client combinations in the inner loop because each costs +only another load test against a deployment already standing. Expressed as +nesting rather than as extra product dimensions, "client knobs are innermost" is +structural — there is no sort key that has to keep getting it right. + +**Client knobs are required in the config**, unlike deployment knobs. An omitted +deployment knob means "leave it alone", which is a meaningful and observable +state. An omitted client knob has no such reading: the load test would still run, +silently on `benchmark.py`'s defaults, and the result CSV records none of it — +reintroducing precisely the "what configuration was actually tested" ambiguity +this design exists to remove. For the same reason the config is the single source +of truth: a client flag passed after `--` that the config also declares is +rejected rather than silently winning in either direction. + +**Not every `benchmark.py` option is a knob, though.** `-m` names the tokenizer +that produces the `input_tokens` / `output_tokens` columns, and it has exactly one +correct value: the model being served. Any other tokenizer reports counts for a +tokenization the deployment never performed. A value with one correct setting is +not a dimension to sweep and not a choice to delegate to a config author, so it +has no config key at all — the runner derives it from the *observed* served model +(`LlmModel.read()`, or the combination's snapshot when `llms.model` is swept) +and renders it per combination. Declaring it, or passing `-m` after `--`, is an +error; an unreadable model aborts rather than falling back to a default tokenizer. + +This is the one place a client argument depends on deployment state, and it is +resolved by *reading a property* rather than by giving the argument a plane — the +observation happens where observation belongs, and the client adapter stays a pure +translation. + +## Authorization & access + +pysweep talks to the live system through two authenticated channels, plus a +possible network hop to reach pod APIs. These are hard prerequisites — the tool +cannot apply or verify anything without them, so they must be resolved (and +checked) up front, not discovered mid-sweep. + +### 1. Kubernetes API access (K8s spec plane) + +- **kubeconfig.** `kr8s` needs a working kubeconfig to reach the cluster API. + Resolution order: explicit `KUBECONFIG` env var → path in the sweep config → + default `~/.kube/config`. pysweep does **not** assume a particular file + location; it fails fast with a clear message if no context is reachable. (On + the bench box the real config lives at + `/root/.kube/igklab_perf_pdt_bench_gnr_kube.config`.) +- **RBAC / permissions required.** The service account or user the kubeconfig + points at must be able to: + - `get`/`patch` the `gmc-config` ConfigMap in the `system` namespace (the + K8s-plane setter), + - `get`/`list` ConfigMaps in the pipeline namespace (`chatqna`) — to see what the + operator *rendered*, the middle of the property's three states, + - `get`/`list`/`watch` Deployments and Pods in `chatqna`, **`create` on + `pods/exec`** there (the observed model is read out of the running containers' + environment, which is the only place it is observable), and **`delete` Pods** + there — the rendered ConfigMap is consumed via `envFrom` with no checksum + annotation, so nothing rolls on its own, + - `get`/`list` `llminferenceservices` in `llm-inference` — to confirm the model + the pipeline names is actually being served and Ready, + - `get` Secrets in the `keycloak` namespace (Keycloak credentials — see below). + + Two notes on grants the earlier plan expected and that are **not** needed: + **no write access to `gmc-controller`** (the plan assumed a `rollout restart` was + required to trigger a reconcile; it is not — see "Design decisions"), and **no + access to Helm release Secrets** (the per-model profiles the setter used to read + from them are now model-manager's concern). Both were dropped from + `REQUIRED_ACCESS`. Note also that a sweep declaring `llms.model` needs whatever + `model-manager` itself needs, which is broader than this list — it creates the + serving CRs. pysweep does not model that: it shells out, and a permission failure + surfaces as the CLI's own non-zero exit. +- A **preflight authorization check** should verify these up front (e.g. a + `SelfSubjectAccessReview` per verb/resource, or a cheap probing `get`) and + report exactly which permission is missing rather than failing on the first + write mid-combination. + +### 2. Runtime API auth (Runtime API plane) + +- The `system_fingerprint` endpoints require a **Keycloak user access token**. + pysweep reuses the existing token machinery (`load_secrets.bash` + + `generate_uat_to_file.sh`) refactored into a **token provider**: it reads the + Keycloak admin/user credentials from the `auth` namespace secrets (hence the + Secrets RBAC above), obtains a UAT, and refreshes it on expiry. +- The provider must be **side-effect free** for reads. Today's flow mutates realm + session/token timeouts and toggles the user's required-actions as a side effect + of minting a token; pysweep should scope or restore any such mutation so a + "check" never changes cluster state. + +### 3. Reaching pod APIs (port-forwarding) + +- Some knobs are read/verified by calling an API served *inside* a pod (the + fingerprint API), and the load test itself has to reach the pipeline's router — + neither of which has a stable externally-routable address on every deployment. +- pysweep establishes access on demand via a **`kr8s` port-forward** to the + target Pod/Service, scoped to the operation and torn down afterward — rather + than assuming a pre-existing ingress or a `kubectl port-forward` running in + another terminal. `kr8s` supports port-forwarding natively, so this stays in + the "everything is a Python object" model. +- Where an ingress route already exists (the fingerprint API is reachable via + `https://${ERAG_DOMAIN_NAME}/v1/system_fingerprint/...`), prefer it and skip + the forward; port-forward is the fallback for pod-local APIs with no route. +- `no_proxy`/`NO_PROXY` must include the ERAG domain (as `load_secrets.bash` + already arranges) so token and API calls don't get routed through a proxy. + +### Summary of access prerequisites + +| Need | Used by | How obtained | +|---|---|---| +| kubeconfig + cluster reachability | K8s-plane `read`/`apply`/`converge` | `KUBECONFIG` / config / default path | +| RBAC on `gmc-config`, `gmc-controller`, workloads, pods, secrets | K8s-plane setters & getters, token provider | cluster RBAC on the kubeconfig identity | +| Keycloak user access token | Runtime-API `read`/`apply` | token provider (refactored from existing scripts) | +| Port-forward to pod/service | reading pod-local APIs with no ingress | `kr8s` port-forward, on demand | +| `no_proxy` for the ERAG domain | all HTTP calls | env, set by the token/secrets step | + +All of the above are validated in a **single up-front access preflight** (before +any combination runs), so a missing credential or permission fails loudly and +early rather than halfway through a multi-minute rollout. + +## Execution flow (per combination) + +``` +preflight_check(config) # BEFORE ANY HEAVY WORK: config-level preconditions, once +for each deployment combination: # OUTER: costs a rollout + validate(combination) # cross-property constraints, fail fast + └─ for each property whose desired value changed: + apply(desired) # idempotent: write only if not is_satisfied + └─ for each plane touched: + wait_until_ready() # observed value == desired + └─ verify: for each property: + assert is_satisfied(read()) # verify via OBSERVED state + └─ snapshot = {dotted path: prop.read() for all props} # persist "what was tested" + └─ tokenizer = observed served model # -m: derived, never declared + └─ for each client combination: # INNER: costs one load test + run benchmark (existing scripts, argv rendered from the client knobs) + summarize # one row: knob columns (dotted paths) + TTFT/TPOT KPIs +``` + +**Preflight is separate from verification.** They fail at different times and mean +different things. Verification asserts that a *property* reached its desired value, +so it can only run after that property was applied and is inherently per-property. +`preflight_check()` asserts preconditions that belong to no property and that the +schema cannot express — whether a declared `client.question_file` names a readable +file, for instance: the schema validates it as a non-empty string, but whether that +string resolves to a file is a fact about the filesystem, not about the config's +shape. It runs **once**, before the first apply, when stopping is still free: every +check it makes is about the config and its environment, so nothing the sweep itself +does can change the answer, and repeating it per load test would only spend a +`kubectl` round trip to re-learn what it already knows. Each check is a named +function (`question_file_verify()`, `model_verify()`) called from that one entry +point rather than an inline `if`, so the flow says what is being asserted and there +is a single place a new precondition is added. + +**Paths inside a sweep config are anchored to the harness, not to the CWD.** A +relative `client.question_file` resolves against `pysweep_bench.py`'s directory, so +one config names the same corpus wherever it is launched from. Resolving against +the working directory — which is what `benchmark.py`'s bare `open()` does, and the +reason the runner hands it an absolute path — would let the same declared string +mean a different file per caller, while the summary CSV recorded only the string. +Two runs would then carry identical provenance and different inputs, which is the +unattributable-result failure this design exists to prevent. The summary still +records the *declared* value, not the resolved absolute path, so provenance shows +what the config asked for. + +The deployment configuration is applied and verified **once** per outer iteration +and then held still for every load scenario — which is both what keeps those +results comparable to each other and what keeps the rollout count at the number of +deployment combinations rather than the number of runs. The inner loop needs no +apply, no convergence wait and no verification, for the reasons in "Client knobs: +sweep dimensions with no plane". + +**Summarizing is part of the flow, not a separate tool.** The runner is the only +thing that knows which configuration produced which CSV — the per-request files +carry neither, and their names carry only what varied — so it writes the row while +it still holds both. That is also why the summary is rewritten after every run +rather than at the end: a sweep is hours long, and a table of what finished is +worth more than a complete one that a failed rollout prevents. Aggregation stays +lossless-by-default: the per-request CSVs are untouched and every row points back +to its own. + +**One output directory per sweep, cleared before the sweep starts.** `--summaries` +(default `./results`) holds `benchmark_summary_results.csv` and a +`per_case_results/` subdirectory, and both are wiped of the previous sweep's +artifacts first. The alternative — writing each run's CSV into the CWD and +accumulating across sweeps, which is what `benchmark.py` alone does — makes the two +halves of one result set independently deletable: a stale per-case CSV with no row +in the current summary is indistinguishable from a result of it, and a re-run +shorter than its predecessor leaves rows pointing at files it never overwrote. +Refusing to merge is a stronger guarantee than any naming scheme, because the +failure it prevents is misattribution, not collision. The wipe is confined to the +one file and the one subdirectory the harness owns, so the directory can hold other +things; it happens after the config is validated and the preflight has passed, so +a mistake that would have failed every run costs nothing. `result_file` is recorded relative to the summary +so the directory survives being copied off the benchmark host. + +## Design decisions + +- **The K8s plane has two owners, and pysweep drives both (decided).** Getting a + model benchmarked means (1) *serving* it and (2) *pointing the pipeline at it*, + and those live in different systems. Each half was decided separately: + - **Serving: delegate to `model-manager`.** It is the deployment team's own + actively-developed CLI and the tool this cluster was built with, so it already + encodes the coupled per-model decisions — runtime and engine version, + CPU/memory, NUMA and balloon placement, the `LLMInferenceService`, the gateway + route. Reimplementing that as CR patches would mean re-deriving all of it from + a catalog pysweep does not own, and drifting from it silently. Its `deploy` is + already idempotent (`kubectl diff --server-side`), which is exactly the + contract a `Property.apply` needs, and its `--dry-run` is side-effect free, + which is what lets both an e2e test and a preflight exercise the real code + path without touching the deployment. `properties/sub/model_manager.py` is a + deliberately thin wrapper: the single place that knows where the executable + lives and how its arguments are spelled, so a CLI change is a one-file fix + with unit tests that pin the argv. + - Trade-off accepted: a subprocess in an otherwise all-`kr8s` design, and + errors that arrive as text rather than as typed API failures. Owning a + second implementation of model serving is the worse trade. + - **Pointing the pipeline: `gmc-config` (Option B, decided).** The pipeline's + workloads are GMC-owned, so direct patches (Option A) are reverted by the + operator, and a full helm re-render per combination (Option C) is too heavy and + isn't a `kr8s` operation. Option B patches the knob *inside the `gmc-config` + ConfigMap* (the value GMC actually reads), which is durable and `kr8s`-native. + - `apply()` = edit the knob inside the relevant `gmc-config` key, then write + the ConfigMap back. **No `gmc-controller` restart** — the operator's + `configMapFilter` returns `true` for any ConfigMap change in the + namespaces it watches, so the write is itself the reconcile trigger + (verified live: the patch logs a `----RECONCILE REQUEST----` for + `gmc-config`/`system` and runs all ten reconcile steps). + - **Line-precise text edits, not a YAML round-trip.** The earlier plan said + "parse the embedded YAML properly, not `sed`". Implementation reversed + that: each `gmc-config` value is a rendered manifest that the operator + `Update`s onto the whole pipeline, and a parse/re-emit reformats it + wholesale. `properties/sub/llm_usvc_manifest.py` instead anchors on a + regex that must match **exactly once** and raises rather than editing when + it doesn't — bounded blast radius, byte-exact round-trip, both asserted + against a verbatim copy of the real manifest. That manifest contains + `LLM_MODEL_NAME` in two roles (the ConfigMap entry, and shell references + in the init container's probe script), so "exactly once" is load-bearing: + a looser anchor would break the readiness gate of every LLM pod. + - **The ordering between the two halves is not free.** The model must be + answering on the gateway *before* the pipeline is repointed, because the + replacement pods' init container refuses to become Ready until it is. So + `apply()` is: deploy, then patch `gmc-config`, then wait for the operator to + render it, then delete the pods. The unit tests assert that order explicitly + rather than trusting it to stay incidental. + - **A ConfigMap change is not always a rollout.** The LLM microservice consumes + the rendered ConfigMap through `envFrom` with no checksum annotation, so the + operator's update leaves the pod template byte-identical and Kubernetes starts + nothing; `envFrom` is resolved once at container start, so the running + processes would keep the old model indefinitely. Hence the explicit pod + deletion — a step that reads like a workaround and is actually the mechanism. + - **Three states, not two.** *declared* (`gmc-config`) → *rendered* + (`llm-usvc-config`) → *observed* (the pods' env). `read()`/`is_satisfied()` + return the last, never the ConfigMap (which is *intended*, not *observed*). + `declared()` exposes the first separately — `apply` needs it for idempotence, + since mid-rollout the pods still serve the old value and an observed-state + check alone would redeploy and restart the rollout on every retry. + - Trade-off accepted: a swap is slow — a weight download plus a pipeline + restart, so `wait_until_ready` budgets **3h** — acceptable because K8s knobs + are the sweep's **outer** loop and change rarely. +- **Kubernetes client: `kr8s`.** All K8s reads/patches go through `kr8s` objects + rather than shelling out to `kubectl`, keeping the "everything is a Python + object" model. Helm is deliberately avoided in the per-combination path. +- **Getters read observed state, never the spec we wrote.** Non-negotiable; it is + what makes the preflight meaningful. +- **Idempotent apply = read-then-write-if-different.** A reliable getter is a + prerequisite for a cheap setter — build getters first. +- **Auth is a factored-out token provider.** The Keycloak token dance + (`load_secrets.bash` + `generate_uat_to_file.sh`) becomes a reusable provider; + the preflight/check step is **side-effect free** (unlike today's `run.bash`, + which mutates realm timeouts as a side effect of "checking"). +- **YAML is schema-validated (Pydantic).** Catches typos in property names and + wrong value types before any rollout is triggered. +- **Every run persists the observed snapshot**, not the intended YAML. + +## Risks & mitigations + +| Risk | Mitigation | +|---|---| +| Convergence timing — spec set ≠ system ready | Split set / converged; getters read observed; explicit `wait_until_ready` | +| GMC operator reverts direct workload patches mid-sweep | Never patch the workload or the operator's rendered output; drive `gmc-config` (Option B), the value GMC reads | +| Combinatorial explosion of the sweep | Explicit combination strategy; expensive plane = outer loop, free client knobs = inner loop | +| A model swap that reimplements serving drifts from how the cluster was actually built | Delegate the deploy to the deployment team's `model-manager` CLI; pysweep owns only the pipeline's pointer to it, and observes the result | +| A ConfigMap update that starts no rollout leaves pods on the old value while every state pysweep can cheaply read says converged | `read()` execs into the containers for their effective env; `apply()` deletes the pods once the operator has rendered | +| Load parameters known only from the shell history of whoever ran it | Client knobs are **required** in the sweep config, logged per run, and a conflicting `--` flag is refused | +| Cross-property constraints (e.g. `TP_SIZE` divides device count; thread bind fits CPU limit) | Whole-combination `validate()` before apply | +| Token counts measured with a tokenizer that is not the served model's, making tokens/s incomparable | `-m` is not configurable at all: derived per combination from the **observed** served model (`LlmModel.read()`, mapped to a tokenizer repo id through model-manager's catalog), so it cannot drift from what is loaded; declaring it or passing it after `--` is refused, and an unreadable model aborts the sweep | +| Partial apply leaves dirty state for next combination | Reconcile *every* property each iteration; baseline snapshot/teardown (future) | +| Setter always writes → needless rollout | Idempotency via read-then-write-if-different | +| Auth token expiry / side effects | Token provider abstraction; side-effect-free checks | +| pysweep silently drifts from the deployment (renamed gmc-config keys, changed API path, changed workload kind/label) → benchmarks test the wrong config | Every property has an e2e test exercising `read`/`apply`/`converge` against a real deployment; drift fails the test, not the benchmark | + +## Future: a third plane + +Env-var / helm-values knobs (e.g. `VLLM_CPU_OMP_THREADS_BIND`, +`config_model_server_extra`) are neither instant (runtime API) nor a simple +`kubectl patch` rollout: the value lives in helm values *and* only takes effect +on the next pod start. This is a likely third plane, deferred for now. + +## Mapping from existing scripts + +| Existing | Plane | Property | +|---|---|---| +| `prepare_change_reranker.sh` (`top_n`) | Runtime API | `RerankerTopN` — **designed, not implemented** (`reranker.top_n`) | +| `prepare_change_retriever.sh` (`k`) | Runtime API | `RetrieverK` — **designed, not implemented** (`retriever.k`) | +| `prepare_change_max_tokens.sh` (`max_new_tokens`) | Runtime API | `MaxNewTokens` — **implemented** (`llms.max_new_tokens`) | +| `switch_llm_model.sh` (the served model) | K8s spec | `LlmModel` — **designed, not implemented** (`llms.model`), via `model-manager` + `gmc-config` | +| `run.bash` model-server replicas / CPU / memory reads | K8s spec | Not ported: these are now per-model facts in model-manager's catalog, so a sweep dimension over them would fight the tool that owns them. Sweep `llms.model` instead. | +| `load_secrets.bash` + `generate_uat_to_file.sh` | — | Bearer file minted by the runner, re-minted per run (`pysweep_bench.provision_benchmark_target`) | + +## TODO / open questions + +- [x] Decide combination strategy — **`product`** (cartesian product of all + list-valued properties; single-valued properties are fixed). +- [x] Decide K8s-plane source of truth — **`gmc-config` ConfigMap (Option B)**, + driven via `kr8s`; observed reads from the live workload/pod status. +- [x] Confirm whether the runtime API exposes a **read/GET** for each knob — + **yes**: `GET system_fingerprint/config?params_key=` returns + `{"values": {...}}` with the component's current arguments. Both runtime-API + properties read through it. +- [x] Confirm what serves the LLM and where — **not a GMC workload at all** on this + architecture: serving moved out to `LLMInferenceService` CRs + (`serving.kserve.io/v1alpha2`) in `llm-inference`, created by `model-manager`, + behind the Envoy AI gateway. What lives in the pipeline namespace (`chatqna`) + is the `llm-usvc` Deployment that *calls* it, and that is where the observed + model is read from. +- [ ] Port `RetrieverK` (`prepare_change_retriever.sh`) and `RerankerTopN` + (`prepare_change_reranker.sh`), the remaining runtime-API knobs from the + original scripts. diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md new file mode 100644 index 00000000..f2703be2 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -0,0 +1,460 @@ + + + +# pysweep + +Declarative configuration sweeps / benchmarking for the ChatQNA (Intel Enterprise +RAG) deployment. pysweep's core promise is that you always know **what +configuration was actually tested**: each tunable is modelled as a `Property` +that can `read` the deployment's observed state, `apply` a desired value, and +report whether the desired value `is_satisfied`. + +See [`DESIGN.md`](./DESIGN.md) for the full architecture (the `Property` / `Plane` +model, the two config planes, the combination strategy, and the authorization & +access requirements). This README covers **how to run the tests** and the +environment gotchas. + +## Layout + +| Path | What it is | +|---|---| +| `base.py` | `Property` interface + `Plane` enum (K8s-spec plane vs Runtime-API plane). | +| `config.py` | Pydantic-validated configs: `load_config()` / `SweepConfig` (+ the `deployment_combinations()` and `client_combinations()` cartesian `product` expansions) and `load_run_config()` / `RunConfig`. | +| `client_args.py` | Adapter mirroring `benchmark.py`'s CLI options as sweep knobs. Not properties — no plane, nothing to apply or read back; see below. | +| `pysweep_bench.py` | Sweep runner: load config → apply/converge/verify each deployment combination → run one load test per client combination, reusing `benchmark.py`. | +| `examples/sweep.yaml` | An example sweep config (`--sweep`): what to vary. | +| `examples/config.yaml` | An example run config (`--config`): how to run. | +| `authentication.py` | `KubernetesAccess` (side-effect-free RBAC preflight via `SelfSubjectAccessReview`), `load_build_config()` (the installed environment's config), `keycloak_helper()` (the maintained `KeycloakHelper`, for user tokens) and `client_token_lifespan()` (a sweep-long access-token lifespan for the UI client, restored afterwards). | +| `runtime_api.py` | `system_fingerprint` client. `HelperFingerprintClient` adapts the suite's `FingerprintApiHelper`; `PortForwardTransport` / `IngressTransport` cover deployments the helper can't reach. | +| `properties/max_tokens.py` | First property: `MaxNewTokens` (LLM `max_new_tokens`, Runtime-API plane). | +| `served_model.py` | `ServedModel`: reads the model the pipeline is **observed** to generate with, out of the running `llm-usvc` pods. Not a knob — the runner uses it to pick the benchmark's tokenizer. | +| `model_catalog.py` | Reader for the model-manager catalog (`models-rag.yaml` / `models.yaml`): maps a served model name to the HuggingFace repo id the benchmark's tokenizer needs. | +| `paths.py` | Where the installed environment's files are looked for (deploy root derived from the checkout's location). | + +Only the modules directly under `properties/` define knobs. A file there means a +`Property` subclass bound to a YAML leaf in `config.py`. + +The **e2e tests live with the rest of the validation suite** at +`src/tests/e2e/validation/pysweep/`, not inside this package. That keeps them in +the shared allure report and lets them reuse the suite's session fixtures +(`k8s_helper`, `keycloak_helper`, `fingerprint_api_helper`). It also avoids a +directory named `tests` shadowing the top-level `tests` package. + +## Why these tests exist (DESIGN.md objective 6) + +Every property has an e2e test that exercises `read` / `apply` / `is_satisfied` +against the **live deployment**. If the deployment's contract drifts (an endpoint +path, a payload shape, a `values` response key, an RBAC grant), the test +fails **here** — before a benchmark silently runs against the wrong +configuration. When the cluster or the API is unreachable the tests `skip` +(runtime `pytest.skip`, not a static marker), so they degrade gracefully in +environments without a live ChatQNA install. + +## Sweep config (YAML) + +A sweep is declared in YAML and validated by `config.load_config()`: + +```yaml +llms: # DEPLOYMENT knobs: optional, outer loop + max_new_tokens: [128, 256, 512] # a list -> one product dimension + +client: # CLIENT knobs: required, inner loop + question_file: ../questions-short.csv # relative to pysweep_bench.py, not the CWD + concurrency: [1, 16, 128] # a list -> the innermost dimension + duration: 3m + worker_startup_delay: 0s + # no 'tokenizer': -m is derived from the served model (see below) + failures_allowed: 200 + input_tokens: 128 + warmup_requests: 1 +``` + +- A **single value** is fixed across the sweep; a **list** contributes one + dimension to a cartesian `product` (see DESIGN.md). +- Each YAML leaf is **bound to its implementation on the field itself** — a + `Property` class for deployment knobs + (`Annotated[..., PropertyBinding(MaxNewTokens)]`, so `llms.max_new_tokens` + statically resolves to `MaxNewTokens`) or a `benchmark.py` flag for client knobs + (`Annotated[..., CONCURRENCY]`). No name-string registry to drift either way. +- **Every deployment knob is optional.** Omit a key to leave that knob untouched. +- **Every client knob is required** (except `server` / `bearer_file`) — see below. +- **Any deviation from the schema raises `ConfigError`**: an unknown key + (`extra="forbid"`), a wrong type, an out-of-range value (`max_new_tokens` is a + `PositiveInt`, `duration` must match ``), or malformed YAML — all + *before* a sweep starts. + +```python +from tests.e2e.benchmarks.chatqna.pysweep.config import load_config + +cfg = load_config("path/to/sweep.yaml") +for combination in cfg.deployment_combinations(): # deployment: apply + verify + for setting in combination: # setting.path, setting.property_cls, setting.value + ... + for client_combination in cfg.client_combinations(): # then load, per scenario + for setting in client_combination: # setting.path, setting.arg, setting.value + ... +``` + +Adding a deployment knob = add one optional, `PropertyBinding`-annotated field to +the relevant section model in `config.py` (and ship the property's e2e test). +Adding a client knob = add a `ClientArg` for the new `benchmark.py` option and one +annotated field on `ClientConfig`. + +### `client:` — the load generator's parameters + +Every option of `benchmark.py` is mirrored in `client_args.py`, and each one that is +genuinely a choice appears as a `client:` knob. They behave like knobs where it +matters — each value is a distinct test scenario and they expand into a `product` — +but they are deliberately **not** `Property` instances and have **no `Plane`**: + +| A `Property` does | A client knob | +|---|---| +| `apply()` mutates the deployment | Nothing to mutate; the value is an argument to a process about to start. | +| `wait_until_ready()` waits out a rollout / reconcile | Nothing to wait for. | +| `read()` returns **observed** state from the live system | Nothing to observe. A "read" could only echo the value pysweep already holds — exactly the spec-read the `Property` contract forbids, which would make the preflight tautological. | + +Modelling them as a third `Plane` would have required a `Property` whose three +methods are all vacuous, quietly weakening the invariant that makes "what was +tested" trustworthy for the knobs that *do* have observable state. So they get +their own adapter instead, and still receive schema validation, product expansion, +result-file naming, and a recorded snapshot. + +**They are required, unlike deployment knobs.** An omitted deployment knob means +"leave it alone" — a meaningful, observable state. An omitted client knob has no +such reading: the load test would run anyway on `benchmark.py`'s defaults (`-c 32`, +`-d 30m`, `-x 0`) and the result CSV records none of it. Requiring them keeps every +result attributable to a configuration someone wrote down, and makes the sweep +config the single source of truth — a client flag passed after `--` that the config +already declares is **rejected**, rather than silently overriding a sweep +dimension. + +`server` (`-s`) and `bearer_file` (`-b`) are optional exceptions: pysweep +auto-provisions both (see "Running a sweep"), and they are single-valued, because +one endpoint serves the whole sweep. + +**There is no `tokenizer` key, though `benchmark.py` has `-m`.** It is not a knob: +[the benchmark README](../README.md) requires it to be the eRAG LLM model, because +it builds the tokenizer that produces the `input_tokens` / `output_tokens` columns +and pads questions to `client.input_tokens`. Those counts only describe what the +deployment tokenized if they come from that model's own tokenizer — any other one +still yields numbers, just on a basis nobody chose, and tokens/s then compares +against nothing. So the value is fully determined by the model being served, and +the only thing declaring it could express is a mismatch. + +pysweep fills it in instead: after each deployment combination converges, +`resolve_tokenizer()` takes the **observed** model — `ServedModel.read()` against +the running pipeline pods — and maps it to a HuggingFace repo id through the model catalog +(`model_catalog.tokenizer_for()`), because the two names differ: the pipeline +serves the catalog name `llama3-8b-awq`, while `AutoTokenizer.from_pretrained` +needs `casperhansen/llama-3-8b-instruct-awq`. The result is appended as `-m` for +every load test in that combination's inner loop, resolved once per combination +since the deployment is held still throughout it. Declaring `client.tokenizer` is +an unknown-key error, and `-m` after `--` is refused. If the served model cannot be +read, or cannot be mapped to a repo id, the sweep aborts rather than falling back +to `benchmark.py`'s default (an embedding model's tokenizer). + +## Iteration order + +The two products are **nested**, not merged into one: + +``` +for each deployment combination: # outer — costs a rollout + apply / wait / verify (once) + tokenizer = observed served model # -m, derived once per combination + for each client combination: # inner — costs one more load test + run benchmark.py + append a row to benchmark_summary_results.csv # knobs + TTFT/TPOT KPIs +``` + +Within the deployment product, `deployment_combinations()` sorts K8s-plane knobs first so +they vary slowest (`itertools.product` varies its leftmost dimension slowest); +runtime-API knobs vary faster. Client knobs are innermost by construction — the +nesting puts them there, so the ordering is structural rather than something a +sort key has to keep getting right. + +The cost gradient is the reason: a deployment knob reconfigures the running +pipeline (`max_new_tokens` is one API call; a K8s-plane knob is a rollout), while a +concurrency change is free. So each deployment configuration +is established and verified **once**, then held still while every load scenario +runs against it — which is also what makes those results comparable to each other. +The example config's `2 max_new_tokens x 3 concurrency` is 6 load tests behind +2 applies, not 6. + +## Running a sweep + +`pysweep_bench.py` runs the ChatQNA benchmark once per (deployment, client) +combination pair. For each deployment combination it applies the declared +properties, waits for convergence, verifies the **observed** state, records the +snapshot of what was tested, then reuses `benchmark.py` unchanged to run one load +test per client combination. + +There are two separate configs: + +| Flag | File | Declares | +|---|---|---| +| `--sweep` (required) | `examples/sweep.yaml` | **What to vary** — the knobs and their values; expands into combinations. | +| `--config` (optional) | `examples/config.yaml` | **How to run** — harness behaviour; never expands into combinations. | + +`--summaries` (optional, default `./results`) is the **directory** a sweep writes +into — see "Where the results go" below. It is cleared of the previous sweep's +artifacts before this one starts. + +**No preparation steps are required.** A sweep needs only `--sweep` — the load +parameters are declared in it, so nothing after `--` is necessary: + +```bash +PYTHONPATH=src python -m tests.e2e.benchmarks.chatqna.pysweep.pysweep_bench \ + --sweep src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml \ + --config src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml +``` + +Run it from anywhere — the repo root above, or any other directory. Paths *inside* +a sweep config are resolved against `pysweep_bench.py`'s directory rather than the +working directory, so a config means the same thing regardless of where it is +launched from. `--sweep` / `--config` / `--summaries` are ordinary command-line +paths and behave normally (relative to the CWD). + +Arguments after `--` are still forwarded to `benchmark.py`, but a flag the sweep +config already declares raises a `SweepError` before anything is applied, and `-m` +is refused outright (it is derived from the served model). `-s` / `-b` are the +usable case: passing them bypasses auto-provisioning when the config leaves them +out. + +pysweep provisions the things the raw `benchmark.py` makes you prepare by hand: + +| Previously manual | Now | +|---|---| +| Look up the ChatQNA URL and pass `-s` | With no `-s`, targets `https:///api/v1/chatqna`, the domain read from the installed environment's build config. | +| Generate a UAT and pass `-b uat.txt`, or every worker logs `no bearer, quitting` | With no `-b`, mints one distinct Keycloak user token per worker (for the widest concurrency in the sweep) into a temporary bearer file. The tokens are re-minted before every run, and for the duration of the sweep the UI client's access-token lifespan is set to 1h (`SWEEP_TOKEN_LIFESPAN_S`, an arbitrary value that only has to outlast one run; the realm default of 5 min does not), then restored. A supplied `-b` is never re-minted, so its tokens must outlive the whole sweep. | +| Results of each combination overwrote one another (same timestamped CSV) | Each run writes `per_case_results/bench_-_..._-.result.csv`. | +| An unreachable endpoint still exited `0` with an empty CSV | A run that records **zero** result rows is reported as a failure (non-zero exit). | +| Load parameters lived only in whatever shell command produced the CSV | Declared in `--sweep` and logged per run alongside the observed deployment state. | +| Comparing runs meant `parse.py` over a directory of headerless CSVs, with the configuration recoverable only from filenames | One `benchmark_summary_results.csv`: a row per run, a column per declared knob (dotted paths), TTFT/TPOT mean and p90. | +| `-m` had to be kept in step with the served model by hand, and defaulted to an embedding model's tokenizer if forgotten | Derived per combination from the model the LLM engine is observed to serve, so token counts always come from that model's tokenizer. | + +Supplying `-s` / `-b` (on the command line or as `client.server` / +`client.bearer_file`) disables the matching auto-provisioning. + +Result filenames carry the knobs that **vary** in this sweep, not every declared +knob: naming them all can overflow the 255-byte filename limit once an HF repo id +and a question-file path are in there. The full configuration of each run — the +observed deployment snapshot, the resolved tokenizer, and the load parameters — is +logged instead. + +### Where the results go (`--summaries`) + +Everything a sweep writes goes under one directory, `--summaries` (default +`./results`, relative to the CWD like any other command-line path): + +``` +results/ + benchmark_summary_results.csv # the sweep's table: one row per run + per_case_results/ # one per-request CSV per run + bench_max_new_tokens-128_concurrency-1_input_tokens-128.result.csv + bench_max_new_tokens-128_concurrency-16_input_tokens-128.result.csv + ... +``` + +The directory is created if missing (parents included), and **the previous +sweep's artifacts in it are deleted before this one starts**: the summary file is +removed and `per_case_results/` is emptied. A sweep's outputs only mean anything +as a set — the summary indexes the per-case CSVs, and a per-case CSV means nothing +without the row saying what produced it — so merging two sweeps into one directory +would leave stale CSVs that read exactly like results of the current run. Nothing +else under the directory is touched, so pointing `--summaries` at a directory that +also holds a copy of the sweep YAML or someone's plots loses none of it. The wipe +happens after the config is validated and the preflight has passed, so a typo in +the YAML or a missing question file does not cost you the previous results. + +### The summary CSV + +Each `bench_*.result.csv` is one row per *request* with no header and no record +of the configuration, so a sweep also writes a single summary table +(`benchmark_summary_results.csv`, `results.py`): + +``` +llms.max_new_tokens,client.concurrency,client.duration,...,requests,mean_ttft,p90_ttft,mean_tpot,p90_tpot,served_model,error,result_file +128,1,10m,...,412,0.284192,0.41133,0.021975,0.02698,casperhansen/llama-3-8b-instruct-awq,0,per_case_results/bench_max_new_tokens-128_concurrency-1_input_tokens-128.result.csv +128,16,10m,...,3907,1.10442,1.83206,0.0344,0.04102,casperhansen/llama-3-8b-instruct-awq,0,per_case_results/bench_max_new_tokens-128_concurrency-16_input_tokens-128.result.csv +``` + +One row per run. The knob columns come first, named by the **dotted config path** +the sweep YAML used (`client.input_tokens` for `client: input_tokens:`), so a +column maps back to the config with no lookup table. *Every* declared knob gets a +column, not only the varying ones — a summary that dropped the constants would not +say what the numbers were measured under, and including them makes two sweeps' +summaries concatenable. Deployment values are the **observed** read-backs; client +values are the declared ones (there is nothing to observe — they are arguments to +a process). `server` / `bearer_file` are excluded as connection plumbing. + +Then the KPIs, in seconds: + +| Column | Meaning | +|---|---| +| `requests` | Successful requests the statistics are over. A p90 over four requests is a number, not a measurement — this is what licenses reading the rest. | +| `mean_ttft`, `p90_ttft` | **Time to first token**: `first_chunk` as `benchmark.py` records it — request issued to first streamed chunk. Prefill plus all queueing ahead of it, so this is the KPI that moves with concurrency. | +| `mean_tpot`, `p90_tpot` | **Time per output token**: `(end_to_end - ttft) / (output_tokens - 1)`, the mean inter-token gap during decode. | +| `served_model`, `error`, `result_file` | The **tokenizer repo id** the tokens were counted with (resolved from the observed served model's catalog name), the run's exit code, and the pointer back to the per-request CSV — relative to the summary itself, so the whole directory can be copied off the benchmark host with its pointers intact. | + +TPOT excludes the first token from **both** the time and the token count, because +its cost is TTFT. `parse.py`'s `next_token_lat` divides by `output_tokens` +instead, which charges decode for a token it did not generate — under a percent at +128 output tokens, material at 8. p90 is linearly interpolated (numpy/pandas' +default method), so it agrees with `parse.py`'s figures. + +The file is rewritten after every run, so a sweep killed at hour three — or a +model rollout that fails midway — still leaves a complete, valid table of what it +got through. The per-request CSVs are untouched: anything the four KPIs do not +answer (distribution shape, drift within a run, the tail past p90) is still there, +and `result_file` is how you get to it. + +### Run config (`--config`) + +Validated by `config.load_run_config()`, with the same strictness as the sweep +config — an unknown key or wrong type raises `ConfigError`. Omitting `--config` +uses the defaults. + +```yaml +display_kubernetes_client_logs: false # default: false +``` + +- **`display_kubernetes_client_logs`** — whether the kr8s/httpx Kubernetes + client's own output is shown. The port-forward carrying the load test produces + two kinds of noise: one `101 Switching Protocols` line *per benchmark request* + (a websocket per forwarded connection), and a multi-frame + `ConnectionResetError` traceback on teardown (a race inside kr8s — the + requests themselves still return 200). Both are hidden by default; genuine + warnings and errors still surface. Set `true` to debug cluster connectivity. + +`benchmark.py`'s own output (its per-worker log lines and parsed-args dump) is +always shown — it is the benchmark's primary output and pysweep does not filter +it. + +A deployment combination whose observed state does not match the desired value +aborts with a `SweepError` rather than benchmarking the wrong configuration — +including all the client combinations that would have run under it. The +fingerprint transport is chosen by `PYSWEEP_FINGERPRINT_TRANSPORT` (see below). + +### What still has to be true + +These are environment facts, not steps to run: + +- **A kubeconfig** the process can find (`~/.kube/config` or `KUBECONFIG`), with + the RBAC in `REQUIRED_ACCESS`. Everything else is derived from the cluster. +- **`PYTHONPATH=src`** so the `tests.e2e...` absolute imports resolve. +- **The served model's tokenizer** must be loadable, since pysweep counts tokens + with it (see above). Gated repos (e.g. `meta-llama/Llama-3.1-8B-Instruct`) need + `HF_TOKEN` or a warm HF cache — so a sweep over a gated model needs the token even + though pysweep itself never downloads weights. +- **A model catalog**, to map the served model to its tokenizer. Found via + `PYSWEEP_MODEL_CATALOG`, else `MM_CONFIG` (which the deployment's + `model-manager` wrapper exports), else the installed environment's + `env/local/models-rag.yaml` (the RAG pipeline's catalog), then + `env/local/models.yaml`, then this repo's shipped `deployment/models.yaml`. + Prefer the deployment's own file: they drift, and only it lists the names the + cluster was built from. +- Running **off-cluster** additionally needs the `no_proxy` / kubeconfig + `server:` handling described under "Environment gotchas". + +### Preflight checks + +Preconditions that the schema cannot express are checked by `preflight_check()`, which +raises `PreflightError` (a `SweepError`) naming the knob, the declared value, and +the path or catalog it was checked against. It runs **once**, before any property +is applied, any rollout triggered, or any port-forward opened: a fault that would +doom every run is then reported while stopping costs nothing. Without it, a +mistyped corpus path surfaces only after the first deployment combination has +been applied. + +Once is enough because every check is about the config and its environment, not +about a run: nothing the sweep does between two load tests can change the answer. + +Each check is its own named function, called from `preflight_check()`, so what is being +asserted is named rather than inlined and a new precondition has one place to go. +In increasing cost order: + +| Check | What it asserts | +|---|---| +| `question_file_verify()` | Every declared `client.question_file` (the knob is sweepable, so a config may name several) resolves to a readable file. A stat per corpus. | + +## Requirements + +Use the validation suite's requirements — no separate set: + +``` +src/tests/e2e/validation/requirements.txt +``` + +Key pins pysweep relies on: `kr8s==0.20.15` (Kubernetes client + port-forward), +`pydantic==2.13.4` (config validation), `requests==2.33.1`, `pytest==9.0.3`, +`allure-pytest==2.15.3`. + +## Running the tests + +pysweep's tests run **as part of the e2e validation suite**, the normal way: + +```bash +cd src/tests +tox -e e2e -- -k pysweep +``` + +`-k pysweep` selects just the pysweep tests; drop it to run the whole suite. The +shared conftest's two options both default to a co-located deployment +(`--build-config-dir`, default `../../../../env/local`, from which it reads +`config.yaml` — it also drives the `fingerprint.enabled` skip — and +`--credentials-file`), so on the deployment host no flags are needed. Elsewhere: + +```bash +tox -e e2e -- -k pysweep \ + --build-config-dir=/env/local \ + --credentials-file=/default_credentials.txt +``` + +The unit tests — every `*_unit.py` module, which is the majority of them — need +neither a cluster nor a deployment config, and have their own environment: + +```bash +cd src +tox -e pysweep_unit_tests +``` + +Without tox (venv with the requirements installed, from the repo root): + +```bash +PYTHONPATH=src python -m pytest \ + --build-config-dir=/env/local \ + --credentials-file=/default_credentials.txt \ + src/tests/e2e/validation/pysweep +``` + +## Environment gotchas + +Running against a remote cluster **from a local machine** (no SSH per run): + +- **Kubeconfig / `KUBECONFIG`.** Point at a kubeconfig whose `server:` is the + node's routable API endpoint, not `127.0.0.1`. On the benchmark cluster the + node IP `10.211.187.170:6443` is directly routable and its serving cert SANs + include that IP, so no SSH tunnel is needed — just rewrite the server URL. +- **`no_proxy` needs the ERAG domain too** when the corporate proxy is set, including + on the cluster node itself: the load test and the Keycloak token requests go to + `https://` and its `keycloak.` subdomain, and the proxy answers + those with `504`. Add `solutions.ai,.solutions.ai` (your `base_domain_name`) to + `no_proxy` / `NO_PROXY`. +- **`no_proxy` needs the literal IP.** The corporate proxy + (`proxy-dmz.intel.com:912`) intercepts cluster traffic, and `httpx`/`kr8s` do + **not** honour a CIDR in `no_proxy` (`10.211.0.0/16` is ignored). Add the + literal node IP: `export no_proxy="$no_proxy,10.211.187.170"` (and + `NO_PROXY` likewise). Without this you get `403`s from the proxy. +- **`PYTHONPATH=src`** so the absolute imports (`tests.e2e...`) resolve, matching + the rest of the suite. +- **`ERAG_DOMAIN_NAME`** (default `erag.com`) is used by the token provider / + ingress transport. + +### Fingerprint API transport + +The `fingerprint_client` fixture prefers the suite's ingress-based +`FingerprintApiHelper`. On deployments where the `system_fingerprint` API has +**no ingress route** (the benchmark cluster returns `404` on `erag.com`), it +automatically falls back to a **kr8s port-forward** to `fingerprint-svc:6012` in +the `fingerprint` namespace. Pod-locally the gateway's auth is bypassed, so the +port-forward path sends no token. If neither path reaches the API the test skips. diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/__init__.py new file mode 100644 index 00000000..7f7470e0 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/__init__.py @@ -0,0 +1,8 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""pysweep — declarative configuration sweeps for ChatQA benchmarks. + +See DESIGN.md for the architecture (Property / Plane model, two planes, +authorization & access requirements). +""" diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py b/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py new file mode 100644 index 00000000..5c926e6c --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py @@ -0,0 +1,386 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Authorization & access for pysweep. + +Three concerns, each the smallest thing that lets pysweep run outside pytest: + +- :class:`KubernetesAccess` — verifies, **up front and without mutating the + cluster**, that the current kubeconfig identity can perform every operation a + sweep needs. It uses ``SelfSubjectAccessReview``, which asks the API server + "am I allowed to do X?" without doing X, so a missing permission fails loudly + before the first rollout rather than halfway through a multi-hour product. + +- :func:`load_build_config` — populates + :data:`tests.e2e.validation.buildcfg.cfg` from the installed environment's + YAML. The maintained helpers (``KeycloakHelper``, ``FingerprintApiHelper``) + read the domain and routing mode from that dict, and under pytest it is + ``conftest.pytest_configure`` that fills it. pysweep has no pytest, so it does + the same load itself — deliberately reading the same three files in the same + order, so a sweep and the e2e suite cannot end up disagreeing about which + cluster they are talking to. + +- :func:`keycloak_helper` — builds the maintained + :class:`~tests.e2e.helpers.keycloak_helper.KeycloakHelper`. pysweep does + **not** implement token minting: that helper already does the password grant, + the required-actions dance, and the credentials-file lookup, and it is kept in + step with the deployment. Duplicating it here is how the two would drift. + +- :func:`client_token_lifespan` — for the duration of a sweep, lengthens the + access tokens Keycloak issues to the ERAG UI client (see + :data:`SWEEP_TOKEN_LIFESPAN_S`), then restores the client's previous setting. +""" + +import logging +import os +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path + +import kr8s +import requests +import urllib3 +import yaml +from kr8s.objects import APIObject + +from tests.e2e.helpers.k8s_helper import K8sHelper +from tests.e2e.helpers.keycloak_helper import KeycloakHelper +from tests.e2e.validation.buildcfg import cfg +from tests.e2e.validation.constants import VITE_KEYCLOAK_CLIENT_ID, VITE_KEYCLOAK_REALM + +from .paths import deploy_roots, is_dir, is_file + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +logger = logging.getLogger(__name__) + +# Kubernetes namespaces pysweep touches (see DESIGN.md). +PIPELINE_NAMESPACE = "chatqna" +INFERENCE_NAMESPACE = "llm-inference" +FINGERPRINT_NAMESPACE = "fingerprint" +KEYCLOAK_NAMESPACE = "keycloak" + +# The installed environment's config directory, mirroring the e2e suite's +# --build-config-dir default. Overridable so a sweep can be run against a +# different environment without editing anything. +BUILD_CONFIG_DIR_ENV_VAR = "PYSWEEP_BUILD_CONFIG_DIR" +BUILD_CONFIG_FALLBACKS = tuple(str(root / "env" / "local") for root in deploy_roots()) +# Same files, same order as tests/e2e/conftest.py — later files win on conflict. +BUILD_CONFIG_FILES = ("global_config.yaml", "config.erag.yaml", "config.inference.yaml") + + +# Access-token lifespan pysweep gives the ERAG UI client while a sweep runs. +# +# ARBITRARY VALUE: 1h has no meaning beyond being comfortably longer than one load +# test. The tokens are re-minted before every run, so they only have to outlive a +# single run (client.duration plus warmup), not the whole sweep; the realm default +# (5 min) does not even cover one 15m run, and each benchmark worker reads its +# token once, when the run starts. Raise it if a run's duration gets near it. +SWEEP_TOKEN_LIFESPAN_S = 3600 +# Keycloak's per-client override of the realm's access-token lifespan. An empty +# value means "inherit the realm setting", which is what an unset client has. +CLIENT_TOKEN_LIFESPAN_ATTRIBUTE = "access.token.lifespan" +KEYCLOAK_ADMIN_TIMEOUT = 30 + + +class AccessError(Exception): + """Raised when a required cluster permission is missing or the API is unreachable.""" + + +class BuildConfigError(Exception): + """Raised when the installed environment's build configuration cannot be loaded.""" + + +class KeycloakConfigError(Exception): + """Raised when the ERAG UI client cannot be found or reconfigured in Keycloak.""" + + +@dataclass(frozen=True) +class RequiredAccess: + """One RBAC permission pysweep needs, expressed for SelfSubjectAccessReview.""" + + verb: str + resource: str + namespace: str + group: str = "" + reason: str = "" + + def describe(self) -> str: + grp = f"{self.group}/" if self.group else "" + return f"{self.verb} {grp}{self.resource} in ns/{self.namespace}" + + +@dataclass +class AccessCheckResult: + """Outcome of a single access check.""" + + required: RequiredAccess + allowed: bool + reason: str = "" + + +# The full set of permissions pysweep requires. Keeping this explicit means the +# access preflight names precisely which permission is missing, and reading the +# list is the fastest way to see everything a sweep can touch. +REQUIRED_ACCESS = [ + # The served model, read back to pick the tokenizer (served_model.py). + RequiredAccess("list", "pods", PIPELINE_NAMESPACE, reason="locate the llm-usvc replicas"), + RequiredAccess("create", "pods/exec", PIPELINE_NAMESPACE, reason="read the pods' effective LLM_MODEL_NAME"), + RequiredAccess( + "get", "llminferenceservices", INFERENCE_NAMESPACE, + group="serving.kserve.io", reason="observed model readiness", + ), + # Runtime-API plane, reached by port-forwarding to fingerprint-svc. + RequiredAccess("list", "pods", FINGERPRINT_NAMESPACE, reason="locate fingerprint-svc endpoints"), + RequiredAccess( + "create", "pods/portforward", FINGERPRINT_NAMESPACE, + reason="port-forward the fingerprint API", + ), + # Keycloak admin password: token minting and the sweep-long token lifespan. + RequiredAccess("get", "secrets", KEYCLOAK_NAMESPACE, reason="Keycloak admin password for token minting"), +] + + +class _SelfSubjectAccessReview(APIObject): + """Minimal kr8s binding for authorization.k8s.io SelfSubjectAccessReview. + + Creating one is a read-only authorization probe: it asks the API server + "am I allowed to do X?" without performing X, so the access preflight never + mutates the cluster. + """ + + kind = "SelfSubjectAccessReview" + version = "authorization.k8s.io/v1" + endpoint = "selfsubjectaccessreviews" + plural = "selfsubjectaccessreviews" + singular = "selfsubjectaccessreview" + namespaced = False + + +class KubernetesAccess: + """Verifies the cluster is reachable and the identity has the needed RBAC.""" + + def __init__(self, k8s_helper: K8sHelper | None = None): + # Reuse the maintained k8s helper for all ordinary cluster access. + self.k8s = k8s_helper or K8sHelper() + + def ensure_reachable(self) -> None: + """Confirm the configured kubeconfig can actually reach the API server.""" + try: + # Cheapest authenticated call that proves connectivity + credentials. + api = kr8s.api() + api.version() + except Exception as exc: # noqa: BLE001 - surfaced as a clear AccessError + raise AccessError( + "Cannot reach the Kubernetes API server. Check KUBECONFIG / the " + "configured context points at a running cluster.\n" + f"Underlying error: {exc}" + ) from exc + + def check(self, required: RequiredAccess) -> AccessCheckResult: + """Run a single SelfSubjectAccessReview for one required permission. + + ``pods/exec`` and ``pods/portforward`` are subresources; the API expects + them split into resource + subresource rather than as one slashed name. + """ + resource, _, subresource = required.resource.partition("/") + attributes = { + "namespace": required.namespace, + "verb": required.verb, + "group": required.group, + "resource": resource, + } + if subresource: + attributes["subresource"] = subresource + + review = _SelfSubjectAccessReview({"spec": {"resourceAttributes": attributes}}) + review.create() + # APIObject.status raises KeyError if the server returned no status; + # read from raw defensively. + status = dict(review.raw.get("status", {}) or {}) + allowed = bool(status.get("allowed", False)) + reason = status.get("reason", "") or ("denied" if not allowed else "") + return AccessCheckResult(required=required, allowed=allowed, reason=reason) + + def verify(self, raise_on_denied: bool = True) -> list[AccessCheckResult]: + """Verify every required permission up front. + + Returns the per-permission results. With ``raise_on_denied`` (default) + it raises :class:`AccessError` listing exactly which permissions are + missing, so the sweep fails before any combination runs. + """ + self.ensure_reachable() + + results = [self.check(req) for req in REQUIRED_ACCESS] + denied = [r for r in results if not r.allowed] + if denied and raise_on_denied: + lines = "\n".join( + f" - {r.required.describe()} ({r.required.reason})" + + (f" [{r.reason}]" if r.reason else "") + for r in denied + ) + raise AccessError( + "The current kubeconfig identity is missing permissions pysweep " + f"requires:\n{lines}" + ) + return results + + +def build_config_dir() -> Path: + """Return the installed environment's config directory, or raise.""" + configured = os.getenv(BUILD_CONFIG_DIR_ENV_VAR) + if configured: + path = Path(configured) + if not is_dir(path): + raise BuildConfigError( + f"{BUILD_CONFIG_DIR_ENV_VAR}={configured!r} is not a directory." + ) + return path + + for candidate in BUILD_CONFIG_FALLBACKS: + path = Path(candidate) + if is_dir(path): + return path + + raise BuildConfigError( + "Cannot find the deployment's build configuration directory. Set " + f"{BUILD_CONFIG_DIR_ENV_VAR} to the env// directory holding " + f"{list(BUILD_CONFIG_FILES)}; tried {list(BUILD_CONFIG_FALLBACKS)}." + ) + + +def load_build_config(directory: str | Path | None = None) -> dict: + """Load the deployment's config into the shared ``cfg`` dict and return it. + + Mutating the module-level ``cfg`` rather than returning a private copy is not + incidental — it is how the maintained helpers get configured, since they read + that dict at construction time. Under pytest the same dict is filled by + ``conftest.pytest_configure``; calling this when it is already populated is + harmless and idempotent. + + Raises :class:`BuildConfigError` if none of the expected files is present, or + if the loaded config carries no ``base_domain_name`` — without that the + helpers would silently build URLs against ``https://None`` and every request + would fail with a DNS error instead of a readable message. + """ + resolved = Path(directory) if directory is not None else build_config_dir() + + loaded: list[str] = [] + for filename in BUILD_CONFIG_FILES: + path = resolved / filename + if not is_file(path): + continue + try: + content = yaml.safe_load(path.read_text()) + except OSError as exc: + raise BuildConfigError(f"Cannot read '{path}': {exc}") from exc + except yaml.YAMLError as exc: + raise BuildConfigError(f"'{path}' is not valid YAML: {exc}") from exc + if content: + cfg.update(content) + loaded.append(filename) + + if not loaded: + raise BuildConfigError( + f"No build configuration found in '{resolved}' (looked for " + f"{list(BUILD_CONFIG_FILES)})." + ) + if not cfg.get("base_domain_name"): + raise BuildConfigError( + f"Build configuration in '{resolved}' has no 'base_domain_name'; the " + "deployment's domain is needed to reach its APIs." + ) + logger.debug("Loaded build configuration from %s: %s", resolved, loaded) + return cfg + + +def keycloak_helper( + credentials_file: str | None = None, k8s_helper: K8sHelper | None = None +) -> KeycloakHelper: + """Build the maintained :class:`KeycloakHelper` for this deployment. + + ``credentials_file`` defaults to the helper's own + ``default_credentials.txt`` lookup, which is where the installer writes the + ERAG users' passwords — so on an installed box no argument is needed. + + :func:`load_build_config` is called first because the helper reads the domain + and routing mode from ``cfg`` in its constructor; building it against an + empty ``cfg`` would bake in an unusable auth URL. + """ + load_build_config() + return KeycloakHelper(credentials_file, k8s_helper or K8sHelper()) + + +def _client_url(helper: KeycloakHelper) -> str: + """Admin URL of the ERAG UI client (the one user tokens are minted for).""" + base = f"{helper.erag_auth_domain}/admin/realms/{VITE_KEYCLOAK_REALM}/clients" + response = requests.get( + base, + params={"clientId": VITE_KEYCLOAK_CLIENT_ID}, + headers={"Authorization": f"Bearer {helper.admin_access_token}"}, + verify=False, # self-signed deployment certs, as in KeycloakHelper + timeout=KEYCLOAK_ADMIN_TIMEOUT, + ) + response.raise_for_status() + clients = response.json() + if not clients: + raise KeycloakConfigError( + f"Client '{VITE_KEYCLOAK_CLIENT_ID}' not found in realm '{VITE_KEYCLOAK_REALM}'." + ) + return f"{base}/{clients[0]['id']}" + + +def _set_client_attribute(helper: KeycloakHelper, url: str, name: str, value: str) -> str: + """Set one client attribute; return its previous value (``""`` if unset). + + The client is read back and PUT whole, because Keycloak's client PUT takes a + full representation. An admin token is fetched per call: the restore runs + after a sweep that lasts hours, long past any token fetched at the start. + """ + headers = {"Authorization": f"Bearer {helper.admin_access_token}"} + response = requests.get( + url, headers=headers, verify=False, timeout=KEYCLOAK_ADMIN_TIMEOUT + ) + response.raise_for_status() + client = response.json() + attributes = client.setdefault("attributes", {}) + previous = attributes.get(name, "") + attributes[name] = value + response = requests.put( + url, json=client, headers=headers, verify=False, timeout=KEYCLOAK_ADMIN_TIMEOUT + ) + response.raise_for_status() + return previous + + +@contextmanager +def client_token_lifespan(helper: KeycloakHelper, seconds: int = SWEEP_TOKEN_LIFESPAN_S): + """Make the ERAG UI client's access tokens last ``seconds`` inside the block. + + A per-client override, so nothing else in the realm changes. The previous + value is restored on exit, including when the sweep fails; ``""`` restores + "inherit from the realm". Restoring is best effort: a failure is logged, not + raised, so it cannot hide the error that ended the sweep. + """ + url = _client_url(helper) + previous = _set_client_attribute( + helper, url, CLIENT_TOKEN_LIFESPAN_ATTRIBUTE, str(seconds) + ) + logger.info( + "Set %s access-token lifespan to %ss for the sweep (was %s).", + VITE_KEYCLOAK_CLIENT_ID, seconds, previous or "the realm default", + ) + try: + yield + finally: + try: + _set_client_attribute(helper, url, CLIENT_TOKEN_LIFESPAN_ATTRIBUTE, previous) + logger.info( + "Restored %s access-token lifespan to %s.", + VITE_KEYCLOAK_CLIENT_ID, previous or "the realm default", + ) + except Exception: # pylint: disable=broad-except + logger.exception( + "Could not restore %s's '%s' attribute to %r; reset it by hand.", + VITE_KEYCLOAK_CLIENT_ID, CLIENT_TOKEN_LIFESPAN_ATTRIBUTE, previous, + ) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/base.py b/src/tests/e2e/benchmarks/chatqna/pysweep/base.py new file mode 100644 index 00000000..0ad6a65f --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/base.py @@ -0,0 +1,88 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Core abstractions for pysweep: the Plane enum and the Property interface. + +A **Property** owns exactly one configuration knob. It knows how to read the +knob's *observed* value from the live system, whether an observed value +satisfies a desired one, how to apply a desired value idempotently, and how to +wait until an applied change has actually converged. + +A **Plane** is the channel through which a knob's value lives and is changed. +See DESIGN.md for the full model. +""" + +from abc import ABC, abstractmethod +from enum import Enum +from typing import Any + + +class PropertyReadError(Exception): + """Raised when a property cannot read a valid observed value. + + A missing or unparseable value is never an acceptable state for a sweep: + it means we cannot know what configuration is live, so it must fail loudly + rather than degrade to a ``None`` that silently never satisfies a desired + value. + """ + + +class PropertyApplyError(Exception): + """Raised when a property cannot establish a desired value. + + Distinct from :class:`PropertyReadError` (which is about not knowing the + current state) and from ``NotImplementedError`` (which is about a knob that + cannot be written at all). This is "the write was attempted and the desired + state could not be reached" — a rejected value, a manifest the property no + longer recognises, or a rollout that never converged. + """ + + +class Plane(str, Enum): + """The channel through which a knob's value lives and is changed.""" + + K8S_SPEC = "k8s_spec" # Kubernetes objects - long wait for change + RUNTIME_API = "runtime_api" # Fingerprint - immediate change + + +class Property(ABC): + """Interface every application (=not client's) configuration knob must implement.""" + + # The way the Property is changed. Important for scheduling sweeps. + # Kubernetes-based props are outer, fingerprint-based are innerly iterated + plane: Plane + + @abstractmethod + def read(self) -> Any: + """Return the knob's current **observed** value from the live system. + + Must reflect actual runtime/observed state, not the last value written. + """ + raise NotImplementedError + + def is_satisfied(self, desired: Any) -> bool: + return self.read() == desired + + @abstractmethod + def apply(self, desired: Any) -> None: + """Drive the knob toward ``desired``. + + Idempotent, that means: + - desired == observed --> do nothing + - desired == applied --> do nothing + + Convergence (readiness) handled separately by `wait_until_ready()` + """ + raise NotImplementedError + + def wait_until_ready(self, desired: Any, timeout: float = 300.0) -> None: + """Block until the property itself is ready — the applied change is live. + + For synchronous planes (runtime API) this is a no-op. For async planes + (K8s spec) this polls observed state until ``is_satisfied(desired)`` + holds or ``timeout`` seconds elapse. + """ + return None + + def __repr__(self) -> str: # pragma: no cover - debugging aid + return f"<{type(self).__name__} plane={self.plane.value}>" diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py b/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py new file mode 100644 index 00000000..be5ad03b --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py @@ -0,0 +1,299 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Adapter between sweep-declared client knobs and ``benchmark.py``'s CLI. + +The load generator's parameters (concurrency, input length, duration, ...) are +sweep knobs in the sense that matters — each distinct value is a different test +scenario and they expand into the cartesian product like any other knob. But +they are **not** :class:`~..base.Property` instances, and deliberately so: + +- There is nothing to ``apply``. The value is an argument to a process pysweep + is about to start, not a mutation of the deployed RAG. +- There is nothing to ``wait_until_ready`` on. No rollout, no reconcile, no + propagation delay. +- There is nothing to ``read``. ``Property.read`` is contractually *observed* + state read back from the live system (DESIGN.md calls this non-negotiable — + it is what makes the preflight meaningful). A client knob has no live system + behind it; "reading" it could only echo the value pysweep itself holds, which + is precisely the spec-read the invariant forbids. + +So instead of weakening ``Property`` (or inventing a ``Plane`` whose ``apply`` / +``read`` / ``wait_until_ready`` are all vacuous), this module mirrors +``benchmark.py``'s options as :class:`ClientArg` descriptors and renders resolved +values back into that CLI. ``config.py`` binds YAML leaves to these descriptors +the same way it binds other leaves to property classes, so the knobs still get +schema validation, product expansion, filename slugs, and the recorded snapshot +— everything except the apply/converge machinery that does not apply to them. + +**Every option is mirrored and the scenario-shaping ones are required** in a +sweep config. A client parameter that silently fell back to ``benchmark.py``'s +own default (``-c 32``, ``-d 30m``, ``-x 0``) would reintroduce exactly the +ambiguity pysweep exists to remove: "what configuration was actually tested". +Requiring them also makes the sweep config the single source of truth, so there +is no precedence question against flags passed after ``--``; passing one of +these flags there is an error (see :func:`conflicting_flags`). + +Three options are exceptions, and none of them is a sweep knob: + +- ``server`` and ``bearer_file`` stay optional because pysweep auto-provisions + them (the deployment's own endpoint + a minted token) to keep the "no + preparation steps required" promise. They are whole-sweep values rather than + per-combination ones — one endpoint and one token carry every combination — so + they are not sweepable. +- ``tokenizer`` (``-m``) is **derived, not declared**. It must name the model + being served, or the ``input_tokens`` / ``output_tokens`` columns (and every + tokens/s figure derived from them) are counted on a different basis than the + model actually processed. That model is not a value a config author can be + trusted to keep in step with ``llms.model`` — it changes with every deployment + combination — so pysweep reads it back from the running engine + (``LlmVllmModel.read()``, the observed value) after each combination converges + and renders it itself. There is no ``client.tokenizer`` key; declaring one is a + config error, and passing ``-m`` after ``--`` is refused. +""" + +from dataclasses import dataclass +from typing import Any, Iterable + + +@dataclass(frozen=True) +class ClientArg: + """One ``benchmark.py`` CLI option, mirrored as a sweep knob. + + Used both as pydantic field metadata (``Annotated[..., CONCURRENCY]``, which + is how ``config.py`` recovers the flag for a YAML leaf) and as the rendering + rule that turns a resolved value back into argv. + """ + + #: The flag ``benchmark.py`` parses, e.g. ``-c``. + flag: str + #: ``benchmark.py``'s argparse destination, e.g. ``c`` for ``args.c``. + dest: str + #: The key this knob has in a sweep YAML's ``client:`` section. + yaml_name: str + #: What the option does, in ``benchmark.py``'s own terms. + summary: str + #: Whether a list may be given (i.e. whether it is a product dimension). + #: False for whole-sweep values that cannot differ between combinations. + sweepable: bool = True + #: True when pysweep supplies this value itself and no config key exists for + #: it, so declaring it is impossible and passing its flag is refused. + derived: bool = False + + @property + def path(self) -> str: + """The knob's dotted config path, e.g. ``client.concurrency``.""" + return f"client.{self.yaml_name}" + + def __repr__(self) -> str: # pragma: no cover - debugging aid + return f"ClientArg({self.flag} -> client.{self.yaml_name})" + + +# -- the mirror of benchmark.py's parse_args ---------------------------------- +# One entry per option in benchmark.parse_args. Keep this table in step with it: +# an option here that benchmark.py does not accept fails at load time, and an +# option benchmark.py grows that is missing here simply cannot be swept. + +QUESTION_FILE = ClientArg( + flag="-f", + dest="f", + yaml_name="question_file", + summary="Question file location; the corpus the load is drawn from.", +) +SERVER = ClientArg( + flag="-s", + dest="s", + yaml_name="server", + summary="ChatQA endpoint URL. Omit to use /api/v1/chatqna on the deployment's domain.", + sweepable=False, +) +CONCURRENCY = ClientArg( + flag="-c", + dest="c", + yaml_name="concurrency", + summary="Number of concurrent users (worker threads).", +) +DURATION = ClientArg( + flag="-d", + dest="d", + yaml_name="duration", + summary="How long each combination generates load for, e.g. '3m'.", +) +WORKER_STARTUP_DELAY = ClientArg( + flag="-u", + dest="u", + yaml_name="worker_startup_delay", + summary="Per-worker startup stagger, e.g. '0s' to start all at once.", +) +TOKENIZER = ClientArg( + flag="-m", + dest="m", + yaml_name="tokenizer", + summary="Tokenizer counting input/output tokens; always the served model.", + sweepable=False, + derived=True, +) +FAILURES_ALLOWED = ClientArg( + flag="-e", + dest="e", + yaml_name="failures_allowed", + summary="Failed requests tolerated before the run aborts.", +) +BEARER_FILE = ClientArg( + flag="-b", + dest="b", + yaml_name="bearer_file", + summary="File of bearer tokens, one per worker. Omit to let pysweep provision one.", + sweepable=False, +) +INPUT_TOKENS = ClientArg( + flag="-x", + dest="x", + yaml_name="input_tokens", + summary="Pad/trim every question to exactly N tokens (0 = leave as written).", +) +WARMUP_REQUESTS = ClientArg( + flag="-w", + dest="w", + yaml_name="warmup_requests", + summary="Requests per worker excluded from the results as warmup.", +) + +#: Every mirrored option, in ``benchmark.py``'s declaration order. +CLIENT_ARGS: tuple[ClientArg, ...] = ( + QUESTION_FILE, + SERVER, + CONCURRENCY, + DURATION, + WORKER_STARTUP_DELAY, + TOKENIZER, + FAILURES_ALLOWED, + BEARER_FILE, + INPUT_TOKENS, + WARMUP_REQUESTS, +) + +#: The two options pysweep provisions itself when they are not declared. They +#: are whole-sweep values, so they are resolved once rather than per combination. +PROVISIONED_ARGS: tuple[ClientArg, ...] = (SERVER, BEARER_FILE) + +#: Options pysweep supplies itself, with no config key to declare them. Unlike +#: PROVISIONED_ARGS these cannot be overridden at all: the value is read from the +#: deployment, so any other value would describe a run that did not happen. +DERIVED_ARGS: tuple[ClientArg, ...] = tuple(arg for arg in CLIENT_ARGS if arg.derived) +DERIVED_FLAGS: frozenset[str] = frozenset(arg.flag for arg in DERIVED_ARGS) + +CLIENT_ARGS_BY_FLAG = {arg.flag: arg for arg in CLIENT_ARGS} +CLIENT_ARGS_BY_NAME = {arg.yaml_name: arg for arg in CLIENT_ARGS} + + +class ClientArgsError(Exception): + """Raised when declared client knobs cannot be turned into a valid invocation.""" + + +class BenchmarkClientArgs: + """Resolved per-combination client knob values, renderable as argv. + + Built from the client settings of one combination. Holds no cluster state and + performs no I/O — it is a pure translation from "what the sweep declared" to + "what ``benchmark.py`` is invoked with", which is the whole reason client + knobs need no plane. + """ + + def __init__(self, values: dict[ClientArg, Any]): + self._values = dict(values) + + @classmethod + def from_settings(cls, settings: Iterable) -> "BenchmarkClientArgs": + """Build from an iterable of :class:`~.config.ClientSetting`. + + Duplicate declarations of the same option are a programming error rather + than a config error (the schema permits each key at most once), so they + raise instead of silently keeping the last value. + """ + values: dict[ClientArg, Any] = {} + for setting in settings: + if setting.arg in values: + raise ClientArgsError( + f"'{setting.arg.path}' was resolved twice in one combination " + f"({values[setting.arg]!r} then {setting.value!r})." + ) + values[setting.arg] = setting.value + return cls(values) + + def value_of(self, arg: ClientArg, default: Any = None) -> Any: + return self._values.get(arg, default) + + def to_argv(self, include: Iterable[ClientArg] | None = None) -> list[str]: + """Render the held values as ``benchmark.py`` arguments. + + Emitted in ``CLIENT_ARGS`` order for stable, diffable command lines. + ``include`` restricts the output to a subset of options, which is how the + per-combination knobs are kept separate from the whole-sweep endpoint + ones (those are resolved once, before the port-forward is opened). + """ + allowed = set(CLIENT_ARGS if include is None else include) + argv: list[str] = [] + for arg in CLIENT_ARGS: + if arg not in allowed or arg not in self._values: + continue + value = self._values[arg] + if value is None: + continue + argv += [arg.flag, str(value)] + return argv + + def snapshot(self) -> dict[str, Any]: + """The recorded 'what was tested' contribution for these knobs. + + Unlike a property's snapshot entry this is the *declared* value, not an + observed read-back — there is no live system to observe. It is recorded + anyway because it is half of what identifies a result: the same + deployment under two different loads produces two different numbers. + """ + return {arg.path: self._values[arg] for arg in CLIENT_ARGS if arg in self._values} + + def __repr__(self) -> str: # pragma: no cover - debugging aid + rendered = " ".join(self.to_argv()) + return f"" + + +def conflicting_flags(benchmark_argv: Iterable[str], declared_names: Iterable[str]) -> list[str]: + """Return flags passed after ``--`` that a declared client knob already owns. + + The sweep config is the single source of truth for client parameters, so a + flag appearing in both places has no defensible resolution: honouring the + YAML would silently ignore an explicit command line, and honouring the + command line would silently collapse a declared sweep dimension. Both are + the "you cannot tell what was tested" failure pysweep exists to prevent, so + the caller reports these and refuses to start. + + ``server`` / ``bearer_file`` are only conflicts when actually declared — + passing ``-s`` / ``-b`` on the command line while the YAML omits them is the + supported way to bypass auto-provisioning. + + Derived options (``-m``) are *always* conflicts. They cannot be declared, so + there is nothing to omit to make room for them: pysweep reads the value from + the deployment, and a caller-supplied one would count tokens with a tokenizer + other than the model that produced them. + """ + argv = list(benchmark_argv) + declared = set(declared_names) + conflicts = [] + for arg in CLIENT_ARGS: + if arg.flag not in argv: + continue + if arg in PROVISIONED_ARGS and arg.yaml_name not in declared: + continue + conflicts.append(arg.flag) + return conflicts + + +def derived_flag_reason(flag: str) -> str: + """Why a derived flag cannot be passed, for the error message.""" + if flag == TOKENIZER.flag: + return ( + "pysweep sets -m from the model the LLM engine is observed to be " + "serving, so token counts come from that model's own tokenizer" + ) + return "pysweep derives this value from the deployment" diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py new file mode 100644 index 00000000..deda5f13 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py @@ -0,0 +1,503 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Schema-validated sweep configuration for pysweep. + +A sweep is declared in YAML (DESIGN.md "Sweep config (YAML)"). This module is +the single place that: + +1. **Validates** that YAML against a Pydantic schema — unknown keys and wrong + value types raise :class:`ConfigError` *before* any rollout is triggered, so + a typo never silently tests the wrong configuration. +2. **Binds** each config leaf to the thing that knows how to realise it. The + binding lives on the field itself, so the YAML key is statically tied to its + implementation and there is no name-string lookup table to drift out of sync. + Two kinds of leaf exist: + + - ``Annotated[..., PropertyBinding(MaxNewTokens)]`` — a **deployment** knob, + driven by a :class:`~..base.Property` that applies it to the cluster and + reads it back. + - ``Annotated[..., CONCURRENCY]`` — a **client** knob, a + :class:`~.client_args.ClientArg` that is rendered into ``benchmark.py``'s + CLI. It has no plane: nothing to apply, converge on, or read back (see + ``client_args.py`` for why that distinction is kept rather than folded into + ``Property``). + +3. **Expands** the declared values into cartesian ``product``\\ s of sweep + combinations (DESIGN.md combination strategy). Deployment and client knobs + expand into *separate* products, because they are nested rather than + interleaved: the runner walks deployment combinations in the outer loop + (each costs a rollout) and, for each one, every client combination in the + inner loop (each costs only another load test against the deployment already + standing). Within the deployment product, expensive K8s-plane knobs are + themselves the outer dimension. + +Every deployment property is **optional**: omit a key to leave that knob +untouched. Client knobs are **required** — see ``client_args.py``; falling back +to ``benchmark.py``'s own defaults would leave "what load was applied" +unanswerable from the config. A value may be a single scalar (fixed across the +sweep) or a list (one product dimension). + +Adding a deployment knob = add one annotated, optional field to the relevant +section model (and, per DESIGN.md objective 6, ship the property's e2e test). +Adding a client knob = add a :class:`~.client_args.ClientArg` mirroring the new +``benchmark.py`` option and one annotated field on :class:`ClientConfig`. No +other wiring — unless the option has only one correct value given the deployment +(as ``-m`` does), in which case it is not a knob: mark the ``ClientArg`` +``derived=True``, add no field here, and have the runner resolve it. +""" + +import itertools +import logging +from dataclasses import dataclass +from pathlib import Path +from typing import Annotated, Any, Iterator + +import yaml +from pydantic import ( + BaseModel, + ConfigDict, + NonNegativeInt, + PositiveInt, + StringConstraints, + ValidationError, +) + +from .base import Plane, Property +from .client_args import ( + BEARER_FILE, + CONCURRENCY, + DURATION, + FAILURES_ALLOWED, + INPUT_TOKENS, + QUESTION_FILE, + SERVER, + WARMUP_REQUESTS, + WORKER_STARTUP_DELAY, + ClientArg, +) +from .properties.max_tokens import MaxNewTokens + +logger = logging.getLogger(__name__) + + +class ConfigError(Exception): + """Raised when a sweep config file is invalid (bad schema, key, or value).""" + + +class PropertyBinding: + """Field metadata tying a config leaf to the ``Property`` class it drives. + + Attached via ``Annotated[, PropertyBinding(SomeProperty)]``. Pydantic + v2 preserves it in ``FieldInfo.metadata``, so :class:`SweepConfig` can walk + its own fields and recover, for each declared knob, the class that applies + it — without a separate name→class registry. + """ + + def __init__(self, property_cls: type[Property]): + self.property_cls = property_cls + + def __repr__(self) -> str: # pragma: no cover - debugging aid + return f"PropertyBinding({self.property_cls.__name__})" + + +@dataclass(frozen=True) +class PropertySetting: + """One resolved deployment knob value within a single sweep combination.""" + + path: str # dotted config path, e.g. "llms.max_new_tokens" + property_cls: type[Property] # the Property class that applies/reads it + value: Any # the concrete value for this combination + + +@dataclass(frozen=True) +class ClientSetting: + """One resolved client knob value within a single client combination. + + Deliberately a separate type from :class:`PropertySetting` rather than the + same type with a null ``property_cls``: the runner's apply/converge/verify + loop takes ``PropertySetting``\\ s, and keeping client knobs out of that type + means they cannot reach it by accident. What they carry instead is the + ``benchmark.py`` flag they render to. + """ + + path: str # dotted config path, e.g. "client.concurrency" + arg: ClientArg # the benchmark.py option it renders to + value: Any # the concrete value for this combination + + +# A sweep combination is an ordered tuple of per-property settings. +Combination = tuple[PropertySetting, ...] +# A client combination is an ordered tuple of per-client-knob settings. +ClientCombination = tuple[ClientSetting, ...] + + +# -- value types -------------------------------------------------------------- +# A knob's YAML value is either a single value or a list of values to sweep. +# Constraints (e.g. PositiveInt) are enforced by Pydantic and reported as +# ConfigError. `| None` + default None makes every knob optional. +MaxTokensValue = PositiveInt | list[PositiveInt] + +# Client knob value types. These mirror benchmark.py's argparse types, tightened +# where argparse accepts more than the tool can actually use: `-c 0` starts no +# workers and `-e -1`/`-w -1` are nonsense, so they are constrained here and +# rejected as a ConfigError instead of producing an empty result CSV an hour later. +CountValue = PositiveInt | list[PositiveInt] +NonNegativeCountValue = NonNegativeInt | list[NonNegativeInt] +PathValue = Annotated[str, StringConstraints(min_length=1, strip_whitespace=True)] +PathListValue = PathValue | list[PathValue] +# benchmark.duration_to_seconds parses "" and raises KeyError on +# anything else. Validating the shape here turns that late crash into a config error. +DurationValue = Annotated[ + str, StringConstraints(strip_whitespace=True, pattern=r"^\d+(\.\d+)?[smh]$") +] +DurationListValue = DurationValue | list[DurationValue] + + +# -- section models ----------------------------------------------------------- +# One model per config section. `extra="forbid"` makes any unknown key an error. + + +class _StrictModel(BaseModel): + """Only pre-defined fields are allowed.""" + model_config = ConfigDict(extra="forbid") + + +class LlmsConfig(_StrictModel): + """LLM knobs.""" + + max_new_tokens: Annotated[MaxTokensValue | None, PropertyBinding(MaxNewTokens)] = None + + +class ClientConfig(_StrictModel): + """Load-generator knobs — the full set of ``benchmark.py``'s options. + + Every field mirrors one option of ``benchmark.parse_args``; the annotated + :class:`~.client_args.ClientArg` is what carries the flag it renders back to. + + **These are required, unlike deployment knobs.** A deployment knob that is + omitted means "leave it alone", which is a meaningful and observable state. + An omitted client knob has no such reading — the load test runs regardless, + silently on ``benchmark.py``'s defaults (``-c 32``, ``-d 30m``, ``-x 0``), + and the result CSV records none of it. Making them mandatory keeps every + result attributable to a configuration someone wrote down. + + ``server`` and ``bearer_file`` are the two optional ones: pysweep provisions + both when absent (the deployment's ingress URL, plus a bearer file of freshly + minted tokens) and that is what keeps a sweep + runnable with no preparation steps. They are connection plumbing rather than + test scenarios, so they are also single-valued — one endpoint serves the + whole sweep, and a list is rejected. + + **There is no ``tokenizer`` field**, though ``benchmark.py`` has a ``-m`` + option, because it is not a knob: it must always match the model being + served, so its value is fully determined by what the deployment runs. The + runner reads the served model back per combination via + ``ServedModel.read()`` and looks up its HuggingFace repo id in the model + catalog. Declaring ``client.tokenizer`` + therefore fails as an unknown key — deliberately, since the only thing a + config author could express with it is a mismatch, and a mismatched tokenizer + silently corrupts every token count in the results. + """ + + question_file: Annotated[PathListValue, QUESTION_FILE] + concurrency: Annotated[CountValue, CONCURRENCY] + duration: Annotated[DurationListValue, DURATION] + worker_startup_delay: Annotated[DurationListValue, WORKER_STARTUP_DELAY] + failures_allowed: Annotated[NonNegativeCountValue, FAILURES_ALLOWED] + # 0 means "use the questions as written"; any other value pads/trims every + # question to exactly that many tokens. + input_tokens: Annotated[NonNegativeCountValue, INPUT_TOKENS] + warmup_requests: Annotated[NonNegativeCountValue, WARMUP_REQUESTS] + + # Auto-provisioned when omitted; never a product dimension. + server: Annotated[PathValue | None, SERVER] = None + bearer_file: Annotated[PathValue | None, BEARER_FILE] = None + + +class RunConfig(_StrictModel): + """pysweep **run** configuration — how a sweep executes, not what it varies. + + Kept separate from :class:`SweepConfig` (and passed via ``--config`` while + the sweep comes from ``--sweep``) because these settings are not sweep + dimensions: they describe the harness's behaviour and never expand into + combinations. Same strictness applies — an unknown key raises + :class:`ConfigError`. + """ + + # The kr8s/httpx Kubernetes client logs one line per API call, including a + # '101 Switching Protocols' for *every* connection the port-forward carries + # — i.e. one per benchmark request, which is pure noise at load. Off by + # default; set true to debug cluster connectivity. + display_kubernetes_client_logs: bool = False + + +class SweepConfig(_StrictModel): + """Top-level pysweep sweep configuration. + + Deployment sections are optional, and within them each knob is optional: the + set of *declared* (non-None) knobs defines what the sweep varies on the + cluster. The ``client`` section is required, because a load test always + applies *some* load and pysweep will not leave that undeclared. + """ + + llms: LlmsConfig | None = None + client: ClientConfig + + # -- introspection -------------------------------------------------------- + + def iter_settings(self) -> Iterator[tuple[str, type[Property], list[Any]]]: + """Yield ``(dotted_path, property_cls, values)`` for every declared *deployment* knob. + + Only knobs actually present in the config are yielded; a single scalar + is normalised to a one-element list so callers treat every knob + uniformly. Client knobs are not properties and are yielded by + :meth:`iter_client_settings` instead. + """ + for path, binding, values in _walk_bindings(self): + if isinstance(binding, PropertyBinding): + yield path, binding.property_cls, values + + def iter_client_settings(self) -> Iterator[tuple[str, ClientArg, list[Any]]]: + """Yield ``(dotted_path, client_arg, values)`` for every sweepable client knob. + + Non-sweepable knobs (``server``, ``bearer_file``) are excluded: they are + whole-sweep connection settings, not product dimensions, and are rendered + once by :meth:`client_provisioning_argv`. + """ + for path, binding, values in _walk_bindings(self): + if isinstance(binding, ClientArg) and binding.sweepable: + yield path, binding, values + + def deployment_combinations(self) -> list[Combination]: + """Expand the *deployment* knobs into the cartesian product of combinations. + + Combinations order by config-plane (later is more inner in the loop): + 1. Kubernetes + 2. Fingerprint + + Never empty. A sweep with no declared deployment knob yields exactly one + combination — the empty one, meaning "apply nothing, benchmark the + deployment as it stands" — which is what an empty cartesian product + already means, so the runner iterates one list either way instead of + special-casing the no-knobs sweep. + """ + settings = list(self.iter_settings()) + # K8s-plane knobs (slow rollout) as the outer loop; itertools.product + # varies its leftmost argument slowest. + settings.sort(key=lambda s: (0 if s[1].plane == Plane.K8S_SPEC else 1, s[0])) + + value_lists = [values for _, _, values in settings] + combos: list[Combination] = [] + for chosen in itertools.product(*value_lists): + combos.append( + tuple( + PropertySetting(path=path, property_cls=cls, value=value) + for (path, cls, _), value in zip(settings, chosen) + ) + ) + return combos + + def client_combinations(self) -> list[ClientCombination]: + """Expand the client knobs into their own cartesian product. + + A *separate* product from :meth:`deployment_combinations` rather than extra + dimensions of it, because the runner nests the two: each deployment + combination is established once, then every client combination is run + against it. That nesting is what makes these knobs cheap — a new + concurrency level costs one more load test, not one more rollout — and + expressing it as nesting means the ordering is structural rather than + something a sort key has to keep getting right. + + Ordered by dotted path so the sequence is stable and diffable across + runs; there is no cost gradient among client knobs to order by, since + none of them touches the deployment. Never empty: the knobs are required, + so the product is at least the single all-scalars combination. + """ + settings = sorted(self.iter_client_settings(), key=lambda s: s[0]) + if not settings: + return [] + + value_lists = [values for _, _, values in settings] + combos: list[ClientCombination] = [] + for chosen in itertools.product(*value_lists): + combos.append( + tuple( + ClientSetting(path=path, arg=arg, value=value) + for (path, arg, _), value in zip(settings, chosen) + ) + ) + return combos + + def client_provisioning_argv(self) -> list[str]: + """Render the declared whole-sweep client knobs (``-s`` / ``-b``) as argv. + + Empty when neither is declared, which is the default and the path where + pysweep provisions both itself. + """ + argv: list[str] = [] + for path, binding, values in _walk_bindings(self): + del path + if isinstance(binding, ClientArg) and not binding.sweepable: + argv += [binding.flag, str(values[0])] + return argv + + def max_concurrency(self) -> int: + """The largest ``client.concurrency`` any combination of this sweep runs. + + Whole-sweep provisioning needs this before the product is expanded: + ``benchmark.py`` reads one bearer token per worker index, so the bearer + file — written once, shared by every combination — has to cover the widest + combination the sweep will reach. + + ``client.concurrency`` is a required field, so the max is always defined. + """ + return max( + int(value) + for _, arg, values in self.iter_client_settings() + if arg is CONCURRENCY + for value in values + ) + + def varying_paths(self) -> set[str]: + """Dotted paths of the knobs declared with more than one value. + + These are the sweep's actual dimensions — the knobs whose value differs + between combinations. Knobs declared as a scalar are constant across the + whole sweep and so distinguish nothing. Used to name result files by what + varies (see :func:`~.pysweep_bench.result_file_name`). + """ + return {path for path, _, values in _walk_bindings(self) if len(values) > 1} + + def knob_paths(self) -> list[str]: + """Dotted paths of every knob this sweep declares, deployment first. + + The sweep's own description of itself, used as the knob columns of the + summary CSV (see :mod:`~.results`). *Every* declared knob is included, + not only the varying ones, because a summary that dropped the constants + would not say what the numbers were measured under — and because it makes + two sweeps' summaries concatenable when they declare the same knobs. + + Ordered deployment-then-client, each group by path, so the columns read + outer-loop to inner-loop and stay stable across runs. ``server`` and + ``bearer_file`` are excluded: they are connection plumbing rather than a + test scenario, identical for every row, and one of them is a file path + that says nothing about what was tested. + """ + deployment = sorted(path for path, _, _ in self.iter_settings()) + client = sorted(path for path, _, _ in self.iter_client_settings()) + return deployment + client + + def declared_client_names(self) -> set[str]: + """YAML names of every client knob this config declares. + + Used to detect a client flag passed after ``--`` that the config already + owns (see :func:`~.client_args.conflicting_flags`). + """ + return { + binding.yaml_name + for _, binding, _ in _walk_bindings(self) + if isinstance(binding, ClientArg) + } + + def declared_question_files(self) -> list[str]: + """Every value declared for ``client.question_file``, in declared order. + + A list, not a set, because the knob is sweepable: a config may name + several corpora and the caller checks all of them. Whether each names a + readable file is not a schema question (the value is validated only as a + non-empty string), so it is checked by the runner's preflight — see + ``pysweep_bench.question_file_verify``. + """ + return [ + str(value) + for _, binding, values in _walk_bindings(self) + if binding is QUESTION_FILE + for value in values + ] + + +def _binding_of(field_info) -> PropertyBinding | ClientArg | None: + """The binding attached to a field, whichever kind it is.""" + for meta in field_info.metadata: + if isinstance(meta, (PropertyBinding, ClientArg)): + return meta + return None + + +def _walk_bindings( + model: BaseModel, prefix: str = "" +) -> Iterator[tuple[str, PropertyBinding | ClientArg, list[Any]]]: + """Recurse a validated model, yielding declared bindings of either kind. + + Callers filter by binding type; walking both kinds in one pass keeps this the + only place that knows how a config's shape maps to dotted paths. + """ + for name, field in type(model).model_fields.items(): + value = getattr(model, name) + path = f"{prefix}{name}" + binding = _binding_of(field) + if binding is not None: + if value is not None: + yield path, binding, _as_list(value) + elif isinstance(value, BaseModel): + yield from _walk_bindings(value, prefix=f"{path}.") + + +def _as_list(value: Any) -> list[Any]: + return list(value) if isinstance(value, list) else [value] + + +# -- loading ------------------------------------------------------------------ + + +def _load_model(source: str | Path | dict, model: type[BaseModel], what: str): + """Load YAML (or take a dict) and validate it against ``model``. + + Shared by the sweep and run configs so both get identical strictness and + error reporting. ``what`` names the config in error messages. + """ + if isinstance(source, dict): + data: Any = source + else: + path = Path(source) + try: + text = path.read_text() + except OSError as exc: + raise ConfigError(f"Cannot read {what} config '{path}': {exc}") from exc + try: + data = yaml.safe_load(text) + except yaml.YAMLError as exc: + raise ConfigError(f"{what.capitalize()} config '{path}' is not valid YAML: {exc}") from exc + + if data is None: + data = {} + if not isinstance(data, dict): + raise ConfigError( + f"{what.capitalize()} config must be a mapping at the top level, " + f"got {type(data).__name__}." + ) + + try: + return model.model_validate(data) + except ValidationError as exc: + raise ConfigError(f"Invalid {what} config:\n{exc}") from exc + + +def load_config(source: str | Path | dict) -> SweepConfig: + """Load and validate a sweep config from a YAML file path or a dict. + + Raises :class:`ConfigError` on anything that violates the schema — an + unknown key, a wrong type, an out-of-range value, or malformed YAML — so + invalid config fails loudly before a sweep starts. + """ + return _load_model(source, SweepConfig, "sweep") + + +def load_run_config(source: str | Path | dict) -> RunConfig: + """Load and validate a pysweep run config (``--config``). + + Same strictness as :func:`load_config`: an unknown key or wrong type raises + :class:`ConfigError` rather than being silently ignored. + """ + return _load_model(source, RunConfig, "run") diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml new file mode 100644 index 00000000..e569dea9 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml @@ -0,0 +1,20 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +# Example pysweep *run* configuration (--config). +# +# This describes how a sweep executes; what it varies lives in the sweep config +# (--sweep, see sweep.yaml). Keys here are never expanded into combinations. +# +# Validated by pysweep.config.load_run_config: any unknown key or wrong value +# type raises ConfigError before the sweep runs. + +# Whether to show the kr8s/httpx Kubernetes client's own output. Two kinds of +# noise come from the port-forward that carries the load test: +# - one '101 Switching Protocols' line per benchmark request (a websocket is +# opened per forwarded connection), and +# - a multi-frame ConnectionResetError traceback when a connection or the +# forward itself is torn down (a race inside kr8s; requests still return 200). +# Both are hidden when false; genuine warnings and errors still surface. Set true +# to debug cluster connectivity. +display_kubernetes_client_logs: false diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml new file mode 100644 index 00000000..82e109c4 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml @@ -0,0 +1,86 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +# Example pysweep sweep configuration. +# +# Two kinds of knob, which the runner nests rather than interleaves: +# +# * DEPLOYMENT knobs (llms:) change the running RAG. Each one is OPTIONAL — +# omit a key to leave that knob untouched. They form the OUTER loop, because +# each change costs a rollout. +# * CLIENT knobs (client:) are the load generator's parameters, passed straight +# to benchmark.py. They are REQUIRED, because a load test always applies some +# load and leaving that undeclared makes a result unattributable. They form +# the INNER loop: each value costs one more load test, nothing on the cluster. +# +# Any knob may be a single value (fixed for the whole sweep) or a list (one +# dimension of the cartesian product — see DESIGN.md "product" strategy). Total +# runs = (deployment combinations) x (client combinations); the config below is +# (2 max_new_tokens) x (3 concurrency x 2 input_tokens) = 12 runs. +# +# Validated by pysweep.config.load_config: any unknown key or wrong/out-of-range +# value raises ConfigError before the sweep runs. +# +# Every run also appends a row to benchmark_summary_results.csv, in the directory +# given by --summaries (default ./results): one column per knob declared below, +# named by its dotted path (e.g. 'client.input_tokens'), then mean/p90 TTFT and +# TPOT. Its per-request CSV goes in per_case_results/ next to it. NOTE that the +# previous sweep's results there are deleted before a new sweep starts. + +llms: + max_new_tokens: [128, 256] + +# Load generator (benchmark.py) parameters. Every option below is required: a +# missing one would silently fall back to benchmark.py's own default and the +# result CSV records none of it. These need no apply/converge/verify — they are +# arguments to the load test, not state on the cluster — which is why they are the +# innermost loop: all of them are re-run against each deployment combination +# without touching it. +client: + # -f Question corpus the load is drawn from. + # + # A relative path is resolved against pysweep_bench.py's directory, NOT the + # directory the sweep was launched from — so this value means the same file + # wherever you run from. The corpora live one level up beside benchmark.py, + # hence the '../'. Absolute paths are used as given. + # + # Checked by preflight() before anything is applied, so a path typo + # fails immediately instead of after a rollout has been paid for. + question_file: ../questions-short.csv + + # -c Concurrent users (worker threads). The classic scaling dimension: a list + # here re-runs the same deployment under each load level, back to back and + # with no reconfiguration between them, so the numbers are comparable. + concurrency: [1, 16, 128] + + # -d from benchmark.py + duration: 5m + + # -u Stagger between worker starts. '0s' starts all workers at once, which is + # the harsher and more repeatable pattern. + worker_startup_delay: 0s + + # NOTE: there is no 'tokenizer' key, though benchmark.py has -m. It has to be + # the model being served (otherwise the token counts come from a tokenizer that + # did not tokenize them), so it is not a knob — pysweep reads the served model + # back from the engine after each deployment combination converges and passes it + # itself. Declaring it here is an error. + + # -e Failed requests tolerated before the run gives up. + failures_allowed: 200 + + # -x Pad/trim every question to exactly this many tokens; 0 leaves them as + # written. Fixing it removes prompt-length variance between runs. + input_tokens: [128, 256] + + # -w Requests per worker discarded as warmup (first-request latency includes + # connection setup and cache warming). + warmup_requests: 1 + + # -s / -b Endpoint and bearer file. Both OPTIONAL and left unset here: pysweep + # targets the deployment's own ingress (https://) and + # mints a fresh bearer file before every run, which is what lets a sweep run + # with no preparation steps. Set them only to benchmark a different endpoint + # or with tokens of your own (a supplied -b is never refreshed). + # server: https://erag.com/api/v1/chatqna + # bearer_file: uat.txt \ No newline at end of file diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py b/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py new file mode 100644 index 00000000..5c0d940b --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py @@ -0,0 +1,178 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The model-manager catalog: deployment names, and the HF repo behind each. + +``model-manager`` deploys models from a YAML catalog (``models.yaml``) in which +every entry has a short **deployment name** and the **HuggingFace repo id** its +weights come from:: + + models: + - name: llama3-8b-awq + model_id: casperhansen/llama-3-8b-instruct-awq + category: llm + +Both halves matter to pysweep, for different reasons. + +**The name is what the deployment serves.** It is what ends up in +``--served-model-name``, and therefore what ``LLM_MODEL_NAME`` holds and what the +served model answers to on the gateway — so it is what :mod:`.served_model` reads. + +**The repo id is what the benchmark's tokenizer needs.** ``benchmark.py -m`` +counts tokens with ``transformers.AutoTokenizer``, which resolves a HF repo, not +a deployment name. The value is therefore *derived*, never configured: the runner +reads the observed model name off the deployment and looks its repo id up here +(see :func:`~.pysweep_bench.resolve_tokenizer`). Deriving it is the point — +a hand-set tokenizer that disagreed with the served model would silently mis-count +every input and output length in the results. + +**Which catalog file.** The one the deployment actually used, which is not +necessarily the one in this repo: ``deployment/models.yaml`` here is the shipped +default, while an installed environment has its own copies under ``env//`` +and they do drift. The RAG pipeline's models come from ``models-rag.yaml`` there; +``models.yaml`` is the inference platform's catalog, which shares only some names +and sizes them differently. The resolution order below therefore prefers explicit +configuration (``PYSWEEP_MODEL_CATALOG``) and then ``MM_CONFIG`` — the same +variable the ``model-manager`` wrapper exports — so pysweep reads the catalog +whose names the cluster was actually built from. +""" + +import logging +import os +from pathlib import Path + +import yaml + +from .paths import REPO_ROOT, deploy_roots, is_file + +logger = logging.getLogger(__name__) + +# Environment variables consulted for the catalog path, in order. MM_CONFIG is +# what the ai-solutions ./model-manager wrapper exports for the real CLI, so +# honouring it makes pysweep read the same catalog the deployment used without +# anyone having to configure pysweep separately. +CATALOG_ENV_VARS = ("PYSWEEP_MODEL_CATALOG", "MM_CONFIG") + +# Catalog paths tried when nothing is configured. The installed environment's +# copies come first, the RAG catalog before the platform one, then this repo's +# shipped default. +CATALOG_FALLBACKS = ( + *( + str(root / "env" / "local" / name) + for root in deploy_roots() + for name in ("models-rag.yaml", "models.yaml") + ), + str(REPO_ROOT / "deployment" / "models.yaml"), +) + + +class CatalogError(Exception): + """Raised when the model catalog is missing, malformed, or lacks a model.""" + + +def catalog_path() -> Path: + """Return the catalog file to read, or raise :class:`CatalogError`. + + Raising when nothing is found is deliberate: the alternative is an empty + catalog, which would make every model name "unknown" and turn a + configuration problem into a confusing per-model failure later on. + """ + for var in CATALOG_ENV_VARS: + configured = os.getenv(var) + if configured: + path = Path(configured) + if not is_file(path): + raise CatalogError( + f"{var}={configured!r} does not point at a readable file." + ) + return path + + for candidate in CATALOG_FALLBACKS: + path = Path(candidate) + if is_file(path): + return path + + raise CatalogError( + "Cannot find a model-manager catalog. Set PYSWEEP_MODEL_CATALOG (or " + "MM_CONFIG) to the models.yaml the deployment was built from; tried " + f"{list(CATALOG_FALLBACKS)}." + ) + + +def load_catalog(path: str | Path | None = None) -> dict[str, dict]: + """Return ``{name: entry}`` for every model in the catalog. + + Entries are returned verbatim, so callers can read whichever field they need + (``model_id``, ``category``, ``cpu``…) without this module having to know + about each one. + """ + resolved = Path(path) if path is not None else catalog_path() + try: + raw = yaml.safe_load(resolved.read_text()) + except OSError as exc: + raise CatalogError(f"Cannot read model catalog '{resolved}': {exc}") from exc + except yaml.YAMLError as exc: + raise CatalogError(f"Model catalog '{resolved}' is not valid YAML: {exc}") from exc + + if not isinstance(raw, dict): + raise CatalogError( + f"Model catalog '{resolved}' must be a mapping at the top level, " + f"got {type(raw).__name__}." + ) + models = raw.get("models") or [] + if not isinstance(models, list): + raise CatalogError( + f"Model catalog '{resolved}' has a 'models' key that is not a list." + ) + + catalog: dict[str, dict] = {} + for entry in models: + if not isinstance(entry, dict): + continue + name = entry.get("name") + if name: + catalog[str(name)] = entry + if not catalog: + raise CatalogError(f"Model catalog '{resolved}' declares no named models.") + logger.debug("Loaded %d model(s) from catalog %s.", len(catalog), resolved) + return catalog + + +def known_models(path: str | Path | None = None) -> list[str]: + """Every deployment name the catalog offers, sorted — the valid ``llms.model`` values.""" + return sorted(load_catalog(path)) + + +def model_entry(name: str, path: str | Path | None = None) -> dict: + """Return one model's catalog entry, or raise naming what *is* available. + + Listing the alternatives matters here because the failure this catches is + almost always a name typo or a repo id used where a name belongs, and both + are obvious the moment the real names are on screen. + """ + catalog = load_catalog(path) + if name not in catalog: + raise CatalogError( + f"Model {name!r} is not in the model-manager catalog. " + f"Available: {sorted(catalog)}. Note that llms.model takes catalog " + "*names* (e.g. 'llama3-8b-awq'), not HuggingFace repo ids." + ) + return catalog[name] + + +def tokenizer_for(name: str, path: str | Path | None = None) -> str: + """Return the HF repo id whose tokenizer matches the model deployed as ``name``. + + Raises :class:`CatalogError` if the entry has no ``model_id``: a model served + from a repo pysweep cannot name is one whose token counts it cannot compute, + and reporting throughput per token off the wrong tokenizer is worse than not + reporting it. + """ + entry = model_entry(name, path) + model_id = entry.get("model_id") + if not model_id: + raise CatalogError( + f"Catalog entry for {name!r} has no 'model_id', so the matching " + "HuggingFace tokenizer cannot be determined." + ) + return str(model_id) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py b/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py new file mode 100644 index 00000000..c796e168 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py @@ -0,0 +1,48 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 +"""Where pysweep looks for the installed environment's files. + +The ai-solutions installer keeps this repo at ``/ext/enterprise.ai-erag`` +and the environment it built at ``/env/local``. So when pysweep runs from +that checkout, the deploy root follows from this file's own location, whoever the +installing user was. ``/root/ai-solutions`` (the default for a root install) is tried +after it. + +Probing is done with :func:`is_file` / :func:`is_dir` rather than the ``Path`` +methods: on Python < 3.14 those raise ``PermissionError`` for a path under an +unreadable directory such as ``/root``, which would turn "not here, try the next +candidate" into a crash for any non-root user. +""" + +from pathlib import Path + +ROOT_DEPLOY_ROOT = Path("/root/ai-solutions") + +# parents[6] is the repo root: pysweep/chatqna/benchmarks/e2e/tests/src/. +REPO_ROOT = Path(__file__).resolve().parents[6] + + +def deploy_roots() -> tuple[Path, ...]: + """Candidate ai-solutions deploy roots, most specific first.""" + roots = [] + if REPO_ROOT.parent.name == "ext": + roots.append(REPO_ROOT.parent.parent) + if ROOT_DEPLOY_ROOT not in roots: + roots.append(ROOT_DEPLOY_ROOT) + return tuple(roots) + + +def is_file(path: Path) -> bool: + """``path.is_file()``, treating an unreadable location as absent.""" + try: + return path.is_file() + except OSError: + return False + + +def is_dir(path: Path) -> bool: + """``path.is_dir()``, treating an unreadable location as absent.""" + try: + return path.is_dir() + except OSError: + return False diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py new file mode 100644 index 00000000..f2495778 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py @@ -0,0 +1,8 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Concrete configuration properties (one knob per class).""" + +from .max_tokens import MaxNewTokens + +__all__ = ["MaxNewTokens"] diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py new file mode 100644 index 00000000..f87121a6 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py @@ -0,0 +1,74 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""``MaxNewTokens`` — the LLM ``max_new_tokens`` knob (Runtime API plane). + +Set with: + + POST /v1/system_fingerprint/change_arguments + [{"name": "llm", "data": {"max_new_tokens": }}] + +and read back from ``GET config?params_key=llm`` (the ``values`` object). This is +the simplest property and the reference implementation of the +:class:`~pysweep.base.Property` interface for the runtime-API plane. +""" + +import logging + +from ..base import Plane, Property, PropertyReadError +from ..runtime_api import FingerprintClient + +logger = logging.getLogger(__name__) + +# The fingerprint component and parameter key this property drives. +COMPONENT = "llm" +PARAMETER = "max_new_tokens" + + +class MaxNewTokens(Property): + """Number of new tokens the LLM is allowed to generate per request.""" + + plane = Plane.RUNTIME_API + + def __init__(self, client: FingerprintClient): + self.client = client + + def read(self) -> int: + """Return the observed ``max_new_tokens`` from the live fingerprint API. + + Raises :class:`PropertyReadError` if the parameter is absent from the + response or is not an integer. A missing value is not an acceptable + state: it means we cannot know what configuration is live, so it fails + loudly rather than degrading to a value that silently never satisfies a + desired one. + """ + values = self.client.read_values(COMPONENT) + if PARAMETER not in values: + raise PropertyReadError( + f"'{PARAMETER}' is absent from the fingerprint '{COMPONENT}' " + f"arguments; got keys: {sorted(values)}" + ) + raw = values[PARAMETER] + try: + return int(raw) + except (TypeError, ValueError) as exc: + raise PropertyReadError( + f"'{PARAMETER}' is not an integer (got {raw!r})." + ) from exc + + def is_satisfied(self, desired: int) -> bool: + return self.read() == int(desired) + + def apply(self, desired: int) -> None: + """Set ``max_new_tokens`` to ``desired`` (idempotent).""" + desired = int(desired) + if self.is_satisfied(desired): + logger.debug("max_new_tokens already %s; skipping change_arguments.", desired) + return + logger.info("Setting %s.%s = %s via change_arguments.", COMPONENT, PARAMETER, desired) + self.client.change_arguments( + [{"name": COMPONENT, "data": {PARAMETER: desired}}] + ) + + # Runtime-API plane is ~synchronous: the value is live once change_arguments + # returns, so the inherited no-op wait_until_ready is correct. diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py new file mode 100644 index 00000000..f221214e --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -0,0 +1,812 @@ +#!/bin/python3 +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""pysweep benchmark runner. + +Ties the pieces together (DESIGN.md "Execution flow"): + +1. **Load & validate** a sweep config (``config.load_config`` — invalid YAML + fails here, before anything is applied), then **preflight** the preconditions + the schema cannot express (``preflight``) — the question corpora, once, + while stopping is still free. +2. For each **deployment** combination in the cartesian ``product`` (outer loop): + a. **apply** every declared property's value (idempotent), + b. **wait_until_ready** on each, + c. **verify** via *observed* state (``is_satisfied(read())``) — a mismatch + aborts that combination rather than benchmarking the wrong config, + d. **snapshot** the observed values (so "what was tested" is recorded), + e. **resolve the tokenizer** from the observed served model, so token counts + come from the tokenizer of the model that actually produced them, + f. for each **client** combination (inner loop), **run the benchmark** by + reusing ``benchmark.run_benchmark`` unchanged, then + g. **summarize** that run into the sweep's summary CSV (``results.py``): one + row per run, a column per declared knob, and the TTFT/TPOT KPIs. + +The nesting is the point. A deployment knob costs a reconfiguration of the +running pipeline, so it is established once and then held still while every +load scenario runs against it. Client knobs (concurrency, input length, duration) +change nothing on the cluster, so each additional value costs only another load +test; they are the innermost dimension and need no apply, no convergence wait, +and no read-back (see ``client_args.py``). One deployment combination therefore +yields ``len(client_combinations)`` result CSVs, all directly comparable because +they ran against a deployment that was verified once and never touched between +them. + +Those per-run CSVs are per-*request* rows and carry no configuration, so a sweep +also writes one **summary CSV** holding a row per run: every declared knob as a +dotted-path column, then the mean and p90 of TTFT and TPOT. It is rewritten after +each run, so a sweep killed partway still leaves a readable table of what it got +through. + +Everything a sweep writes goes under one directory (``--summaries``, default +``./results``):: + + results/ + benchmark_summary_results.csv # the table: one row per run + per_case_results/ # one per-request CSV per run + bench_max_new_tokens-64_k-3_concurrency-1.result.csv + ... + +That directory is **cleared of the previous run's artifacts before the sweep +starts** — see :func:`~.results.prepare_summaries_dir` for why a merge would be +worse than a clean slate. + +Usage:: + + PYTHONPATH=src python -m tests.e2e.benchmarks.chatqna.pysweep.pysweep_bench \ + --sweep sweep.yaml [--config config.yaml] + +``--sweep`` declares *what to vary* (the knobs and their values, including the +required ``client:`` section); ``--config`` declares *how to run* (harness +behaviour, e.g. whether benchmark.py's own logs are displayed) and is optional. +Arguments after ``--`` are still forwarded to benchmark.py, but a flag the sweep +config already owns is rejected rather than silently overriding a declared sweep +dimension — the config is the single source of truth for load parameters. + +**Zero-prerequisite runs.** With no benchmark ``-s`` given, pysweep_bench drives +the deployment's own ChatQNA endpoint — the same path ``benchmark.py`` defaults +to, on the domain read from the installed environment's build config (see +:func:`chatqna_url`). With no ``-b`` (bearer file) given it provisions one +automatically, minting one real Keycloak token per worker. The only thing a +caller must supply is ``--sweep``. +""" + +import argparse +import csv +import linecache +import logging +import re +import sys +import tempfile +from contextlib import ExitStack, contextmanager +from pathlib import Path + +import yaml + +from tests.e2e.benchmarks.chatqna import benchmark +from tests.e2e.benchmarks.chatqna.pysweep.base import ( + Plane, + Property, + PropertyApplyError, + PropertyReadError, +) +from tests.e2e.benchmarks.chatqna.pysweep.client_args import ( + DERIVED_FLAGS, + QUESTION_FILE, + TOKENIZER, + BenchmarkClientArgs, + conflicting_flags, + derived_flag_reason, +) +from tests.e2e.benchmarks.chatqna.pysweep.config import ( + ClientCombination, + Combination, + PropertySetting, + SweepConfig, + load_config, + load_run_config, +) +from tests.e2e.benchmarks.chatqna.pysweep import model_catalog +from tests.e2e.benchmarks.chatqna.pysweep.results import ( + DEFAULT_SUMMARIES_DIR, + SweepSummary, + prepare_summaries_dir, +) +from tests.e2e.benchmarks.chatqna.pysweep.runtime_api import ( + FingerprintClient, + default_transport, +) +from tests.e2e.benchmarks.chatqna.pysweep.served_model import ServedModel + +logger = logging.getLogger(__name__) + +# ChatQNA entrypoint: the same API path benchmark.py drives, so a sweep measures +# what a plain benchmark.py run measures. Only the host differs, and it is not a +# constant — see chatqna_url(). +CHATQNA_PATH = "/api/v1/chatqna" + +# Relative paths in a sweep config are resolved against THIS file's directory, +# never the process's working directory. A sweep YAML is checked in next to the +# harness, so a path in it means the same thing wherever the sweep is launched +# from; resolving against the CWD would instead make the same config name a +# different file per caller — and `benchmark.py`'s bare open() does exactly that, +# which is the bug this anchor exists to close. +PYSWEEP_DIR = Path(__file__).resolve().parent + + +class SweepError(Exception): + """Raised when a combination cannot be applied or fails verification.""" + + +class PreflightError(SweepError): + """Raised when a precondition for running the sweep is not met. + + Distinct from a bare :class:`SweepError` because it is raised *before* + anything is applied or benchmarked: nothing has to be undone, and the fix is + always in the caller's config or environment rather than in the cluster. + """ + + +def build_property(setting: PropertySetting, fingerprint_client: FingerprintClient) -> Property: + """Instantiate the ``Property`` bound to a config leaf with the resources it needs. + + Properties differ in what they need to reach their plane. Runtime-API + properties take the fingerprint client; K8s-plane properties talk to the + cluster themselves (kr8s reads its own kubeconfig) and so take no argument. + Dispatch on the class's declared plane so adding a property of an existing + plane needs no change here. + """ + if setting.property_cls.plane == Plane.RUNTIME_API: + return setting.property_cls(fingerprint_client) + if setting.property_cls.plane == Plane.K8S_SPEC: + return setting.property_cls() + raise SweepError( + f"No builder for property '{setting.property_cls.__name__}' " + f"(plane {setting.property_cls.plane.value}); wire it up in build_property()." + ) + + +def apply_combination( + combination: Combination, fingerprint_client: FingerprintClient +) -> dict: + """Apply, converge, and verify one combination; return the observed snapshot. + + Raises :class:`SweepError` if any property fails to converge to its desired + value, so a benchmark never runs against a configuration we could not + actually establish. + """ + properties = [(setting, build_property(setting, fingerprint_client)) for setting in combination] + + for setting, prop in properties: + logger.info("Applying %s = %r", setting.path, setting.value) + try: + prop.apply(setting.value) + except (PropertyApplyError, NotImplementedError) as exc: + # The property could not establish the requested state (a value the + # deployment cannot run, a manifest it no longer recognises, or a + # knob that is not writable). That is a sweep problem, not a crash. + raise SweepError(f"{setting.path}: {exc}") from exc + + for setting, prop in properties: + try: + prop.wait_until_ready(setting.value) + except PropertyApplyError as exc: + # Applied but never took effect — never benchmark on that. + raise SweepError(f"{setting.path}: {exc}") from exc + + # Verify against OBSERVED state (DESIGN.md: the set/verify split). + snapshot = {} + for setting, prop in properties: + observed = prop.read() + if not prop.is_satisfied(setting.value): + raise SweepError( + f"{setting.path}: desired {setting.value!r} not satisfied; " + f"observed {observed!r} after apply/converge." + ) + snapshot[setting.path] = observed + return snapshot + + +def resolve_tokenizer() -> str: + """The tokenizer to count tokens with: the one of the *observed* served model. + + ``benchmark.py``'s ``-m`` is not a sweep knob, so nobody declares it. It has + exactly one correct value — the served model's tokenizer — because it produces + the ``input_tokens`` / ``output_tokens`` columns and pads questions to + ``client.input_tokens``. Counted with any other model's tokenizer, those + numbers describe a tokenization the deployment never performed, and tokens/s + stops being comparable to anything. + + Two steps, because the two names differ. What the deployment serves is a + *catalog* name (``llama3-8b-awq``, the value of ``LLM_MODEL_NAME`` and the name + of the ``LLMInferenceService``); ``AutoTokenizer.from_pretrained`` needs a + HuggingFace repo id. The model catalog holds both, so the observed name is + resolved through it (:func:`model_catalog.tokenizer_for`) rather than guessed. + + Reads observed state rather than any declared value, for the same reason + properties do: a pipeline that half-switched models would otherwise be + tokenized as though it had not. + """ + try: + served = ServedModel().read() + except PropertyReadError as exc: + # Without it every token count would be on an unknown basis, so this + # is not something to fall back from silently. + raise SweepError( + f"Cannot determine the served model to tokenize with: {exc}. " + f"The benchmark's -m must be the tokenizer of the model the " + f"deployment serves." + ) from exc + try: + return model_catalog.tokenizer_for(served) + except model_catalog.CatalogError as exc: + raise SweepError( + f"Cannot map the served model '{served}' to a tokenizer: {exc}" + ) from exc + + +def _slug(value) -> str: + """Filesystem-safe fragment for a config value (used in result filenames). + + Underscores are preserved so knob names stay readable (``max_new_tokens``). + """ + return re.sub(r"[^0-9A-Za-z_]+", "-", str(value)).strip("-") + + +def _settings_slug(settings, only=None) -> str: + """Join ``-`` fragments for the given settings. + + ``only`` restricts the output to those dotted paths — see + :func:`result_file_name` for why a filename names only what varies. + """ + return "_".join( + f"{_slug(s.path.rsplit('.', 1)[-1])}-{_slug(s.value)}" + for s in settings + if only is None or s.path in only + ) + + +def combination_slug(combination: Combination, only=None) -> str: + """A short, unique-per-combination tag like ``max_new_tokens-128``.""" + return _settings_slug(combination, only) + + +def client_combination_slug(client_combination: ClientCombination, only=None) -> str: + """A short tag for one client combination, e.g. ``concurrency-4_duration-3m``.""" + return _settings_slug(client_combination, only) + + +def result_file_name( + combination: Combination, + client_combination: ClientCombination, + only=None, + fallback: str = "single", +) -> str: + """Result CSV *file name* for one (deployment, client) pair. + + A bare name, not a path: where it goes is the caller's business (the + ``per_case_results`` subdirectory of ``--summaries``), and what it is called is + this function's. + + Both slugs contribute, because both identify the run and either alone repeats + across the sweep — a name built from one would clobber the other's results. + + ``only`` (the sweep's varying paths) is what keeps the name usable. Naming + every declared knob is tempting since the filename is the record of what + produced the numbers, but with every option declared an HF repo id and a + question-file path push it past the 255-byte filename limit. So the name + carries what *distinguishes* + this run, and the full configuration — deployment snapshot and load parameters + both — is logged per run instead. ``fallback`` names the degenerate case where + the sweep has a single combination and so nothing varies at all. + """ + slug = "_".join( + part + for part in ( + combination_slug(combination, only), + client_combination_slug(client_combination, only), + ) + if part + ) + return f"bench_{slug or fallback}.result.csv" + + +def count_result_rows(output_file) -> int: + """Number of data rows the benchmark wrote (0 if the file is missing).""" + path = Path(output_file) + if not path.exists(): + return 0 + with path.open(newline="") as handle: + return sum(1 for _ in csv.reader(handle)) + + +# Loggers belonging to the Kubernetes client stack. kr8s talks to the API server +# over httpx/httpcore and logs a line per call; with a port-forward under load +# that is one '101 Switching Protocols' per benchmark request. +KUBERNETES_CLIENT_LOGGERS = ("httpx", "httpcore", "kr8s", "websockets") + + +class _DropPortForwardTeardownNoise(logging.Filter): + """Drop kr8s's port-forward connection-reset tracebacks. + + When the load test closes a connection (and again when the sweep tears the + forward down), kr8s's background asyncio task may still be writing to the + now-closed socket. The resulting ``ConnectionResetError`` is not awaited by + anyone, so asyncio's default handler dumps a multi-frame ExceptionGroup + traceback. It is a teardown race *inside kr8s* with no effect on the + benchmark — verified: every recorded request still returns 200 — but it + swamps the output. Only these reset/closed records are dropped; any other + asyncio error still surfaces. + """ + + _NOISE = ( + "ConnectionResetError", + "Connection lost", + "Connection reset by peer", + "client_connected_cb", + ) + + def filter(self, record: logging.LogRecord) -> bool: + text = record.getMessage() + if record.exc_info and record.exc_info[1] is not None: + text = f"{text} {record.exc_info[1]!r}" + return not any(marker in text for marker in self._NOISE) + + +def configure_kubernetes_client_logs(enabled: bool) -> None: + """Quiet the kr8s/httpx client loggers unless explicitly enabled. + + Applied once at startup (not scoped to the benchmark) because the port-forward + spans the whole sweep. Raising the level rather than filtering keeps genuine + warnings and errors — only the per-call INFO chatter goes away. The asyncio + logger keeps its level (real errors matter) but loses kr8s's teardown resets. + """ + if enabled: + return + for name in KUBERNETES_CLIENT_LOGGERS: + logging.getLogger(name).setLevel(logging.WARNING) + logging.getLogger("asyncio").addFilter(_DropPortForwardTeardownNoise()) + + +def resolve_question_file(value: str) -> Path: + """Resolve a declared ``client.question_file`` to a concrete path. + + Relative values are anchored at :data:`PYSWEEP_DIR` (this file's directory), + so ``../questions-short.csv`` names the corpus beside ``benchmark.py`` + regardless of where the sweep was launched from. Absolute paths are returned + unchanged — an explicit absolute path is already unambiguous, and rewriting + it would be surprising. + """ + path = Path(value) + return path if path.is_absolute() else (PYSWEEP_DIR / path) + + +def question_file_verify(config: SweepConfig) -> None: + """Check every declared ``client.question_file`` names a readable file. + + ``question_file`` is sweepable, so a config may declare a list of corpora; + all of them are checked, since a bad path in the *last* one would otherwise + surface only after the earlier runs had already spent their load. + + The schema cannot do this: it validates the value as a non-empty string + (``PathValue``), and whether that string resolves to a file is a fact about + the filesystem rather than about the config's shape. + """ + for value in config.declared_question_files(): + path = resolve_question_file(value) + if not path.is_file(): + raise PreflightError( + f"client.question_file '{value}' does not resolve to a readable file " + f"(looked for {path}). Relative paths are resolved against " + f"{PYSWEEP_DIR}, not the current directory — the corpora live one " + f"level up beside benchmark.py, so a bare name needs a '../' prefix " + f"(e.g. '../questions-short.csv')." + ) + logger.debug("Preflight: question_file '%s' -> %s", value, path) + + +def preflight_check(config: SweepConfig) -> None: + question_file_verify(config) + + +def chatqna_url() -> str: + """The deployed ChatQNA endpoint, with the domain read from the deployment. + + The host is **derived, not declared**: it comes from ``base_domain_name`` in + the installed environment's build config — the same value, read from the same + files, that :class:`~.runtime_api.IngressTransport` and ``KeycloakHelper`` + use. Hardcoding a domain here would let a sweep drive load at one cluster + while configuring another, and the minted token would not even be valid for + it. Point ``PYSWEEP_BUILD_CONFIG_DIR`` at a different ``env//`` to + benchmark a different deployment, exactly as for every other plane. + """ + from tests.e2e.benchmarks.chatqna.pysweep.authentication import load_build_config + + # load_build_config guarantees a non-empty base_domain_name or raises. + return f"https://{load_build_config()['base_domain_name']}{CHATQNA_PATH}" + + +class ProvisionedArgv(list): + """The benchmark argv, plus a way to re-mint the bearer file it points at. + + A plain ``list`` for every existing use (comparison, slicing, ``+``). + :meth:`refresh` is a no-op unless pysweep minted the tokens itself. + """ + + def __init__(self, argv, refresh=None): + super().__init__(argv) + self._refresh = refresh + + def refresh(self) -> None: + """Re-mint the tokens, if pysweep owns the bearer file.""" + if self._refresh is not None: + self._refresh() + + +def write_bearer_file(path: str, helper, workers: int) -> None: + """Write ``workers`` freshly minted, distinct user tokens to ``path``, one per line. + + One DISTINCT token per worker, matching generate_uat_to_file.sh, which the + shell benchmark calls with the concurrency for exactly this reason. Each + ``access_token`` read is a fresh password grant, so the strings differ. That + matters because APISIX's limit-count plugin on /api/v1/chatqna buckets by the + Authorization header *value*: one token repeated would put every worker in a + single 30-requests-per-60s bucket, capping the whole sweep near 0.5 req/s no + matter what concurrency it declares. + """ + tokens = [helper.access_token for _ in range(workers)] + Path(path).write_text("".join(token + "\n" for token in tokens)) + # benchmark.py reads each worker's token with linecache, which caches the + # file; without this a run would be handed the previous run's tokens. Cleared + # outright: checkcache() goes by size and mtime, and a same-size file rewritten + # within one mtime tick would look unchanged. + linecache.clearcache() + + +@contextmanager +def provision_benchmark_target(benchmark_args: list[str], workers: int = 1): + """Ensure the benchmark has a reachable endpoint and a bearer file. + + Yields a :class:`ProvisionedArgv`: the ``benchmark_args`` to actually use. If + the caller supplied no ``-s``, inject :func:`chatqna_url` (the deployment's + own ChatQNA endpoint, the same path ``benchmark.py`` defaults to). If the + caller supplied no ``-b``, write a bearer file holding ``workers`` + freshly-minted Keycloak tokens, one per line, and let the caller re-mint them + before each load test with :meth:`ProvisionedArgv.refresh`. + + Re-minting per run is what lets a sweep last longer than a token does: each + benchmark worker reads its token once, when the run starts, so a token only + has to outlive one run. For that to hold, the tokens are also lengthened to + :data:`~.authentication.SWEEP_TOKEN_LIFESPAN_S` for the sweep (the realm's + 5-minute default is shorter than one run), and set back afterwards. + + ``workers`` must be the *widest* concurrency the sweep will reach (see + :meth:`~.config.SweepConfig.max_concurrency`), because the file is shared by + every combination while ``benchmark.py`` indexes into it per worker. + + "Supplied" covers both sources: a flag after ``--`` and a ``client.server`` / + ``client.bearer_file`` in the sweep config, since :func:`main` renders the + latter into these args before calling. A supplied ``-b`` is the caller's: it + is never re-minted, and the token lifespan is left alone. + """ + args = list(benchmark_args) + refresh = None + + with ExitStack() as stack: + if "-s" not in args: + url = chatqna_url() + logger.info("No -s given; using the deployment's ChatQNA endpoint %s", url) + args += ["-s", url] + + if "-b" not in args: + tmp = stack.enter_context( + tempfile.NamedTemporaryFile("w", suffix=".uat", delete=True) + ) + # The target is the authenticated ERAG ingress, so mint real Keycloak + # user tokens. + from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( + client_token_lifespan, + keycloak_helper, + ) + + helper = keycloak_helper() + stack.enter_context(client_token_lifespan(helper)) + + def refresh(): + logger.info( + "Minting %d Keycloak token(s), one per worker.", workers + ) + write_bearer_file(tmp.name, helper, workers) + + refresh() + args += ["-b", tmp.name] + + yield ProvisionedArgv(args, refresh) + + +def parse_args(argv=None): + parser = argparse.ArgumentParser( + description="Run the ChatQNA benchmark across a pysweep sweep config.", + epilog="Arguments after '--' are passed verbatim to benchmark.py.", + ) + parser.add_argument( + "--sweep", + required=True, + help="Path to the sweep config YAML (what to vary; see examples/sweep.yaml).", + ) + parser.add_argument( + "--config", + help="Path to the pysweep run config YAML (how to run; see examples/config.yaml).", + ) + parser.add_argument( + "--summaries", + default=DEFAULT_SUMMARIES_DIR, + help=( + "Directory a sweep writes into: benchmark_summary_results.csv (a row " + "per run, a column per declared knob, TTFT/TPOT mean/p90) and " + "per_case_results/ (one per-request CSV per run). Created if missing. " + "WARNING: the previous sweep's summary and per-case CSVs there are " + f"DELETED before this one starts (default: {DEFAULT_SUMMARIES_DIR})." + ), + ) + # Everything after '--' is forwarded to the existing benchmark CLI. Load + # parameters belong in the sweep config's `client:` section; a flag here that + # the config already declares is an error, not an override. + parser.add_argument( + "benchmark_args", + nargs=argparse.REMAINDER, + help=( + "Extra arguments forwarded to benchmark.py (prefix with '--'). " + "Load parameters belong in the sweep config's 'client:' section." + ), + ) + args = parser.parse_args(argv) + # argparse.REMAINDER keeps the leading '--'; drop it so it isn't forwarded. + if args.benchmark_args and args.benchmark_args[0] == "--": + args.benchmark_args = args.benchmark_args[1:] + return args + + +def resolve_benchmark_argv(config: SweepConfig, benchmark_args: list[str]) -> list[str]: + """Merge the sweep config's whole-sweep client knobs with the caller's ``--`` args. + + Raises :class:`SweepError` if a forwarded flag duplicates a client knob the + config declares. Silently letting one win would mean the command line and the + config disagree about what was tested, which is the failure mode this harness + exists to prevent — so it is refused before anything is applied. + """ + conflicts = conflicting_flags(benchmark_args, config.declared_client_names()) + derived = [flag for flag in conflicts if flag in DERIVED_FLAGS] + if derived: + raise SweepError( + "benchmark flag(s) " + + ", ".join(f"{flag} ({derived_flag_reason(flag)})" for flag in derived) + + " cannot be passed after '--': pysweep derives them from the " + "deployment and there is no config key for them either." + ) + if conflicts: + raise SweepError( + f"benchmark flag(s) {' '.join(conflicts)} passed after '--' are already " + f"declared in the sweep config's 'client:' section. Remove them from the " + f"command line (the sweep config is the source of truth for load " + f"parameters), or remove the client knob to set it per-invocation." + ) + # Config-declared -s/-b first so provision_benchmark_target sees them as + # "supplied" and skips auto-provisioning for those. + return config.client_provisioning_argv() + list(benchmark_args) + + +def resolve_question_file_argv(argv: list[str]) -> list[str]: + """Rewrite the ``-f`` value in ``argv`` to its anchored absolute path. + + Done at the argv boundary because ``benchmark.py`` opens the value with a + bare ``open()``, i.e. against the process's working directory. Handing it an + absolute path is what makes the anchor authoritative without modifying + ``benchmark.py``, whose other callers rely on its current behaviour. + + Only the value pysweep rendered from the config is rewritten; the declared + string is what the summary CSV records, so provenance still shows what the + config asked for rather than a machine-specific absolute path. + """ + argv = list(argv) + if QUESTION_FILE.flag in argv: + index = argv.index(QUESTION_FILE.flag) + 1 + argv[index] = str(resolve_question_file(argv[index])) + return argv + + +#: Indentation of the logged YAML blocks. Four spaces, matching the sweep config +#: files those blocks are meant to be read against. +LOG_YAML_INDENT = 4 + + +def format_settings_yaml(values: dict, indent: int = LOG_YAML_INDENT) -> str: + """Render a ``{dotted_path: value}`` mapping as a YAML block, for logging. + + A dict repr of a run's knobs is one unreadable line quoted by Python's rules; + the same values grouped back into their config sections read like the sweep + YAML they came from:: + + client: + question_file: ../questions-short.csv + concurrency: 16 + + Undotted keys (the summary row's KPIs) stay at the top level. Key order is the + caller's, not sorted, and values ``yaml.safe_dump`` cannot represent are + stringified rather than raised — a log line must not end a long sweep. + Returns ``""`` for an empty mapping, so a caller can say "(unchanged)". + """ + if not values: + return "" + + tree: dict = {} + for path, value in values.items(): + if not isinstance(value, (str, int, float, bool, type(None))): + value = str(value) + section, _, leaf = str(path).rpartition(".") + if section: + tree.setdefault(section, {})[leaf] = value + else: + tree[leaf] = value + + return yaml.safe_dump( + tree, indent=indent, sort_keys=False, default_flow_style=False + ).rstrip("\n") + + +def run_client_combination( + benchmark, + bench_argv: list[str], + combination: Combination, + client_combination: ClientCombination, + label: str, + results_dir, + varying_paths=None, + tokenizer: str | None = None, +) -> tuple[int, Path]: + """Run one load test: the innermost step of the sweep. + + No apply, no convergence wait, no verification — the client knobs are + arguments to the process about to start, so establishing them *is* rendering + them into argv. Returns ``(error, output_file)``. + + ``tokenizer`` is the one client argument nobody declares: it is the served + model, resolved once per deployment combination by :func:`resolve_tokenizer` + and passed in here rather than re-read per load test, since the deployment is + held still across this whole inner loop. + + ``results_dir`` is where the per-request CSV goes — the ``per_case_results`` + subdirectory of ``--summaries``. It is joined here, and absolute, because + ``benchmark.py`` opens its output file with a bare ``open()``: a relative name + would land against the process's working directory instead. + """ + client_args = BenchmarkClientArgs.from_settings(client_combination) + argv = resolve_question_file_argv(bench_argv + client_args.to_argv()) + if tokenizer is not None: + argv += [TOKENIZER.flag, tokenizer] + # The tokenizer stays out of the YAML block: it is derived from the served + # model, and 'client.tokenizer' is a ConfigError, so a block containing it + # would not be pasteable into a sweep config. + logger.info( + "%s load parameters (tokenizer: %s):\n%s", + label, tokenizer, format_settings_yaml(client_args.snapshot()), + ) + + # Reuse benchmark.py unchanged: parse its args, then run one load test into a + # CSV named for both combinations so results are never clobbered. + bench_args = benchmark.parse_args(argv) + output_file = Path(results_dir) / result_file_name( + combination, client_combination, only=varying_paths + ) + error, output_file = benchmark.run_benchmark(bench_args, output_file=output_file) + + rows = count_result_rows(output_file) + if rows == 0: + # A load test that recorded nothing is a failed run, not a pass: + # surface it instead of exiting 0 with an empty CSV. + logger.error( + "%s produced NO result rows in %s " + "(endpoint unreachable, all requests failed, or duration too short).", + label, output_file, + ) + error = error or 1 + logger.info("%s finished (error=%s, rows=%d); results in %s", label, error, rows, output_file) + return error, output_file + + +def main(argv=None): + args = parse_args(argv) + logging.basicConfig(stream=sys.stderr, level=logging.INFO) + + # Run config is optional; its defaults are the previous behaviour. + run_config = load_run_config(args.config) if args.config else load_run_config({}) + configure_kubernetes_client_logs(run_config.display_kubernetes_client_logs) + + config = load_config(args.sweep) + bench_argv = resolve_benchmark_argv(config, args.benchmark_args) + + preflight_check(config) + + deployment_combinations = config.deployment_combinations() + client_combinations = config.client_combinations() + # Result files are named by what varies; the rest is constant and logged. + varying_paths = config.varying_paths() + # Last thing before the sweep proper, and the first destructive one: the + # output directory is cleared here rather than at startup, so a bad config or a + # failed preflight does not cost the previous sweep's results. + layout = prepare_summaries_dir(args.summaries) + # ...and everything declared, varying or not, becomes a column of the summary, + # which is the artifact that has to stand on its own once the sweep is over. + summary = SweepSummary(config.knob_paths(), path=layout.summary_file) + + fingerprint_client = FingerprintClient(default_transport()) + + total = len(deployment_combinations) * len(client_combinations) + logger.info( + "Sweep: %d deployment combination(s) x %d client combination(s) = %d run(s).", + len(deployment_combinations), len(client_combinations), total, + ) + overall_error = 0 + # Provision the endpoint/bearer once for the whole sweep; the tokens in it are + # re-minted before each load test (see provision_benchmark_target). Sized to + # the widest concurrency, since one bearer file has to serve every combination. + with provision_benchmark_target(bench_argv, config.max_concurrency()) as provisioned_argv: + for index, combination in enumerate(deployment_combinations, start=1): + desired = {s.path: s.value for s in combination} + logger.info( + "=== Deployment combination %d/%d: %s ===", + index, len(deployment_combinations), desired or "(unchanged)", + ) + + # Applied and verified ONCE, then held still for every client + # combination below — which is what makes those results comparable. + snapshot = apply_combination(combination, fingerprint_client) + logger.info( + "Observed configuration under test:\n%s", format_settings_yaml(snapshot) + ) + + # Resolved here, not per load test: the deployment is held still for + # the whole inner loop, so the served model cannot change within it. + tokenizer = resolve_tokenizer() + logger.info("Counting tokens with the served model's tokenizer: %s", tokenizer) + + for client_index, client_combination in enumerate(client_combinations, start=1): + label = ( + f"Run {index}.{client_index} " + f"(deployment {index}/{len(deployment_combinations)}, " + f"client {client_index}/{len(client_combinations)})" + ) + # Fresh tokens per run, so none expires during a long sweep. Test + # doubles may yield a plain list, which has nothing to refresh. + if isinstance(provisioned_argv, ProvisionedArgv): + provisioned_argv.refresh() + error, output_file = run_client_combination( + benchmark, provisioned_argv, combination, client_combination, label, + results_dir=layout.per_case_dir, + varying_paths=varying_paths, tokenizer=tokenizer, + ) + overall_error = overall_error or error + + # Observed values for the deployment half, declared ones for the + # client half — the same asymmetry as the per-run log line, for + # the same reason (see BenchmarkClientArgs.snapshot). + row = summary.add_run( + knob_values={ + **snapshot, + **{s.path: s.value for s in client_combination}, + }, + result_file=output_file, + error=error, + served_model=tokenizer, + ) + # The summary row's KPI keys are undotted, so they stay top-level + # under the knob sections rather than nesting. + logger.info("%s summary:\n%s", label, format_settings_yaml(row)) + + logger.info("Sweep summary (%d run(s)) written to %s", len(summary.rows), summary.write()) + return overall_error + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py new file mode 100644 index 00000000..62ca44c9 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py @@ -0,0 +1,415 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Post-processing: one summary CSV for a whole sweep. + +``benchmark.py`` writes one CSV per load test, with one row per completed +request and no header:: + + input_tokens,output_tokens,ttft,end_to_end,err,code + +That is the right raw format — it is written incrementally under load and loses +nothing — but it answers nothing on its own. Which configuration produced it +lives in the *filename*, and only partially: :func:`~.pysweep_bench.result_file_name` +names a run by what *varies*, so the constant half of the configuration is not +there at all, and neither is the served model. + +So this module turns a sweep into a single table: one row per run, a column per +declared knob (named by its dotted config path, e.g. ``client.input_tokens``), +and the KPIs that make runs comparable — TTFT and TPOT, mean and p90. Knob +columns come first so the file reads as "these settings produced these numbers", +and every declared knob gets a column, not just the varying ones: a summary that +omitted the constants would be unreadable a month later and impossible to +concatenate with a different sweep's. + +The per-request CSVs are kept as they are. This is a summary, not a replacement: +anything the four KPIs do not answer (distribution shape, drift over the run, +the tail past p90) is still in them, and the ``result_file`` column is the +pointer back. + +**Definitions** (seconds, since that is what ``benchmark.py`` measures): + +``ttft`` + Time to first token — ``first_chunk``, as recorded: the wall time from + issuing the request to the first streamed content chunk. Prefill plus every + queueing delay ahead of it, which is why it is the KPI that moves with + concurrency. +``tpot`` + Time per output token — ``(end_to_end - ttft) / (output_tokens - 1)``: the + average inter-token gap during decode. The first token is excluded from both + sides, because its cost is TTFT; dividing by ``output_tokens`` instead (as + ``parse.py``'s ``next_token_lat`` does) charges the decode phase for a token + it did not generate, which understates TPOT by ``1/output_tokens``. The + difference is under a percent at 128 tokens and material at 8. + +p90 uses linear interpolation between the two nearest ranks (the numpy/pandas +default), so it agrees with what ``parse.py`` reports and needs no dependency +beyond the standard library — pysweep stays importable without pandas, which +matters because the config/apply half of it runs in the validation suite. +""" + +import csv +import logging +import math +import shutil +from pathlib import Path +from typing import Any, Iterable, NamedTuple, Sequence + +logger = logging.getLogger(__name__) + +#: Everything a sweep writes goes under one directory, given by ``--summaries``. +#: Relative to the CWD, like any other command-line path. +DEFAULT_SUMMARIES_DIR = "./results" + +#: The sweep's own table, at the root of that directory. Deliberately not named +#: ``bench_*.csv``: that glob is what ``parse.py`` consumes as per-request data, +#: and this file is not that shape. +SUMMARY_FILE_NAME = "benchmark_summary_results.csv" + +#: The per-run CSVs, in a subdirectory of it. Separated because there is one per +#: run and they are the raw data, while the summary is one file and is the +#: artifact people read — mixing them made the interesting file hard to find, and +#: made "wipe the previous run's results" impossible to express safely. +PER_CASE_DIR_NAME = "per_case_results" + +#: KPI and provenance columns, in the order they appear after the knob columns. +#: ``requests`` comes first of them because it is what licenses reading the +#: rest — a p90 over four requests is a number, not a measurement. +SUMMARY_COLUMNS: tuple[str, ...] = ( + "requests", + "mean_ttft", + "p90_ttft", + "mean_tpot", + "p90_tpot", + "served_model", + "error", + "result_file", +) + +#: Seconds are recorded to microseconds. Enough to keep sub-millisecond TPOT +#: differences visible, few enough that the CSV stays readable. +_PRECISION = 6 + + +class SummariesLayoutError(Exception): + """The ``--summaries`` directory cannot be prepared for a sweep.""" + + +class SummariesLayout(NamedTuple): + """Where a sweep's artifacts go, resolved once and passed down. + + Resolved to absolute paths: the load test runs through ``benchmark.py``, which + opens its output with a bare ``open()``, so anything relative would land + against the process's working directory instead. + """ + + root: Path + summary_file: Path + per_case_dir: Path + + +def _clear_directory(directory: Path) -> int: + """Delete every entry inside ``directory``, returning how many were removed. + + Symlinks are unlinked, not followed: a link inside the directory names + something outside it, which is not this sweep's to delete. + """ + removed = 0 + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + removed += 1 + return removed + + +def prepare_summaries_dir(root=DEFAULT_SUMMARIES_DIR) -> SummariesLayout: + """Create the sweep's output layout, **discarding any previous run's results**. + + A sweep's artifacts only make sense as a set: the summary indexes the per-case + CSVs, and a per-case CSV means nothing without the row that says what produced + it. Leaving the previous run's files in place would silently mix two sweeps — + stale per-case CSVs with no row in the current summary, or rows pointing at + files a shorter sweep never overwrote. So this is a clean slate, not a merge: + + * ``/`` is created if missing (parents included). + * ``/benchmark_summary_results.csv`` is deleted if present. + * ``/per_case_results/`` is emptied if present, created if not. + + **Nothing else under ```` is touched** — the deletion is confined to the + one file and the one subdirectory this function owns, so pointing + ``--summaries`` at a directory that holds other things loses none of them. Two + shapes are refused outright rather than resolved: + + * ```` or the summary path already being the wrong kind of file, which + means this directory is not a results directory and the caller has the wrong + path; + * ``per_case_results`` being a symlink, since emptying it would delete + whatever it points at, outside the tree the caller named. + + Raises :class:`SummariesLayoutError` in those cases, before any deletion. + """ + root = Path(root) + if root.exists() and not root.is_dir(): + raise SummariesLayoutError( + f"--summaries {root} exists and is not a directory; it names the " + f"directory a sweep writes into (holding {SUMMARY_FILE_NAME} and " + f"{PER_CASE_DIR_NAME}/), not a file." + ) + + summary_file = root / SUMMARY_FILE_NAME + per_case_dir = root / PER_CASE_DIR_NAME + if summary_file.is_dir(): + raise SummariesLayoutError( + f"{summary_file} is a directory; a sweep needs to write its summary " + "table there." + ) + if per_case_dir.is_symlink(): + raise SummariesLayoutError( + f"{per_case_dir} is a symlink. It is emptied before every sweep, and " + "following it would delete files outside the directory you named; " + "point --summaries at a real directory instead." + ) + if per_case_dir.exists() and not per_case_dir.is_dir(): + raise SummariesLayoutError( + f"{per_case_dir} exists and is not a directory; a sweep needs to write " + "one CSV per run there." + ) + + root.mkdir(parents=True, exist_ok=True) + + if summary_file.exists(): + summary_file.unlink() + logger.info("Discarded the previous summary %s.", summary_file) + + if per_case_dir.is_dir(): + removed = _clear_directory(per_case_dir) + if removed: + logger.info( + "Discarded %d previous result(s) from %s.", removed, per_case_dir + ) + else: + per_case_dir.mkdir() + + layout = SummariesLayout( + root=root.resolve(), + summary_file=summary_file.resolve(), + per_case_dir=per_case_dir.resolve(), + ) + logger.info( + "Writing results to %s (summary: %s, per-case CSVs: %s/).", + layout.root, SUMMARY_FILE_NAME, PER_CASE_DIR_NAME, + ) + return layout + + +class RequestRecord(NamedTuple): + """One completed request, as ``benchmark.py`` recorded it.""" + + input_tokens: int + output_tokens: int + ttft: float + end_to_end: float + err: str + code: int + + @property + def tpot(self) -> float | None: + """Mean inter-token gap during decode, or ``None`` if undefined. + + Undefined for a single-token answer: there is no gap *between* tokens to + average, and the whole latency is already reported as TTFT. + """ + if self.output_tokens < 2: + return None + return (self.end_to_end - self.ttft) / (self.output_tokens - 1) + + +def read_requests(result_file) -> list[RequestRecord]: + """Parse one ``benchmark.py`` result CSV into records. + + Rows that are malformed, unsuccessful, or nonsensical are dropped rather + than crashing the summary: a sweep is hours long and the summary is written + after every run, so one damaged line must not cost the rest of the table. + Every drop is logged at debug level. ``benchmark.py`` only enqueues 200s with + no error, so in practice nothing is dropped — the filtering is here so the + summary keeps the same meaning if that ever changes. + """ + path = Path(result_file) + if not path.exists(): + return [] + + records: list[RequestRecord] = [] + with path.open(newline="") as handle: + for line, row in enumerate(csv.reader(handle), start=1): + if len(row) < 6: + logger.debug("%s:%d: expected 6 columns, got %d; skipped", path, line, len(row)) + continue + try: + record = RequestRecord( + input_tokens=int(row[0]), + output_tokens=int(row[1]), + ttft=float(row[2]), + end_to_end=float(row[3]), + err=row[4], + code=int(row[5]), + ) + except ValueError as exc: + logger.debug("%s:%d: unparsable (%s); skipped", path, line, exc) + continue + if record.code != 200 or record.err: + logger.debug("%s:%d: not a successful request; skipped", path, line) + continue + if record.ttft <= 0 or record.end_to_end < record.ttft: + # No first chunk was ever timed, or the totals contradict each + # other. Either way the latencies are not measurements. + logger.debug("%s:%d: implausible timings %r; skipped", path, line, record) + continue + records.append(record) + return records + + +def percentile(values: Sequence[float], quantile: float) -> float | None: + """Linear-interpolated percentile, matching numpy/pandas' default method. + + Returns ``None`` for an empty sample rather than raising, so a run that + recorded nothing still produces a row (with blank KPIs) instead of aborting + the summary — "this configuration produced no data" is itself a result worth + keeping in the table. + """ + ordered = sorted(values) + if not ordered: + return None + if len(ordered) == 1: + return ordered[0] + position = (len(ordered) - 1) * quantile + lower, upper = math.floor(position), math.ceil(position) + if lower == upper: + return ordered[lower] + return ordered[lower] + (ordered[upper] - ordered[lower]) * (position - lower) + + +def _mean(values: Sequence[float]) -> float | None: + return sum(values) / len(values) if values else None + + +def _round(value: float | None) -> str: + """Render a KPI for the CSV; an undefined one renders as an empty cell.""" + return "" if value is None else f"{round(value, _PRECISION)}" + + +def summarize_requests(records: Iterable[RequestRecord]) -> dict[str, Any]: + """Aggregate request records into the KPI columns. + + ``requests`` counts the sample the TTFT statistics are over. The TPOT + statistics are over the subset with at least two output tokens (see + :attr:`RequestRecord.tpot`); that subset is normally the whole sample, and + when it is not, a blank TPOT with a non-zero ``requests`` is the honest + reading — the run happened, the decode rate is not defined for it. + """ + records = list(records) + ttfts = [record.ttft for record in records] + tpots = [record.tpot for record in records if record.tpot is not None] + return { + "requests": len(records), + "mean_ttft": _mean(ttfts), + "p90_ttft": percentile(ttfts, 0.9), + "mean_tpot": _mean(tpots), + "p90_tpot": percentile(tpots, 0.9), + } + + +class SweepSummary: + """Accumulates one row per run and writes the sweep's summary CSV. + + Rewritten in full after every run rather than appended to. A sweep of a + dozen runs is a few hundred bytes, and the rewrite means the file on disk is + always a complete, valid CSV of everything finished so far — so a sweep that + is killed at hour three (or a model rollout that fails midway) still leaves a + readable table instead of a truncated last line. + + ``knob_paths`` fixes the columns up front, from the config rather than from + the rows: every run of a sweep has the same knobs, and taking them from the + config means the header is right before the first run finishes. It is written + at construction for that reason — the first run of a sweep can be an hour of + load behind a multi-replica rollout, and until then a missing file is + indistinguishable from a harness that forgot to summarize. A header-only file + says "this sweep is running and here is the shape of its results". + """ + + def __init__( + self, + knob_paths: Sequence[str], + path=Path(DEFAULT_SUMMARIES_DIR) / SUMMARY_FILE_NAME, + ): + self.knob_paths = list(knob_paths) + self.path = Path(path) + self.rows: list[dict[str, Any]] = [] + self.write() + + def _pointer(self, result_file) -> str: + """How the ``result_file`` column names a per-case CSV. + + Relative to the summary's own directory when the CSV is inside it, which + is the normal case (``per_case_results/bench_….result.csv``). That keeps + the whole results directory movable: copy it off the benchmark host or + rename it, and every pointer still resolves. An absolute path would name a + directory that only existed on the machine that ran the sweep. + + A CSV from outside the directory is recorded verbatim, since there is no + relative name for it that means anything. + """ + path = Path(result_file) + try: + return str(path.relative_to(self.path.parent)) + except ValueError: + return str(result_file) + + @property + def columns(self) -> list[str]: + """Header: knob columns in dotted-path form, then the KPIs.""" + return self.knob_paths + list(SUMMARY_COLUMNS) + + def add_run( + self, + knob_values: dict[str, Any], + result_file, + error: int = 0, + served_model: str | None = None, + ) -> dict[str, Any]: + """Summarize one finished run and return the row that was recorded. + + ``knob_values`` maps dotted paths to the values that run used — observed + read-backs for deployment knobs (what the cluster actually did), declared + values for client knobs (there is nothing to observe: they are arguments + to the process). A path with no entry renders blank, which is what makes + it safe to call before every knob has a value. + """ + summary = summarize_requests(read_requests(result_file)) + row: dict[str, Any] = {path: knob_values.get(path, "") for path in self.knob_paths} + row.update(summary) + row["served_model"] = served_model or "" + row["error"] = error + row["result_file"] = self._pointer(result_file) + self.rows.append(row) + self.write() + return row + + def write(self) -> Path: + """Write the whole table, header included, replacing any previous copy.""" + with self.path.open("w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=self.columns) + writer.writeheader() + for row in self.rows: + writer.writerow( + { + column: ( + _round(row[column]) + if column in ("mean_ttft", "p90_ttft", "mean_tpot", "p90_tpot") + else row.get(column, "") + ) + for column in self.columns + } + ) + return self.path diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py b/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py new file mode 100644 index 00000000..bc61720e --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py @@ -0,0 +1,253 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Client for the ChatQNA ``system_fingerprint`` runtime API (Runtime API plane). + +Wraps the two endpoints the runtime-plane properties use: + +- ``POST change_arguments`` — the **setter**. A list of + ``{"name": , "data": {...}}`` entries. +- ``GET config?params_key=`` — the **reader**. Returns that one + component's live arguments under ``values``. + +The reader is per-component, which is why every property names the component it +drives: asking for ``retriever`` gets the retriever's arguments and nothing else, +so a property can never accidentally read a same-named key belonging to another +component. + +**Scope.** Writes carry a ``pipeline``/``tenant`` pair, because the microservice +stores arguments per scope and the ChatQNA router reads the ``chatqna``/``_global`` +one — a write with no scope lands somewhere the pipeline under test does not +read. Reads take the same pair for symmetry. + +Two transports are supported (DESIGN.md "Reaching pod APIs"): + +- :class:`PortForwardTransport` (default) — forwards to ``fingerprint-svc`` via + ``kr8s``. Needs no token, because authentication is enforced at the ingress + gateway and this path is pod-local. That makes it the robust choice for a + multi-hour sweep: nothing to expire. +- :class:`IngressTransport` — the ERAG domain, authenticated with a Keycloak + access token. Used when the cluster is only reachable through its ingress. +""" + +import logging +import os +import secrets +import socket +import time +from contextlib import contextmanager + +import kr8s +import requests +import urllib3 + +from tests.e2e.validation.buildcfg import cfg + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +logger = logging.getLogger(__name__) + +FINGERPRINT_NAMESPACE = "fingerprint" +FINGERPRINT_SERVICE = "fingerprint-svc" +FINGERPRINT_PORT = 6012 +API_PREFIX = "/v1/system_fingerprint" + +# The scope the ChatQNA router reads its component arguments from. '_global' is +# the shared tenant; see FingerprintApiHelper.set_chatqa_component_parameters, +# which fixes the same pair for the e2e suite's ChatQNA tests. +PIPELINE = "chatqna" +TENANT = "_global" + + +def find_unused_port(start: int = 10000, end: int = 60000) -> int: + """Return a currently-free local TCP port in ``[start, end)``.""" + while True: + port = secrets.randbelow(end - start) + start + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + if sock.connect_ex(("127.0.0.1", port)) != 0: + return port + + +def wait_until_listening(port: int, timeout: float = 10.0) -> None: + """Block until a local port accepts connections. + + ``PortForward.start()`` returns before the tunnel is actually listening, so + probe the socket to avoid a connection-refused race. + """ + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + if sock.connect_ex(("127.0.0.1", port)) == 0: + return + time.sleep(0.1) + raise TimeoutError(f"port-forward to 127.0.0.1:{port} did not start within {timeout}s") + + +@contextmanager +def object_port_forward(obj, remote_port: int): + """Port-forward ``remote_port`` on any kr8s object; yield the local port. + + Works for a ``Service`` (load-balanced across its endpoints) or a ``Pod`` + (one specific replica). The forward is scoped to the context and torn down + afterwards. This is the single code path for reaching in-cluster HTTP APIs + pod-locally — shared by the fingerprint transport and the benchmark's ChatQNA + endpoint. + """ + local_port = find_unused_port() + pf = kr8s.portforward.PortForward(obj, remote_port=remote_port, local_port=local_port) + pf.start() + try: + wait_until_listening(local_port) + yield local_port + finally: + pf.stop() + + +@contextmanager +def service_port_forward(namespace: str, service: str, remote_port: int): + """Port-forward ``service:remote_port`` via kr8s; yield the local port.""" + svc = kr8s.objects.Service.get(service, namespace=namespace) + with object_port_forward(svc, remote_port) as local_port: + yield local_port + + +class IngressTransport: + """Reach the fingerprint API over the ERAG ingress with a Keycloak token. + + The token is fetched per session rather than cached, because a sweep runs for + hours and a cached one would expire mid-product. ``keycloak_helper`` is the + maintained helper (see :mod:`.authentication`), whose ``access_token`` + property already re-mints on each read. + """ + + def __init__(self, keycloak_helper, domain: str | None = None): + self.keycloak_helper = keycloak_helper + self.domain = domain or cfg.get("base_domain_name") + if not self.domain: + raise ValueError( + "No ERAG domain available for the ingress transport; call " + "authentication.load_build_config() first or pass domain=." + ) + + @contextmanager + def session(self): + base_url = f"https://{self.domain}{API_PREFIX}" + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {self.keycloak_helper.access_token}", + } + yield base_url, headers + + +class PortForwardTransport: + """Reach the fingerprint API by port-forwarding to the service via kr8s. + + The forward is scoped to the ``session()`` context and torn down afterwards, + so a sweep holds no tunnel open between property reads. + """ + + def __init__( + self, + namespace: str = FINGERPRINT_NAMESPACE, + service: str = FINGERPRINT_SERVICE, + remote_port: int = FINGERPRINT_PORT, + ): + self.namespace = namespace + self.service = service + self.remote_port = remote_port + + @contextmanager + def session(self): + with service_port_forward(self.namespace, self.service, self.remote_port) as local_port: + # No auth needed pod-locally; the gateway enforces it on ingress. + yield f"http://127.0.0.1:{local_port}{API_PREFIX}", {"Content-Type": "application/json"} + + +class HelperFingerprintClient: + """Adapter exposing the pysweep client interface over the suite helper. + + When pysweep runs as part of the e2e validation suite the maintained + :class:`tests.e2e.helpers.fingerprint_api_helper.FingerprintApiHelper` + already knows how to reach the fingerprint API over ingress (with the suite's + Keycloak auth). Reusing it keeps the e2e property tests exercising the same + transport the rest of the suite does, rather than a pysweep-only one. This + adapter just re-expresses it as the ``change_arguments`` / ``read_values`` + interface the property classes expect. + """ + + def __init__(self, fingerprint_api_helper): + self._helper = fingerprint_api_helper + + def change_arguments(self, body: list[dict]) -> None: + resp = self._helper.change_arguments(body, pipeline=PIPELINE, tenant=TENANT) + if resp.status_code != 200: + raise RuntimeError( + f"change_arguments failed (status {resp.status_code}): {resp.text}" + ) + + def read_values(self, component: str) -> dict: + resp = self._helper.read_config(component, pipeline=PIPELINE, tenant=TENANT) + if resp.status_code != 200: + raise RuntimeError( + f"config?params_key={component} failed (status {resp.status_code}): {resp.text}" + ) + return resp.json().get("values", {}) or {} + + +class FingerprintClient: + """Thin client over ``/v1/system_fingerprint/{change_arguments,config}``. + + Delegates connectivity to a transport so the same logic works whether the + API is reached over ingress or a port-forward. + """ + + def __init__(self, transport, pipeline: str = PIPELINE, tenant: str = TENANT): + self.transport = transport + self.pipeline = pipeline + self.tenant = tenant + + @property + def _scope(self) -> dict: + return {"pipeline": self.pipeline, "tenant": self.tenant} + + def change_arguments(self, body: list[dict]) -> None: + """POST a change_arguments body to the configured scope; raises on non-2xx.""" + with self.transport.session() as (base_url, headers): + resp = requests.post( + f"{base_url}/change_arguments", + headers=headers, + json=body, + params=self._scope, + verify=False, + timeout=30, + ) + resp.raise_for_status() + + def read_values(self, component: str) -> dict: + """Return one component's live arguments (the response's ``values`` object).""" + with self.transport.session() as (base_url, headers): + resp = requests.get( + f"{base_url}/config", + headers=headers, + params={"params_key": component, **self._scope}, + verify=False, + timeout=30, + ) + resp.raise_for_status() + return resp.json().get("values", {}) or {} + + +def default_transport(keycloak_helper=None): + """Pick a transport from the environment. + + ``PYSWEEP_FINGERPRINT_TRANSPORT=portforward`` (default) forwards to the + service; ``=ingress`` uses the ERAG domain and requires a Keycloak helper. + """ + mode = os.getenv("PYSWEEP_FINGERPRINT_TRANSPORT", "portforward").lower() + if mode == "ingress": + if keycloak_helper is None: + from .authentication import keycloak_helper as build_keycloak_helper + + keycloak_helper = build_keycloak_helper() + return IngressTransport(keycloak_helper) + return PortForwardTransport() diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py b/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py new file mode 100644 index 00000000..c4892fbc --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py @@ -0,0 +1,160 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The model the ChatQNA pipeline is **observed** to generate with. + +Not a knob: nothing here writes. The runner needs the served model whether or not +a sweep varies it, because ``benchmark.py``'s ``-m`` must be that model's +tokenizer (see ``pysweep_bench.resolve_tokenizer``). + +The model is read where it takes effect. ChatQNA's LLM microservice (``llm-usvc``) +sends ``LLM_MODEL_NAME`` as ``model=`` on every request, and that variable comes +from the ``llm-usvc-config`` ConfigMap through ``envFrom``, which is resolved once, +at container start. So :meth:`ServedModel.read` execs into every live replica for +the value its process actually has, and additionally requires that model to be a +Ready ``LLMInferenceService`` in ``llm-inference``: a pipeline pointed at a model +nothing serves answers nothing, and that is not a configuration to benchmark. + +**Values are catalog names, not repo ids.** ``llama3-8b-awq``, not +``casperhansen/llama-3-8b-instruct-awq``: the short name is what the gateway routes +on and what ``LLM_MODEL_NAME`` contains. :mod:`.model_catalog` maps it to the +HuggingFace repo id the tokenizer needs. +""" + +import logging + +import kr8s +from kr8s.objects import APIObject + +from .base import PropertyReadError + +logger = logging.getLogger(__name__) + +# The ChatQNA LLM microservice: the Deployment is 'llm-svc-deployment' but the +# stable handle across chart versions is the label, and the container name is +# needed because the pod also has an init container. +PIPELINE_NAMESPACE = "chatqna" +LLM_USVC_LABEL_SELECTOR = {"app.kubernetes.io/name": "llm-usvc"} +LLM_USVC_CONTAINER = "llm-usvc" +MODEL_NAME_ENV = "LLM_MODEL_NAME" + +# Where model serving lives. +INFERENCE_NAMESPACE = "llm-inference" + + +class LLMInferenceService(APIObject): + """Minimal kr8s binding for KServe's ``LLMInferenceService``. + + Hand-written rather than looked up dynamically so the apiVersion this + property depends on is stated in one visible place: if the CRD moves past + ``v1alpha2``, the failure is a clear "not found" here rather than a subtle + mismatch elsewhere. + """ + + kind = "LLMInferenceService" + version = "serving.kserve.io/v1alpha2" + endpoint = "llminferenceservices" + plural = "llminferenceservices" + singular = "llminferenceservice" + namespaced = True + + +class ServedModel: + """Reader for the model every ChatQNA LLM replica generates with.""" + + def __init__( + self, + namespace: str = PIPELINE_NAMESPACE, + inference_namespace: str = INFERENCE_NAMESPACE, + ): + self.namespace = namespace + self.inference_namespace = inference_namespace + + def _pipeline_pods(self) -> list: + """Return the LLM microservice pods, or raise if none are selectable.""" + try: + pods = list( + kr8s.get("pods", namespace=self.namespace, label_selector=LLM_USVC_LABEL_SELECTOR) + ) + except Exception as exc: # noqa: BLE001 - reported as an unreadable state + raise PropertyReadError( + f"Cannot list llm-usvc pods in ns/{self.namespace} " + f"(selector {LLM_USVC_LABEL_SELECTOR}): {exc}" + ) from exc + # Pods being replaced are not part of the observed configuration; counting + # them would make read() disagree with itself for the whole grace period. + live = [pod for pod in pods if not pod.metadata.get("deletionTimestamp")] + if not live: + raise PropertyReadError( + f"No live llm-usvc pods in ns/{self.namespace} matching " + f"{LLM_USVC_LABEL_SELECTOR}; the ChatQNA LLM microservice is not running." + ) + return live + + def _pod_model(self, pod) -> str: + """Return the model name one replica's process actually has in its env. + + Read by exec, not from the ConfigMap or the pod spec, because ``envFrom`` + is resolved once at container start: the ConfigMap can already hold the + new value while this process still runs with the old one, and that gap is + precisely what must not be reported as converged. + """ + command = ["sh", "-c", f"printf %s \"${MODEL_NAME_ENV}\""] + try: + result = pod.exec(command, container=LLM_USVC_CONTAINER) + except Exception as exc: # noqa: BLE001 - starting/terminating pod + raise PropertyReadError( + f"Cannot read ${MODEL_NAME_ENV} from pod {pod.name}: {exc}" + ) from exc + stdout = result.stdout + if isinstance(stdout, bytes): + stdout = stdout.decode() + model = stdout.strip() + if not model: + raise PropertyReadError( + f"Pod {pod.name} has an empty ${MODEL_NAME_ENV}; it is not pointed " + "at any model." + ) + return model + + def _model_ready(self, model: str) -> bool: + """Whether ``model`` is a Ready ``LLMInferenceService`` in the inference namespace.""" + try: + llmisvc = LLMInferenceService.get(model, namespace=self.inference_namespace) + except Exception as exc: # noqa: BLE001 - absent or CRD missing + logger.debug("LLMInferenceService %r not readable: %s", model, exc) + return False + conditions = (llmisvc.raw.get("status", {}) or {}).get("conditions", []) or [] + return any( + cond.get("type") == "Ready" and cond.get("status") == "True" + for cond in conditions + ) + + def read(self) -> str: + """Return the model the pipeline is **observed** to be generating with. + + Raises :class:`PropertyReadError` unless the whole picture is consistent: + every live replica names the same model, and that model is Ready in + ``llm-inference``. Replicas disagreeing means a rollout is in flight; + the model not being Ready means the pipeline points somewhere that cannot + answer. Neither is a configuration a benchmark may be run against, so + both fail loudly rather than being reported as a model. + """ + observed = {pod.name: self._pod_model(pod) for pod in self._pipeline_pods()} + + distinct = set(observed.values()) + if len(distinct) > 1: + raise PropertyReadError( + "llm-usvc replicas do not agree on the model (a rollout is likely " + f"in progress): {observed}" + ) + model = distinct.pop() + + if not self._model_ready(model): + raise PropertyReadError( + f"The pipeline points at model {model!r} but no Ready " + f"LLMInferenceService of that name exists in " + f"ns/{self.inference_namespace}; nothing is serving it." + ) + logger.debug("Observed pipeline model %r across %d replica(s).", model, len(observed)) + return model diff --git a/src/tests/e2e/validation/pysweep/conftest.py b/src/tests/e2e/validation/pysweep/conftest.py new file mode 100644 index 00000000..70b71979 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/conftest.py @@ -0,0 +1,94 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Fixtures for pysweep's e2e tests, run *inside* the validation suite. + +These tests live under ``validation`` (next to ``test_fingerprint.py`` et al.) +so they collect and report through the shared ``src/tests/e2e/conftest.py`` — +same invocation (``tox -e e2e``), same allure report, same session fixtures +(``k8s_helper``, ``keycloak_helper``, ``fingerprint_api_helper``, the +required-actions handling). The pysweep *package* itself lives at +``tests/e2e/benchmarks/chatqna/pysweep`` and is imported by absolute path. + +Per DESIGN.md objective 6, these are the "stay in sync with the deployment" +contract for the property classes: they exercise ``read`` / ``apply`` / +``is_satisfied`` against the live deployment so a drift in the runtime-API +contract fails here rather than silently mis-configuring a benchmark. + +Access is layered on the maintained suite helpers rather than duplicated: +- the fingerprint API is reached via the suite's ``fingerprint_api_helper`` + (ingress + Keycloak auth), falling back to a kr8s port-forward for + deployments where the API has no ingress route; +- the pysweep-specific RBAC preflight (:class:`KubernetesAccess`) is layered on + the suite ``k8s_helper`` to fail early and clearly if the kubeconfig identity + lacks a permission a sweep will need. +""" + +import logging + +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( + AccessError, + KubernetesAccess, +) +from tests.e2e.benchmarks.chatqna.pysweep.runtime_api import ( + HelperFingerprintClient, + PortForwardTransport, + FingerprintClient, +) +from tests.e2e.validation.buildcfg import cfg + +logger = logging.getLogger(__name__) + +# Component asked for when probing whether the fingerprint API answers at all. +# Any deployed component would do; 'llm' is present in every ChatQNA pipeline. +PROBE_COMPONENT = "llm" + + +@pytest.fixture(scope="session") +def pysweep_kubernetes_access(k8s_helper): + """Verify (without mutation) that pysweep has the cluster access it needs. + + Layered on the suite ``k8s_helper``. Skips if a required permission is + missing — that is an environment/RBAC problem, not a property regression. + """ + access = KubernetesAccess(k8s_helper=k8s_helper) + try: + access.verify() + except AccessError as exc: + pytest.skip(f"Kubernetes access prerequisites not met: {exc}") + return access + + +@pytest.fixture(scope="session") +def fingerprint_client(fingerprint_api_helper, pysweep_kubernetes_access): + """A pysweep FingerprintClient backed by the suite helper. + + Prefers the maintained ingress helper. If the fingerprint API is not routed + on this deployment (no ingress route -> the probe fails), falls back to a + kr8s port-forward to ``fingerprint-svc``. Skips if neither path reaches the + API, so individual tests fail only on genuine property regressions. + """ + if not cfg.get("fingerprint_enabled"): + pytest.skip("Fingerprint is not deployed") + + # Reachability probe. The reader is per-component, so probing needs a + # component name; 'llm' is the one every ChatQNA deployment has. + helper_client = HelperFingerprintClient(fingerprint_api_helper) + try: + helper_client.read_values(PROBE_COMPONENT) + return helper_client + except Exception as exc: # noqa: BLE001 + logger.warning( + "Fingerprint API not reachable via the suite helper (%s); " + "falling back to a port-forward transport.", + exc, + ) + + pf_client = FingerprintClient(PortForwardTransport()) + try: + pf_client.read_values(PROBE_COMPONENT) + except Exception as exc: # noqa: BLE001 + pytest.skip(f"system_fingerprint API not reachable (ingress or port-forward): {exc}") + return pf_client diff --git a/src/tests/e2e/validation/pysweep/test_config_unit.py b/src/tests/e2e/validation/pysweep/test_config_unit.py new file mode 100644 index 00000000..c53b017b --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_config_unit.py @@ -0,0 +1,448 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for the pysweep sweep-config validator. + +These test the schema/validation/expansion logic only — no cluster is needed, +so they run anywhere the requirements are installed. They assert three guarantees +the design leans on: (1) any YAML that violates the schema raises ConfigError, +(2) each declared deployment knob is bound to the correct Property class and +expands into the right cartesian product, and (3) client knobs are required, +bound to the right ``benchmark.py`` flag, and expand into their own separate +product (the runner's inner loop). +""" + +import ast +import textwrap +from pathlib import Path + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import client_args +from tests.e2e.benchmarks.chatqna.pysweep.base import Plane +from tests.e2e.benchmarks.chatqna.pysweep.config import ( + ConfigError, + SweepConfig, + load_config, + load_run_config, +) +from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens + +# The client section is mandatory, so every config in these tests carries one. +# Kept minimal and boring: these values are never asserted on except by the +# client-specific tests below, which override what they care about. +CLIENT = { + "question_file": "questions-short.csv", + "concurrency": 4, + "duration": "3m", + "worker_startup_delay": "0s", + "failures_allowed": 200, + "input_tokens": 128, + "warmup_requests": 1, +} + +# Same, as YAML, for the file-loading tests. +CLIENT_YAML = """ + client: + question_file: questions-short.csv + concurrency: 4 + duration: 3m + worker_startup_delay: 0s + failures_allowed: 200 + input_tokens: 128 + warmup_requests: 1 +""" + + +def _sweep(**sections): + """A valid config: the required client section plus whatever is under test.""" + return {"client": dict(CLIENT), **sections} + + +def _client(**overrides): + """A config whose client section differs from the default in ``overrides``.""" + return {"client": {**CLIENT, **overrides}} + + +def _write(tmp_path, text): + path = tmp_path / "sweep.yaml" + path.write_text(textwrap.dedent(text)) + return path + + +def _benchmark_option_flags(): + """The flags ``benchmark.parse_args`` adds, read from its source. + + Parsed rather than imported: ``benchmark.py`` pulls in ``transformers``, which + is only needed to *run* a load test and is not in the validation suite's + requirements (the runner imports it lazily for the same reason). Reading the + source keeps this check on the real parser without that dependency. + """ + source = ( + Path(__file__).resolve().parents[3] / "e2e/benchmarks/chatqna/benchmark.py" + ).read_text() + tree = ast.parse(source) + parse_args = next( + node + for node in ast.walk(tree) + if isinstance(node, ast.FunctionDef) and node.name == "parse_args" + ) + return { + node.args[0].value + for node in ast.walk(parse_args) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "add_argument" + and node.args + and isinstance(node.args[0], ast.Constant) + } + + +@allure.feature("pysweep") +def test_config_with_only_client_knobs_is_valid(): + """A sweep may vary load alone: no deployment knobs is a valid sweep. + + Nothing is declared, so the deployment product is the single empty + combination — one pass with nothing to apply, benchmarking the deployment + exactly as it stands. + """ + cfg = load_config(_sweep()) + assert isinstance(cfg, SweepConfig) + assert list(cfg.iter_settings()) == [] + assert cfg.deployment_combinations() == [()] + # The client product is never empty either — the knobs are required. + assert len(cfg.client_combinations()) == 1 + + +@allure.feature("pysweep") +def test_config_without_client_section_raises(): + """Load parameters must be declared; an empty config is no longer valid. + + An omitted deployment knob means "leave it alone", which is observable. An + omitted client knob has no such reading — the load test would silently run on + benchmark.py's defaults and no record of it would exist. + """ + with pytest.raises(ConfigError, match="client"): + load_config({}) + + +@allure.feature("pysweep") +def test_single_value_binds_to_property_and_yields_one_combination(): + cfg = load_config(_sweep(llms={"max_new_tokens": 256})) + + settings = list(cfg.iter_settings()) + assert len(settings) == 1 + path, property_cls, values = settings[0] + assert path == "llms.max_new_tokens" + assert property_cls is MaxNewTokens + assert values == [256] + + combos = cfg.deployment_combinations() + assert len(combos) == 1 + (setting,) = combos[0] + assert setting.path == "llms.max_new_tokens" + assert setting.property_cls is MaxNewTokens + assert setting.value == 256 + + +@allure.feature("pysweep") +def test_list_value_expands_to_product(): + cfg = load_config(_sweep(llms={"max_new_tokens": [128, 256, 512]})) + combos = cfg.deployment_combinations() + assert [c[0].value for c in combos] == [128, 256, 512] + assert all(c[0].property_cls is MaxNewTokens for c in combos) + + +@allure.feature("pysweep") +def test_omitted_knob_is_not_swept(): + """Optional *deployment* knobs left out contribute nothing to the sweep.""" + cfg = load_config(_sweep(llms={})) + assert list(cfg.iter_settings()) == [] + # No dimension to expand, so the product stays at its one empty combination. + assert cfg.deployment_combinations() == [()] + + +@allure.feature("pysweep") +def test_unknown_top_level_key_raises(): + with pytest.raises(ConfigError): + load_config(_sweep(llmsss={"max_new_tokens": 256})) + + +@allure.feature("pysweep") +def test_unknown_knob_key_raises(): + with pytest.raises(ConfigError): + load_config(_sweep(llms={"max_new_tokenz": 256})) + + +@allure.feature("pysweep") +@pytest.mark.parametrize("bad", ["abc", -1, 0, 1.5, [128, "oops"]]) +def test_wrong_value_type_or_range_raises(bad): + with pytest.raises(ConfigError): + load_config(_sweep(llms={"max_new_tokens": bad})) + + +@allure.feature("pysweep") +def test_top_level_must_be_mapping(tmp_path): + path = tmp_path / "sweep.yaml" + path.write_text("- 1\n- 2\n- 3\n") + with pytest.raises(ConfigError): + load_config(path) + + +@allure.feature("pysweep") +def test_load_from_yaml_file(tmp_path): + path = _write( + tmp_path, + """ + llms: + max_new_tokens: [128, 256] + """ + + CLIENT_YAML, + ) + cfg = load_config(path) + assert [c[0].value for c in cfg.deployment_combinations()] == [128, 256] + + +@allure.feature("pysweep") +def test_malformed_yaml_raises(tmp_path): + path = tmp_path / "sweep.yaml" + path.write_text("llms: [unbalanced\n") + with pytest.raises(ConfigError): + load_config(path) + + +@allure.feature("pysweep") +def test_max_new_tokens_is_runtime_api_plane(): + """Guards the outer/inner loop ordering assumption in combinations().""" + assert MaxNewTokens.plane == Plane.RUNTIME_API + + +# -- client knobs ------------------------------------------------------------- + + +@allure.feature("pysweep") +@pytest.mark.parametrize("missing", sorted(CLIENT)) +def test_every_scenario_client_knob_is_required(missing): + """Omitting any load parameter is a config error, naming the missing key. + + Parametrised over the whole set rather than spot-checking one, because the + point is that none of them silently falls back to benchmark.py's default. + """ + section = {k: v for k, v in CLIENT.items() if k != missing} + with pytest.raises(ConfigError, match=missing): + load_config({"client": section}) + + +@allure.feature("pysweep") +def test_client_knobs_bind_to_benchmark_flags(): + """Each client knob is bound to the benchmark.py option it renders to.""" + cfg = load_config(_client()) + bound = {path: arg.flag for path, arg, _ in cfg.iter_client_settings()} + assert bound == { + "client.question_file": "-f", + "client.concurrency": "-c", + "client.duration": "-d", + "client.worker_startup_delay": "-u", + "client.failures_allowed": "-e", + "client.input_tokens": "-x", + "client.warmup_requests": "-w", + } + + +@allure.feature("pysweep") +def test_every_benchmark_option_is_mirrored(): + """The adapter must cover benchmark.parse_args exactly — no drift either way. + + A ``benchmark.py`` option missing here cannot be swept; one that exists here + but not there would be rendered into argv and rejected at run time. Compared + against the real parser so the two cannot diverge silently. + """ + mirrored = [a.flag for a in client_args.CLIENT_ARGS] + assert set(mirrored) == _benchmark_option_flags() + assert len(mirrored) == len(set(mirrored)), "a benchmark option is mirrored twice" + # Mirrored != declarable: every option is covered, but -m is supplied by the + # runner (from the served model) and so has no field on ClientConfig. + declarable = {a.yaml_name for a in client_args.CLIENT_ARGS if not a.derived} + assert set(SweepConfig.model_fields["client"].annotation.model_fields) == declarable + + +@allure.feature("pysweep") +def test_client_list_expands_to_its_own_product(): + """Client knobs form a separate product — the runner's inner loop.""" + cfg = load_config(_client(concurrency=[1, 16])) + # The deployment product is untouched by client knobs: still one empty pass. + assert cfg.deployment_combinations() == [()] + combos = cfg.client_combinations() + assert len(combos) == 2 + assert [s.value for c in combos for s in c if s.path == "client.concurrency"] == [1, 16] + + +@allure.feature("pysweep") +def test_max_concurrency_is_the_widest_declared_value(): + """One bearer file serves every combination, so it is sized to the widest one. + + Taking the max rather than the last/first value is the point: a sweep that + ramps 1 -> 128 would otherwise leave the 128-worker run short of tokens, and + benchmark.py quits any worker whose bearer line is empty. + """ + assert load_config(_client(concurrency=[1, 16, 128])).max_concurrency() == 128 + assert load_config(_client(concurrency=[128, 16, 1])).max_concurrency() == 128 + # A scalar is the whole sweep's concurrency. + assert load_config(_client(concurrency=4)).max_concurrency() == 4 + + +@allure.feature("pysweep") +def test_client_product_multiplies_dimensions(): + cfg = load_config(_client(concurrency=[1, 16], input_tokens=[128, 256])) + combos = cfg.client_combinations() + pairs = [ + ( + next(s.value for s in c if s.path == "client.concurrency"), + next(s.value for s in c if s.path == "client.input_tokens"), + ) + for c in combos + ] + assert pairs == [(1, 128), (1, 256), (16, 128), (16, 256)] + + +@allure.feature("pysweep") +def test_client_knobs_are_not_properties(): + """Client settings must never reach the apply/converge/verify path. + + ``iter_settings`` (which feeds ``combinations()`` and thus ``build_property``) + yields only Property-bound knobs, so a client knob cannot be mistaken for + something the runner should apply to the cluster. + """ + cfg = load_config(_client(concurrency=[1, 16])) + assert list(cfg.iter_settings()) == [] + assert not hasattr(cfg.client_combinations()[0][0], "property_cls") + + +@allure.feature("pysweep") +def test_server_and_bearer_file_are_optional_and_not_swept(): + """The auto-provisioned connection settings default to absent.""" + cfg = load_config(_client()) + assert cfg.client_provisioning_argv() == [] + assert "server" not in cfg.declared_client_names() + # Declared, they render once for the whole sweep rather than as a dimension. + cfg = load_config(_client(server="https://erag.com/api/v1/chatqna", bearer_file="uat.txt")) + assert cfg.client_provisioning_argv() == [ + "-s", "https://erag.com/api/v1/chatqna", "-b", "uat.txt", + ] + assert [p for p, _, _ in cfg.iter_client_settings() if "server" in p] == [] + + +@allure.feature("pysweep") +@pytest.mark.parametrize("bad", ["3 minutes", "3", "m", "3d", 3, ""]) +def test_duration_must_be_a_parsable_duration(bad): + """benchmark.duration_to_seconds raises KeyError on anything else. + + Catching the shape here turns a crash an hour into a sweep into a config + error before anything is applied. + """ + with pytest.raises(ConfigError): + load_config(_client(duration=bad)) + + +@allure.feature("pysweep") +@pytest.mark.parametrize("bad", [0, -1, "many", 1.5]) +def test_concurrency_must_be_a_positive_integer(bad): + """``-c 0`` starts no workers and would produce an empty result CSV.""" + with pytest.raises(ConfigError): + load_config(_client(concurrency=bad)) + + +@allure.feature("pysweep") +@pytest.mark.parametrize("knob", ["input_tokens", "warmup_requests", "failures_allowed"]) +def test_zero_is_allowed_where_it_is_meaningful(knob): + """0 is a real setting for these: no input fixing, no warmup, no failures.""" + cfg = load_config(_client(**{knob: 0})) + assert next(v for p, _, v in cfg.iter_client_settings() if p.endswith(knob)) == [0] + + +@allure.feature("pysweep") +def test_unknown_client_knob_raises(): + with pytest.raises(ConfigError): + load_config(_client(concurency=4)) # missing 'r' + + +@allure.feature("pysweep") +def test_tokenizer_cannot_be_declared(): + """``-m`` is not a knob: it must be the served model, so it is derived. + + Rejecting the key rather than accepting and overriding it is the point — the + only thing declaring it could express is a tokenizer that disagrees with the + model whose tokens are being counted. + """ + with pytest.raises(ConfigError): + load_config(_client(tokenizer="nomic-ai/nomic-embed-text-v1")) + assert client_args.TOKENIZER.derived + # Still mirrored, so the runner can render it; just not swept or declared. + assert client_args.TOKENIZER in client_args.CLIENT_ARGS + assert not client_args.TOKENIZER.sweepable + cfg = load_config(_client()) + assert [p for p, _, _ in cfg.iter_client_settings() if "tokenizer" in p] == [] + + +@allure.feature("pysweep") +def test_varying_paths_reports_only_multi_valued_knobs(): + """Result files are named by what varies; scalars distinguish nothing.""" + cfg = load_config( + { + "client": {**CLIENT, "concurrency": [1, 16]}, + "llms": {"max_new_tokens": [128, 256]}, + } + ) + assert cfg.varying_paths() == {"client.concurrency", "llms.max_new_tokens"} + + +@allure.feature("pysweep") +def test_shipped_example_sweep_config_is_valid(): + """The committed examples/sweep.yaml must load (docs stay honest).""" + example = ( + Path(__file__).resolve().parents[3] + / "e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml" + ) + cfg = load_config(example) + assert cfg.deployment_combinations() + assert cfg.client_combinations() + + +# -- run config (--config) ---------------------------------------------------- + + +@allure.feature("pysweep") +def test_run_config_reads_display_kubernetes_client_logs(tmp_path): + path = tmp_path / "config.yaml" + path.write_text("display_kubernetes_client_logs: true\n") + assert load_run_config(path).display_kubernetes_client_logs is True + + +@allure.feature("pysweep") +def test_kubernetes_client_logs_default_to_off(): + """The kr8s/httpx per-call chatter is noise by default (one line per request).""" + assert load_run_config({}).display_kubernetes_client_logs is False + + +@allure.feature("pysweep") +def test_run_config_rejects_unknown_key(): + """Same strictness as the sweep config: a typo must not be ignored.""" + with pytest.raises(ConfigError): + load_run_config({"display_kubernetes_client_log": False}) # missing trailing 's' + + +@allure.feature("pysweep") +def test_run_config_rejects_non_boolean(): + with pytest.raises(ConfigError): + load_run_config({"display_kubernetes_client_logs": "sometimes"}) + + +@allure.feature("pysweep") +def test_shipped_example_run_config_is_valid(): + """The committed examples/config.yaml must load (docs stay honest).""" + example = ( + Path(__file__).resolve().parents[3] + / "e2e/benchmarks/chatqna/pysweep/examples/config.yaml" + ) + assert load_run_config(example).display_kubernetes_client_logs is False diff --git a/src/tests/e2e/validation/pysweep/test_max_tokens.py b/src/tests/e2e/validation/pysweep/test_max_tokens.py new file mode 100644 index 00000000..cda86cad --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_max_tokens.py @@ -0,0 +1,74 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""e2e test for the ``MaxNewTokens`` property. + +This is the DESIGN.md objective-6 contract: it exercises ``read`` / ``apply`` / +``is_satisfied`` against the live ``system_fingerprint`` API, so if the +deployment's runtime-API contract drifts (endpoint path, payload shape, or the +``values`` response key) this test fails *before* a benchmark silently runs +against the wrong configuration. + +The test restores the original value on teardown so it leaves no side effect. +""" + +import logging + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens + +logger = logging.getLogger(__name__) + + +@pytest.fixture +def max_tokens_property(fingerprint_client): + return MaxNewTokens(fingerprint_client) + + +@pytest.fixture +def restore_max_tokens(max_tokens_property): + """Snapshot the observed value and restore it after the test.""" + original = max_tokens_property.read() + yield original + max_tokens_property.apply(original) + + +@allure.feature("pysweep") +def test_read_returns_int(max_tokens_property): + """read() must return an int parsed from observed API state. + + A missing value is not acceptable — read() raises rather than returning + None (see MaxNewTokens.read / PropertyReadError), so any deployment where + the value is absent fails here. + """ + value = max_tokens_property.read() + assert isinstance(value, int) + + +@allure.feature("pysweep") +def test_apply_then_read_reflects_desired(max_tokens_property, restore_max_tokens): + """apply(desired) makes the observed value satisfy desired. + + Uses a value different from the current one so the write path is exercised. + """ + current = restore_max_tokens + desired = 256 if current != 256 else 128 + + max_tokens_property.apply(desired) + + assert max_tokens_property.read() == desired + assert max_tokens_property.is_satisfied(desired) + + +@allure.feature("pysweep") +def test_apply_is_idempotent(max_tokens_property, restore_max_tokens): + """A second apply of an already-satisfied value is a no-op that still holds.""" + desired = 200 + max_tokens_property.apply(desired) + assert max_tokens_property.is_satisfied(desired) + + # Applying again must not change or break the observed state. + max_tokens_property.apply(desired) + assert max_tokens_property.read() == desired diff --git a/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py b/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py new file mode 100644 index 00000000..3cee5d8d --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py @@ -0,0 +1,124 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for the ``MaxNewTokens`` property. + +The fingerprint client is stubbed, so these cover the property's own logic with no +deployment: the request body it sends, the component it reads back from, and its +refusal to guess when the observed value is missing or unparseable. The live +contract (that the deployment really exposes ``llm``/``max_new_tokens`` at this +shape) is ``test_max_tokens.py``. + +The payload assertions are the API contract: ``change_arguments`` takes +``[{"name": "llm", "data": {"max_new_tokens": N}}]``, and a property that posted +anything else would be accepted and change nothing — the worst outcome for a +sweep, since every row would then be a rerun of the previous configuration. +""" + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.base import Plane, PropertyReadError +from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens + + +class FakeClient: + """Records what was written and read, and serves a settable values dict.""" + + def __init__(self, values=None): + self.values = {"max_new_tokens": 128} if values is None else values + self.bodies = [] + self.read_components = [] + + def read_values(self, component): + self.read_components.append(component) + return dict(self.values) + + def change_arguments(self, body): + self.bodies.append(body) + for entry in body: + self.values.update(entry["data"]) + + +@allure.feature("pysweep") +def test_is_runtime_api_plane(): + """Runtime-API plane: varies as an inner dimension, no rollout to wait out.""" + assert MaxNewTokens.plane == Plane.RUNTIME_API + + +@allure.feature("pysweep") +def test_read_returns_the_observed_value(): + assert MaxNewTokens(FakeClient({"max_new_tokens": 256})).read() == 256 + + +@allure.feature("pysweep") +def test_read_asks_for_the_llm_component(): + """The reader is per-component; another component could carry a same-named key.""" + client = FakeClient() + MaxNewTokens(client).read() + assert client.read_components == ["llm"] + + +@allure.feature("pysweep") +def test_read_coerces_a_string_value(): + """The API may return the value as a string; the sweep compares ints.""" + assert MaxNewTokens(FakeClient({"max_new_tokens": "512"})).read() == 512 + + +@allure.feature("pysweep") +def test_read_raises_when_the_parameter_is_absent(): + """Unknown is not a value. + + Returning ``None`` would make ``is_satisfied`` permanently false and the sweep + would re-apply forever; failing says which keys were actually offered. + """ + with pytest.raises(PropertyReadError) as excinfo: + MaxNewTokens(FakeClient({"streaming": True})).read() + assert "streaming" in str(excinfo.value) + + +@allure.feature("pysweep") +def test_read_raises_on_an_unparseable_value(): + with pytest.raises(PropertyReadError, match="not an integer"): + MaxNewTokens(FakeClient({"max_new_tokens": "unlimited"})).read() + + +@allure.feature("pysweep") +def test_is_satisfied_compares_as_integers(): + """YAML can hand over a string; a type mismatch must not force a needless write.""" + prop = MaxNewTokens(FakeClient({"max_new_tokens": 128})) + assert prop.is_satisfied("128") + assert not prop.is_satisfied(256) + + +@allure.feature("pysweep") +def test_apply_posts_the_documented_body(): + client = FakeClient({"max_new_tokens": 128}) + MaxNewTokens(client).apply(256) + assert client.bodies == [[{"name": "llm", "data": {"max_new_tokens": 256}}]] + + +@allure.feature("pysweep") +def test_apply_then_read_reflects_the_desired_value(): + client = FakeClient({"max_new_tokens": 128}) + prop = MaxNewTokens(client) + prop.apply(256) + assert prop.read() == 256 + assert prop.is_satisfied(256) + + +@allure.feature("pysweep") +def test_apply_skips_the_write_when_already_satisfied(): + """Idempotence: re-running a combination must not touch the deployment.""" + client = FakeClient({"max_new_tokens": 128}) + MaxNewTokens(client).apply(128) + assert client.bodies == [] + + +@allure.feature("pysweep") +def test_apply_coerces_the_desired_value(): + """A value read from YAML arrives as a string; the API expects a number.""" + client = FakeClient({"max_new_tokens": 128}) + MaxNewTokens(client).apply("256") + (body,) = client.bodies + assert body[0]["data"]["max_new_tokens"] == 256 diff --git a/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py b/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py new file mode 100644 index 00000000..d122c083 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py @@ -0,0 +1,237 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for the model-manager catalog reader. + +Two things are being pinned here, both of which pysweep depends on and neither of +which it owns: + +* **The catalog's shape** — ``models:`` is a *list* of entries each carrying a + ``name`` and a ``model_id``. ``CATALOG_SAMPLE`` below is copied from the + deployed ``env/local/models.yaml``, so a format change in model-manager's + catalog fails here rather than as an empty "available models" list in a + preflight message. +* **Which file is read** — the deployment's own catalog, not this repo's shipped + default, since the two drift and only the former lists the names the cluster was + built from. + +No cluster and no model-manager CLI are involved: this module is a YAML reader. +""" + +from pathlib import Path + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import model_catalog +from tests.e2e.benchmarks.chatqna.pysweep.model_catalog import ( + CatalogError, + catalog_path, + known_models, + load_catalog, + model_entry, + tokenizer_for, +) + +# Trimmed from the deployed env/local/models.yaml: two model entries plus the +# surrounding sections the reader has to ignore. +CATALOG_SAMPLE = """\ +defaults: + namespace: llm-inference + runtime: vllm + replicas: 1 + +storage: + pvc_name: model-store + +models: + # LLM - quantized Llama-3 8B, chat/completion (shorthand form) + - name: llama3-8b-awq + model_id: casperhansen/llama-3-8b-instruct-awq + category: llm + runtime: vllm + server_version: "0.24.0" + cpu: 16 + memory: 32Gi + + - name: qwen3-5-2b-ovms + model_id: OpenVINO/Qwen3.5-2B-int4-ov + category: llm + runtime: ovms +""" + + +@pytest.fixture +def catalog_file(tmp_path, monkeypatch): + """A catalog on disk, selected via ``PYSWEEP_MODEL_CATALOG``.""" + path = tmp_path / "models.yaml" + path.write_text(CATALOG_SAMPLE) + monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(path)) + monkeypatch.delenv("MM_CONFIG", raising=False) + return path + + +@allure.feature("pysweep") +def test_loads_every_named_model(catalog_file): + assert sorted(load_catalog()) == ["llama3-8b-awq", "qwen3-5-2b-ovms"] + + +@allure.feature("pysweep") +def test_entries_are_returned_verbatim(catalog_file): + """Callers read whichever field they need, so nothing is dropped or renamed.""" + entry = model_entry("llama3-8b-awq") + assert entry["model_id"] == "casperhansen/llama-3-8b-instruct-awq" + assert entry["cpu"] == 16 + assert entry["memory"] == "32Gi" + + +@allure.feature("pysweep") +def test_known_models_is_sorted(catalog_file): + """These names go into error messages, where a stable order is what makes them readable.""" + assert known_models() == ["llama3-8b-awq", "qwen3-5-2b-ovms"] + + +@allure.feature("pysweep") +def test_tokenizer_is_the_huggingface_repo_id(catalog_file): + """The name/repo-id distinction the whole module exists for. + + ``LLM_MODEL_NAME`` carries the catalog name; ``benchmark.py``'s + ``-m`` needs the repo id. Conflating them would count every token with the + wrong tokenizer. + """ + assert tokenizer_for("llama3-8b-awq") == "casperhansen/llama-3-8b-instruct-awq" + assert tokenizer_for("qwen3-5-2b-ovms") == "OpenVINO/Qwen3.5-2B-int4-ov" + + +@allure.feature("pysweep") +def test_unknown_model_error_lists_the_available_names(catalog_file): + """The failure is nearly always a typo or a repo id in a name's place. + + Both are obvious the moment the real names are on screen, so the message + carries them. + """ + with pytest.raises(CatalogError) as excinfo: + model_entry("casperhansen/llama-3-8b-instruct-awq") + message = str(excinfo.value) + assert "llama3-8b-awq" in message + assert "qwen3-5-2b-ovms" in message + + +@allure.feature("pysweep") +def test_entry_without_a_model_id_has_no_tokenizer(tmp_path, monkeypatch): + """Better to fail than to report throughput per token off a guessed tokenizer.""" + path = tmp_path / "models.yaml" + path.write_text("models:\n - name: mystery\n category: llm\n") + monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(path)) + + with pytest.raises(CatalogError, match="model_id"): + tokenizer_for("mystery") + + +@allure.feature("pysweep") +def test_env_var_selects_the_catalog(catalog_file, tmp_path, monkeypatch): + """The deployment's catalog must win over this repo's shipped default.""" + assert catalog_path() == catalog_file + + other = tmp_path / "other.yaml" + other.write_text("models:\n - name: only-here\n model_id: org/only\n") + monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(other)) + assert known_models() == ["only-here"] + + +@allure.feature("pysweep") +def test_mm_config_is_honoured_as_a_fallback(tmp_path, monkeypatch): + """``MM_CONFIG`` is what the model-manager wrapper exports. + + Honouring it means pysweep reads the same catalog the deploy will, with + nothing extra to configure. + """ + path = tmp_path / "models.yaml" + path.write_text(CATALOG_SAMPLE) + monkeypatch.delenv("PYSWEEP_MODEL_CATALOG", raising=False) + monkeypatch.setenv("MM_CONFIG", str(path)) + + assert catalog_path() == path + + +@allure.feature("pysweep") +def test_pysweep_var_wins_over_mm_config(tmp_path, monkeypatch): + """An explicit pysweep setting is the one place to override a wrong environment.""" + preferred = tmp_path / "preferred.yaml" + preferred.write_text(CATALOG_SAMPLE) + other = tmp_path / "other.yaml" + other.write_text(CATALOG_SAMPLE) + monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(preferred)) + monkeypatch.setenv("MM_CONFIG", str(other)) + + assert catalog_path() == preferred + + +@allure.feature("pysweep") +def test_a_configured_path_that_does_not_exist_is_an_error(tmp_path, monkeypatch): + """Silently falling through would read a *different* catalog than asked for.""" + monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(tmp_path / "missing.yaml")) + with pytest.raises(CatalogError, match="PYSWEEP_MODEL_CATALOG"): + catalog_path() + + +@allure.feature("pysweep") +def test_no_catalog_anywhere_is_an_error(monkeypatch): + """An empty catalog would make every model name 'unknown', which misreports the cause.""" + monkeypatch.delenv("PYSWEEP_MODEL_CATALOG", raising=False) + monkeypatch.delenv("MM_CONFIG", raising=False) + monkeypatch.setattr(model_catalog, "CATALOG_FALLBACKS", ()) + + with pytest.raises(CatalogError, match="Cannot find a model-manager catalog"): + catalog_path() + + +@allure.feature("pysweep") +# Explicit ids: these values are multi-line YAML, and the suite's conftest names +# per-test log files after the test id. +@pytest.mark.parametrize( + "content", + [ + "models: [", # not YAML at all + "- just\n- a\n- list\n", # not a mapping at the top level + "models:\n llama3-8b-awq:\n model_id: org/x\n", # a mapping, not a list + "defaults:\n namespace: llm-inference\n", # no models section + ], + ids=["not-yaml", "top-level-list", "models-as-mapping", "no-models-section"], +) +def test_a_malformed_catalog_is_reported_as_such(tmp_path, monkeypatch, content): + """Every one of these would otherwise surface as 'model X is not in the catalog'.""" + path = tmp_path / "models.yaml" + path.write_text(content) + monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(path)) + + with pytest.raises(CatalogError): + load_catalog() + + +@allure.feature("pysweep") +def test_the_repo_default_catalog_is_readable(): + """The shipped ``deployment/models.yaml`` must parse with this reader. + + It is the fallback for anyone running pysweep from a checkout, and it is also + the check that the fallback path (``paths.REPO_ROOT``) still points at the repo + root after any move of this package. + """ + repo_default = model_catalog.CATALOG_FALLBACKS[-1] + models = known_models(repo_default) + assert models, "the shipped catalog declares no models" + for name in models: + assert tokenizer_for(name, repo_default) + + +@allure.feature("pysweep") +def test_the_rag_catalog_is_preferred_over_the_platform_one(): + """An install has both; the RAG pipeline's models come from models-rag.yaml. + + The platform catalog shares only some names (it calls Llama 3.1 8B + 'llama-3-1-8b' where the RAG one says 'llama3-1-8b'), so reading it first + would fail to resolve models the pipeline really serves. + """ + fallbacks = [Path(p).name for p in model_catalog.CATALOG_FALLBACKS] + for root_rag, root_platform in zip(fallbacks[0:-1:2], fallbacks[1:-1:2]): + assert (root_rag, root_platform) == ("models-rag.yaml", "models.yaml") diff --git a/src/tests/e2e/validation/pysweep/test_paths_unit.py b/src/tests/e2e/validation/pysweep/test_paths_unit.py new file mode 100644 index 00000000..8ab3f856 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_paths_unit.py @@ -0,0 +1,91 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for where pysweep looks for the installed environment. + +Two regressions are pinned: + +* **The deploy root follows the checkout.** The installer keeps this repo at + ``/ext/enterprise.ai-erag``, so the environment is found next to it + for whichever user installed it, not only under ``/root/ai-solutions``. +* **An unreadable candidate is skipped, not fatal.** On Python < 3.14 + ``Path.is_dir()`` raises ``PermissionError`` for a path under ``/root``; probing + that fallback as a non-root user used to crash the sweep before it started. +""" + +from pathlib import Path + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import authentication, paths +from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( + BUILD_CONFIG_FILES, + BuildConfigError, + build_config_dir, +) + + +@allure.feature("pysweep") +def test_repo_root_is_the_checkout(): + """``REPO_ROOT`` must still point at the repo after any move of the package.""" + assert (paths.REPO_ROOT / "src" / "tests" / "e2e").is_dir() + assert (paths.REPO_ROOT / "deployment").is_dir() + + +@allure.feature("pysweep") +def test_deploy_root_is_derived_from_an_installer_layout(monkeypatch, tmp_path): + repo = tmp_path / "ai-solutions" / "ext" / "enterprise.ai-erag" + monkeypatch.setattr(paths, "REPO_ROOT", repo) + assert paths.deploy_roots() == (tmp_path / "ai-solutions", paths.ROOT_DEPLOY_ROOT) + + +@allure.feature("pysweep") +def test_a_plain_checkout_only_falls_back_to_root(monkeypatch, tmp_path): + """Outside ``ext/`` the checkout's parent is not a deploy root; don't guess one.""" + monkeypatch.setattr(paths, "REPO_ROOT", tmp_path / "PycharmProjects" / "ai-erag") + assert paths.deploy_roots() == (paths.ROOT_DEPLOY_ROOT,) + + +@allure.feature("pysweep") +@pytest.mark.parametrize("probe", [paths.is_dir, paths.is_file], ids=["is_dir", "is_file"]) +def test_an_unreadable_path_counts_as_absent(monkeypatch, probe): + def denied(self, *args, **kwargs): + raise PermissionError(13, "Permission denied", str(self)) + + monkeypatch.setattr(Path, "stat", denied) + assert probe(Path("/root/ai-solutions/env/local")) is False + + +@allure.feature("pysweep") +def test_build_config_dir_skips_an_unreadable_fallback(monkeypatch, tmp_path): + readable = tmp_path / "env" / "local" + readable.mkdir(parents=True) + unreadable = Path("/root/ai-solutions/env/local") + real_stat = Path.stat + + def stat(self, *args, **kwargs): + if self == unreadable: + raise PermissionError(13, "Permission denied", str(self)) + return real_stat(self, *args, **kwargs) + + monkeypatch.delenv(authentication.BUILD_CONFIG_DIR_ENV_VAR, raising=False) + monkeypatch.setattr(Path, "stat", stat) + monkeypatch.setattr(authentication, "BUILD_CONFIG_FALLBACKS", (str(unreadable), str(readable))) + assert build_config_dir() == readable + + +@allure.feature("pysweep") +def test_no_build_config_dir_anywhere_is_an_error(monkeypatch): + monkeypatch.delenv(authentication.BUILD_CONFIG_DIR_ENV_VAR, raising=False) + monkeypatch.setattr(authentication, "BUILD_CONFIG_FALLBACKS", ()) + with pytest.raises(BuildConfigError, match="Cannot find"): + build_config_dir() + + +@allure.feature("pysweep") +def test_build_config_files_match_the_e2e_suite(): + """pysweep must load the same env files ``tests/e2e/conftest.py`` does.""" + conftest = (paths.REPO_ROOT / "src" / "tests" / "e2e" / "conftest.py").read_text() + for filename in BUILD_CONFIG_FILES: + assert f'"{filename}"' in conftest, filename diff --git a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py new file mode 100644 index 00000000..a440f545 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -0,0 +1,1134 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for the pysweep_bench orchestration. + +These cover the glue logic — argument splitting, property building, the +apply/converge/verify step, and the nesting of the client loop inside the +deployment loop — with a fake fingerprint client, so no cluster, transformers, or +benchmark load is needed. The actual benchmark run (``benchmark.run_benchmark``) +is exercised by the existing benchmark tooling, not re-tested here. +""" + +import argparse +import ast +import csv +import itertools +import linecache +import logging +from contextlib import contextmanager +from pathlib import Path + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import pysweep_bench as psb +from tests.e2e.benchmarks.chatqna.pysweep.base import ( + Plane, + Property, + PropertyApplyError, + PropertyReadError, +) +from tests.e2e.benchmarks.chatqna.pysweep.client_args import BenchmarkClientArgs +from tests.e2e.benchmarks.chatqna.pysweep import results +from tests.e2e.benchmarks.chatqna.pysweep.config import PropertySetting, load_config +from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens +from tests.e2e.benchmarks.chatqna.pysweep.served_model import ServedModel + +# The client section is mandatory; these tests care about the deployment side, so +# it stays fixed and minimal except where a test overrides a knob. +# +# question_file is the real corpus path (relative to pysweep_bench.py, hence the +# '../'), because the tests that call main() run preflight(), which +# resolves and stats it. A placeholder name would fail there rather than in the +# logic under test. +CLIENT = { + "question_file": "../questions-short.csv", + "concurrency": 4, + "duration": "3m", + "worker_startup_delay": "0s", + "failures_allowed": 200, + "input_tokens": 128, + "warmup_requests": 1, +} + + +def _sweep(**sections): + return {"client": dict(CLIENT), **sections} + + +def _client(**overrides): + return {"client": {**CLIENT, **overrides}} + + +def _parse_benchmark_argv(argv): + """Parse argv with a parser rebuilt from ``benchmark.parse_args``'s source. + + Predates the lazy ``transformers`` import inside ``run_benchmark``: importing + ``benchmark`` used to mean importing ``transformers``, which this suite does not + install, so the parser was rebuilt from the file instead. That is no longer a + constraint — this could call ``benchmark.parse_args`` directly — but rebuilding + from the real source is still a genuine check that the adapter's argv is + acceptable: a flag or type the tool does not actually declare would not be + reconstructed here either. + """ + source = ( + Path(__file__).resolve().parents[3] / "e2e/benchmarks/chatqna/benchmark.py" + ).read_text() + tree = ast.parse(source) + func = next( + node + for node in ast.walk(tree) + if isinstance(node, ast.FunctionDef) and node.name == "parse_args" + ) + parser = argparse.ArgumentParser() + for node in ast.walk(func): + if not ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "add_argument" + ): + continue + flag = node.args[0].value + kwargs = {kw.arg: kw.value for kw in node.keywords} + arg_type = {"int": int, "str": str}[kwargs["type"].id] + default = ast.literal_eval(kwargs["default"]) if "default" in kwargs else None + parser.add_argument(flag, type=arg_type, default=default) + return parser.parse_args(argv) + + +class FakeFingerprintClient: + """In-memory stand-in for FingerprintClient that actually applies writes. + + The real reader is per-component; the properties under test here all read the + values of the component they write, so one dict is enough and the component + name is ignored. + """ + + def __init__(self, initial=999): + self.params = {"max_new_tokens": initial} + + def read_values(self, component): + return dict(self.params) + + def change_arguments(self, body): + for entry in body: + self.params.update(entry["data"]) + + +class IgnoringClient(FakeFingerprintClient): + """Client whose writes never take effect (simulates a non-converging plane).""" + + def change_arguments(self, body): + pass + + +@allure.feature("pysweep") +def test_parse_args_splits_benchmark_args_after_double_dash(): + args = psb.parse_args(["--sweep", "s.yaml", "--", "-s", "http://x", "-c", "32"]) + assert args.sweep == "s.yaml" + assert args.benchmark_args == ["-s", "http://x", "-c", "32"] + + +@allure.feature("pysweep") +def test_parse_args_without_benchmark_args(): + args = psb.parse_args(["--sweep", "s.yaml"]) + assert args.benchmark_args == [] + + +@allure.feature("pysweep") +def test_parse_args_run_config_is_optional(): + """``--sweep`` alone is valid; ``--config`` is the optional run config.""" + assert psb.parse_args(["--sweep", "s.yaml"]).config is None + args = psb.parse_args(["--sweep", "s.yaml", "--config", "c.yaml"]) + assert (args.sweep, args.config) == ("s.yaml", "c.yaml") + + +@allure.feature("pysweep") +def test_build_property_dispatches_runtime_api_to_fingerprint_client(): + cfg = load_config(_sweep(llms={"max_new_tokens": 128})) + setting = cfg.deployment_combinations()[0][0] + prop = psb.build_property(setting, FakeFingerprintClient()) + assert isinstance(prop, MaxNewTokens) + + +@allure.feature("pysweep") +def test_build_property_dispatches_k8s_plane_without_fingerprint_client(): + """K8s-plane properties reach the cluster themselves, so take no client.""" + + class _K8sKnob(Property): + plane = Plane.K8S_SPEC + + def __init__(self): + pass + + def read(self): + return None + + def apply(self, desired): + pass + + setting = PropertySetting(path="fake.knob", property_cls=_K8sKnob, value=1) + assert isinstance(psb.build_property(setting, FakeFingerprintClient()), _K8sKnob) + + +@allure.feature("pysweep") +def test_apply_combination_reports_unestablishable_state_as_sweep_error(monkeypatch): + """A property that cannot establish its value aborts the sweep cleanly. + + E.g. a value the deployment rejects: apply raises PropertyApplyError and + apply_combination must surface it as a SweepError naming the knob, rather + than letting it escape as a crash. + """ + cfg = load_config(_sweep(llms={"max_new_tokens": 128})) + + def refuse(self, desired): + raise PropertyApplyError("value rejected") + + monkeypatch.setattr(MaxNewTokens, "apply", refuse) + with pytest.raises(psb.SweepError, match="llms.max_new_tokens"): + psb.apply_combination(cfg.deployment_combinations()[0], FakeFingerprintClient()) + + +@allure.feature("pysweep") +def test_apply_combination_reports_failed_convergence_as_sweep_error(monkeypatch): + """Applied but never ready must abort, not benchmark the old config.""" + cfg = load_config(_sweep(llms={"max_new_tokens": 128})) + monkeypatch.setattr(MaxNewTokens, "apply", lambda self, desired: None) + + def never_ready(self, desired, timeout=None): + raise PropertyApplyError("did not converge") + + monkeypatch.setattr(MaxNewTokens, "wait_until_ready", never_ready) + with pytest.raises(psb.SweepError, match="llms.max_new_tokens"): + psb.apply_combination(cfg.deployment_combinations()[0], FakeFingerprintClient()) + + +@allure.feature("pysweep") +def test_apply_combination_applies_and_snapshots_observed(): + cfg = load_config(_sweep(llms={"max_new_tokens": [128, 256]})) + client = FakeFingerprintClient() + snapshots = [psb.apply_combination(c, client) for c in cfg.deployment_combinations()] + assert snapshots == [ + {"llms.max_new_tokens": 128}, + {"llms.max_new_tokens": 256}, + ] + + +@allure.feature("pysweep") +def test_apply_combination_raises_when_not_converged(): + cfg = load_config(_sweep(llms={"max_new_tokens": 128})) + with pytest.raises(psb.SweepError): + psb.apply_combination(cfg.deployment_combinations()[0], IgnoringClient()) + + +@allure.feature("pysweep") +def test_combination_slug_is_unique_per_combination(): + """Each combination must map to a distinct result filename fragment. + + Regression guard: combinations previously shared one timestamped CSV, so a + later combination silently clobbered an earlier one's results. + """ + cfg = load_config(_sweep(llms={"max_new_tokens": [128, 256]})) + slugs = [psb.combination_slug(c) for c in cfg.deployment_combinations()] + assert slugs == ["max_new_tokens-128", "max_new_tokens-256"] + assert len(set(slugs)) == len(slugs) + + +# -- client knobs: the innermost loop ----------------------------------------- + + +class FakeBenchmark: + """Stand-in for the benchmark module, recording each invocation. + + Lets the nesting be asserted without transformers, a cluster, or minutes of + load: what matters is *which* argv each run got and in what order. + """ + + def __init__(self, rows=1): + self.calls = [] + self._rows = rows + + #: Mirrors benchmark.parse_args's signature without importing it (that pulls + #: in transformers, which only a real load test needs). The faithfulness of + #: the mirror is what test_rendered_argv_is_accepted_by_benchmark_parse_args + #: checks against the real parser. + parse_args = staticmethod(lambda argv: _parse_benchmark_argv(argv)) + + def run_benchmark(self, args, output_file=None): + self.calls.append((args, output_file)) + if self._rows: + Path(output_file).write_text("128,128,0.8,6.9,,200\n" * self._rows) + return 0, output_file + + +@allure.feature("pysweep") +def test_client_combination_renders_to_benchmark_argv(): + """Every declared client knob reaches benchmark.py as its own flag. + + ``-m`` is absent by design: it is not declared, so the client combination + cannot carry it. The runner appends it from the served model (see + ``test_tokenizer_comes_from_the_served_model``). + """ + cfg = load_config(_client(concurrency=16)) + argv = BenchmarkClientArgs.from_settings(cfg.client_combinations()[0]).to_argv() + # The DECLARED path, verbatim: the adapter is a pure translation. Anchoring it + # to an absolute path happens later, at the argv boundary + # (``resolve_question_file_argv``), so that the recorded value stays the one + # the config author wrote. + assert argv == [ + "-f", "../questions-short.csv", + "-c", "16", + "-d", "3m", + "-u", "0s", + "-e", "200", + "-x", "128", + "-w", "1", + ] + + +@allure.feature("pysweep") +def test_rendered_argv_is_accepted_by_benchmark_parse_args(): + """The adapter's output must actually parse — the mirror has to be faithful. + + Types matter as much as flag names: every value is rendered through ``str``, + so a knob bound to an option benchmark.py declares as ``type=int`` has to + round-trip back to an int. + """ + cfg = load_config(_client(concurrency=16, input_tokens=0)) + argv = BenchmarkClientArgs.from_settings(cfg.client_combinations()[0]).to_argv() + parsed = _parse_benchmark_argv(argv) + assert (parsed.c, parsed.d, parsed.x, parsed.f) == (16, "3m", 0, "../questions-short.csv") + assert (parsed.e, parsed.w, parsed.u) == (200, 1, "0s") + + +@allure.feature("pysweep") +def test_client_knobs_vary_innermost(monkeypatch, tmp_path): + """The whole point of the nesting: load varies within a fixed deployment. + + Each deployment combination must be applied once and then benchmarked under + every client combination before the next (expensive) deployment change. + """ + monkeypatch.chdir(tmp_path) + cfg = load_config( + {"client": {**CLIENT, "concurrency": [1, 16]}, "llms": {"max_new_tokens": [128, 256]}} + ) + fake = FakeBenchmark() + applied = [] + + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + + def record_apply(combination, client): + applied.append(tuple(s.value for s in combination)) + return {s.path: s.value for s in combination} + + monkeypatch.setattr(psb, "apply_combination", record_apply) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, fake) + + assert psb.main(["--sweep", "ignored.yaml"]) == 0 + + # Two deployment combinations, applied once each — not once per load level. + assert applied == [(128,), (256,)] + # ...each benchmarked under both concurrencies before the next apply. + assert [args.c for args, _ in fake.calls] == [1, 16, 1, 16] + assert [args.d for args, _ in fake.calls] == ["3m"] * 4 + # The derived tokenizer reaches every run, though no config declares it. + assert [args.m for args, _ in fake.calls] == ["served/model"] * 4 + + +@allure.feature("pysweep") +def test_sweep_writes_one_summary_row_per_run(monkeypatch, tmp_path): + """The sweep's own artifact: every run, its knob values, and its KPIs. + + Checked through ``main`` rather than against ``SweepSummary`` directly + (``test_results.py`` covers the arithmetic), because what could realistically + break here is the wiring: a row per run, the observed deployment value and + the declared client value in their dotted-path columns, and the served model + recorded even though nothing declares it. + """ + monkeypatch.chdir(tmp_path) + cfg = load_config( + {"client": {**CLIENT, "concurrency": [1, 16]}, "llms": {"max_new_tokens": [128, 256]}} + ) + fake = FakeBenchmark(rows=2) + + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr( + psb, "apply_combination", lambda combination, client: {s.path: s.value for s in combination} + ) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, fake) + + assert psb.main(["--sweep", "ignored.yaml", "--summaries", "out"]) == 0 + + summary_file = tmp_path / "out" / results.SUMMARY_FILE_NAME + rows = list(csv.DictReader(summary_file.open())) + assert len(rows) == 4 + assert [(r["llms.max_new_tokens"], r["client.concurrency"]) for r in rows] == [ + ("128", "1"), ("128", "16"), ("256", "1"), ("256", "16"), + ] + # Constant knobs get columns too, so a row says what it was measured under. + assert {r["client.duration"] for r in rows} == {"3m"} + # FakeBenchmark writes 128,128,0.8,6.9,,200 twice per run. + assert {r["requests"] for r in rows} == {"2"} + assert {r["mean_ttft"] for r in rows} == {"0.8"} + assert {r["mean_tpot"] for r in rows} == {str(round((6.9 - 0.8) / 127, 6))} + assert {r["served_model"] for r in rows} == {"served/model"} + # And each row points back at the per-request CSV it summarises, by a path + # relative to the summary itself — so the whole directory can be copied off the + # benchmark host with its pointers intact. + assert all(not Path(r["result_file"]).is_absolute() for r in rows) + assert all((summary_file.parent / r["result_file"]).exists() for r in rows) + # ...and that CSV lives in the per-case subdirectory, not beside the summary. + assert {Path(r["result_file"]).parent.name for r in rows} == {results.PER_CASE_DIR_NAME} + + +@allure.feature("pysweep") +def test_the_previous_sweeps_results_are_gone_before_this_one_starts(monkeypatch, tmp_path): + """``--summaries`` is a clean slate per sweep, wired through ``main``. + + ``test_results.py`` covers what gets deleted; what matters here is that the + sweep does it at all. Without it, a per-case CSV from a longer previous sweep + survives with no row in the new summary, and reads exactly like a result of it. + """ + monkeypatch.chdir(tmp_path) + cfg = load_config(_client()) + stale = tmp_path / "out" / results.PER_CASE_DIR_NAME / "bench_from_last_week.result.csv" + stale.parent.mkdir(parents=True) + stale.write_text("128,128,9.9,99.9,,200\n") + + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr(psb, "apply_combination", lambda c, f: {}) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, FakeBenchmark()) + + assert psb.main(["--sweep", "ignored.yaml", "--summaries", "out"]) == 0 + + assert not stale.exists() + # And this sweep's own run is there, so the wipe happened before it, not after. + assert [p.name for p in stale.parent.iterdir()] == ["bench_single.result.csv"] + + +def _passthrough_provision(benchmark_args, workers=1): + """provision_benchmark_target with no cluster: yield the args unchanged. + + ``workers`` is accepted and ignored — nothing is minted here, but the runner + passes the sweep's widest concurrency, so the signature has to match. + """ + from contextlib import contextmanager + + @contextmanager + def cm(): + yield list(benchmark_args) + ["-s", "http://127.0.0.1:1/api", "-b", "uat.txt"] + + return cm() + + +def _install_fake_benchmark(monkeypatch, fake): + """Point the runner's module-level ``benchmark`` at ``fake``. + + Without it, a test that runs ``main()`` would start a real load test against + whatever ``-s`` happened to be set. One binding is enough: ``main()`` reads the + name off this module, and monkeypatch restores it afterwards. + """ + monkeypatch.setattr(psb, "benchmark", fake) + + +@allure.feature("pysweep") +def test_result_file_names_are_unique_per_run(): + """Deployment x client must not collide: each run gets its own CSV. + + Regression guard in the same spirit as the per-combination slug — with the + client loop added, a name built from the deployment alone would have every + load level overwrite the previous one's results. + """ + cfg = load_config( + {"client": {**CLIENT, "concurrency": [1, 16]}, "llms": {"max_new_tokens": [128, 256]}} + ) + varying = cfg.varying_paths() + names = [ + psb.result_file_name(c, cc, only=varying) + for c in cfg.deployment_combinations() + for cc in cfg.client_combinations() + ] + assert names == [ + "bench_max_new_tokens-128_concurrency-1.result.csv", + "bench_max_new_tokens-128_concurrency-16.result.csv", + "bench_max_new_tokens-256_concurrency-1.result.csv", + "bench_max_new_tokens-256_concurrency-16.result.csv", + ] + assert len(set(names)) == len(names) + + +@allure.feature("pysweep") +def test_result_file_name_omits_constant_knobs(): + """Only the knobs that vary are named; the rest are constant and logged.""" + cfg = load_config(_client(concurrency=[1, 16])) + name = psb.result_file_name((), cfg.client_combinations()[0], only=cfg.varying_paths()) + assert name == "bench_concurrency-1.result.csv" + + +@allure.feature("pysweep") +def test_result_file_name_stays_within_the_filesystem_limit(): + """Naming every declared knob can overflow the 255-byte filename limit. + + Why names carry only the varying knobs. The values here are all plausible — + an HF repo id and a question file under a real path — and together they push + the all-knobs name past what the filesystem accepts, while the filtered name + stays short regardless of how many knobs are held constant. + """ + cfg = load_config( + { + "client": { + **CLIENT, + "concurrency": [1, 16], + "question_file": ( + "datasets/pubmed/long-form/2026-01/reviewed/" + "questions-pubmed-long-form-with-reference-answers-and-citations-2026-01.csv" + ), + }, + "llms": {"max_new_tokens": [128, 256]}, + } + ) + combination = cfg.deployment_combinations()[0] + client_combination = cfg.client_combinations()[0] + + assert len(Path(psb.result_file_name(combination, client_combination)).name) > 255 + filtered = psb.result_file_name(combination, client_combination, only=cfg.varying_paths()) + assert len(Path(filtered).name) <= 255 + # And the shipped example, whatever it declares, must also be nameable. + example = ( + Path(__file__).resolve().parents[3] + / "e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml" + ) + shipped = load_config(example) + for combo in shipped.deployment_combinations(): + for client_combo in shipped.client_combinations(): + name = psb.result_file_name(combo, client_combo, only=shipped.varying_paths()) + assert len(Path(name).name) <= 255 + + +@allure.feature("pysweep") +def test_result_file_name_falls_back_when_nothing_varies(): + """A single-combination sweep still needs a name.""" + cfg = load_config(_client()) + name = psb.result_file_name((), cfg.client_combinations()[0], only=cfg.varying_paths()) + assert name == "bench_single.result.csv" + + +@allure.feature("pysweep") +def test_tokenizer_is_the_catalog_model_id_not_the_served_name(monkeypatch, tmp_path): + """The two names differ, and using the wrong one breaks every token count. + + What the deployment serves is a catalog name ('llama3-8b-awq' — the value of + LLM_MODEL_NAME and the name of the LLMInferenceService); AutoTokenizer needs a + HuggingFace repo id. This goes through the real catalog lookup, so a wiring + mistake that passed the served name straight to -m fails here. + """ + catalog = tmp_path / "models.yaml" + catalog.write_text( + "models:\n" + " - name: llama3-8b-awq\n" + " model_id: casperhansen/llama-3-8b-instruct-awq\n" + " category: llm\n" + ) + monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(catalog)) + monkeypatch.setattr(ServedModel, "read", lambda self: "llama3-8b-awq") + + assert psb.resolve_tokenizer() == "casperhansen/llama-3-8b-instruct-awq" + + +@allure.feature("pysweep") +def test_unreadable_model_aborts_rather_than_guessing_a_tokenizer(monkeypatch): + """No served model means no defensible token counts, so the sweep stops. + + Falling back to benchmark.py's default (an embedding model's tokenizer) would + produce numbers on a basis nobody chose, which is worse than failing. + """ + def unreadable(self): + raise PropertyReadError("no llm-usvc pods") + + monkeypatch.setattr(ServedModel, "read", unreadable) + with pytest.raises(psb.SweepError, match="served model"): + psb.resolve_tokenizer() + + +@allure.feature("pysweep") +def test_a_served_model_missing_from_the_catalog_aborts(monkeypatch, tmp_path): + """Same reasoning one step later: a name with no model_id has no tokenizer. + + This is reachable without a config typo — the deployment may serve a model the + local catalog does not list — so it must fail rather than tokenize on a guess. + """ + catalog = tmp_path / "models.yaml" + catalog.write_text("models:\n - name: other-model\n model_id: org/other\n") + monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(catalog)) + monkeypatch.setattr(ServedModel, "read", lambda self: "llama3-8b-awq") + + with pytest.raises(psb.SweepError, match="tokenizer"): + psb.resolve_tokenizer() + + +@allure.feature("pysweep") +def test_forwarded_tokenizer_flag_is_refused(): + """``-m`` cannot be passed after ``--``: it is derived, not configurable. + + Unlike -s/-b there is no "omit it from the config to pass it here" escape — + there is no config key at all, and any value other than the served model + misattributes the token counts. + """ + cfg = load_config(_client()) + with pytest.raises(psb.SweepError, match=r"-m"): + psb.resolve_benchmark_argv(cfg, ["-m", "nomic-ai/nomic-embed-text-v1"]) + + +@allure.feature("pysweep") +def test_forwarded_flag_that_the_config_declares_is_refused(): + """A load flag in both places has no defensible winner, so it is an error. + + Honouring the YAML would ignore an explicit command line; honouring the + command line would silently collapse a declared sweep dimension. Both leave + "what was tested" unanswerable, so the sweep refuses to start. + """ + cfg = load_config(_client(concurrency=[1, 16])) + with pytest.raises(psb.SweepError, match=r"-c"): + psb.resolve_benchmark_argv(cfg, ["-c", "8"]) + + +@allure.feature("pysweep") +def test_forwarded_server_is_allowed_when_the_config_omits_it(): + """Passing -s/-b on the command line is the supported provisioning bypass.""" + cfg = load_config(_client()) + assert psb.resolve_benchmark_argv(cfg, ["-s", "https://erag.com/api/v1/chatqna"]) == [ + "-s", "https://erag.com/api/v1/chatqna", + ] + + +@allure.feature("pysweep") +def test_config_declared_server_and_bearer_reach_benchmark(): + """Declared connection settings render once and suppress auto-provisioning.""" + cfg = load_config(_client(server="https://erag.com/api/v1/chatqna", bearer_file="uat.txt")) + argv = psb.resolve_benchmark_argv(cfg, []) + assert argv == ["-s", "https://erag.com/api/v1/chatqna", "-b", "uat.txt"] + # provision_benchmark_target sees both as supplied and touches neither. + with psb.provision_benchmark_target(argv) as provisioned: + assert provisioned == argv + + +@allure.feature("pysweep") +def test_count_result_rows_counts_and_tolerates_missing(tmp_path): + """An absent file counts as zero rows rather than raising.""" + assert psb.count_result_rows(tmp_path / "nope.csv") == 0 + csv_file = tmp_path / "r.csv" + csv_file.write_text("128,128,0.8,6.9,,200\n128,128,1.2,7.1,,200\n") + assert psb.count_result_rows(csv_file) == 2 + + +@allure.feature("pysweep") +def _fake_keycloak(monkeypatch, domain="box.example"): + """Point provisioning at a fake deployment whose every token mint differs.""" + from tests.e2e.benchmarks.chatqna.pysweep import authentication + + minted = itertools.count(1) + + # access_token must yield a *fresh* value per read, as the real property does + # (each read is a new password grant), which is what makes the tokens distinct. + class _Helper: + @property + def access_token(self): + return f"token-{next(minted)}" + + monkeypatch.setattr( + authentication, "load_build_config", lambda: {"base_domain_name": domain} + ) + monkeypatch.setattr(authentication, "keycloak_helper", _Helper) + + # Record the lifespan override instead of calling the Keycloak admin API. + lifespan_calls = [] + + @contextmanager + def _lifespan(helper, seconds=authentication.SWEEP_TOKEN_LIFESPAN_S): + lifespan_calls.append(("set", seconds)) + try: + yield + finally: + lifespan_calls.append(("restored", seconds)) + + monkeypatch.setattr(authentication, "client_token_lifespan", _lifespan) + return lifespan_calls + + +@allure.feature("pysweep") +def test_provision_defaults_to_the_deployments_chatqna_endpoint(monkeypatch): + """With no -s, the endpoint is built from the deployment's own domain. + + The host must come from the build config rather than a constant, or a sweep + would drive load at a different cluster than the one it configures. + """ + _fake_keycloak(monkeypatch) + with psb.provision_benchmark_target([]) as args: + assert args[args.index("-s") + 1] == "https://box.example/api/v1/chatqna" + + +@allure.feature("pysweep") +def test_provision_mints_one_distinct_token_per_worker(monkeypatch): + """The bearer file holds ``workers`` *different* tokens, one per line. + + benchmark.py quits a worker whose line is empty, so the file must cover every + worker index. They must also be distinct: APISIX rate-limits /api/v1/chatqna + per Authorization header value, so one repeated token would put all workers in + a single bucket and cap the sweep's throughput regardless of concurrency. + """ + _fake_keycloak(monkeypatch) + with psb.provision_benchmark_target([], workers=8) as args: + lines = Path(args[args.index("-b") + 1]).read_text().splitlines() + assert len(lines) == 8 + assert len(set(lines)) == 8, "workers must not share a rate-limit bucket" + assert all(line for line in lines), "an empty line makes that worker quit" + + +@allure.feature("pysweep") +def test_provision_refresh_mints_new_tokens_benchmark_can_see(monkeypatch): + """Each run gets fresh tokens, and benchmark.py's linecache reads the new ones. + + A token only has to outlive one run that way. Without invalidating linecache, + the rewrite would be invisible: benchmark.py would hand out the cached, + possibly expired, tokens of the first run. + """ + _fake_keycloak(monkeypatch) + with psb.provision_benchmark_target([], workers=2) as args: + bearer = args[args.index("-b") + 1] + first = [linecache.getline(bearer, n).strip() for n in (1, 2)] + args.refresh() + second = [linecache.getline(bearer, n).strip() for n in (1, 2)] + assert all(first) and all(second) + assert not set(first) & set(second), "a refresh must hand out new tokens" + + +@allure.feature("pysweep") +def test_provision_lengthens_tokens_for_the_sweep_and_restores(monkeypatch): + """The lifespan override spans exactly the sweep: set on entry, undone on exit.""" + calls = _fake_keycloak(monkeypatch) + with psb.provision_benchmark_target([], workers=1): + assert calls == [("set", 3600)] + assert calls == [("set", 3600), ("restored", 3600)] + + +@allure.feature("pysweep") +def test_a_supplied_bearer_is_neither_refreshed_nor_lengthened(monkeypatch, tmp_path): + """-b is the caller's file: pysweep must not overwrite it or touch Keycloak.""" + calls = _fake_keycloak(monkeypatch) + uat = tmp_path / "uat.txt" + uat.write_text("real-token\n") + with psb.provision_benchmark_target(["-b", str(uat)]) as args: + args.refresh() + assert uat.read_text() == "real-token\n" + assert calls == [] + + +@allure.feature("pysweep") +def test_main_refreshes_tokens_before_every_run(monkeypatch, tmp_path): + """One refresh per load test, each one before that test starts.""" + monkeypatch.chdir(tmp_path) + cfg = load_config( + {"client": {**CLIENT, "concurrency": [1, 16]}, "llms": {"max_new_tokens": [128, 256]}} + ) + events = [] + + class _RecordingBenchmark(FakeBenchmark): + def run_benchmark(self, args, output_file=None): + events.append("run") + return super().run_benchmark(args, output_file=output_file) + + @contextmanager + def _provision(benchmark_args, workers=1): + yield psb.ProvisionedArgv( + list(benchmark_args) + ["-s", "http://127.0.0.1:1/api", "-b", "uat.txt"], + refresh=lambda: events.append("refresh"), + ) + + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr( + psb, "apply_combination", lambda combination, client: {s.path: s.value for s in combination} + ) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _provision) + _install_fake_benchmark(monkeypatch, _RecordingBenchmark(rows=1)) + + assert psb.main(["--sweep", "ignored.yaml", "--summaries", "out"]) == 0 + assert events == ["refresh", "run"] * 4 + + +@allure.feature("pysweep") +def test_configure_kubernetes_client_logs_quiets_httpx(): + """Disabled: the kr8s/httpx loggers stop emitting INFO but keep warnings.""" + levels = {n: logging.getLogger(n).level for n in psb.KUBERNETES_CLIENT_LOGGERS} + asyncio_log = logging.getLogger("asyncio") + installed = list(asyncio_log.filters) + try: + psb.configure_kubernetes_client_logs(enabled=False) + for name in psb.KUBERNETES_CLIENT_LOGGERS: + log = logging.getLogger(name) + assert not log.isEnabledFor(logging.INFO) + assert log.isEnabledFor(logging.WARNING) + # asyncio keeps its level (real errors matter) but gains the noise filter. + assert asyncio_log.isEnabledFor(logging.ERROR) + assert any( + isinstance(f, psb._DropPortForwardTeardownNoise) for f in asyncio_log.filters + ) + finally: + for name, level in levels.items(): + logging.getLogger(name).setLevel(level) + asyncio_log.filters = installed + + +@allure.feature("pysweep") +def test_kubernetes_client_log_filter_drops_only_teardown_noise(): + """kr8s's port-forward resets are dropped; other asyncio errors survive.""" + log_filter = psb._DropPortForwardTeardownNoise() + + def record(msg, exc=None): + rec = logging.LogRecord("asyncio", logging.ERROR, __file__, 1, msg, (), None) + if exc is not None: + rec.exc_info = (type(exc), exc, None) + return rec + + assert not log_filter.filter(record("Unhandled exception in client_connected_cb")) + assert not log_filter.filter(record("boom", ConnectionResetError("Connection lost"))) + # A genuine problem must still be reported. + assert log_filter.filter(record("Task exception was never retrieved")) + + +@allure.feature("pysweep") +def test_configure_kubernetes_client_logs_enabled_is_a_noop(): + """Enabled: levels are left exactly as the caller/CLI configured them.""" + levels = {n: logging.getLogger(n).level for n in psb.KUBERNETES_CLIENT_LOGGERS} + psb.configure_kubernetes_client_logs(enabled=True) + assert {n: logging.getLogger(n).level for n in psb.KUBERNETES_CLIENT_LOGGERS} == levels + + +@allure.feature("pysweep") +def test_provision_preserves_caller_supplied_server_and_bearer(tmp_path): + """Explicit -s/-b are left untouched (no port-forward, no token minting).""" + uat = tmp_path / "uat.txt" + uat.write_text("real-token\n") + original = ["-s", "https://erag.com/api/v1/chatqna", "-b", str(uat), "-c", "8"] + with psb.provision_benchmark_target(list(original)) as args: + assert args == original + + +# -- preflight: question_file resolution & verification ----------------------- +# The CWD-relative bug these cover: benchmark.py opens question_file with a bare +# open(), so before anchoring, the documented repo-root invocation could not find +# the corpus at all, and a same-named file in some other CWD would have been used +# silently while the summary recorded only the declared string. + + +@allure.feature("pysweep") +def test_question_file_resolves_against_pysweep_dir_not_cwd(monkeypatch, tmp_path): + """The anchor is the harness directory, whatever the process's CWD is.""" + monkeypatch.chdir(tmp_path) + resolved = psb.resolve_question_file("../questions-short.csv") + + assert resolved.is_absolute() + assert resolved == (psb.PYSWEEP_DIR / ".." / "questions-short.csv") + # The shipped corpora really are one level up, beside benchmark.py. + assert resolved.resolve().is_file() + + +@allure.feature("pysweep") +def test_question_file_absolute_path_is_untouched(tmp_path): + """An absolute path is already unambiguous; rewriting it would surprise.""" + corpus = tmp_path / "questions.csv" + corpus.write_text("q\n") + assert psb.resolve_question_file(str(corpus)) == corpus + + +@allure.feature("pysweep") +def test_preflight_accepts_the_shipped_example_config(monkeypatch): + """The example must pass its own preflight, or the docs ship a broken config. + + That is, every path the example declares really resolves. + """ + example = psb.PYSWEEP_DIR / "examples" / "sweep.yaml" + psb.preflight_check(load_config(example)) + + +@allure.feature("pysweep") +def test_preflight_rejects_a_missing_question_file(): + cfg = load_config(_client(question_file="../no-such-corpus.csv")) + with pytest.raises(psb.PreflightError, match="no-such-corpus.csv"): + psb.preflight_check(cfg) + + +@allure.feature("pysweep") +def test_preflight_error_names_the_resolved_path_and_the_anchor(): + """The message has to be actionable: what was looked for, and relative to what.""" + cfg = load_config(_client(question_file="questions-short.csv")) # missing '../' + with pytest.raises(psb.PreflightError) as excinfo: + psb.preflight_check(cfg) + + message = str(excinfo.value) + assert str(psb.PYSWEEP_DIR) in message + assert "not the current directory" in message + + +@allure.feature("pysweep") +def test_preflight_checks_every_declared_corpus_not_just_the_first(): + """question_file is sweepable: a bad path in the last value must fail up front, + not after the earlier runs have already spent their load.""" + cfg = load_config(_client(question_file=["../questions-short.csv", "../gone.csv"])) + with pytest.raises(psb.PreflightError, match="gone.csv"): + psb.preflight_check(cfg) + + +@allure.feature("pysweep") +def test_preflight_error_is_a_sweep_error(): + """Callers catching SweepError keep working; the subclass only adds meaning.""" + assert issubclass(psb.PreflightError, psb.SweepError) + + +@allure.feature("pysweep") +def test_preflight_runs_before_anything_is_applied(monkeypatch, tmp_path): + """The whole point of the up-front call: a bad path costs no rollout. + + A model swap takes hours, so a config typo must fail before apply, not after. + """ + monkeypatch.chdir(tmp_path) + cfg = load_config({"client": {**CLIENT, "question_file": "../gone.csv"}}) + applied = [] + + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr(psb, "apply_combination", lambda c, f: applied.append(c) or {}) + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + + with pytest.raises(psb.PreflightError): + psb.main(["--sweep", "ignored.yaml"]) + + assert applied == [] + + +@allure.feature("pysweep") +def test_benchmark_receives_the_resolved_absolute_question_file(monkeypatch, tmp_path): + """benchmark.py opens the value relative to ITS CWD, so it must get an absolute + path — that is what makes the anchor authoritative without editing benchmark.py.""" + monkeypatch.chdir(tmp_path) + cfg = load_config(_client()) + fake = FakeBenchmark() + + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr(psb, "apply_combination", lambda c, f: {}) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, fake) + + assert psb.main(["--sweep", "ignored.yaml"]) == 0 + + (args, _), = fake.calls + assert Path(args.f).is_absolute() + assert Path(args.f).is_file() + + +@allure.feature("pysweep") +def test_summary_records_the_declared_path_not_the_resolved_one(monkeypatch, tmp_path): + """Provenance shows what the config asked for; an absolute path would be + machine-specific and make two identical configs look different.""" + monkeypatch.chdir(tmp_path) + cfg = load_config(_client()) + fake = FakeBenchmark() + + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr(psb, "apply_combination", lambda c, f: {}) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, fake) + + assert psb.main(["--sweep", "ignored.yaml"]) == 0 + + summary = tmp_path / results.DEFAULT_SUMMARIES_DIR / results.SUMMARY_FILE_NAME + rows = list(csv.DictReader(summary.read_text().splitlines())) + assert rows[0]["client.question_file"] == "../questions-short.csv" + + +@allure.feature("pysweep") +def test_preflight_runs_once_for_the_whole_sweep(monkeypatch, tmp_path): + """Checked before the sweep and not again: every check is about the config and + its environment, so no run can change the answer and repeating it per load test + would only re-learn it. + """ + monkeypatch.chdir(tmp_path) + corpus = tmp_path / "questions.csv" + corpus.write_text("q\n") + cfg = load_config(_client(question_file=str(corpus), concurrency=[1, 16])) + fake = FakeBenchmark() + + calls = [] + + def counting_preflight(config): + calls.append(len(fake.calls)) + + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "preflight_check", counting_preflight) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr(psb, "apply_combination", lambda c, f: {}) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, fake) + + assert psb.main(["--sweep", "ignored.yaml"]) == 0 + + # Once, with no run done yet — and both client combinations still ran. + assert calls == [0] + assert len(fake.calls) == 2 + + +@allure.feature("pysweep") +def test_preflight_runs_the_corpus_check(monkeypatch): + """One entry point, so a new precondition is wired in one place and callers + (and this test) do not have to know how many checks there are.""" + called = [] + monkeypatch.setattr(psb, "question_file_verify", lambda config: called.append("corpus")) + + psb.preflight_check(load_config(_client())) + + assert called == ["corpus"] + + +# -- logging: what a run is announced as -------------------------------------- + + +@allure.feature("pysweep") +def test_format_settings_yaml_nests_dotted_paths_with_four_spaces(): + """The block has to read like the sweep config it came from. + + Dotted paths back into sections, four-space indentation to match the config + files — so the logged text is comparable to (and pasteable into) a sweep YAML + rather than being a Python repr of the runner's internals. + """ + block = psb.format_settings_yaml({"client.concurrency": 16, "client.duration": "3m"}) + assert block == "client:\n concurrency: 16\n duration: 3m" + + +@allure.feature("pysweep") +def test_format_settings_yaml_groups_sections_and_keeps_kpis_top_level(): + """A summary row mixes knob paths with undotted KPIs; both have to read well. + + Sections group (in the caller's order, not sorted — for load parameters that + order is benchmark.py's own), and the KPI keys have no section to belong to, + so they stay at the top level instead of being invented one. + """ + block = psb.format_settings_yaml( + { + "llms.max_new_tokens": 1024, + "retriever.k": 5, + "reranker.top_n": 3, + "client.concurrency": 128, + "requests": 3225, + "error": 0, + } + ) + assert block.splitlines() == [ + "llms:", + " max_new_tokens: 1024", + "retriever:", + " k: 5", + "reranker:", + " top_n: 3", + "client:", + " concurrency: 128", + "requests: 3225", + "error: 0", + ] + + +@allure.feature("pysweep") +def test_format_settings_yaml_is_empty_for_no_settings(): + """So a caller can say '(unchanged)' instead of logging an empty block.""" + assert psb.format_settings_yaml({}) == "" + + +@allure.feature("pysweep") +def test_format_settings_yaml_stringifies_what_yaml_cannot_represent(): + """A log line must never be what kills a four-hour sweep. + + Property read-backs are ints and strings today, but yaml.safe_dump raises on + anything else, so unknown types are rendered rather than propagated. + """ + block = psb.format_settings_yaml({"client.question_file": Path("/tmp/q.csv")}) + assert block == "client:\n question_file: /tmp/q.csv" + + +@allure.feature("pysweep") +def test_load_parameters_are_logged_as_yaml(caplog, tmp_path): + """The 'load parameters' step announces the client section, not a dict repr. + + That line is how a reader of a multi-hour log knows what the next load test + is about to do, so it is asserted here: YAML block, four-space indent, the + declared corpus path (not the anchored absolute one), and no dict/JSON braces. + """ + cfg = load_config(_client(concurrency=16)) + + with caplog.at_level(logging.INFO, logger=psb.logger.name): + psb.run_client_combination( + FakeBenchmark(), [], (), cfg.client_combinations()[0], "Run 1.1", + results_dir=tmp_path, tokenizer="served/model", + ) + + message = next( + record.getMessage() for record in caplog.records + if "load parameters" in record.getMessage() + ) + assert "\nclient:\n" in message + assert " question_file: ../questions-short.csv" in message + assert " concurrency: 16" in message + assert "{" not in message and "'" not in message + + +@allure.feature("pysweep") +def test_load_parameters_line_names_the_derived_tokenizer(): + """It is a load parameter too (-m), but it has no config key. + + So it is reported in the prose rather than inside the YAML block: a block + containing 'tokenizer:' would look declarable, and 'client.tokenizer' is a + ConfigError by design. + """ + cfg = load_config(_client()) + block = psb.format_settings_yaml( + BenchmarkClientArgs.from_settings(cfg.client_combinations()[0]).snapshot() + ) + assert "tokenizer" not in block diff --git a/src/tests/e2e/validation/pysweep/test_results_unit.py b/src/tests/e2e/validation/pysweep/test_results_unit.py new file mode 100644 index 00000000..375cd999 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_results_unit.py @@ -0,0 +1,397 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for the sweep summary post-processing (``pysweep/results.py``). + +Pure computation over CSV files, so nothing here needs a cluster, transformers, +or a load test — the inputs are hand-written result files whose KPIs can be +checked by arithmetic. +""" + +import csv + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.config import load_config +from tests.e2e.benchmarks.chatqna.pysweep.results import ( + PER_CASE_DIR_NAME, + SUMMARY_COLUMNS, + SUMMARY_FILE_NAME, + RequestRecord, + SummariesLayoutError, + SweepSummary, + percentile, + prepare_summaries_dir, + read_requests, + summarize_requests, +) + +CLIENT = { + "question_file": "questions-short.csv", + "concurrency": 4, + "duration": "3m", + "worker_startup_delay": "0s", + "failures_allowed": 200, + "input_tokens": 128, + "warmup_requests": 1, +} + + +def _result_file(tmp_path, rows, name="bench_x.result.csv"): + """Write a benchmark.py-shaped result CSV: no header, one row per request.""" + path = tmp_path / name + with path.open("w", newline="") as handle: + csv.writer(handle).writerows(rows) + return path + + +@allure.feature("pysweep") +def test_tpot_excludes_the_first_token(): + """TPOT is the *inter-token* gap, so neither TTFT nor its token counts in it. + + With 11 output tokens, 1.0s to the first and 3.0s overall, decode produced + the remaining 10 tokens in 2.0s: 0.2s per token. Dividing by 11 instead (as + ``parse.py``'s next_token_lat does) would report 0.1818 and understate the + decode cost, which is the distinction this KPI exists to make. + """ + record = RequestRecord(128, 11, 1.0, 3.0, "", 200) + assert record.tpot == pytest.approx(0.2) + + +@allure.feature("pysweep") +def test_tpot_is_undefined_for_a_single_token_answer(): + """One token means no gap between tokens; its whole latency is TTFT.""" + assert RequestRecord(128, 1, 1.0, 1.0, "", 200).tpot is None + assert RequestRecord(128, 0, 1.0, 1.0, "", 200).tpot is None + + +@allure.feature("pysweep") +def test_percentile_interpolates_like_pandas(): + """p90 must agree with what parse.py reports, i.e. numpy's default method. + + For 1..10 the 0.9 quantile sits between the 9th and 10th values at 9.1 — + not 9 (nearest-rank) and not 10 (ceiling). + """ + assert percentile(list(range(1, 11)), 0.9) == pytest.approx(9.1) + assert percentile([5.0], 0.9) == 5.0 + assert percentile([], 0.9) is None + + +@allure.feature("pysweep") +def test_kpis_are_computed_over_the_recorded_requests(tmp_path): + """The four KPIs come out of the per-request rows by plain arithmetic. + + Two requests, TTFT 1.0 and 2.0 -> mean 1.5, p90 1.9 (interpolated). Each has + 11 output tokens and 2.0s/4.0s of decode after the first token -> TPOT 0.2 + and 0.4, mean 0.3, p90 0.38. + """ + path = _result_file( + tmp_path, + [ + [128, 11, 1.0, 3.0, "", 200], + [128, 11, 2.0, 6.0, "", 200], + ], + ) + summary = summarize_requests(read_requests(path)) + assert summary["requests"] == 2 + assert summary["mean_ttft"] == pytest.approx(1.5) + assert summary["p90_ttft"] == pytest.approx(1.9) + assert summary["mean_tpot"] == pytest.approx(0.3) + assert summary["p90_tpot"] == pytest.approx(0.38) + + +@allure.feature("pysweep") +def test_unsuccessful_and_implausible_rows_are_excluded(tmp_path): + """A summary must describe successful requests only. + + A non-200, an errored row, one that never timed a first chunk, and a + malformed line would each poison the mean if counted. Dropping them (rather + than raising) also means one damaged line cannot cost an hours-long sweep its + summary. + """ + path = _result_file( + tmp_path, + [ + [128, 11, 1.0, 3.0, "", 200], + [128, 11, 1.0, 3.0, "", 500], + [128, 11, 1.0, 3.0, "connection reset", 200], + [128, 11, 0.0, 3.0, "", 200], # no first chunk ever timed + [128, 11, 5.0, 1.0, "", 200], # overall precedes the first chunk + ["not", "a", "row"], + ], + ) + records = read_requests(path) + assert len(records) == 1 + assert summarize_requests(records)["requests"] == 1 + + +@allure.feature("pysweep") +def test_a_run_that_recorded_nothing_still_gets_a_row(tmp_path): + """"This configuration produced no data" is a result, not a reason to abort. + + Blank KPIs with ``requests`` 0 says exactly that; dropping the row would + leave a hole in the sweep that looks like a configuration never tried. + """ + summary = SweepSummary(["client.concurrency"], path=tmp_path / "s.csv") + row = summary.add_run({"client.concurrency": 128}, tmp_path / "missing.csv", error=1) + assert row["requests"] == 0 + assert row["mean_ttft"] is None + written = list(csv.DictReader((tmp_path / "s.csv").open())) + assert written == [ + { + "client.concurrency": "128", + "requests": "0", + "mean_ttft": "", + "p90_ttft": "", + "mean_tpot": "", + "p90_tpot": "", + "served_model": "", + "error": "1", + "result_file": "missing.csv", + } + ] + + +@allure.feature("pysweep") +def test_result_file_is_recorded_relative_to_the_summary(tmp_path): + """The pointer column is relative, so the results directory can be moved. + + A sweep runs on the benchmark host and is read somewhere else. An absolute + path in the column would name a directory that only ever existed on the host; + ``per_case_results/bench_x.result.csv`` still resolves after the directory is + copied off it or renamed. + """ + per_case = tmp_path / PER_CASE_DIR_NAME + per_case.mkdir() + result = _result_file(per_case, [[128, 11, 1.0, 3.0, "", 200]]) + summary = SweepSummary(["client.concurrency"], path=tmp_path / SUMMARY_FILE_NAME) + + row = summary.add_run({"client.concurrency": 4}, result) + + assert row["result_file"] == f"{PER_CASE_DIR_NAME}/bench_x.result.csv" + assert (summary.path.parent / row["result_file"]).exists() + + +@allure.feature("pysweep") +def test_a_result_file_from_outside_the_directory_is_recorded_verbatim(tmp_path): + """There is no meaningful relative name for it, so the absolute one is kept. + + Not a shape the sweep produces, but the column must stay resolvable rather + than becoming a ``../..``-prefixed guess at where the reader will stand. + """ + elsewhere = _result_file(tmp_path, [[128, 11, 1.0, 3.0, "", 200]]) + root = tmp_path / "results" + root.mkdir() + summary = SweepSummary([], path=root / SUMMARY_FILE_NAME) + + row = summary.add_run({}, elsewhere) + + assert row["result_file"] == str(elsewhere) + + +@allure.feature("pysweep") +def test_summary_columns_are_the_declared_knobs_in_dot_notation(tmp_path): + """Header = every declared knob as its dotted config path, then the KPIs. + + Dotted paths are the point: the column name is the key the sweep YAML used, + so a reader can go from a column back to the config with no lookup table. + Constants get columns too (``client.duration`` is single-valued here), because a + summary that only named the varying knobs would not say what the numbers + were measured under. + """ + cfg = load_config( + { + "client": {**CLIENT, "concurrency": [1, 16], "input_tokens": [128, 256]}, + "llms": {"max_new_tokens": [128, 256]}, + } + ) + summary = SweepSummary(cfg.knob_paths(), path=tmp_path / "s.csv") + assert summary.columns == [ + "llms.max_new_tokens", + "client.concurrency", + "client.duration", + "client.failures_allowed", + "client.input_tokens", + "client.question_file", + "client.warmup_requests", + "client.worker_startup_delay", + *SUMMARY_COLUMNS, + ] + + +@allure.feature("pysweep") +def test_header_exists_before_the_first_run_finishes(tmp_path): + """A sweep's first row can be an hour away; the file must not be missing. + + The first run sits behind a multi-replica rollout, and until it completes a + missing file is indistinguishable from a harness that never summarizes at + all. A header-only file says "running, and here is the shape of the results". + """ + path = tmp_path / "sweep_summary.csv" + summary = SweepSummary(["client.concurrency"], path=path) + assert path.exists() + assert next(csv.reader(path.open())) == summary.columns + assert list(csv.DictReader(path.open())) == [] + + +@allure.feature("pysweep") +def test_summary_is_readable_after_every_run(tmp_path): + """Rewritten per run, so a sweep killed at hour three still leaves a table. + + An hours-long sweep that only wrote its summary at the end would lose + everything to a failed rollout in the middle. + """ + path = tmp_path / "sweep_summary.csv" + summary = SweepSummary(["client.concurrency"], path=path) + for index, concurrency in enumerate((1, 16), start=1): + result = _result_file( + tmp_path, [[128, 11, 1.0, 3.0, "", 200]], name=f"bench_{concurrency}.csv" + ) + summary.add_run({"client.concurrency": concurrency}, result) + rows = list(csv.DictReader(path.open())) + assert len(rows) == index + assert [row["client.concurrency"] for row in rows] == ["1", "16"] + assert [row["mean_tpot"] for row in rows] == ["0.2", "0.2"] + + +@allure.feature("pysweep") +def test_unset_knobs_render_blank_rather_than_shifting_columns(tmp_path): + """A knob with no value for a run leaves an empty cell. + + The columns are fixed from the config up front, so a missing value must not + be able to misalign a row — that would silently attribute one knob's value + to another column. + """ + summary = SweepSummary(["llms.max_new_tokens", "client.concurrency"], path=tmp_path / "s.csv") + row = summary.add_run({"client.concurrency": 4}, tmp_path / "none.csv") + assert row["llms.max_new_tokens"] == "" + header = next(csv.reader((tmp_path / "s.csv").open())) + assert header[:2] == ["llms.max_new_tokens", "client.concurrency"] + + +@allure.feature("pysweep") +def test_the_output_layout_is_created_when_nothing_is_there(tmp_path): + """A sweep must not fail because its output directory does not exist yet. + + That includes intermediate directories: ``--summaries runs/today`` is a + reasonable thing to type on a fresh host. + """ + layout = prepare_summaries_dir(tmp_path / "runs" / "today") + + assert layout.root.is_dir() + assert layout.per_case_dir.is_dir() + assert layout.summary_file == layout.root / SUMMARY_FILE_NAME + assert layout.per_case_dir == layout.root / PER_CASE_DIR_NAME + + +@allure.feature("pysweep") +def test_the_paths_are_absolute(tmp_path, monkeypatch): + """``benchmark.py`` opens its output with a bare ``open()``. + + A relative per-case path would land against the working directory of whatever + process happened to do the opening, so the layout is resolved once, here. + """ + monkeypatch.chdir(tmp_path) + + layout = prepare_summaries_dir("results") + + assert layout.root.is_absolute() + assert layout.summary_file.is_absolute() + assert layout.per_case_dir.is_absolute() + + +@allure.feature("pysweep") +def test_the_previous_sweep_is_discarded(tmp_path): + """A sweep's artifacts only make sense as a set, so the slate is wiped clean. + + Keeping them would mix two sweeps: per-case CSVs with no row in the current + summary, or — if the previous sweep was longer — rows in a stale summary + pointing at files this one never overwrote. + """ + root = tmp_path / "results" + per_case = root / PER_CASE_DIR_NAME + per_case.mkdir(parents=True) + (root / SUMMARY_FILE_NAME).write_text("stale header\n") + (per_case / "bench_old.result.csv").write_text("stale\n") + (per_case / "nested").mkdir() + (per_case / "nested" / "deeper.csv").write_text("stale\n") + + layout = prepare_summaries_dir(root) + + assert not layout.summary_file.exists() + assert list(layout.per_case_dir.iterdir()) == [] + + +@allure.feature("pysweep") +def test_nothing_else_in_the_directory_is_touched(tmp_path): + """The deletion is confined to the summary and the per-case subdirectory. + + ``--summaries`` is a path a user types, and it may well point at a directory + that already holds notes, a copy of the sweep YAML, or someone's plots. Only + what this sweep is about to rewrite is removed. + """ + root = tmp_path / "results" + root.mkdir() + (root / "sweep.yaml").write_text("client: {}\n") + (root / "notes").mkdir() + (root / "notes" / "why.md").write_text("because\n") + + prepare_summaries_dir(root) + + assert (root / "sweep.yaml").exists() + assert (root / "notes" / "why.md").exists() + + +@allure.feature("pysweep") +def test_a_symlinked_per_case_directory_is_refused(tmp_path): + """Emptying it would delete files outside the directory the caller named. + + The flag is destructive by design, but only within the tree it was pointed at; + following a link out of that tree is not something to do quietly. + """ + outside = tmp_path / "outside" + outside.mkdir() + (outside / "precious.csv").write_text("keep\n") + root = tmp_path / "results" + root.mkdir() + (root / PER_CASE_DIR_NAME).symlink_to(outside, target_is_directory=True) + + with pytest.raises(SummariesLayoutError): + prepare_summaries_dir(root) + + assert (outside / "precious.csv").exists() + + +@allure.feature("pysweep") +def test_a_file_where_a_directory_belongs_is_refused(tmp_path): + """``--summaries`` names a directory; a file there means the wrong path. + + Most likely the old ``--summary sweep_summary.csv`` habit. Failing beats + guessing at the parent directory, and beats deleting the file. + """ + as_file = tmp_path / "results" + as_file.write_text("not a directory\n") + + with pytest.raises(SummariesLayoutError): + prepare_summaries_dir(as_file) + + assert as_file.read_text() == "not a directory\n" + + +@allure.feature("pysweep") +def test_nothing_is_deleted_when_the_layout_is_refused(tmp_path): + """The checks all run before the first deletion. + + Otherwise a directory that turns out to be unusable would still have lost the + previous sweep's results by the time the error was raised. + """ + root = tmp_path / "results" + root.mkdir() + (root / SUMMARY_FILE_NAME).write_text("previous sweep\n") + (root / PER_CASE_DIR_NAME).write_text("not a directory\n") + + with pytest.raises(SummariesLayoutError): + prepare_summaries_dir(root) + + assert (root / SUMMARY_FILE_NAME).read_text() == "previous sweep\n" diff --git a/src/tests/e2e/validation/pysweep/test_served_model.py b/src/tests/e2e/validation/pysweep/test_served_model.py new file mode 100644 index 00000000..0d801343 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_served_model.py @@ -0,0 +1,93 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""e2e test for :mod:`served_model` — its bindings to the live deployment. + +The runner tokenizes every load test with the model this module reads, and the +read rests on assumptions about objects this repo does not own: the ``llm-usvc`` +label selector and container name, ``LLM_MODEL_NAME`` in the pods' env, and +KServe's ``LLMInferenceService`` at ``serving.kserve.io/v1alpha2``. Any of them can +be renamed by a chart bump without a single unit test noticing, and the symptom +would be a sweep that cannot pick a tokenizer. This module is where that drift +fails. + +Read-only: nothing here changes the deployment. +""" + +import logging + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import model_catalog, served_model +from tests.e2e.benchmarks.chatqna.pysweep.served_model import LLMInferenceService, ServedModel + +logger = logging.getLogger(__name__) + + +@pytest.fixture(scope="module") +def observed_model(pysweep_kubernetes_access): + """The model the deployment is observed to serve, gated on the RBAC preflight. + + Every test needs it, and it comes from ``read()`` — so a deployment that is + mid-rollout or pointed at an unserved model fails here once, with the reason, + rather than in each test. + """ + model = ServedModel().read() + logger.info("Deployment observed serving model %r.", model) + return model + + +@allure.feature("pysweep") +def test_read_returns_the_served_model_name(observed_model): + """The selector selects, the exec works, and the env var is populated. + + ``read`` must observe the pods, so if the label selector or the container name + stopped matching, this is where it surfaces. + """ + assert observed_model + assert observed_model == observed_model.strip() + + +@allure.feature("pysweep") +def test_the_observed_model_is_a_catalog_name(observed_model): + """Not a HuggingFace repo id. + + ``LLM_MODEL_NAME`` carries model-manager's short name, which is what the + gateway routes on. If a deployment ever put a repo id here, the tokenizer + lookup in :mod:`.model_catalog` would have nothing to map. + """ + known = model_catalog.known_models() + assert observed_model in known, ( + f"The deployment serves {observed_model!r}, which is not a name in the " + f"model catalog ({known}), so no tokenizer can be derived for it." + ) + + +@allure.feature("pysweep") +def test_the_observed_model_has_a_tokenizer(observed_model): + """The benchmark's ``-m`` is derived, never configured. + + Every token count in every result row depends on this mapping resolving for the + model actually being served. + """ + tokenizer = model_catalog.tokenizer_for(observed_model) + assert "/" in tokenizer, ( + f"{tokenizer!r} does not look like a HuggingFace repo id; the benchmark " + f"would fail to load a tokenizer for it." + ) + + +@allure.feature("pysweep") +def test_the_served_model_is_a_ready_llminferenceservice(observed_model): + """Binds the hand-written kr8s class to the live CRD. + + The apiVersion is pinned in one place on purpose (see + :class:`LLMInferenceService`); when KServe moves past ``v1alpha2`` this test is + the notice. + """ + llmisvc = LLMInferenceService.get(observed_model, namespace=served_model.INFERENCE_NAMESPACE) + conditions = (llmisvc.raw.get("status", {}) or {}).get("conditions", []) or [] + assert any( + cond.get("type") == "Ready" and cond.get("status") == "True" for cond in conditions + ), f"{observed_model} is not Ready; conditions: {conditions}" diff --git a/src/tests/e2e/validation/pysweep/test_served_model_unit.py b/src/tests/e2e/validation/pysweep/test_served_model_unit.py new file mode 100644 index 00000000..db698d25 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_served_model_unit.py @@ -0,0 +1,188 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for :mod:`served_model`, the read-only served-model probe. + +The runner tokenizes with whatever this returns, so what is pinned is that it +observes the running pods (not a ConfigMap), and that every inconsistent picture +(replicas disagreeing, nothing serving the named model, a model still loading, +an unreadable pod) is an error rather than a model name. + +``kr8s`` and ``LLMInferenceService`` are replaced module-locally. That the real +objects have this shape is covered by ``test_served_model.py``, which needs a +deployment. +""" + +from types import SimpleNamespace + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import served_model +from tests.e2e.benchmarks.chatqna.pysweep.base import PropertyReadError +from tests.e2e.benchmarks.chatqna.pysweep.served_model import ServedModel + +MODEL = "llama3-8b-awq" +OTHER = "qwen3-5-2b-ovms" + + +class FakePod: + def __init__(self, name, model, terminating=False, exec_error=None): + self.name = name + self.model = model + self.metadata = {"deletionTimestamp": "2026-01-01T00:00:00Z"} if terminating else {} + self.exec_error = exec_error + self.exec_calls = [] + + def exec(self, command, container=None): + self.exec_calls.append((command, container)) + if self.exec_error is not None: + raise self.exec_error + return SimpleNamespace(stdout=self.model) + + +class FakeCluster: + """The pipeline's LLM pods and the models being served.""" + + def __init__(self, pods=None, served=None): + self.pods = [FakePod("llm-usvc-a", MODEL)] if pods is None else list(pods) + # model name -> replica count; membership means "an LLMInferenceService exists". + self.served = {MODEL: 4} if served is None else dict(served) + self.not_ready = set() + + def get(self, resource, namespace=None, label_selector=None): + assert resource == "pods" + assert label_selector == served_model.LLM_USVC_LABEL_SELECTOR + return list(self.pods) + + def llmisvc_get(self, name, namespace=None): + if name not in self.served: + raise RuntimeError(f"llminferenceservices '{name}' not found") + conditions = [] + if name not in self.not_ready: + conditions = [{"type": "Ready", "status": "True"}] + return SimpleNamespace(raw={"status": {"conditions": conditions}}) + + +@pytest.fixture +def cluster(monkeypatch): + fake = FakeCluster() + install(monkeypatch, fake) + return fake + + +def install(monkeypatch, fake): + """Point the probe at ``fake`` instead of a cluster.""" + monkeypatch.setattr(served_model, "kr8s", SimpleNamespace(get=fake.get)) + monkeypatch.setattr( + served_model, "LLMInferenceService", SimpleNamespace(get=fake.llmisvc_get) + ) + return fake + + +# -- read --------------------------------------------------------------------- + + +@allure.feature("pysweep") +def test_read_returns_the_model_the_pods_actually_run(cluster): + assert ServedModel().read() == MODEL + + +@allure.feature("pysweep") +def test_read_execs_into_the_application_container(cluster): + """Not the init container: it has no ``LLM_MODEL_NAME`` and is gone by then.""" + ServedModel().read() + (_, container), = cluster.pods[0].exec_calls + assert container == served_model.LLM_USVC_CONTAINER + + +@allure.feature("pysweep") +def test_read_reports_the_pods_model_even_when_another_is_served(monkeypatch): + """Serving a model is not the pipeline using it. + + Two models can be Ready at once (e.g. mid-swap); only the one the replicas' + processes name is what the benchmark exercises, so that is the one to tokenize + with. + """ + fake = FakeCluster(served={MODEL: 4, OTHER: 4}) + install(monkeypatch, fake) + + assert ServedModel().read() == MODEL + + +@allure.feature("pysweep") +def test_read_ignores_terminating_pods(monkeypatch): + """A pod being replaced is not part of the observed configuration. + + Counting it would make ``read`` report a disagreement for the whole grace + period after a restart that has otherwise already converged. + """ + fake = FakeCluster( + pods=[FakePod("old", OTHER, terminating=True), FakePod("new", MODEL)], + served={MODEL: 4, OTHER: 4}, + ) + install(monkeypatch, fake) + + assert ServedModel().read() == MODEL + + +@allure.feature("pysweep") +def test_read_raises_when_replicas_disagree(monkeypatch): + """Half the fleet on each model is not a configuration a benchmark may run against.""" + fake = FakeCluster( + pods=[FakePod("a", MODEL), FakePod("b", OTHER)], + served={MODEL: 4, OTHER: 4}, + ) + install(monkeypatch, fake) + + with pytest.raises(PropertyReadError, match="do not agree"): + ServedModel().read() + + +@allure.feature("pysweep") +def test_read_raises_when_no_pods_are_running(monkeypatch): + fake = FakeCluster(pods=[]) + install(monkeypatch, fake) + + with pytest.raises(PropertyReadError, match="No live llm-usvc pods"): + ServedModel().read() + + +@allure.feature("pysweep") +def test_read_raises_when_the_named_model_is_not_served(monkeypatch): + """A pipeline pointed at an absent model answers nothing; that is not 'configured'.""" + fake = FakeCluster(served={}) + install(monkeypatch, fake) + + with pytest.raises(PropertyReadError, match="nothing is serving it"): + ServedModel().read() + + +@allure.feature("pysweep") +def test_read_raises_when_the_model_is_served_but_not_ready(monkeypatch): + """Weights still loading is exactly the window a sweep must not benchmark in.""" + fake = FakeCluster() + fake.not_ready = {MODEL} + install(monkeypatch, fake) + + with pytest.raises(PropertyReadError, match="no Ready"): + ServedModel().read() + + +@allure.feature("pysweep") +def test_read_raises_on_an_empty_env_var(monkeypatch): + fake = FakeCluster(pods=[FakePod("a", "")]) + install(monkeypatch, fake) + + with pytest.raises(PropertyReadError, match="empty"): + ServedModel().read() + + +@allure.feature("pysweep") +def test_read_raises_when_exec_fails(monkeypatch): + """A starting container cannot be exec'd into; unreadable is not 'unchanged'.""" + fake = FakeCluster(pods=[FakePod("a", MODEL, exec_error=RuntimeError("container not running"))]) + install(monkeypatch, fake) + + with pytest.raises(PropertyReadError, match="container not running"): + ServedModel().read() diff --git a/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py b/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py new file mode 100644 index 00000000..2457c023 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py @@ -0,0 +1,135 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for the sweep-long access-token lifespan override. + +Pinned: the override is per client (nothing else in the realm changes), the +client's previous value comes back afterwards, including after a failed sweep, and +a client with no override goes back to inheriting the realm setting. +No Keycloak is involved: ``requests`` is replaced with an in-memory client store. +""" + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import authentication +from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( + CLIENT_TOKEN_LIFESPAN_ATTRIBUTE, + KeycloakConfigError, + client_token_lifespan, +) +from tests.e2e.validation.constants import VITE_KEYCLOAK_CLIENT_ID, VITE_KEYCLOAK_REALM + +DOMAIN = "https://keycloak.box.example" +CLIENTS_URL = f"{DOMAIN}/admin/realms/{VITE_KEYCLOAK_REALM}/clients" + + +class _Response: + def __init__(self, payload=None, status=200): + self._payload = payload + self.status_code = status + + def json(self): + return self._payload + + def raise_for_status(self): + if self.status_code >= 400: + raise RuntimeError(f"HTTP {self.status_code}") + + +class _FakeKeycloak: + """Just enough of the admin API: list clients by clientId, GET/PUT one client.""" + + def __init__(self, attributes=None, exists=True): + self.client = {"id": "uuid-1", "clientId": VITE_KEYCLOAK_CLIENT_ID, + "attributes": dict(attributes or {})} + self.exists = exists + self.puts = [] + self.fail_puts = False + + def get(self, url, params=None, **kwargs): + if url == CLIENTS_URL: + assert params == {"clientId": VITE_KEYCLOAK_CLIENT_ID} + return _Response([dict(self.client)] if self.exists else []) + assert url == f"{CLIENTS_URL}/uuid-1" + return _Response({**self.client, "attributes": dict(self.client["attributes"])}) + + def put(self, url, json=None, **kwargs): + assert url == f"{CLIENTS_URL}/uuid-1" + if self.fail_puts: + return _Response(status=500) + self.puts.append(json["attributes"].get(CLIENT_TOKEN_LIFESPAN_ATTRIBUTE)) + self.client = json + return _Response(status=204) + + @property + def lifespan(self): + return self.client["attributes"].get(CLIENT_TOKEN_LIFESPAN_ATTRIBUTE) + + +class _Helper: + erag_auth_domain = DOMAIN + admin_access_token = "admin-token" + + +@pytest.fixture +def keycloak(monkeypatch): + def install(**kwargs): + fake = _FakeKeycloak(**kwargs) + monkeypatch.setattr(authentication.requests, "get", fake.get) + monkeypatch.setattr(authentication.requests, "put", fake.put) + return fake + + return install + + +@allure.feature("pysweep") +def test_the_sweep_value_is_arbitrary_but_outlasts_a_long_run(): + """Only has to cover one run; 15m runs are the longest used so far.""" + assert authentication.SWEEP_TOKEN_LIFESPAN_S == 3600 + + +@allure.feature("pysweep") +def test_an_unset_client_goes_back_to_inheriting_the_realm(keycloak): + fake = keycloak() + with client_token_lifespan(_Helper(), seconds=3600): + assert fake.lifespan == "3600" + # "" is Keycloak's "inherit": the client is as it was before the sweep. + assert fake.lifespan == "" + assert fake.puts == ["3600", ""] + + +@allure.feature("pysweep") +def test_a_client_override_is_put_back(keycloak): + fake = keycloak(attributes={CLIENT_TOKEN_LIFESPAN_ATTRIBUTE: "900", "other": "kept"}) + with client_token_lifespan(_Helper(), seconds=3600): + assert fake.lifespan == "3600" + assert fake.lifespan == "900" + assert fake.client["attributes"]["other"] == "kept" + + +@allure.feature("pysweep") +def test_restored_even_when_the_sweep_fails(keycloak): + fake = keycloak(attributes={CLIENT_TOKEN_LIFESPAN_ATTRIBUTE: "900"}) + with pytest.raises(ValueError): + with client_token_lifespan(_Helper(), seconds=3600): + raise ValueError("sweep failed") + assert fake.lifespan == "900" + + +@allure.feature("pysweep") +def test_a_failed_restore_does_not_mask_the_sweeps_own_error(keycloak): + fake = keycloak() + with pytest.raises(ValueError, match="sweep failed"): + with client_token_lifespan(_Helper(), seconds=3600): + fake.fail_puts = True + raise ValueError("sweep failed") + + +@allure.feature("pysweep") +def test_a_missing_client_fails_before_anything_is_changed(keycloak): + fake = keycloak(exists=False) + with pytest.raises(KeycloakConfigError, match=VITE_KEYCLOAK_CLIENT_ID): + with client_token_lifespan(_Helper()): + pass + assert fake.puts == [] diff --git a/src/tests/e2e/validation/requirements.txt b/src/tests/e2e/validation/requirements.txt index b5ed42cb..e6f88608 100644 --- a/src/tests/e2e/validation/requirements.txt +++ b/src/tests/e2e/validation/requirements.txt @@ -10,6 +10,7 @@ pytest==9.0.3 # MIT allure-pytest==2.15.3 # Apache 2.0 requests==2.33.1 # Apache 2.0 kr8s==0.20.15 # BSD 3-Clause License +pydantic==2.13.4 # MIT sniffio==1.3.1 # MIT pytest-timeout==2.4.0 # MIT sentence-transformers==5.6.0 # Apache 2.0 diff --git a/src/tox.ini b/src/tox.ini index 3ffc0174..df2f8931 100644 --- a/src/tox.ini +++ b/src/tox.ini @@ -325,6 +325,33 @@ commands = # ----------------------------------------------------------------------------- +[testenv:pysweep_unit_tests] +description = Run pysweep harness unit tests (no cluster required) +setenv = + PYTHONPATH = . +deps = + pytest==9.0.3 + PyYAML==6.0.2 + # Every test module in the suite is @allure.feature-tagged, so the plugin is + # needed even when no report is generated. + allure-pytest==2.15.3 + # The sweep config schema is pydantic, and the property/runtime-API modules + # the tests import pull in kr8s and requests at import time. + pydantic==2.13.4 + kr8s==0.20.15 + requests==2.33.1 +commands = + # Only the *_unit.py modules: they stub the cluster and the fingerprint API, so + # they run anywhere. The rest of tests/e2e/validation/pysweep needs a live + # deployment and runs under `tox -e e2e` (which collects both). + # + # --confcutdir stops pytest loading tests/e2e/conftest.py, whose session + # fixtures read a deployment's config files and talk to the cluster. Without it + # these tests could not run off a deployment host at all. + pytest -s --disable-warnings --confcutdir=tests/e2e/validation/pysweep -k "_unit" tests/e2e/validation/pysweep {posargs} + +# ----------------------------------------------------------------------------- + [testenv:deployment_scripts_unit_tests] description = Run deployment helper script unit tests (pipeline composer) setenv = From 2263b1083951b1ce00bfc974843074b15567e984 Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Wed, 25 Nov 2026 15:52:48 +0100 Subject: [PATCH 02/11] refactor(benchmarks): import pysweep's namespaces from the e2e suite constants Signed-off-by: Kurzacz, Kamil --- .../chatqna/pysweep/authentication.py | 21 ++++++++++--------- .../benchmarks/chatqna/pysweep/runtime_api.py | 2 +- .../chatqna/pysweep/served_model.py | 10 ++++----- src/tests/e2e/validation/constants.py | 2 ++ .../validation/pysweep/test_served_model.py | 5 +++-- 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py b/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py index 5c926e6c..f1732ef2 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py @@ -46,7 +46,14 @@ from tests.e2e.helpers.k8s_helper import K8sHelper from tests.e2e.helpers.keycloak_helper import KeycloakHelper from tests.e2e.validation.buildcfg import cfg -from tests.e2e.validation.constants import VITE_KEYCLOAK_CLIENT_ID, VITE_KEYCLOAK_REALM +from tests.e2e.validation.constants import ( + CHATQNA_NAMESPACE, + FINGERPRINT_NAMESPACE, + KEYCLOAK_NAMESPACE, + LLM_INFERENCE_NAMESPACE, + VITE_KEYCLOAK_CLIENT_ID, + VITE_KEYCLOAK_REALM, +) from .paths import deploy_roots, is_dir, is_file @@ -54,12 +61,6 @@ logger = logging.getLogger(__name__) -# Kubernetes namespaces pysweep touches (see DESIGN.md). -PIPELINE_NAMESPACE = "chatqna" -INFERENCE_NAMESPACE = "llm-inference" -FINGERPRINT_NAMESPACE = "fingerprint" -KEYCLOAK_NAMESPACE = "keycloak" - # The installed environment's config directory, mirroring the e2e suite's # --build-config-dir default. Overridable so a sweep can be run against a # different environment without editing anything. @@ -124,10 +125,10 @@ class AccessCheckResult: # list is the fastest way to see everything a sweep can touch. REQUIRED_ACCESS = [ # The served model, read back to pick the tokenizer (served_model.py). - RequiredAccess("list", "pods", PIPELINE_NAMESPACE, reason="locate the llm-usvc replicas"), - RequiredAccess("create", "pods/exec", PIPELINE_NAMESPACE, reason="read the pods' effective LLM_MODEL_NAME"), + RequiredAccess("list", "pods", CHATQNA_NAMESPACE, reason="locate the llm-usvc replicas"), + RequiredAccess("create", "pods/exec", CHATQNA_NAMESPACE, reason="read the pods' effective LLM_MODEL_NAME"), RequiredAccess( - "get", "llminferenceservices", INFERENCE_NAMESPACE, + "get", "llminferenceservices", LLM_INFERENCE_NAMESPACE, group="serving.kserve.io", reason="observed model readiness", ), # Runtime-API plane, reached by port-forwarding to fingerprint-svc. diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py b/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py index bc61720e..b0d056dc 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py @@ -42,12 +42,12 @@ import urllib3 from tests.e2e.validation.buildcfg import cfg +from tests.e2e.validation.constants import FINGERPRINT_NAMESPACE urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) logger = logging.getLogger(__name__) -FINGERPRINT_NAMESPACE = "fingerprint" FINGERPRINT_SERVICE = "fingerprint-svc" FINGERPRINT_PORT = 6012 API_PREFIX = "/v1/system_fingerprint" diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py b/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py index c4892fbc..a65c2922 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py @@ -26,6 +26,8 @@ import kr8s from kr8s.objects import APIObject +from tests.e2e.validation.constants import CHATQNA_NAMESPACE, LLM_INFERENCE_NAMESPACE + from .base import PropertyReadError logger = logging.getLogger(__name__) @@ -33,14 +35,10 @@ # The ChatQNA LLM microservice: the Deployment is 'llm-svc-deployment' but the # stable handle across chart versions is the label, and the container name is # needed because the pod also has an init container. -PIPELINE_NAMESPACE = "chatqna" LLM_USVC_LABEL_SELECTOR = {"app.kubernetes.io/name": "llm-usvc"} LLM_USVC_CONTAINER = "llm-usvc" MODEL_NAME_ENV = "LLM_MODEL_NAME" -# Where model serving lives. -INFERENCE_NAMESPACE = "llm-inference" - class LLMInferenceService(APIObject): """Minimal kr8s binding for KServe's ``LLMInferenceService``. @@ -64,8 +62,8 @@ class ServedModel: def __init__( self, - namespace: str = PIPELINE_NAMESPACE, - inference_namespace: str = INFERENCE_NAMESPACE, + namespace: str = CHATQNA_NAMESPACE, + inference_namespace: str = LLM_INFERENCE_NAMESPACE, ): self.namespace = namespace self.inference_namespace = inference_namespace diff --git a/src/tests/e2e/validation/constants.py b/src/tests/e2e/validation/constants.py index 3890eb1c..41f84138 100644 --- a/src/tests/e2e/validation/constants.py +++ b/src/tests/e2e/validation/constants.py @@ -15,6 +15,8 @@ INGRESS_NGINX_CONTROLLER_POD_LABEL_SELECTOR = {"app.kubernetes.io/name": "ingress-nginx"} CHATQNA_NAMESPACE = "chatqna" EDP_NAMESPACE = "edp" +FINGERPRINT_NAMESPACE = "fingerprint" +KEYCLOAK_NAMESPACE = "keycloak" # ChatQnA model microservice pod labels — used to assert which model servers are (un)deployed # (e.g. the upload variant is embedding-only: LLM + reranking are undeployed). diff --git a/src/tests/e2e/validation/pysweep/test_served_model.py b/src/tests/e2e/validation/pysweep/test_served_model.py index 0d801343..881bcf0c 100644 --- a/src/tests/e2e/validation/pysweep/test_served_model.py +++ b/src/tests/e2e/validation/pysweep/test_served_model.py @@ -19,8 +19,9 @@ import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep import model_catalog, served_model +from tests.e2e.benchmarks.chatqna.pysweep import model_catalog from tests.e2e.benchmarks.chatqna.pysweep.served_model import LLMInferenceService, ServedModel +from tests.e2e.validation.constants import LLM_INFERENCE_NAMESPACE logger = logging.getLogger(__name__) @@ -86,7 +87,7 @@ def test_the_served_model_is_a_ready_llminferenceservice(observed_model): :class:`LLMInferenceService`); when KServe moves past ``v1alpha2`` this test is the notice. """ - llmisvc = LLMInferenceService.get(observed_model, namespace=served_model.INFERENCE_NAMESPACE) + llmisvc = LLMInferenceService.get(observed_model, namespace=LLM_INFERENCE_NAMESPACE) conditions = (llmisvc.raw.get("status", {}) or {}).get("conditions", []) or [] assert any( cond.get("type") == "Ready" and cond.get("status") == "True" for cond in conditions From c7146d468c8d8b196fe1262645bd76f3aaca6cbb Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Wed, 25 Nov 2026 18:34:12 +0100 Subject: [PATCH 03/11] refactor(benchmarks): move pysweep config docs to configs/README.md and drop extra prose Rename examples/ to configs/ and config.yaml to general.yaml, strip the comments from both YAML files, and remove explanatory docstrings from the package and the max_new_tokens property. Signed-off-by: Kurzacz, Kamil --- .../e2e/benchmarks/chatqna/pysweep/README.md | 31 +++---- .../benchmarks/chatqna/pysweep/__init__.py | 6 -- .../chatqna/pysweep/configs/README.md | 55 ++++++++++++ .../chatqna/pysweep/configs/general.yaml | 4 + .../chatqna/pysweep/configs/sweep.yaml | 14 +++ .../chatqna/pysweep/examples/config.yaml | 20 ----- .../chatqna/pysweep/examples/sweep.yaml | 86 ------------------- .../chatqna/pysweep/properties/max_tokens.py | 21 +---- .../chatqna/pysweep/pysweep_bench.py | 6 +- .../validation/pysweep/test_config_unit.py | 8 +- .../pysweep/test_pysweep_bench_unit.py | 4 +- 11 files changed, 93 insertions(+), 162 deletions(-) create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml delete mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml delete mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md index f2703be2..7e1f4e83 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -22,8 +22,8 @@ environment gotchas. | `config.py` | Pydantic-validated configs: `load_config()` / `SweepConfig` (+ the `deployment_combinations()` and `client_combinations()` cartesian `product` expansions) and `load_run_config()` / `RunConfig`. | | `client_args.py` | Adapter mirroring `benchmark.py`'s CLI options as sweep knobs. Not properties — no plane, nothing to apply or read back; see below. | | `pysweep_bench.py` | Sweep runner: load config → apply/converge/verify each deployment combination → run one load test per client combination, reusing `benchmark.py`. | -| `examples/sweep.yaml` | An example sweep config (`--sweep`): what to vary. | -| `examples/config.yaml` | An example run config (`--config`): how to run. | +| `configs/sweep.yaml` | Sweep config (`--sweep`): what to vary. Keys are described in [`configs/README.md`](./configs/README.md). | +| `configs/general.yaml` | Run config (`--config`): how to run. | | `authentication.py` | `KubernetesAccess` (side-effect-free RBAC preflight via `SelfSubjectAccessReview`), `load_build_config()` (the installed environment's config), `keycloak_helper()` (the maintained `KeycloakHelper`, for user tokens) and `client_token_lifespan()` (a sweep-long access-token lifespan for the UI client, restored afterwards). | | `runtime_api.py` | `system_fingerprint` client. `HelperFingerprintClient` adapts the suite's `FingerprintApiHelper`; `PortForwardTransport` / `IngressTransport` cover deployments the helper can't reach. | | `properties/max_tokens.py` | First property: `MaxNewTokens` (LLM `max_new_tokens`, Runtime-API plane). | @@ -192,8 +192,8 @@ There are two separate configs: | Flag | File | Declares | |---|---|---| -| `--sweep` (required) | `examples/sweep.yaml` | **What to vary** — the knobs and their values; expands into combinations. | -| `--config` (optional) | `examples/config.yaml` | **How to run** — harness behaviour; never expands into combinations. | +| `--sweep` (required) | `configs/sweep.yaml` | **What to vary** — the knobs and their values; expands into combinations. | +| `--config` (optional) | `configs/general.yaml` | **How to run** — harness behaviour; never expands into combinations. | `--summaries` (optional, default `./results`) is the **directory** a sweep writes into — see "Where the results go" below. It is cleared of the previous sweep's @@ -204,8 +204,8 @@ parameters are declared in it, so nothing after `--` is necessary: ```bash PYTHONPATH=src python -m tests.e2e.benchmarks.chatqna.pysweep.pysweep_bench \ - --sweep src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml \ - --config src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml + --sweep src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml \ + --config src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml ``` Run it from anywhere — the repo root above, or any other directory. Paths *inside* @@ -311,20 +311,8 @@ and `result_file` is how you get to it. ### Run config (`--config`) Validated by `config.load_run_config()`, with the same strictness as the sweep -config — an unknown key or wrong type raises `ConfigError`. Omitting `--config` -uses the defaults. - -```yaml -display_kubernetes_client_logs: false # default: false -``` - -- **`display_kubernetes_client_logs`** — whether the kr8s/httpx Kubernetes - client's own output is shown. The port-forward carrying the load test produces - two kinds of noise: one `101 Switching Protocols` line *per benchmark request* - (a websocket per forwarded connection), and a multi-frame - `ConnectionResetError` traceback on teardown (a race inside kr8s — the - requests themselves still return 200). Both are hidden by default; genuine - warnings and errors still surface. Set `true` to debug cluster connectivity. +config. Omitting `--config` uses the defaults; the keys are listed in +[`configs/README.md`](./configs/README.md). `benchmark.py`'s own output (its per-worker log lines and parsed-args dump) is always shown — it is the benchmark's primary output and pysweep does not filter @@ -401,7 +389,8 @@ tox -e e2e -- -k pysweep `-k pysweep` selects just the pysweep tests; drop it to run the whole suite. The shared conftest's two options both default to a co-located deployment (`--build-config-dir`, default `../../../../env/local`, from which it reads -`config.yaml` — it also drives the `fingerprint.enabled` skip — and +`global_config.yaml`, `config.erag.yaml` and `config.inference.yaml` — they also +drive the `fingerprint.enabled` skip — and `--credentials-file`), so on the deployment host no flags are needed. Elsewhere: ```bash diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/__init__.py index 7f7470e0..91da480a 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/__init__.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/__init__.py @@ -1,8 +1,2 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 - -"""pysweep — declarative configuration sweeps for ChatQA benchmarks. - -See DESIGN.md for the architecture (Property / Plane model, two planes, -authorization & access requirements). -""" diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md new file mode 100644 index 00000000..9a5d0ea9 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md @@ -0,0 +1,55 @@ + + + +# pysweep configs + +| File | Flag | Declares | +|---|---|---| +| `sweep.yaml` | `--sweep` (required) | What to vary. | +| `general.yaml` | `--config` (optional) | How the sweep runs. Never expanded into combinations. | + +Both are validated before the sweep starts: an unknown key, a wrong type or an +out-of-range value is a `ConfigError`. + +## `sweep.yaml` + +Any knob takes a single value (fixed for the whole sweep) or a list (one +dimension of the product). Runs = deployment combinations × client combinations; +the file here is 2 × (3 × 2) = 12 runs. + +**Deployment knobs** change the running RAG. Each is optional: omit it to leave +the deployment as it is. They are the outer loop, applied and verified once per +combination. + +| Key | Meaning | +|---|---| +| `llms.max_new_tokens` | Tokens the LLM may generate per request. | + +**Client knobs** are `benchmark.py`'s options. All are required, so no run +silently falls back to the tool's defaults. They are the inner loop: each value +is one more load test, and nothing on the cluster changes. + +| Key | Flag | Meaning | +|---|---|---| +| `question_file` | `-f` | Question corpus. A relative path is resolved against `pysweep_bench.py`'s directory, not the working directory. Checked before anything is applied. | +| `concurrency` | `-c` | Concurrent users. | +| `duration` | `-d` | Length of each run (``). | +| `worker_startup_delay` | `-u` | Stagger between worker starts; `0s` starts them all at once. | +| `failures_allowed` | `-e` | Failed requests tolerated before the run gives up. | +| `input_tokens` | `-x` | Pad/trim every question to this many tokens; `0` leaves them as written. | +| `warmup_requests` | `-w` | Requests per worker discarded as warmup. | +| `server` | `-s` | Optional. Default: the deployment's own ingress, `https:///api/v1/chatqna`. | +| `bearer_file` | `-b` | Optional. Default: tokens minted by pysweep and re-minted before every run. A supplied file is never refreshed. | + +There is no `tokenizer` key: `-m` is derived from the model the deployment +serves, and declaring it is an error. + +Every run adds a row to `benchmark_summary_results.csv` in `--summaries` +(default `./results`), with one column per declared knob; the previous sweep's +results there are deleted first. + +## `general.yaml` + +| Key | Default | Meaning | +|---|---|---| +| `display_kubernetes_client_logs` | `false` | Show the Kubernetes client's per-request and port-forward teardown log noise; for debugging connectivity. | diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml new file mode 100644 index 00000000..a603bad2 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml @@ -0,0 +1,4 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +display_kubernetes_client_logs: false diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml new file mode 100644 index 00000000..72f3bd9e --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml @@ -0,0 +1,14 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +llms: + max_new_tokens: [128, 256] + +client: + question_file: ../questions-short.csv + concurrency: [1, 16, 128] + duration: 5m + worker_startup_delay: 0s + failures_allowed: 200 + input_tokens: [128, 256] + warmup_requests: 1 diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml deleted file mode 100644 index e569dea9..00000000 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/examples/config.yaml +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (C) 2026 Intel Corporation -# SPDX-License-Identifier: Apache-2.0 - -# Example pysweep *run* configuration (--config). -# -# This describes how a sweep executes; what it varies lives in the sweep config -# (--sweep, see sweep.yaml). Keys here are never expanded into combinations. -# -# Validated by pysweep.config.load_run_config: any unknown key or wrong value -# type raises ConfigError before the sweep runs. - -# Whether to show the kr8s/httpx Kubernetes client's own output. Two kinds of -# noise come from the port-forward that carries the load test: -# - one '101 Switching Protocols' line per benchmark request (a websocket is -# opened per forwarded connection), and -# - a multi-frame ConnectionResetError traceback when a connection or the -# forward itself is torn down (a race inside kr8s; requests still return 200). -# Both are hidden when false; genuine warnings and errors still surface. Set true -# to debug cluster connectivity. -display_kubernetes_client_logs: false diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml deleted file mode 100644 index 82e109c4..00000000 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright (C) 2026 Intel Corporation -# SPDX-License-Identifier: Apache-2.0 - -# Example pysweep sweep configuration. -# -# Two kinds of knob, which the runner nests rather than interleaves: -# -# * DEPLOYMENT knobs (llms:) change the running RAG. Each one is OPTIONAL — -# omit a key to leave that knob untouched. They form the OUTER loop, because -# each change costs a rollout. -# * CLIENT knobs (client:) are the load generator's parameters, passed straight -# to benchmark.py. They are REQUIRED, because a load test always applies some -# load and leaving that undeclared makes a result unattributable. They form -# the INNER loop: each value costs one more load test, nothing on the cluster. -# -# Any knob may be a single value (fixed for the whole sweep) or a list (one -# dimension of the cartesian product — see DESIGN.md "product" strategy). Total -# runs = (deployment combinations) x (client combinations); the config below is -# (2 max_new_tokens) x (3 concurrency x 2 input_tokens) = 12 runs. -# -# Validated by pysweep.config.load_config: any unknown key or wrong/out-of-range -# value raises ConfigError before the sweep runs. -# -# Every run also appends a row to benchmark_summary_results.csv, in the directory -# given by --summaries (default ./results): one column per knob declared below, -# named by its dotted path (e.g. 'client.input_tokens'), then mean/p90 TTFT and -# TPOT. Its per-request CSV goes in per_case_results/ next to it. NOTE that the -# previous sweep's results there are deleted before a new sweep starts. - -llms: - max_new_tokens: [128, 256] - -# Load generator (benchmark.py) parameters. Every option below is required: a -# missing one would silently fall back to benchmark.py's own default and the -# result CSV records none of it. These need no apply/converge/verify — they are -# arguments to the load test, not state on the cluster — which is why they are the -# innermost loop: all of them are re-run against each deployment combination -# without touching it. -client: - # -f Question corpus the load is drawn from. - # - # A relative path is resolved against pysweep_bench.py's directory, NOT the - # directory the sweep was launched from — so this value means the same file - # wherever you run from. The corpora live one level up beside benchmark.py, - # hence the '../'. Absolute paths are used as given. - # - # Checked by preflight() before anything is applied, so a path typo - # fails immediately instead of after a rollout has been paid for. - question_file: ../questions-short.csv - - # -c Concurrent users (worker threads). The classic scaling dimension: a list - # here re-runs the same deployment under each load level, back to back and - # with no reconfiguration between them, so the numbers are comparable. - concurrency: [1, 16, 128] - - # -d from benchmark.py - duration: 5m - - # -u Stagger between worker starts. '0s' starts all workers at once, which is - # the harsher and more repeatable pattern. - worker_startup_delay: 0s - - # NOTE: there is no 'tokenizer' key, though benchmark.py has -m. It has to be - # the model being served (otherwise the token counts come from a tokenizer that - # did not tokenize them), so it is not a knob — pysweep reads the served model - # back from the engine after each deployment combination converges and passes it - # itself. Declaring it here is an error. - - # -e Failed requests tolerated before the run gives up. - failures_allowed: 200 - - # -x Pad/trim every question to exactly this many tokens; 0 leaves them as - # written. Fixing it removes prompt-length variance between runs. - input_tokens: [128, 256] - - # -w Requests per worker discarded as warmup (first-request latency includes - # connection setup and cache warming). - warmup_requests: 1 - - # -s / -b Endpoint and bearer file. Both OPTIONAL and left unset here: pysweep - # targets the deployment's own ingress (https://) and - # mints a fresh bearer file before every run, which is what lets a sweep run - # with no preparation steps. Set them only to benchmark a different endpoint - # or with tokens of your own (a supplied -b is never refreshed). - # server: https://erag.com/api/v1/chatqna - # bearer_file: uat.txt \ No newline at end of file diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py index f87121a6..0d4cc31f 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py @@ -1,18 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""``MaxNewTokens`` — the LLM ``max_new_tokens`` knob (Runtime API plane). - -Set with: - - POST /v1/system_fingerprint/change_arguments - [{"name": "llm", "data": {"max_new_tokens": }}] - -and read back from ``GET config?params_key=llm`` (the ``values`` object). This is -the simplest property and the reference implementation of the -:class:`~pysweep.base.Property` interface for the runtime-API plane. -""" - import logging from ..base import Plane, Property, PropertyReadError @@ -34,14 +22,7 @@ def __init__(self, client: FingerprintClient): self.client = client def read(self) -> int: - """Return the observed ``max_new_tokens`` from the live fingerprint API. - - Raises :class:`PropertyReadError` if the parameter is absent from the - response or is not an integer. A missing value is not an acceptable - state: it means we cannot know what configuration is live, so it fails - loudly rather than degrading to a value that silently never satisfies a - desired one. - """ + """Return the observed ``max_new_tokens`` from the live fingerprint API.""" values = self.client.read_values(COMPONENT) if PARAMETER not in values: raise PropertyReadError( diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py index f221214e..c836597d 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -55,7 +55,7 @@ Usage:: PYTHONPATH=src python -m tests.e2e.benchmarks.chatqna.pysweep.pysweep_bench \ - --sweep sweep.yaml [--config config.yaml] + --sweep sweep.yaml [--config general.yaml] ``--sweep`` declares *what to vary* (the knobs and their values, including the required ``client:`` section); ``--config`` declares *how to run* (harness @@ -533,11 +533,11 @@ def parse_args(argv=None): parser.add_argument( "--sweep", required=True, - help="Path to the sweep config YAML (what to vary; see examples/sweep.yaml).", + help="Path to the sweep config YAML (what to vary; see configs/sweep.yaml).", ) parser.add_argument( "--config", - help="Path to the pysweep run config YAML (how to run; see examples/config.yaml).", + help="Path to the pysweep run config YAML (how to run; see configs/general.yaml).", ) parser.add_argument( "--summaries", diff --git a/src/tests/e2e/validation/pysweep/test_config_unit.py b/src/tests/e2e/validation/pysweep/test_config_unit.py index c53b017b..21a48a81 100644 --- a/src/tests/e2e/validation/pysweep/test_config_unit.py +++ b/src/tests/e2e/validation/pysweep/test_config_unit.py @@ -399,10 +399,10 @@ def test_varying_paths_reports_only_multi_valued_knobs(): @allure.feature("pysweep") def test_shipped_example_sweep_config_is_valid(): - """The committed examples/sweep.yaml must load (docs stay honest).""" + """The committed configs/sweep.yaml must load (docs stay honest).""" example = ( Path(__file__).resolve().parents[3] - / "e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml" + / "e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml" ) cfg = load_config(example) assert cfg.deployment_combinations() @@ -440,9 +440,9 @@ def test_run_config_rejects_non_boolean(): @allure.feature("pysweep") def test_shipped_example_run_config_is_valid(): - """The committed examples/config.yaml must load (docs stay honest).""" + """The committed configs/general.yaml must load (docs stay honest).""" example = ( Path(__file__).resolve().parents[3] - / "e2e/benchmarks/chatqna/pysweep/examples/config.yaml" + / "e2e/benchmarks/chatqna/pysweep/configs/general.yaml" ) assert load_run_config(example).display_kubernetes_client_logs is False diff --git a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py index a440f545..b710aefa 100644 --- a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -515,7 +515,7 @@ def test_result_file_name_stays_within_the_filesystem_limit(): # And the shipped example, whatever it declares, must also be nameable. example = ( Path(__file__).resolve().parents[3] - / "e2e/benchmarks/chatqna/pysweep/examples/sweep.yaml" + / "e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml" ) shipped = load_config(example) for combo in shipped.deployment_combinations(): @@ -870,7 +870,7 @@ def test_preflight_accepts_the_shipped_example_config(monkeypatch): That is, every path the example declares really resolves. """ - example = psb.PYSWEEP_DIR / "examples" / "sweep.yaml" + example = psb.PYSWEEP_DIR / "configs" / "sweep.yaml" psb.preflight_check(load_config(example)) From fcd151e4843516895e4a22f81b6d138141635cad Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Wed, 25 Nov 2026 19:00:57 +0100 Subject: [PATCH 04/11] refactor(benchmarks): trim pysweep comments and docstrings Drop module docstrings, cut docstrings to one line or remove them where the name says it, and keep only one-line comments for non-obvious constraints. Remove the comments from the pysweep tox env; the --confcutdir reason moves to the README. No code changes. Signed-off-by: Kurzacz, Kamil --- src/tests/e2e/benchmarks/chatqna/benchmark.py | 15 +- .../e2e/benchmarks/chatqna/pysweep/README.md | 3 + .../chatqna/pysweep/authentication.py | 126 +------ .../e2e/benchmarks/chatqna/pysweep/base.py | 56 +-- .../benchmarks/chatqna/pysweep/client_args.py | 132 +------ .../e2e/benchmarks/chatqna/pysweep/config.py | 281 ++------------ .../chatqna/pysweep/model_catalog.py | 74 +--- .../e2e/benchmarks/chatqna/pysweep/paths.py | 16 +- .../chatqna/pysweep/properties/__init__.py | 2 - .../chatqna/pysweep/properties/max_tokens.py | 4 +- .../chatqna/pysweep/pysweep_bench.py | 352 +----------------- .../e2e/benchmarks/chatqna/pysweep/results.py | 175 +-------- .../benchmarks/chatqna/pysweep/runtime_api.py | 87 +---- .../chatqna/pysweep/served_model.py | 62 +-- src/tests/e2e/validation/pysweep/conftest.py | 42 +-- .../validation/pysweep/test_config_unit.py | 100 +---- .../e2e/validation/pysweep/test_max_tokens.py | 24 -- .../pysweep/test_max_tokens_unit.py | 28 +- .../pysweep/test_model_catalog_unit.py | 69 +--- .../e2e/validation/pysweep/test_paths_unit.py | 15 - .../pysweep/test_pysweep_bench_unit.py | 274 +------------- .../validation/pysweep/test_results_unit.py | 116 +----- .../validation/pysweep/test_served_model.py | 41 -- .../pysweep/test_served_model_unit.py | 36 +- .../pysweep/test_token_lifespan_unit.py | 11 - src/tox.ini | 11 - 26 files changed, 153 insertions(+), 1999 deletions(-) diff --git a/src/tests/e2e/benchmarks/chatqna/benchmark.py b/src/tests/e2e/benchmarks/chatqna/benchmark.py index e817af92..c3106dc7 100644 --- a/src/tests/e2e/benchmarks/chatqna/benchmark.py +++ b/src/tests/e2e/benchmarks/chatqna/benchmark.py @@ -79,13 +79,6 @@ def __init__(self): self.code = 0 def parse_args(argv=None): - """Parse the load-test options. - - ``argv`` defaults to the process's arguments, so running this as a script is - unchanged. Passing a list is what lets an in-process caller (pysweep) drive - one load test per sweep combination without re-implementing the CLI or - shelling out. - """ parser = argparse.ArgumentParser(description="Load testing tool.") parser.add_argument("-f", type=str, help="Question File Location") parser.add_argument("-s", type=str, default="https://solutions.ai/api/v1/chatqna", help="Server Address format") @@ -189,13 +182,7 @@ def signal_handler(var, signal, frame): var[0] = var[0] + 1 def run_benchmark(args, output_file=None): - """Run one load test and return ``(error, output_file)``. - - Split out of ``main`` so a caller can run several load tests in one process - and know where each wrote its rows: ``main`` still exits on ``error``, but - pysweep needs the exit code *and* the CSV path per sweep combination, and it - passes ``output_file`` so results land under the combination's own name. - """ + """Run one load test and return ``(error, output_file)``.""" print(' \n'.join(f'{k}: {v}' for k, v in vars(args).items())) # Local import due to heavy library diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md index 7e1f4e83..f6c35b78 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -407,6 +407,9 @@ cd src tox -e pysweep_unit_tests ``` +It runs only the `*_unit.py` modules, with `--confcutdir` so pytest doesn't load +`tests/e2e/conftest.py`, whose session fixtures need a deployment. + Without tox (venv with the requirements installed, from the repo root): ```bash diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py b/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py index f1732ef2..b6165773 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py @@ -1,36 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Authorization & access for pysweep. - -Three concerns, each the smallest thing that lets pysweep run outside pytest: - -- :class:`KubernetesAccess` — verifies, **up front and without mutating the - cluster**, that the current kubeconfig identity can perform every operation a - sweep needs. It uses ``SelfSubjectAccessReview``, which asks the API server - "am I allowed to do X?" without doing X, so a missing permission fails loudly - before the first rollout rather than halfway through a multi-hour product. - -- :func:`load_build_config` — populates - :data:`tests.e2e.validation.buildcfg.cfg` from the installed environment's - YAML. The maintained helpers (``KeycloakHelper``, ``FingerprintApiHelper``) - read the domain and routing mode from that dict, and under pytest it is - ``conftest.pytest_configure`` that fills it. pysweep has no pytest, so it does - the same load itself — deliberately reading the same three files in the same - order, so a sweep and the e2e suite cannot end up disagreeing about which - cluster they are talking to. - -- :func:`keycloak_helper` — builds the maintained - :class:`~tests.e2e.helpers.keycloak_helper.KeycloakHelper`. pysweep does - **not** implement token minting: that helper already does the password grant, - the required-actions dance, and the credentials-file lookup, and it is kept in - step with the deployment. Duplicating it here is how the two would drift. - -- :func:`client_token_lifespan` — for the duration of a sweep, lengthens the - access tokens Keycloak issues to the ERAG UI client (see - :data:`SWEEP_TOKEN_LIFESPAN_S`), then restores the client's previous setting. -""" - import logging import os from contextlib import contextmanager @@ -61,25 +31,15 @@ logger = logging.getLogger(__name__) -# The installed environment's config directory, mirroring the e2e suite's -# --build-config-dir default. Overridable so a sweep can be run against a -# different environment without editing anything. BUILD_CONFIG_DIR_ENV_VAR = "PYSWEEP_BUILD_CONFIG_DIR" BUILD_CONFIG_FALLBACKS = tuple(str(root / "env" / "local") for root in deploy_roots()) -# Same files, same order as tests/e2e/conftest.py — later files win on conflict. +# Same files and order as tests/e2e/conftest.py; later files win. BUILD_CONFIG_FILES = ("global_config.yaml", "config.erag.yaml", "config.inference.yaml") -# Access-token lifespan pysweep gives the ERAG UI client while a sweep runs. -# -# ARBITRARY VALUE: 1h has no meaning beyond being comfortably longer than one load -# test. The tokens are re-minted before every run, so they only have to outlive a -# single run (client.duration plus warmup), not the whole sweep; the realm default -# (5 min) does not even cover one 15m run, and each benchmark worker reads its -# token once, when the run starts. Raise it if a run's duration gets near it. +# Arbitrary; only has to outlast one run. SWEEP_TOKEN_LIFESPAN_S = 3600 -# Keycloak's per-client override of the realm's access-token lifespan. An empty -# value means "inherit the realm setting", which is what an unset client has. +# An empty value means "inherit the realm setting". CLIENT_TOKEN_LIFESPAN_ATTRIBUTE = "access.token.lifespan" KEYCLOAK_ADMIN_TIMEOUT = 30 @@ -113,43 +73,28 @@ def describe(self) -> str: @dataclass class AccessCheckResult: - """Outcome of a single access check.""" - required: RequiredAccess allowed: bool reason: str = "" -# The full set of permissions pysweep requires. Keeping this explicit means the -# access preflight names precisely which permission is missing, and reading the -# list is the fastest way to see everything a sweep can touch. REQUIRED_ACCESS = [ - # The served model, read back to pick the tokenizer (served_model.py). RequiredAccess("list", "pods", CHATQNA_NAMESPACE, reason="locate the llm-usvc replicas"), RequiredAccess("create", "pods/exec", CHATQNA_NAMESPACE, reason="read the pods' effective LLM_MODEL_NAME"), RequiredAccess( "get", "llminferenceservices", LLM_INFERENCE_NAMESPACE, group="serving.kserve.io", reason="observed model readiness", ), - # Runtime-API plane, reached by port-forwarding to fingerprint-svc. RequiredAccess("list", "pods", FINGERPRINT_NAMESPACE, reason="locate fingerprint-svc endpoints"), RequiredAccess( "create", "pods/portforward", FINGERPRINT_NAMESPACE, reason="port-forward the fingerprint API", ), - # Keycloak admin password: token minting and the sweep-long token lifespan. RequiredAccess("get", "secrets", KEYCLOAK_NAMESPACE, reason="Keycloak admin password for token minting"), ] class _SelfSubjectAccessReview(APIObject): - """Minimal kr8s binding for authorization.k8s.io SelfSubjectAccessReview. - - Creating one is a read-only authorization probe: it asks the API server - "am I allowed to do X?" without performing X, so the access preflight never - mutates the cluster. - """ - kind = "SelfSubjectAccessReview" version = "authorization.k8s.io/v1" endpoint = "selfsubjectaccessreviews" @@ -162,16 +107,13 @@ class KubernetesAccess: """Verifies the cluster is reachable and the identity has the needed RBAC.""" def __init__(self, k8s_helper: K8sHelper | None = None): - # Reuse the maintained k8s helper for all ordinary cluster access. self.k8s = k8s_helper or K8sHelper() def ensure_reachable(self) -> None: - """Confirm the configured kubeconfig can actually reach the API server.""" try: - # Cheapest authenticated call that proves connectivity + credentials. api = kr8s.api() api.version() - except Exception as exc: # noqa: BLE001 - surfaced as a clear AccessError + except Exception as exc: # noqa: BLE001 raise AccessError( "Cannot reach the Kubernetes API server. Check KUBECONFIG / the " "configured context points at a running cluster.\n" @@ -179,11 +121,7 @@ def ensure_reachable(self) -> None: ) from exc def check(self, required: RequiredAccess) -> AccessCheckResult: - """Run a single SelfSubjectAccessReview for one required permission. - - ``pods/exec`` and ``pods/portforward`` are subresources; the API expects - them split into resource + subresource rather than as one slashed name. - """ + # The API wants subresources (pods/exec) split out, not slash-joined. resource, _, subresource = required.resource.partition("/") attributes = { "namespace": required.namespace, @@ -196,20 +134,14 @@ def check(self, required: RequiredAccess) -> AccessCheckResult: review = _SelfSubjectAccessReview({"spec": {"resourceAttributes": attributes}}) review.create() - # APIObject.status raises KeyError if the server returned no status; - # read from raw defensively. + # APIObject.status raises KeyError when the server returned no status. status = dict(review.raw.get("status", {}) or {}) allowed = bool(status.get("allowed", False)) reason = status.get("reason", "") or ("denied" if not allowed else "") return AccessCheckResult(required=required, allowed=allowed, reason=reason) def verify(self, raise_on_denied: bool = True) -> list[AccessCheckResult]: - """Verify every required permission up front. - - Returns the per-permission results. With ``raise_on_denied`` (default) - it raises :class:`AccessError` listing exactly which permissions are - missing, so the sweep fails before any combination runs. - """ + """Check every required permission; raise AccessError naming the denied ones.""" self.ensure_reachable() results = [self.check(req) for req in REQUIRED_ACCESS] @@ -228,7 +160,6 @@ def verify(self, raise_on_denied: bool = True) -> list[AccessCheckResult]: def build_config_dir() -> Path: - """Return the installed environment's config directory, or raise.""" configured = os.getenv(BUILD_CONFIG_DIR_ENV_VAR) if configured: path = Path(configured) @@ -251,19 +182,7 @@ def build_config_dir() -> Path: def load_build_config(directory: str | Path | None = None) -> dict: - """Load the deployment's config into the shared ``cfg`` dict and return it. - - Mutating the module-level ``cfg`` rather than returning a private copy is not - incidental — it is how the maintained helpers get configured, since they read - that dict at construction time. Under pytest the same dict is filled by - ``conftest.pytest_configure``; calling this when it is already populated is - harmless and idempotent. - - Raises :class:`BuildConfigError` if none of the expected files is present, or - if the loaded config carries no ``base_domain_name`` — without that the - helpers would silently build URLs against ``https://None`` and every request - would fail with a DNS error instead of a readable message. - """ + """Load the deployment's config into the shared ``cfg`` dict the helpers read, and return it.""" resolved = Path(directory) if directory is not None else build_config_dir() loaded: list[str] = [] @@ -298,28 +217,18 @@ def load_build_config(directory: str | Path | None = None) -> dict: def keycloak_helper( credentials_file: str | None = None, k8s_helper: K8sHelper | None = None ) -> KeycloakHelper: - """Build the maintained :class:`KeycloakHelper` for this deployment. - - ``credentials_file`` defaults to the helper's own - ``default_credentials.txt`` lookup, which is where the installer writes the - ERAG users' passwords — so on an installed box no argument is needed. - - :func:`load_build_config` is called first because the helper reads the domain - and routing mode from ``cfg`` in its constructor; building it against an - empty ``cfg`` would bake in an unusable auth URL. - """ + """Build the KeycloakHelper, loading ``cfg`` first since its constructor reads it.""" load_build_config() return KeycloakHelper(credentials_file, k8s_helper or K8sHelper()) def _client_url(helper: KeycloakHelper) -> str: - """Admin URL of the ERAG UI client (the one user tokens are minted for).""" base = f"{helper.erag_auth_domain}/admin/realms/{VITE_KEYCLOAK_REALM}/clients" response = requests.get( base, params={"clientId": VITE_KEYCLOAK_CLIENT_ID}, headers={"Authorization": f"Bearer {helper.admin_access_token}"}, - verify=False, # self-signed deployment certs, as in KeycloakHelper + verify=False, # self-signed deployment certs timeout=KEYCLOAK_ADMIN_TIMEOUT, ) response.raise_for_status() @@ -332,12 +241,7 @@ def _client_url(helper: KeycloakHelper) -> str: def _set_client_attribute(helper: KeycloakHelper, url: str, name: str, value: str) -> str: - """Set one client attribute; return its previous value (``""`` if unset). - - The client is read back and PUT whole, because Keycloak's client PUT takes a - full representation. An admin token is fetched per call: the restore runs - after a sweep that lasts hours, long past any token fetched at the start. - """ + # Token fetched per call: the restore runs hours after the sweep started. headers = {"Authorization": f"Bearer {helper.admin_access_token}"} response = requests.get( url, headers=headers, verify=False, timeout=KEYCLOAK_ADMIN_TIMEOUT @@ -356,13 +260,7 @@ def _set_client_attribute(helper: KeycloakHelper, url: str, name: str, value: st @contextmanager def client_token_lifespan(helper: KeycloakHelper, seconds: int = SWEEP_TOKEN_LIFESPAN_S): - """Make the ERAG UI client's access tokens last ``seconds`` inside the block. - - A per-client override, so nothing else in the realm changes. The previous - value is restored on exit, including when the sweep fails; ``""`` restores - "inherit from the realm". Restoring is best effort: a failure is logged, not - raised, so it cannot hide the error that ended the sweep. - """ + """Make the ERAG UI client's access tokens last ``seconds`` inside the block, then restore.""" url = _client_url(helper) previous = _set_client_attribute( helper, url, CLIENT_TOKEN_LIFESPAN_ATTRIBUTE, str(seconds) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/base.py b/src/tests/e2e/benchmarks/chatqna/pysweep/base.py index 0ad6a65f..b75f568e 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/base.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/base.py @@ -1,63 +1,35 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Core abstractions for pysweep: the Plane enum and the Property interface. - -A **Property** owns exactly one configuration knob. It knows how to read the -knob's *observed* value from the live system, whether an observed value -satisfies a desired one, how to apply a desired value idempotently, and how to -wait until an applied change has actually converged. - -A **Plane** is the channel through which a knob's value lives and is changed. -See DESIGN.md for the full model. -""" - from abc import ABC, abstractmethod from enum import Enum from typing import Any class PropertyReadError(Exception): - """Raised when a property cannot read a valid observed value. - - A missing or unparseable value is never an acceptable state for a sweep: - it means we cannot know what configuration is live, so it must fail loudly - rather than degrade to a ``None`` that silently never satisfies a desired - value. - """ + """Raised when a property cannot read a valid observed value.""" class PropertyApplyError(Exception): - """Raised when a property cannot establish a desired value. - - Distinct from :class:`PropertyReadError` (which is about not knowing the - current state) and from ``NotImplementedError`` (which is about a knob that - cannot be written at all). This is "the write was attempted and the desired - state could not be reached" — a rejected value, a manifest the property no - longer recognises, or a rollout that never converged. - """ + """Raised when a property cannot establish a desired value.""" class Plane(str, Enum): """The channel through which a knob's value lives and is changed.""" - K8S_SPEC = "k8s_spec" # Kubernetes objects - long wait for change - RUNTIME_API = "runtime_api" # Fingerprint - immediate change + K8S_SPEC = "k8s_spec" + RUNTIME_API = "runtime_api" class Property(ABC): """Interface every application (=not client's) configuration knob must implement.""" - # The way the Property is changed. Important for scheduling sweeps. - # Kubernetes-based props are outer, fingerprint-based are innerly iterated + # K8s-plane properties iterate in the outer loop, runtime-API ones inner. plane: Plane @abstractmethod def read(self) -> Any: - """Return the knob's current **observed** value from the live system. - - Must reflect actual runtime/observed state, not the last value written. - """ + """Return the knob's current observed value, not the last value written.""" raise NotImplementedError def is_satisfied(self, desired: Any) -> bool: @@ -65,23 +37,11 @@ def is_satisfied(self, desired: Any) -> bool: @abstractmethod def apply(self, desired: Any) -> None: - """Drive the knob toward ``desired``. - - Idempotent, that means: - - desired == observed --> do nothing - - desired == applied --> do nothing - - Convergence (readiness) handled separately by `wait_until_ready()` - """ + """Drive the knob toward ``desired`` idempotently, without waiting for convergence.""" raise NotImplementedError def wait_until_ready(self, desired: Any, timeout: float = 300.0) -> None: - """Block until the property itself is ready — the applied change is live. - - For synchronous planes (runtime API) this is a no-op. For async planes - (K8s spec) this polls observed state until ``is_satisfied(desired)`` - holds or ``timeout`` seconds elapse. - """ + """Block until the applied change is live; a no-op for synchronous planes.""" return None def __repr__(self) -> str: # pragma: no cover - debugging aid diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py b/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py index be5ad03b..d8b8aa0e 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py @@ -1,99 +1,31 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Adapter between sweep-declared client knobs and ``benchmark.py``'s CLI. - -The load generator's parameters (concurrency, input length, duration, ...) are -sweep knobs in the sense that matters — each distinct value is a different test -scenario and they expand into the cartesian product like any other knob. But -they are **not** :class:`~..base.Property` instances, and deliberately so: - -- There is nothing to ``apply``. The value is an argument to a process pysweep - is about to start, not a mutation of the deployed RAG. -- There is nothing to ``wait_until_ready`` on. No rollout, no reconcile, no - propagation delay. -- There is nothing to ``read``. ``Property.read`` is contractually *observed* - state read back from the live system (DESIGN.md calls this non-negotiable — - it is what makes the preflight meaningful). A client knob has no live system - behind it; "reading" it could only echo the value pysweep itself holds, which - is precisely the spec-read the invariant forbids. - -So instead of weakening ``Property`` (or inventing a ``Plane`` whose ``apply`` / -``read`` / ``wait_until_ready`` are all vacuous), this module mirrors -``benchmark.py``'s options as :class:`ClientArg` descriptors and renders resolved -values back into that CLI. ``config.py`` binds YAML leaves to these descriptors -the same way it binds other leaves to property classes, so the knobs still get -schema validation, product expansion, filename slugs, and the recorded snapshot -— everything except the apply/converge machinery that does not apply to them. - -**Every option is mirrored and the scenario-shaping ones are required** in a -sweep config. A client parameter that silently fell back to ``benchmark.py``'s -own default (``-c 32``, ``-d 30m``, ``-x 0``) would reintroduce exactly the -ambiguity pysweep exists to remove: "what configuration was actually tested". -Requiring them also makes the sweep config the single source of truth, so there -is no precedence question against flags passed after ``--``; passing one of -these flags there is an error (see :func:`conflicting_flags`). - -Three options are exceptions, and none of them is a sweep knob: - -- ``server`` and ``bearer_file`` stay optional because pysweep auto-provisions - them (the deployment's own endpoint + a minted token) to keep the "no - preparation steps required" promise. They are whole-sweep values rather than - per-combination ones — one endpoint and one token carry every combination — so - they are not sweepable. -- ``tokenizer`` (``-m``) is **derived, not declared**. It must name the model - being served, or the ``input_tokens`` / ``output_tokens`` columns (and every - tokens/s figure derived from them) are counted on a different basis than the - model actually processed. That model is not a value a config author can be - trusted to keep in step with ``llms.model`` — it changes with every deployment - combination — so pysweep reads it back from the running engine - (``LlmVllmModel.read()``, the observed value) after each combination converges - and renders it itself. There is no ``client.tokenizer`` key; declaring one is a - config error, and passing ``-m`` after ``--`` is refused. -""" - from dataclasses import dataclass from typing import Any, Iterable @dataclass(frozen=True) class ClientArg: - """One ``benchmark.py`` CLI option, mirrored as a sweep knob. - - Used both as pydantic field metadata (``Annotated[..., CONCURRENCY]``, which - is how ``config.py`` recovers the flag for a YAML leaf) and as the rendering - rule that turns a resolved value back into argv. - """ + """One ``benchmark.py`` CLI option; pydantic field metadata and its argv rendering rule.""" - #: The flag ``benchmark.py`` parses, e.g. ``-c``. flag: str - #: ``benchmark.py``'s argparse destination, e.g. ``c`` for ``args.c``. dest: str - #: The key this knob has in a sweep YAML's ``client:`` section. yaml_name: str - #: What the option does, in ``benchmark.py``'s own terms. summary: str - #: Whether a list may be given (i.e. whether it is a product dimension). - #: False for whole-sweep values that cannot differ between combinations. sweepable: bool = True - #: True when pysweep supplies this value itself and no config key exists for - #: it, so declaring it is impossible and passing its flag is refused. + # Supplied by pysweep with no config key; passing its flag is refused. derived: bool = False @property def path(self) -> str: - """The knob's dotted config path, e.g. ``client.concurrency``.""" return f"client.{self.yaml_name}" def __repr__(self) -> str: # pragma: no cover - debugging aid return f"ClientArg({self.flag} -> client.{self.yaml_name})" -# -- the mirror of benchmark.py's parse_args ---------------------------------- -# One entry per option in benchmark.parse_args. Keep this table in step with it: -# an option here that benchmark.py does not accept fails at load time, and an -# option benchmark.py grows that is missing here simply cannot be swept. - +# Keep in step with benchmark.parse_args. QUESTION_FILE = ClientArg( flag="-f", dest="f", @@ -159,7 +91,6 @@ def __repr__(self) -> str: # pragma: no cover - debugging aid summary="Requests per worker excluded from the results as warmup.", ) -#: Every mirrored option, in ``benchmark.py``'s declaration order. CLIENT_ARGS: tuple[ClientArg, ...] = ( QUESTION_FILE, SERVER, @@ -173,13 +104,9 @@ def __repr__(self) -> str: # pragma: no cover - debugging aid WARMUP_REQUESTS, ) -#: The two options pysweep provisions itself when they are not declared. They -#: are whole-sweep values, so they are resolved once rather than per combination. PROVISIONED_ARGS: tuple[ClientArg, ...] = (SERVER, BEARER_FILE) -#: Options pysweep supplies itself, with no config key to declare them. Unlike -#: PROVISIONED_ARGS these cannot be overridden at all: the value is read from the -#: deployment, so any other value would describe a run that did not happen. +# Read from the deployment, so unlike PROVISIONED_ARGS these can never be overridden. DERIVED_ARGS: tuple[ClientArg, ...] = tuple(arg for arg in CLIENT_ARGS if arg.derived) DERIVED_FLAGS: frozenset[str] = frozenset(arg.flag for arg in DERIVED_ARGS) @@ -192,25 +119,14 @@ class ClientArgsError(Exception): class BenchmarkClientArgs: - """Resolved per-combination client knob values, renderable as argv. - - Built from the client settings of one combination. Holds no cluster state and - performs no I/O — it is a pure translation from "what the sweep declared" to - "what ``benchmark.py`` is invoked with", which is the whole reason client - knobs need no plane. - """ + """Resolved per-combination client knob values, renderable as argv.""" def __init__(self, values: dict[ClientArg, Any]): self._values = dict(values) @classmethod def from_settings(cls, settings: Iterable) -> "BenchmarkClientArgs": - """Build from an iterable of :class:`~.config.ClientSetting`. - - Duplicate declarations of the same option are a programming error rather - than a config error (the schema permits each key at most once), so they - raise instead of silently keeping the last value. - """ + """Build from an iterable of :class:`~.config.ClientSetting`; duplicates raise.""" values: dict[ClientArg, Any] = {} for setting in settings: if setting.arg in values: @@ -225,13 +141,7 @@ def value_of(self, arg: ClientArg, default: Any = None) -> Any: return self._values.get(arg, default) def to_argv(self, include: Iterable[ClientArg] | None = None) -> list[str]: - """Render the held values as ``benchmark.py`` arguments. - - Emitted in ``CLIENT_ARGS`` order for stable, diffable command lines. - ``include`` restricts the output to a subset of options, which is how the - per-combination knobs are kept separate from the whole-sweep endpoint - ones (those are resolved once, before the port-forward is opened). - """ + """Render the held values as ``benchmark.py`` arguments, in ``CLIENT_ARGS`` order.""" allowed = set(CLIENT_ARGS if include is None else include) argv: list[str] = [] for arg in CLIENT_ARGS: @@ -244,13 +154,7 @@ def to_argv(self, include: Iterable[ClientArg] | None = None) -> list[str]: return argv def snapshot(self) -> dict[str, Any]: - """The recorded 'what was tested' contribution for these knobs. - - Unlike a property's snapshot entry this is the *declared* value, not an - observed read-back — there is no live system to observe. It is recorded - anyway because it is half of what identifies a result: the same - deployment under two different loads produces two different numbers. - """ + """Declared (not observed) values keyed by dotted path.""" return {arg.path: self._values[arg] for arg in CLIENT_ARGS if arg in self._values} def __repr__(self) -> str: # pragma: no cover - debugging aid @@ -259,24 +163,7 @@ def __repr__(self) -> str: # pragma: no cover - debugging aid def conflicting_flags(benchmark_argv: Iterable[str], declared_names: Iterable[str]) -> list[str]: - """Return flags passed after ``--`` that a declared client knob already owns. - - The sweep config is the single source of truth for client parameters, so a - flag appearing in both places has no defensible resolution: honouring the - YAML would silently ignore an explicit command line, and honouring the - command line would silently collapse a declared sweep dimension. Both are - the "you cannot tell what was tested" failure pysweep exists to prevent, so - the caller reports these and refuses to start. - - ``server`` / ``bearer_file`` are only conflicts when actually declared — - passing ``-s`` / ``-b`` on the command line while the YAML omits them is the - supported way to bypass auto-provisioning. - - Derived options (``-m``) are *always* conflicts. They cannot be declared, so - there is nothing to omit to make room for them: pysweep reads the value from - the deployment, and a caller-supplied one would count tokens with a tokenizer - other than the model that produced them. - """ + """Return flags after ``--`` owned by the config: declared knobs and every derived flag.""" argv = list(benchmark_argv) declared = set(declared_names) conflicts = [] @@ -290,7 +177,6 @@ def conflicting_flags(benchmark_argv: Iterable[str], declared_names: Iterable[st def derived_flag_reason(flag: str) -> str: - """Why a derived flag cannot be passed, for the error message.""" if flag == TOKENIZER.flag: return ( "pysweep sets -m from the model the LLM engine is observed to be " diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py index deda5f13..3b54d364 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py @@ -1,52 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Schema-validated sweep configuration for pysweep. - -A sweep is declared in YAML (DESIGN.md "Sweep config (YAML)"). This module is -the single place that: - -1. **Validates** that YAML against a Pydantic schema — unknown keys and wrong - value types raise :class:`ConfigError` *before* any rollout is triggered, so - a typo never silently tests the wrong configuration. -2. **Binds** each config leaf to the thing that knows how to realise it. The - binding lives on the field itself, so the YAML key is statically tied to its - implementation and there is no name-string lookup table to drift out of sync. - Two kinds of leaf exist: - - - ``Annotated[..., PropertyBinding(MaxNewTokens)]`` — a **deployment** knob, - driven by a :class:`~..base.Property` that applies it to the cluster and - reads it back. - - ``Annotated[..., CONCURRENCY]`` — a **client** knob, a - :class:`~.client_args.ClientArg` that is rendered into ``benchmark.py``'s - CLI. It has no plane: nothing to apply, converge on, or read back (see - ``client_args.py`` for why that distinction is kept rather than folded into - ``Property``). - -3. **Expands** the declared values into cartesian ``product``\\ s of sweep - combinations (DESIGN.md combination strategy). Deployment and client knobs - expand into *separate* products, because they are nested rather than - interleaved: the runner walks deployment combinations in the outer loop - (each costs a rollout) and, for each one, every client combination in the - inner loop (each costs only another load test against the deployment already - standing). Within the deployment product, expensive K8s-plane knobs are - themselves the outer dimension. - -Every deployment property is **optional**: omit a key to leave that knob -untouched. Client knobs are **required** — see ``client_args.py``; falling back -to ``benchmark.py``'s own defaults would leave "what load was applied" -unanswerable from the config. A value may be a single scalar (fixed across the -sweep) or a list (one product dimension). - -Adding a deployment knob = add one annotated, optional field to the relevant -section model (and, per DESIGN.md objective 6, ship the property's e2e test). -Adding a client knob = add a :class:`~.client_args.ClientArg` mirroring the new -``benchmark.py`` option and one annotated field on :class:`ClientConfig`. No -other wiring — unless the option has only one correct value given the deployment -(as ``-m`` does), in which case it is not a knob: mark the ``ClientArg`` -``derived=True``, add no field here, and have the runner resolve it. -""" - import itertools import logging from dataclasses import dataclass @@ -86,13 +40,7 @@ class ConfigError(Exception): class PropertyBinding: - """Field metadata tying a config leaf to the ``Property`` class it drives. - - Attached via ``Annotated[, PropertyBinding(SomeProperty)]``. Pydantic - v2 preserves it in ``FieldInfo.metadata``, so :class:`SweepConfig` can walk - its own fields and recover, for each declared knob, the class that applies - it — without a separate name→class registry. - """ + """Field metadata tying a config leaf to the ``Property`` class it drives.""" def __init__(self, property_cls: type[Property]): self.property_cls = property_cls @@ -105,108 +53,54 @@ def __repr__(self) -> str: # pragma: no cover - debugging aid class PropertySetting: """One resolved deployment knob value within a single sweep combination.""" - path: str # dotted config path, e.g. "llms.max_new_tokens" - property_cls: type[Property] # the Property class that applies/reads it - value: Any # the concrete value for this combination + path: str + property_cls: type[Property] + value: Any @dataclass(frozen=True) class ClientSetting: - """One resolved client knob value within a single client combination. - - Deliberately a separate type from :class:`PropertySetting` rather than the - same type with a null ``property_cls``: the runner's apply/converge/verify - loop takes ``PropertySetting``\\ s, and keeping client knobs out of that type - means they cannot reach it by accident. What they carry instead is the - ``benchmark.py`` flag they render to. - """ + """One resolved client knob value within a single client combination.""" - path: str # dotted config path, e.g. "client.concurrency" - arg: ClientArg # the benchmark.py option it renders to - value: Any # the concrete value for this combination + path: str + arg: ClientArg + value: Any -# A sweep combination is an ordered tuple of per-property settings. Combination = tuple[PropertySetting, ...] -# A client combination is an ordered tuple of per-client-knob settings. ClientCombination = tuple[ClientSetting, ...] -# -- value types -------------------------------------------------------------- -# A knob's YAML value is either a single value or a list of values to sweep. -# Constraints (e.g. PositiveInt) are enforced by Pydantic and reported as -# ConfigError. `| None` + default None makes every knob optional. MaxTokensValue = PositiveInt | list[PositiveInt] -# Client knob value types. These mirror benchmark.py's argparse types, tightened -# where argparse accepts more than the tool can actually use: `-c 0` starts no -# workers and `-e -1`/`-w -1` are nonsense, so they are constrained here and -# rejected as a ConfigError instead of producing an empty result CSV an hour later. +# Tighter than benchmark.py's argparse, which accepts -c 0, -e -1 and -w -1. CountValue = PositiveInt | list[PositiveInt] NonNegativeCountValue = NonNegativeInt | list[NonNegativeInt] PathValue = Annotated[str, StringConstraints(min_length=1, strip_whitespace=True)] PathListValue = PathValue | list[PathValue] -# benchmark.duration_to_seconds parses "" and raises KeyError on -# anything else. Validating the shape here turns that late crash into a config error. +# benchmark.duration_to_seconds raises KeyError on anything but . DurationValue = Annotated[ str, StringConstraints(strip_whitespace=True, pattern=r"^\d+(\.\d+)?[smh]$") ] DurationListValue = DurationValue | list[DurationValue] -# -- section models ----------------------------------------------------------- -# One model per config section. `extra="forbid"` makes any unknown key an error. - - class _StrictModel(BaseModel): - """Only pre-defined fields are allowed.""" model_config = ConfigDict(extra="forbid") class LlmsConfig(_StrictModel): - """LLM knobs.""" - max_new_tokens: Annotated[MaxTokensValue | None, PropertyBinding(MaxNewTokens)] = None class ClientConfig(_StrictModel): - """Load-generator knobs — the full set of ``benchmark.py``'s options. - - Every field mirrors one option of ``benchmark.parse_args``; the annotated - :class:`~.client_args.ClientArg` is what carries the flag it renders back to. - - **These are required, unlike deployment knobs.** A deployment knob that is - omitted means "leave it alone", which is a meaningful and observable state. - An omitted client knob has no such reading — the load test runs regardless, - silently on ``benchmark.py``'s defaults (``-c 32``, ``-d 30m``, ``-x 0``), - and the result CSV records none of it. Making them mandatory keeps every - result attributable to a configuration someone wrote down. - - ``server`` and ``bearer_file`` are the two optional ones: pysweep provisions - both when absent (the deployment's ingress URL, plus a bearer file of freshly - minted tokens) and that is what keeps a sweep - runnable with no preparation steps. They are connection plumbing rather than - test scenarios, so they are also single-valued — one endpoint serves the - whole sweep, and a list is rejected. - - **There is no ``tokenizer`` field**, though ``benchmark.py`` has a ``-m`` - option, because it is not a knob: it must always match the model being - served, so its value is fully determined by what the deployment runs. The - runner reads the served model back per combination via - ``ServedModel.read()`` and looks up its HuggingFace repo id in the model - catalog. Declaring ``client.tokenizer`` - therefore fails as an unknown key — deliberately, since the only thing a - config author could express with it is a mismatch, and a mismatched tokenizer - silently corrupts every token count in the results. - """ + """Load-generator knobs mirroring ``benchmark.py``; ``-m`` is derived, not declared.""" question_file: Annotated[PathListValue, QUESTION_FILE] concurrency: Annotated[CountValue, CONCURRENCY] duration: Annotated[DurationListValue, DURATION] worker_startup_delay: Annotated[DurationListValue, WORKER_STARTUP_DELAY] failures_allowed: Annotated[NonNegativeCountValue, FAILURES_ALLOWED] - # 0 means "use the questions as written"; any other value pads/trims every - # question to exactly that many tokens. input_tokens: Annotated[NonNegativeCountValue, INPUT_TOKENS] warmup_requests: Annotated[NonNegativeCountValue, WARMUP_REQUESTS] @@ -216,75 +110,32 @@ class ClientConfig(_StrictModel): class RunConfig(_StrictModel): - """pysweep **run** configuration — how a sweep executes, not what it varies. - - Kept separate from :class:`SweepConfig` (and passed via ``--config`` while - the sweep comes from ``--sweep``) because these settings are not sweep - dimensions: they describe the harness's behaviour and never expand into - combinations. Same strictness applies — an unknown key raises - :class:`ConfigError`. - """ - - # The kr8s/httpx Kubernetes client logs one line per API call, including a - # '101 Switching Protocols' for *every* connection the port-forward carries - # — i.e. one per benchmark request, which is pure noise at load. Off by - # default; set true to debug cluster connectivity. + """How a sweep executes, as opposed to what it varies.""" + + # kr8s/httpx logs a '101 Switching Protocols' line for every port-forwarded request. display_kubernetes_client_logs: bool = False class SweepConfig(_StrictModel): - """Top-level pysweep sweep configuration. - - Deployment sections are optional, and within them each knob is optional: the - set of *declared* (non-None) knobs defines what the sweep varies on the - cluster. The ``client`` section is required, because a load test always - applies *some* load and pysweep will not leave that undeclared. - """ - llms: LlmsConfig | None = None client: ClientConfig - # -- introspection -------------------------------------------------------- - def iter_settings(self) -> Iterator[tuple[str, type[Property], list[Any]]]: - """Yield ``(dotted_path, property_cls, values)`` for every declared *deployment* knob. - - Only knobs actually present in the config are yielded; a single scalar - is normalised to a one-element list so callers treat every knob - uniformly. Client knobs are not properties and are yielded by - :meth:`iter_client_settings` instead. - """ + """Yield ``(path, property_cls, values)`` for every declared deployment knob.""" for path, binding, values in _walk_bindings(self): if isinstance(binding, PropertyBinding): yield path, binding.property_cls, values def iter_client_settings(self) -> Iterator[tuple[str, ClientArg, list[Any]]]: - """Yield ``(dotted_path, client_arg, values)`` for every sweepable client knob. - - Non-sweepable knobs (``server``, ``bearer_file``) are excluded: they are - whole-sweep connection settings, not product dimensions, and are rendered - once by :meth:`client_provisioning_argv`. - """ + """Yield ``(path, client_arg, values)`` for every sweepable client knob.""" for path, binding, values in _walk_bindings(self): if isinstance(binding, ClientArg) and binding.sweepable: yield path, binding, values def deployment_combinations(self) -> list[Combination]: - """Expand the *deployment* knobs into the cartesian product of combinations. - - Combinations order by config-plane (later is more inner in the loop): - 1. Kubernetes - 2. Fingerprint - - Never empty. A sweep with no declared deployment knob yields exactly one - combination — the empty one, meaning "apply nothing, benchmark the - deployment as it stands" — which is what an empty cartesian product - already means, so the runner iterates one list either way instead of - special-casing the no-knobs sweep. - """ + """Cartesian product of deployment knobs, K8s-plane outermost; never empty.""" settings = list(self.iter_settings()) - # K8s-plane knobs (slow rollout) as the outer loop; itertools.product - # varies its leftmost argument slowest. + # itertools.product varies its leftmost argument slowest. settings.sort(key=lambda s: (0 if s[1].plane == Plane.K8S_SPEC else 1, s[0])) value_lists = [values for _, _, values in settings] @@ -299,21 +150,7 @@ def deployment_combinations(self) -> list[Combination]: return combos def client_combinations(self) -> list[ClientCombination]: - """Expand the client knobs into their own cartesian product. - - A *separate* product from :meth:`deployment_combinations` rather than extra - dimensions of it, because the runner nests the two: each deployment - combination is established once, then every client combination is run - against it. That nesting is what makes these knobs cheap — a new - concurrency level costs one more load test, not one more rollout — and - expressing it as nesting means the ordering is structural rather than - something a sort key has to keep getting right. - - Ordered by dotted path so the sequence is stable and diffable across - runs; there is no cost gradient among client knobs to order by, since - none of them touches the deployment. Never empty: the knobs are required, - so the product is at least the single all-scalars combination. - """ + """Cartesian product of sweepable client knobs, ordered by path.""" settings = sorted(self.iter_client_settings(), key=lambda s: s[0]) if not settings: return [] @@ -330,11 +167,7 @@ def client_combinations(self) -> list[ClientCombination]: return combos def client_provisioning_argv(self) -> list[str]: - """Render the declared whole-sweep client knobs (``-s`` / ``-b``) as argv. - - Empty when neither is declared, which is the default and the path where - pysweep provisions both itself. - """ + """Render the declared whole-sweep client knobs (``-s`` / ``-b``) as argv.""" argv: list[str] = [] for path, binding, values in _walk_bindings(self): del path @@ -343,15 +176,7 @@ def client_provisioning_argv(self) -> list[str]: return argv def max_concurrency(self) -> int: - """The largest ``client.concurrency`` any combination of this sweep runs. - - Whole-sweep provisioning needs this before the product is expanded: - ``benchmark.py`` reads one bearer token per worker index, so the bearer - file — written once, shared by every combination — has to cover the widest - combination the sweep will reach. - - ``client.concurrency`` is a required field, so the max is always defined. - """ + """Largest ``client.concurrency`` in the sweep; sizes the shared bearer file.""" return max( int(value) for _, arg, values in self.iter_client_settings() @@ -360,40 +185,17 @@ def max_concurrency(self) -> int: ) def varying_paths(self) -> set[str]: - """Dotted paths of the knobs declared with more than one value. - - These are the sweep's actual dimensions — the knobs whose value differs - between combinations. Knobs declared as a scalar are constant across the - whole sweep and so distinguish nothing. Used to name result files by what - varies (see :func:`~.pysweep_bench.result_file_name`). - """ + """Dotted paths of the knobs declared with more than one value.""" return {path for path, _, values in _walk_bindings(self) if len(values) > 1} def knob_paths(self) -> list[str]: - """Dotted paths of every knob this sweep declares, deployment first. - - The sweep's own description of itself, used as the knob columns of the - summary CSV (see :mod:`~.results`). *Every* declared knob is included, - not only the varying ones, because a summary that dropped the constants - would not say what the numbers were measured under — and because it makes - two sweeps' summaries concatenable when they declare the same knobs. - - Ordered deployment-then-client, each group by path, so the columns read - outer-loop to inner-loop and stay stable across runs. ``server`` and - ``bearer_file`` are excluded: they are connection plumbing rather than a - test scenario, identical for every row, and one of them is a file path - that says nothing about what was tested. - """ + """Declared knob paths (minus ``server``/``bearer_file``), deployment first.""" deployment = sorted(path for path, _, _ in self.iter_settings()) client = sorted(path for path, _, _ in self.iter_client_settings()) return deployment + client def declared_client_names(self) -> set[str]: - """YAML names of every client knob this config declares. - - Used to detect a client flag passed after ``--`` that the config already - owns (see :func:`~.client_args.conflicting_flags`). - """ + """YAML names of every client knob this config declares.""" return { binding.yaml_name for _, binding, _ in _walk_bindings(self) @@ -401,14 +203,6 @@ def declared_client_names(self) -> set[str]: } def declared_question_files(self) -> list[str]: - """Every value declared for ``client.question_file``, in declared order. - - A list, not a set, because the knob is sweepable: a config may name - several corpora and the caller checks all of them. Whether each names a - readable file is not a schema question (the value is validated only as a - non-empty string), so it is checked by the runner's preflight — see - ``pysweep_bench.question_file_verify``. - """ return [ str(value) for _, binding, values in _walk_bindings(self) @@ -418,7 +212,6 @@ def declared_question_files(self) -> list[str]: def _binding_of(field_info) -> PropertyBinding | ClientArg | None: - """The binding attached to a field, whichever kind it is.""" for meta in field_info.metadata: if isinstance(meta, (PropertyBinding, ClientArg)): return meta @@ -428,11 +221,6 @@ def _binding_of(field_info) -> PropertyBinding | ClientArg | None: def _walk_bindings( model: BaseModel, prefix: str = "" ) -> Iterator[tuple[str, PropertyBinding | ClientArg, list[Any]]]: - """Recurse a validated model, yielding declared bindings of either kind. - - Callers filter by binding type; walking both kinds in one pass keeps this the - only place that knows how a config's shape maps to dotted paths. - """ for name, field in type(model).model_fields.items(): value = getattr(model, name) path = f"{prefix}{name}" @@ -448,15 +236,7 @@ def _as_list(value: Any) -> list[Any]: return list(value) if isinstance(value, list) else [value] -# -- loading ------------------------------------------------------------------ - - def _load_model(source: str | Path | dict, model: type[BaseModel], what: str): - """Load YAML (or take a dict) and validate it against ``model``. - - Shared by the sweep and run configs so both get identical strictness and - error reporting. ``what`` names the config in error messages. - """ if isinstance(source, dict): data: Any = source else: @@ -485,19 +265,10 @@ def _load_model(source: str | Path | dict, model: type[BaseModel], what: str): def load_config(source: str | Path | dict) -> SweepConfig: - """Load and validate a sweep config from a YAML file path or a dict. - - Raises :class:`ConfigError` on anything that violates the schema — an - unknown key, a wrong type, an out-of-range value, or malformed YAML — so - invalid config fails loudly before a sweep starts. - """ + """Load and validate a sweep config from a YAML file path or a dict.""" return _load_model(source, SweepConfig, "sweep") def load_run_config(source: str | Path | dict) -> RunConfig: - """Load and validate a pysweep run config (``--config``). - - Same strictness as :func:`load_config`: an unknown key or wrong type raises - :class:`ConfigError` rather than being silently ignored. - """ + """Load and validate a pysweep run config (``--config``).""" return _load_model(source, RunConfig, "run") diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py b/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py index 5c0d940b..526a66df 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py @@ -1,42 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""The model-manager catalog: deployment names, and the HF repo behind each. - -``model-manager`` deploys models from a YAML catalog (``models.yaml``) in which -every entry has a short **deployment name** and the **HuggingFace repo id** its -weights come from:: - - models: - - name: llama3-8b-awq - model_id: casperhansen/llama-3-8b-instruct-awq - category: llm - -Both halves matter to pysweep, for different reasons. - -**The name is what the deployment serves.** It is what ends up in -``--served-model-name``, and therefore what ``LLM_MODEL_NAME`` holds and what the -served model answers to on the gateway — so it is what :mod:`.served_model` reads. - -**The repo id is what the benchmark's tokenizer needs.** ``benchmark.py -m`` -counts tokens with ``transformers.AutoTokenizer``, which resolves a HF repo, not -a deployment name. The value is therefore *derived*, never configured: the runner -reads the observed model name off the deployment and looks its repo id up here -(see :func:`~.pysweep_bench.resolve_tokenizer`). Deriving it is the point — -a hand-set tokenizer that disagreed with the served model would silently mis-count -every input and output length in the results. - -**Which catalog file.** The one the deployment actually used, which is not -necessarily the one in this repo: ``deployment/models.yaml`` here is the shipped -default, while an installed environment has its own copies under ``env//`` -and they do drift. The RAG pipeline's models come from ``models-rag.yaml`` there; -``models.yaml`` is the inference platform's catalog, which shares only some names -and sizes them differently. The resolution order below therefore prefers explicit -configuration (``PYSWEEP_MODEL_CATALOG``) and then ``MM_CONFIG`` — the same -variable the ``model-manager`` wrapper exports — so pysweep reads the catalog -whose names the cluster was actually built from. -""" - import logging import os from pathlib import Path @@ -47,15 +11,9 @@ logger = logging.getLogger(__name__) -# Environment variables consulted for the catalog path, in order. MM_CONFIG is -# what the ai-solutions ./model-manager wrapper exports for the real CLI, so -# honouring it makes pysweep read the same catalog the deployment used without -# anyone having to configure pysweep separately. +# MM_CONFIG is what the ai-solutions ./model-manager wrapper exports. CATALOG_ENV_VARS = ("PYSWEEP_MODEL_CATALOG", "MM_CONFIG") -# Catalog paths tried when nothing is configured. The installed environment's -# copies come first, the RAG catalog before the platform one, then this repo's -# shipped default. CATALOG_FALLBACKS = ( *( str(root / "env" / "local" / name) @@ -71,12 +29,6 @@ class CatalogError(Exception): def catalog_path() -> Path: - """Return the catalog file to read, or raise :class:`CatalogError`. - - Raising when nothing is found is deliberate: the alternative is an empty - catalog, which would make every model name "unknown" and turn a - configuration problem into a confusing per-model failure later on. - """ for var in CATALOG_ENV_VARS: configured = os.getenv(var) if configured: @@ -100,12 +52,7 @@ def catalog_path() -> Path: def load_catalog(path: str | Path | None = None) -> dict[str, dict]: - """Return ``{name: entry}`` for every model in the catalog. - - Entries are returned verbatim, so callers can read whichever field they need - (``model_id``, ``category``, ``cpu``…) without this module having to know - about each one. - """ + """Return ``{name: entry}`` for every model in the catalog.""" resolved = Path(path) if path is not None else catalog_path() try: raw = yaml.safe_load(resolved.read_text()) @@ -139,17 +86,12 @@ def load_catalog(path: str | Path | None = None) -> dict[str, dict]: def known_models(path: str | Path | None = None) -> list[str]: - """Every deployment name the catalog offers, sorted — the valid ``llms.model`` values.""" + """Sorted catalog names: the valid ``llms.model`` values.""" return sorted(load_catalog(path)) def model_entry(name: str, path: str | Path | None = None) -> dict: - """Return one model's catalog entry, or raise naming what *is* available. - - Listing the alternatives matters here because the failure this catches is - almost always a name typo or a repo id used where a name belongs, and both - are obvious the moment the real names are on screen. - """ + """Return one model's catalog entry, or raise listing the available names.""" catalog = load_catalog(path) if name not in catalog: raise CatalogError( @@ -161,13 +103,7 @@ def model_entry(name: str, path: str | Path | None = None) -> dict: def tokenizer_for(name: str, path: str | Path | None = None) -> str: - """Return the HF repo id whose tokenizer matches the model deployed as ``name``. - - Raises :class:`CatalogError` if the entry has no ``model_id``: a model served - from a repo pysweep cannot name is one whose token counts it cannot compute, - and reporting throughput per token off the wrong tokenizer is worse than not - reporting it. - """ + """Return the HF repo id whose tokenizer matches the model deployed as ``name``.""" entry = model_entry(name, path) model_id = entry.get("model_id") if not model_id: diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py b/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py index c796e168..d7f65ea7 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py @@ -1,18 +1,5 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Where pysweep looks for the installed environment's files. - -The ai-solutions installer keeps this repo at ``/ext/enterprise.ai-erag`` -and the environment it built at ``/env/local``. So when pysweep runs from -that checkout, the deploy root follows from this file's own location, whoever the -installing user was. ``/root/ai-solutions`` (the default for a root install) is tried -after it. - -Probing is done with :func:`is_file` / :func:`is_dir` rather than the ``Path`` -methods: on Python < 3.14 those raise ``PermissionError`` for a path under an -unreadable directory such as ``/root``, which would turn "not here, try the next -candidate" into a crash for any non-root user. -""" from pathlib import Path @@ -32,8 +19,8 @@ def deploy_roots() -> tuple[Path, ...]: return tuple(roots) +# Path.is_file/is_dir raise PermissionError under /root on Python < 3.14. def is_file(path: Path) -> bool: - """``path.is_file()``, treating an unreadable location as absent.""" try: return path.is_file() except OSError: @@ -41,7 +28,6 @@ def is_file(path: Path) -> bool: def is_dir(path: Path) -> bool: - """``path.is_dir()``, treating an unreadable location as absent.""" try: return path.is_dir() except OSError: diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py index f2495778..a16d09bf 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py @@ -1,8 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Concrete configuration properties (one knob per class).""" - from .max_tokens import MaxNewTokens __all__ = ["MaxNewTokens"] diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py index 0d4cc31f..ea60bfa2 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py @@ -8,7 +8,6 @@ logger = logging.getLogger(__name__) -# The fingerprint component and parameter key this property drives. COMPONENT = "llm" PARAMETER = "max_new_tokens" @@ -51,5 +50,4 @@ def apply(self, desired: int) -> None: [{"name": COMPONENT, "data": {PARAMETER: desired}}] ) - # Runtime-API plane is ~synchronous: the value is live once change_arguments - # returns, so the inherited no-op wait_until_ready is correct. + # change_arguments is synchronous, so the inherited no-op wait_until_ready suffices. diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py index c836597d..0b169f67 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -2,76 +2,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""pysweep benchmark runner. - -Ties the pieces together (DESIGN.md "Execution flow"): - -1. **Load & validate** a sweep config (``config.load_config`` — invalid YAML - fails here, before anything is applied), then **preflight** the preconditions - the schema cannot express (``preflight``) — the question corpora, once, - while stopping is still free. -2. For each **deployment** combination in the cartesian ``product`` (outer loop): - a. **apply** every declared property's value (idempotent), - b. **wait_until_ready** on each, - c. **verify** via *observed* state (``is_satisfied(read())``) — a mismatch - aborts that combination rather than benchmarking the wrong config, - d. **snapshot** the observed values (so "what was tested" is recorded), - e. **resolve the tokenizer** from the observed served model, so token counts - come from the tokenizer of the model that actually produced them, - f. for each **client** combination (inner loop), **run the benchmark** by - reusing ``benchmark.run_benchmark`` unchanged, then - g. **summarize** that run into the sweep's summary CSV (``results.py``): one - row per run, a column per declared knob, and the TTFT/TPOT KPIs. - -The nesting is the point. A deployment knob costs a reconfiguration of the -running pipeline, so it is established once and then held still while every -load scenario runs against it. Client knobs (concurrency, input length, duration) -change nothing on the cluster, so each additional value costs only another load -test; they are the innermost dimension and need no apply, no convergence wait, -and no read-back (see ``client_args.py``). One deployment combination therefore -yields ``len(client_combinations)`` result CSVs, all directly comparable because -they ran against a deployment that was verified once and never touched between -them. - -Those per-run CSVs are per-*request* rows and carry no configuration, so a sweep -also writes one **summary CSV** holding a row per run: every declared knob as a -dotted-path column, then the mean and p90 of TTFT and TPOT. It is rewritten after -each run, so a sweep killed partway still leaves a readable table of what it got -through. - -Everything a sweep writes goes under one directory (``--summaries``, default -``./results``):: - - results/ - benchmark_summary_results.csv # the table: one row per run - per_case_results/ # one per-request CSV per run - bench_max_new_tokens-64_k-3_concurrency-1.result.csv - ... - -That directory is **cleared of the previous run's artifacts before the sweep -starts** — see :func:`~.results.prepare_summaries_dir` for why a merge would be -worse than a clean slate. - -Usage:: - - PYTHONPATH=src python -m tests.e2e.benchmarks.chatqna.pysweep.pysweep_bench \ - --sweep sweep.yaml [--config general.yaml] - -``--sweep`` declares *what to vary* (the knobs and their values, including the -required ``client:`` section); ``--config`` declares *how to run* (harness -behaviour, e.g. whether benchmark.py's own logs are displayed) and is optional. -Arguments after ``--`` are still forwarded to benchmark.py, but a flag the sweep -config already owns is rejected rather than silently overriding a declared sweep -dimension — the config is the single source of truth for load parameters. - -**Zero-prerequisite runs.** With no benchmark ``-s`` given, pysweep_bench drives -the deployment's own ChatQNA endpoint — the same path ``benchmark.py`` defaults -to, on the domain read from the installed environment's build config (see -:func:`chatqna_url`). With no ``-b`` (bearer file) given it provisions one -automatically, minting one real Keycloak token per worker. The only thing a -caller must supply is ``--sweep``. -""" - import argparse import csv import linecache @@ -121,17 +51,9 @@ logger = logging.getLogger(__name__) -# ChatQNA entrypoint: the same API path benchmark.py drives, so a sweep measures -# what a plain benchmark.py run measures. Only the host differs, and it is not a -# constant — see chatqna_url(). CHATQNA_PATH = "/api/v1/chatqna" -# Relative paths in a sweep config are resolved against THIS file's directory, -# never the process's working directory. A sweep YAML is checked in next to the -# harness, so a path in it means the same thing wherever the sweep is launched -# from; resolving against the CWD would instead make the same config name a -# different file per caller — and `benchmark.py`'s bare open() does exactly that, -# which is the bug this anchor exists to close. +# Relative sweep-config paths resolve against this directory, not the CWD. PYSWEEP_DIR = Path(__file__).resolve().parent @@ -140,23 +62,11 @@ class SweepError(Exception): class PreflightError(SweepError): - """Raised when a precondition for running the sweep is not met. - - Distinct from a bare :class:`SweepError` because it is raised *before* - anything is applied or benchmarked: nothing has to be undone, and the fix is - always in the caller's config or environment rather than in the cluster. - """ + """Raised before anything is applied when a sweep precondition is not met.""" def build_property(setting: PropertySetting, fingerprint_client: FingerprintClient) -> Property: - """Instantiate the ``Property`` bound to a config leaf with the resources it needs. - - Properties differ in what they need to reach their plane. Runtime-API - properties take the fingerprint client; K8s-plane properties talk to the - cluster themselves (kr8s reads its own kubeconfig) and so take no argument. - Dispatch on the class's declared plane so adding a property of an existing - plane needs no change here. - """ + """Instantiate the Property for a config leaf, dispatching on its plane.""" if setting.property_cls.plane == Plane.RUNTIME_API: return setting.property_cls(fingerprint_client) if setting.property_cls.plane == Plane.K8S_SPEC: @@ -170,12 +80,7 @@ def build_property(setting: PropertySetting, fingerprint_client: FingerprintClie def apply_combination( combination: Combination, fingerprint_client: FingerprintClient ) -> dict: - """Apply, converge, and verify one combination; return the observed snapshot. - - Raises :class:`SweepError` if any property fails to converge to its desired - value, so a benchmark never runs against a configuration we could not - actually establish. - """ + """Apply, converge and verify one combination; return the observed snapshot.""" properties = [(setting, build_property(setting, fingerprint_client)) for setting in combination] for setting, prop in properties: @@ -183,19 +88,14 @@ def apply_combination( try: prop.apply(setting.value) except (PropertyApplyError, NotImplementedError) as exc: - # The property could not establish the requested state (a value the - # deployment cannot run, a manifest it no longer recognises, or a - # knob that is not writable). That is a sweep problem, not a crash. raise SweepError(f"{setting.path}: {exc}") from exc for setting, prop in properties: try: prop.wait_until_ready(setting.value) except PropertyApplyError as exc: - # Applied but never took effect — never benchmark on that. raise SweepError(f"{setting.path}: {exc}") from exc - # Verify against OBSERVED state (DESIGN.md: the set/verify split). snapshot = {} for setting, prop in properties: observed = prop.read() @@ -209,30 +109,10 @@ def apply_combination( def resolve_tokenizer() -> str: - """The tokenizer to count tokens with: the one of the *observed* served model. - - ``benchmark.py``'s ``-m`` is not a sweep knob, so nobody declares it. It has - exactly one correct value — the served model's tokenizer — because it produces - the ``input_tokens`` / ``output_tokens`` columns and pads questions to - ``client.input_tokens``. Counted with any other model's tokenizer, those - numbers describe a tokenization the deployment never performed, and tokens/s - stops being comparable to anything. - - Two steps, because the two names differ. What the deployment serves is a - *catalog* name (``llama3-8b-awq``, the value of ``LLM_MODEL_NAME`` and the name - of the ``LLMInferenceService``); ``AutoTokenizer.from_pretrained`` needs a - HuggingFace repo id. The model catalog holds both, so the observed name is - resolved through it (:func:`model_catalog.tokenizer_for`) rather than guessed. - - Reads observed state rather than any declared value, for the same reason - properties do: a pipeline that half-switched models would otherwise be - tokenized as though it had not. - """ + """Return the HF tokenizer of the observed served model.""" try: served = ServedModel().read() except PropertyReadError as exc: - # Without it every token count would be on an unknown basis, so this - # is not something to fall back from silently. raise SweepError( f"Cannot determine the served model to tokenize with: {exc}. " f"The benchmark's -m must be the tokenizer of the model the " @@ -247,19 +127,10 @@ def resolve_tokenizer() -> str: def _slug(value) -> str: - """Filesystem-safe fragment for a config value (used in result filenames). - - Underscores are preserved so knob names stay readable (``max_new_tokens``). - """ return re.sub(r"[^0-9A-Za-z_]+", "-", str(value)).strip("-") def _settings_slug(settings, only=None) -> str: - """Join ``-`` fragments for the given settings. - - ``only`` restricts the output to those dotted paths — see - :func:`result_file_name` for why a filename names only what varies. - """ return "_".join( f"{_slug(s.path.rsplit('.', 1)[-1])}-{_slug(s.value)}" for s in settings @@ -283,24 +154,7 @@ def result_file_name( only=None, fallback: str = "single", ) -> str: - """Result CSV *file name* for one (deployment, client) pair. - - A bare name, not a path: where it goes is the caller's business (the - ``per_case_results`` subdirectory of ``--summaries``), and what it is called is - this function's. - - Both slugs contribute, because both identify the run and either alone repeats - across the sweep — a name built from one would clobber the other's results. - - ``only`` (the sweep's varying paths) is what keeps the name usable. Naming - every declared knob is tempting since the filename is the record of what - produced the numbers, but with every option declared an HF repo id and a - question-file path push it past the 255-byte filename limit. So the name - carries what *distinguishes* - this run, and the full configuration — deployment snapshot and load parameters - both — is logged per run instead. ``fallback`` names the degenerate case where - the sweep has a single combination and so nothing varies at all. - """ + """Result CSV file name for one run; names only the varying knobs to stay under 255 bytes.""" slug = "_".join( part for part in ( @@ -321,25 +175,11 @@ def count_result_rows(output_file) -> int: return sum(1 for _ in csv.reader(handle)) -# Loggers belonging to the Kubernetes client stack. kr8s talks to the API server -# over httpx/httpcore and logs a line per call; with a port-forward under load -# that is one '101 Switching Protocols' per benchmark request. KUBERNETES_CLIENT_LOGGERS = ("httpx", "httpcore", "kr8s", "websockets") +# kr8s's port-forward task writes to closed sockets on teardown; asyncio logs harmless reset tracebacks. class _DropPortForwardTeardownNoise(logging.Filter): - """Drop kr8s's port-forward connection-reset tracebacks. - - When the load test closes a connection (and again when the sweep tears the - forward down), kr8s's background asyncio task may still be writing to the - now-closed socket. The resulting ``ConnectionResetError`` is not awaited by - anyone, so asyncio's default handler dumps a multi-frame ExceptionGroup - traceback. It is a teardown race *inside kr8s* with no effect on the - benchmark — verified: every recorded request still returns 200 — but it - swamps the output. Only these reset/closed records are dropped; any other - asyncio error still surfaces. - """ - _NOISE = ( "ConnectionResetError", "Connection lost", @@ -355,13 +195,6 @@ def filter(self, record: logging.LogRecord) -> bool: def configure_kubernetes_client_logs(enabled: bool) -> None: - """Quiet the kr8s/httpx client loggers unless explicitly enabled. - - Applied once at startup (not scoped to the benchmark) because the port-forward - spans the whole sweep. Raising the level rather than filtering keeps genuine - warnings and errors — only the per-call INFO chatter goes away. The asyncio - logger keeps its level (real errors matter) but loses kr8s's teardown resets. - """ if enabled: return for name in KUBERNETES_CLIENT_LOGGERS: @@ -370,29 +203,13 @@ def configure_kubernetes_client_logs(enabled: bool) -> None: def resolve_question_file(value: str) -> Path: - """Resolve a declared ``client.question_file`` to a concrete path. - - Relative values are anchored at :data:`PYSWEEP_DIR` (this file's directory), - so ``../questions-short.csv`` names the corpus beside ``benchmark.py`` - regardless of where the sweep was launched from. Absolute paths are returned - unchanged — an explicit absolute path is already unambiguous, and rewriting - it would be surprising. - """ + """Resolve a client.question_file against PYSWEEP_DIR; absolute paths pass through.""" path = Path(value) return path if path.is_absolute() else (PYSWEEP_DIR / path) def question_file_verify(config: SweepConfig) -> None: - """Check every declared ``client.question_file`` names a readable file. - - ``question_file`` is sweepable, so a config may declare a list of corpora; - all of them are checked, since a bad path in the *last* one would otherwise - surface only after the earlier runs had already spent their load. - - The schema cannot do this: it validates the value as a non-empty string - (``PathValue``), and whether that string resolves to a file is a fact about - the filesystem rather than about the config's shape. - """ + """Raise PreflightError unless every declared client.question_file is a readable file.""" for value in config.declared_question_files(): path = resolve_question_file(value) if not path.is_file(): @@ -411,85 +228,35 @@ def preflight_check(config: SweepConfig) -> None: def chatqna_url() -> str: - """The deployed ChatQNA endpoint, with the domain read from the deployment. - - The host is **derived, not declared**: it comes from ``base_domain_name`` in - the installed environment's build config — the same value, read from the same - files, that :class:`~.runtime_api.IngressTransport` and ``KeycloakHelper`` - use. Hardcoding a domain here would let a sweep drive load at one cluster - while configuring another, and the minted token would not even be valid for - it. Point ``PYSWEEP_BUILD_CONFIG_DIR`` at a different ``env//`` to - benchmark a different deployment, exactly as for every other plane. - """ + """Return the ChatQNA URL on the deployment's base_domain_name.""" from tests.e2e.benchmarks.chatqna.pysweep.authentication import load_build_config - # load_build_config guarantees a non-empty base_domain_name or raises. return f"https://{load_build_config()['base_domain_name']}{CHATQNA_PATH}" class ProvisionedArgv(list): - """The benchmark argv, plus a way to re-mint the bearer file it points at. - - A plain ``list`` for every existing use (comparison, slicing, ``+``). - :meth:`refresh` is a no-op unless pysweep minted the tokens itself. - """ + """Benchmark argv with refresh() to re-mint the bearer file, if pysweep owns it.""" def __init__(self, argv, refresh=None): super().__init__(argv) self._refresh = refresh def refresh(self) -> None: - """Re-mint the tokens, if pysweep owns the bearer file.""" if self._refresh is not None: self._refresh() def write_bearer_file(path: str, helper, workers: int) -> None: - """Write ``workers`` freshly minted, distinct user tokens to ``path``, one per line. - - One DISTINCT token per worker, matching generate_uat_to_file.sh, which the - shell benchmark calls with the concurrency for exactly this reason. Each - ``access_token`` read is a fresh password grant, so the strings differ. That - matters because APISIX's limit-count plugin on /api/v1/chatqna buckets by the - Authorization header *value*: one token repeated would put every worker in a - single 30-requests-per-60s bucket, capping the whole sweep near 0.5 req/s no - matter what concurrency it declares. - """ + """Write one distinct token per worker; APISIX rate-limits per Authorization header value.""" tokens = [helper.access_token for _ in range(workers)] Path(path).write_text("".join(token + "\n" for token in tokens)) - # benchmark.py reads each worker's token with linecache, which caches the - # file; without this a run would be handed the previous run's tokens. Cleared - # outright: checkcache() goes by size and mtime, and a same-size file rewritten - # within one mtime tick would look unchanged. + # benchmark.py reads tokens via linecache; checkcache() misses same-size, same-mtime rewrites. linecache.clearcache() @contextmanager def provision_benchmark_target(benchmark_args: list[str], workers: int = 1): - """Ensure the benchmark has a reachable endpoint and a bearer file. - - Yields a :class:`ProvisionedArgv`: the ``benchmark_args`` to actually use. If - the caller supplied no ``-s``, inject :func:`chatqna_url` (the deployment's - own ChatQNA endpoint, the same path ``benchmark.py`` defaults to). If the - caller supplied no ``-b``, write a bearer file holding ``workers`` - freshly-minted Keycloak tokens, one per line, and let the caller re-mint them - before each load test with :meth:`ProvisionedArgv.refresh`. - - Re-minting per run is what lets a sweep last longer than a token does: each - benchmark worker reads its token once, when the run starts, so a token only - has to outlive one run. For that to hold, the tokens are also lengthened to - :data:`~.authentication.SWEEP_TOKEN_LIFESPAN_S` for the sweep (the realm's - 5-minute default is shorter than one run), and set back afterwards. - - ``workers`` must be the *widest* concurrency the sweep will reach (see - :meth:`~.config.SweepConfig.max_concurrency`), because the file is shared by - every combination while ``benchmark.py`` indexes into it per worker. - - "Supplied" covers both sources: a flag after ``--`` and a ``client.server`` / - ``client.bearer_file`` in the sweep config, since :func:`main` renders the - latter into these args before calling. A supplied ``-b`` is the caller's: it - is never re-minted, and the token lifespan is left alone. - """ + """Yield the argv with -s and a minted bearer file (one token per worker) added unless supplied.""" args = list(benchmark_args) refresh = None @@ -503,8 +270,6 @@ def provision_benchmark_target(benchmark_args: list[str], workers: int = 1): tmp = stack.enter_context( tempfile.NamedTemporaryFile("w", suffix=".uat", delete=True) ) - # The target is the authenticated ERAG ingress, so mint real Keycloak - # user tokens. from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( client_token_lifespan, keycloak_helper, @@ -550,9 +315,6 @@ def parse_args(argv=None): f"DELETED before this one starts (default: {DEFAULT_SUMMARIES_DIR})." ), ) - # Everything after '--' is forwarded to the existing benchmark CLI. Load - # parameters belong in the sweep config's `client:` section; a flag here that - # the config already declares is an error, not an override. parser.add_argument( "benchmark_args", nargs=argparse.REMAINDER, @@ -569,13 +331,7 @@ def parse_args(argv=None): def resolve_benchmark_argv(config: SweepConfig, benchmark_args: list[str]) -> list[str]: - """Merge the sweep config's whole-sweep client knobs with the caller's ``--`` args. - - Raises :class:`SweepError` if a forwarded flag duplicates a client knob the - config declares. Silently letting one win would mean the command line and the - config disagree about what was tested, which is the failure mode this harness - exists to prevent — so it is refused before anything is applied. - """ + """Merge the config's client knobs with the `--` args; raise SweepError on duplicated flags.""" conflicts = conflicting_flags(benchmark_args, config.declared_client_names()) derived = [flag for flag in conflicts if flag in DERIVED_FLAGS] if derived: @@ -592,23 +348,11 @@ def resolve_benchmark_argv(config: SweepConfig, benchmark_args: list[str]) -> li f"command line (the sweep config is the source of truth for load " f"parameters), or remove the client knob to set it per-invocation." ) - # Config-declared -s/-b first so provision_benchmark_target sees them as - # "supplied" and skips auto-provisioning for those. return config.client_provisioning_argv() + list(benchmark_args) def resolve_question_file_argv(argv: list[str]) -> list[str]: - """Rewrite the ``-f`` value in ``argv`` to its anchored absolute path. - - Done at the argv boundary because ``benchmark.py`` opens the value with a - bare ``open()``, i.e. against the process's working directory. Handing it an - absolute path is what makes the anchor authoritative without modifying - ``benchmark.py``, whose other callers rely on its current behaviour. - - Only the value pysweep rendered from the config is rewritten; the declared - string is what the summary CSV records, so provenance still shows what the - config asked for rather than a machine-specific absolute path. - """ + """Rewrite the -f value to an absolute path; benchmark.py opens it relative to the CWD.""" argv = list(argv) if QUESTION_FILE.flag in argv: index = argv.index(QUESTION_FILE.flag) + 1 @@ -616,27 +360,11 @@ def resolve_question_file_argv(argv: list[str]) -> list[str]: return argv -#: Indentation of the logged YAML blocks. Four spaces, matching the sweep config -#: files those blocks are meant to be read against. LOG_YAML_INDENT = 4 def format_settings_yaml(values: dict, indent: int = LOG_YAML_INDENT) -> str: - """Render a ``{dotted_path: value}`` mapping as a YAML block, for logging. - - A dict repr of a run's knobs is one unreadable line quoted by Python's rules; - the same values grouped back into their config sections read like the sweep - YAML they came from:: - - client: - question_file: ../questions-short.csv - concurrency: 16 - - Undotted keys (the summary row's KPIs) stay at the top level. Key order is the - caller's, not sorted, and values ``yaml.safe_dump`` cannot represent are - stringified rather than raised — a log line must not end a long sweep. - Returns ``""`` for an empty mapping, so a caller can say "(unchanged)". - """ + """Render a {dotted_path: value} mapping as sectioned YAML for logging; "" if empty.""" if not values: return "" @@ -665,36 +393,16 @@ def run_client_combination( varying_paths=None, tokenizer: str | None = None, ) -> tuple[int, Path]: - """Run one load test: the innermost step of the sweep. - - No apply, no convergence wait, no verification — the client knobs are - arguments to the process about to start, so establishing them *is* rendering - them into argv. Returns ``(error, output_file)``. - - ``tokenizer`` is the one client argument nobody declares: it is the served - model, resolved once per deployment combination by :func:`resolve_tokenizer` - and passed in here rather than re-read per load test, since the deployment is - held still across this whole inner loop. - - ``results_dir`` is where the per-request CSV goes — the ``per_case_results`` - subdirectory of ``--summaries``. It is joined here, and absolute, because - ``benchmark.py`` opens its output file with a bare ``open()``: a relative name - would land against the process's working directory instead. - """ + """Run one load test; return (error, output_file).""" client_args = BenchmarkClientArgs.from_settings(client_combination) argv = resolve_question_file_argv(bench_argv + client_args.to_argv()) if tokenizer is not None: argv += [TOKENIZER.flag, tokenizer] - # The tokenizer stays out of the YAML block: it is derived from the served - # model, and 'client.tokenizer' is a ConfigError, so a block containing it - # would not be pasteable into a sweep config. logger.info( "%s load parameters (tokenizer: %s):\n%s", label, tokenizer, format_settings_yaml(client_args.snapshot()), ) - # Reuse benchmark.py unchanged: parse its args, then run one load test into a - # CSV named for both combinations so results are never clobbered. bench_args = benchmark.parse_args(argv) output_file = Path(results_dir) / result_file_name( combination, client_combination, only=varying_paths @@ -703,8 +411,6 @@ def run_client_combination( rows = count_result_rows(output_file) if rows == 0: - # A load test that recorded nothing is a failed run, not a pass: - # surface it instead of exiting 0 with an empty CSV. logger.error( "%s produced NO result rows in %s " "(endpoint unreachable, all requests failed, or duration too short).", @@ -719,7 +425,6 @@ def main(argv=None): args = parse_args(argv) logging.basicConfig(stream=sys.stderr, level=logging.INFO) - # Run config is optional; its defaults are the previous behaviour. run_config = load_run_config(args.config) if args.config else load_run_config({}) configure_kubernetes_client_logs(run_config.display_kubernetes_client_logs) @@ -730,14 +435,8 @@ def main(argv=None): deployment_combinations = config.deployment_combinations() client_combinations = config.client_combinations() - # Result files are named by what varies; the rest is constant and logged. varying_paths = config.varying_paths() - # Last thing before the sweep proper, and the first destructive one: the - # output directory is cleared here rather than at startup, so a bad config or a - # failed preflight does not cost the previous sweep's results. layout = prepare_summaries_dir(args.summaries) - # ...and everything declared, varying or not, becomes a column of the summary, - # which is the artifact that has to stand on its own once the sweep is over. summary = SweepSummary(config.knob_paths(), path=layout.summary_file) fingerprint_client = FingerprintClient(default_transport()) @@ -748,9 +447,6 @@ def main(argv=None): len(deployment_combinations), len(client_combinations), total, ) overall_error = 0 - # Provision the endpoint/bearer once for the whole sweep; the tokens in it are - # re-minted before each load test (see provision_benchmark_target). Sized to - # the widest concurrency, since one bearer file has to serve every combination. with provision_benchmark_target(bench_argv, config.max_concurrency()) as provisioned_argv: for index, combination in enumerate(deployment_combinations, start=1): desired = {s.path: s.value for s in combination} @@ -759,15 +455,11 @@ def main(argv=None): index, len(deployment_combinations), desired or "(unchanged)", ) - # Applied and verified ONCE, then held still for every client - # combination below — which is what makes those results comparable. snapshot = apply_combination(combination, fingerprint_client) logger.info( "Observed configuration under test:\n%s", format_settings_yaml(snapshot) ) - # Resolved here, not per load test: the deployment is held still for - # the whole inner loop, so the served model cannot change within it. tokenizer = resolve_tokenizer() logger.info("Counting tokens with the served model's tokenizer: %s", tokenizer) @@ -777,8 +469,7 @@ def main(argv=None): f"(deployment {index}/{len(deployment_combinations)}, " f"client {client_index}/{len(client_combinations)})" ) - # Fresh tokens per run, so none expires during a long sweep. Test - # doubles may yield a plain list, which has nothing to refresh. + # Test doubles may yield a plain list. if isinstance(provisioned_argv, ProvisionedArgv): provisioned_argv.refresh() error, output_file = run_client_combination( @@ -788,9 +479,6 @@ def main(argv=None): ) overall_error = overall_error or error - # Observed values for the deployment half, declared ones for the - # client half — the same asymmetry as the per-run log line, for - # the same reason (see BenchmarkClientArgs.snapshot). row = summary.add_run( knob_values={ **snapshot, @@ -800,8 +488,6 @@ def main(argv=None): error=error, served_model=tokenizer, ) - # The summary row's KPI keys are undotted, so they stay top-level - # under the knob sections rather than nesting. logger.info("%s summary:\n%s", label, format_settings_yaml(row)) logger.info("Sweep summary (%d run(s)) written to %s", len(summary.rows), summary.write()) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py index 62ca44c9..997cf250 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py @@ -1,53 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Post-processing: one summary CSV for a whole sweep. - -``benchmark.py`` writes one CSV per load test, with one row per completed -request and no header:: - - input_tokens,output_tokens,ttft,end_to_end,err,code - -That is the right raw format — it is written incrementally under load and loses -nothing — but it answers nothing on its own. Which configuration produced it -lives in the *filename*, and only partially: :func:`~.pysweep_bench.result_file_name` -names a run by what *varies*, so the constant half of the configuration is not -there at all, and neither is the served model. - -So this module turns a sweep into a single table: one row per run, a column per -declared knob (named by its dotted config path, e.g. ``client.input_tokens``), -and the KPIs that make runs comparable — TTFT and TPOT, mean and p90. Knob -columns come first so the file reads as "these settings produced these numbers", -and every declared knob gets a column, not just the varying ones: a summary that -omitted the constants would be unreadable a month later and impossible to -concatenate with a different sweep's. - -The per-request CSVs are kept as they are. This is a summary, not a replacement: -anything the four KPIs do not answer (distribution shape, drift over the run, -the tail past p90) is still in them, and the ``result_file`` column is the -pointer back. - -**Definitions** (seconds, since that is what ``benchmark.py`` measures): - -``ttft`` - Time to first token — ``first_chunk``, as recorded: the wall time from - issuing the request to the first streamed content chunk. Prefill plus every - queueing delay ahead of it, which is why it is the KPI that moves with - concurrency. -``tpot`` - Time per output token — ``(end_to_end - ttft) / (output_tokens - 1)``: the - average inter-token gap during decode. The first token is excluded from both - sides, because its cost is TTFT; dividing by ``output_tokens`` instead (as - ``parse.py``'s ``next_token_lat`` does) charges the decode phase for a token - it did not generate, which understates TPOT by ``1/output_tokens``. The - difference is under a percent at 128 tokens and material at 8. - -p90 uses linear interpolation between the two nearest ranks (the numpy/pandas -default), so it agrees with what ``parse.py`` reports and needs no dependency -beyond the standard library — pysweep stays importable without pandas, which -matters because the config/apply half of it runs in the validation suite. -""" - import csv import logging import math @@ -57,24 +10,13 @@ logger = logging.getLogger(__name__) -#: Everything a sweep writes goes under one directory, given by ``--summaries``. -#: Relative to the CWD, like any other command-line path. DEFAULT_SUMMARIES_DIR = "./results" -#: The sweep's own table, at the root of that directory. Deliberately not named -#: ``bench_*.csv``: that glob is what ``parse.py`` consumes as per-request data, -#: and this file is not that shape. +# Not bench_*.csv: parse.py globs that as per-request data. SUMMARY_FILE_NAME = "benchmark_summary_results.csv" -#: The per-run CSVs, in a subdirectory of it. Separated because there is one per -#: run and they are the raw data, while the summary is one file and is the -#: artifact people read — mixing them made the interesting file hard to find, and -#: made "wipe the previous run's results" impossible to express safely. PER_CASE_DIR_NAME = "per_case_results" -#: KPI and provenance columns, in the order they appear after the knob columns. -#: ``requests`` comes first of them because it is what licenses reading the -#: rest — a p90 over four requests is a number, not a measurement. SUMMARY_COLUMNS: tuple[str, ...] = ( "requests", "mean_ttft", @@ -86,8 +28,6 @@ "result_file", ) -#: Seconds are recorded to microseconds. Enough to keep sub-millisecond TPOT -#: differences visible, few enough that the CSV stays readable. _PRECISION = 6 @@ -96,12 +36,7 @@ class SummariesLayoutError(Exception): class SummariesLayout(NamedTuple): - """Where a sweep's artifacts go, resolved once and passed down. - - Resolved to absolute paths: the load test runs through ``benchmark.py``, which - opens its output with a bare ``open()``, so anything relative would land - against the process's working directory instead. - """ + """Where a sweep's artifacts go, as absolute paths (benchmark.py opens them bare).""" root: Path summary_file: Path @@ -109,11 +44,6 @@ class SummariesLayout(NamedTuple): def _clear_directory(directory: Path) -> int: - """Delete every entry inside ``directory``, returning how many were removed. - - Symlinks are unlinked, not followed: a link inside the directory names - something outside it, which is not this sweep's to delete. - """ removed = 0 for entry in directory.iterdir(): if entry.is_dir() and not entry.is_symlink(): @@ -125,31 +55,7 @@ def _clear_directory(directory: Path) -> int: def prepare_summaries_dir(root=DEFAULT_SUMMARIES_DIR) -> SummariesLayout: - """Create the sweep's output layout, **discarding any previous run's results**. - - A sweep's artifacts only make sense as a set: the summary indexes the per-case - CSVs, and a per-case CSV means nothing without the row that says what produced - it. Leaving the previous run's files in place would silently mix two sweeps — - stale per-case CSVs with no row in the current summary, or rows pointing at - files a shorter sweep never overwrote. So this is a clean slate, not a merge: - - * ``/`` is created if missing (parents included). - * ``/benchmark_summary_results.csv`` is deleted if present. - * ``/per_case_results/`` is emptied if present, created if not. - - **Nothing else under ```` is touched** — the deletion is confined to the - one file and the one subdirectory this function owns, so pointing - ``--summaries`` at a directory that holds other things loses none of them. Two - shapes are refused outright rather than resolved: - - * ```` or the summary path already being the wrong kind of file, which - means this directory is not a results directory and the caller has the wrong - path; - * ``per_case_results`` being a symlink, since emptying it would delete - whatever it points at, outside the tree the caller named. - - Raises :class:`SummariesLayoutError` in those cases, before any deletion. - """ + """Create the sweep's output layout, discarding the previous run's summary and per-case CSVs.""" root = Path(root) if root.exists() and not root.is_dir(): raise SummariesLayoutError( @@ -216,26 +122,14 @@ class RequestRecord(NamedTuple): @property def tpot(self) -> float | None: - """Mean inter-token gap during decode, or ``None`` if undefined. - - Undefined for a single-token answer: there is no gap *between* tokens to - average, and the whole latency is already reported as TTFT. - """ + """Mean inter-token gap during decode; ``None`` for a single-token answer.""" if self.output_tokens < 2: return None return (self.end_to_end - self.ttft) / (self.output_tokens - 1) def read_requests(result_file) -> list[RequestRecord]: - """Parse one ``benchmark.py`` result CSV into records. - - Rows that are malformed, unsuccessful, or nonsensical are dropped rather - than crashing the summary: a sweep is hours long and the summary is written - after every run, so one damaged line must not cost the rest of the table. - Every drop is logged at debug level. ``benchmark.py`` only enqueues 200s with - no error, so in practice nothing is dropped — the filtering is here so the - summary keeps the same meaning if that ever changes. - """ + """Parse one ``benchmark.py`` result CSV, dropping malformed or unsuccessful rows.""" path = Path(result_file) if not path.exists(): return [] @@ -262,8 +156,6 @@ def read_requests(result_file) -> list[RequestRecord]: logger.debug("%s:%d: not a successful request; skipped", path, line) continue if record.ttft <= 0 or record.end_to_end < record.ttft: - # No first chunk was ever timed, or the totals contradict each - # other. Either way the latencies are not measurements. logger.debug("%s:%d: implausible timings %r; skipped", path, line, record) continue records.append(record) @@ -271,13 +163,7 @@ def read_requests(result_file) -> list[RequestRecord]: def percentile(values: Sequence[float], quantile: float) -> float | None: - """Linear-interpolated percentile, matching numpy/pandas' default method. - - Returns ``None`` for an empty sample rather than raising, so a run that - recorded nothing still produces a row (with blank KPIs) instead of aborting - the summary — "this configuration produced no data" is itself a result worth - keeping in the table. - """ + """Linear-interpolated percentile (numpy's default); ``None`` for an empty sample.""" ordered = sorted(values) if not ordered: return None @@ -295,19 +181,11 @@ def _mean(values: Sequence[float]) -> float | None: def _round(value: float | None) -> str: - """Render a KPI for the CSV; an undefined one renders as an empty cell.""" return "" if value is None else f"{round(value, _PRECISION)}" def summarize_requests(records: Iterable[RequestRecord]) -> dict[str, Any]: - """Aggregate request records into the KPI columns. - - ``requests`` counts the sample the TTFT statistics are over. The TPOT - statistics are over the subset with at least two output tokens (see - :attr:`RequestRecord.tpot`); that subset is normally the whole sample, and - when it is not, a blank TPOT with a non-zero ``requests`` is the honest - reading — the run happened, the decode rate is not defined for it. - """ + """Aggregate request records into the KPI columns.""" records = list(records) ttfts = [record.ttft for record in records] tpots = [record.tpot for record in records if record.tpot is not None] @@ -321,22 +199,7 @@ def summarize_requests(records: Iterable[RequestRecord]) -> dict[str, Any]: class SweepSummary: - """Accumulates one row per run and writes the sweep's summary CSV. - - Rewritten in full after every run rather than appended to. A sweep of a - dozen runs is a few hundred bytes, and the rewrite means the file on disk is - always a complete, valid CSV of everything finished so far — so a sweep that - is killed at hour three (or a model rollout that fails midway) still leaves a - readable table instead of a truncated last line. - - ``knob_paths`` fixes the columns up front, from the config rather than from - the rows: every run of a sweep has the same knobs, and taking them from the - config means the header is right before the first run finishes. It is written - at construction for that reason — the first run of a sweep can be an hour of - load behind a multi-replica rollout, and until then a missing file is - indistinguishable from a harness that forgot to summarize. A header-only file - says "this sweep is running and here is the shape of its results". - """ + """Accumulates one row per run and rewrites the summary CSV after each.""" def __init__( self, @@ -349,17 +212,6 @@ def __init__( self.write() def _pointer(self, result_file) -> str: - """How the ``result_file`` column names a per-case CSV. - - Relative to the summary's own directory when the CSV is inside it, which - is the normal case (``per_case_results/bench_….result.csv``). That keeps - the whole results directory movable: copy it off the benchmark host or - rename it, and every pointer still resolves. An absolute path would name a - directory that only existed on the machine that ran the sweep. - - A CSV from outside the directory is recorded verbatim, since there is no - relative name for it that means anything. - """ path = Path(result_file) try: return str(path.relative_to(self.path.parent)) @@ -368,7 +220,6 @@ def _pointer(self, result_file) -> str: @property def columns(self) -> list[str]: - """Header: knob columns in dotted-path form, then the KPIs.""" return self.knob_paths + list(SUMMARY_COLUMNS) def add_run( @@ -378,14 +229,7 @@ def add_run( error: int = 0, served_model: str | None = None, ) -> dict[str, Any]: - """Summarize one finished run and return the row that was recorded. - - ``knob_values`` maps dotted paths to the values that run used — observed - read-backs for deployment knobs (what the cluster actually did), declared - values for client knobs (there is nothing to observe: they are arguments - to the process). A path with no entry renders blank, which is what makes - it safe to call before every knob has a value. - """ + """Summarize one finished run and return the recorded row.""" summary = summarize_requests(read_requests(result_file)) row: dict[str, Any] = {path: knob_values.get(path, "") for path in self.knob_paths} row.update(summary) @@ -397,7 +241,6 @@ def add_run( return row def write(self) -> Path: - """Write the whole table, header included, replacing any previous copy.""" with self.path.open("w", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=self.columns) writer.writeheader() diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py b/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py index b0d056dc..7605f44a 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py @@ -1,35 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Client for the ChatQNA ``system_fingerprint`` runtime API (Runtime API plane). - -Wraps the two endpoints the runtime-plane properties use: - -- ``POST change_arguments`` — the **setter**. A list of - ``{"name": , "data": {...}}`` entries. -- ``GET config?params_key=`` — the **reader**. Returns that one - component's live arguments under ``values``. - -The reader is per-component, which is why every property names the component it -drives: asking for ``retriever`` gets the retriever's arguments and nothing else, -so a property can never accidentally read a same-named key belonging to another -component. - -**Scope.** Writes carry a ``pipeline``/``tenant`` pair, because the microservice -stores arguments per scope and the ChatQNA router reads the ``chatqna``/``_global`` -one — a write with no scope lands somewhere the pipeline under test does not -read. Reads take the same pair for symmetry. - -Two transports are supported (DESIGN.md "Reaching pod APIs"): - -- :class:`PortForwardTransport` (default) — forwards to ``fingerprint-svc`` via - ``kr8s``. Needs no token, because authentication is enforced at the ingress - gateway and this path is pod-local. That makes it the robust choice for a - multi-hour sweep: nothing to expire. -- :class:`IngressTransport` — the ERAG domain, authenticated with a Keycloak - access token. Used when the cluster is only reachable through its ingress. -""" - import logging import os import secrets @@ -52,15 +23,12 @@ FINGERPRINT_PORT = 6012 API_PREFIX = "/v1/system_fingerprint" -# The scope the ChatQNA router reads its component arguments from. '_global' is -# the shared tenant; see FingerprintApiHelper.set_chatqa_component_parameters, -# which fixes the same pair for the e2e suite's ChatQNA tests. +# The scope the ChatQNA router reads component arguments from. PIPELINE = "chatqna" TENANT = "_global" def find_unused_port(start: int = 10000, end: int = 60000) -> int: - """Return a currently-free local TCP port in ``[start, end)``.""" while True: port = secrets.randbelow(end - start) + start with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: @@ -69,11 +37,6 @@ def find_unused_port(start: int = 10000, end: int = 60000) -> int: def wait_until_listening(port: int, timeout: float = 10.0) -> None: - """Block until a local port accepts connections. - - ``PortForward.start()`` returns before the tunnel is actually listening, so - probe the socket to avoid a connection-refused race. - """ deadline = time.monotonic() + timeout while time.monotonic() < deadline: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: @@ -85,18 +48,12 @@ def wait_until_listening(port: int, timeout: float = 10.0) -> None: @contextmanager def object_port_forward(obj, remote_port: int): - """Port-forward ``remote_port`` on any kr8s object; yield the local port. - - Works for a ``Service`` (load-balanced across its endpoints) or a ``Pod`` - (one specific replica). The forward is scoped to the context and torn down - afterwards. This is the single code path for reaching in-cluster HTTP APIs - pod-locally — shared by the fingerprint transport and the benchmark's ChatQNA - endpoint. - """ + """Port-forward remote_port on a kr8s Service or Pod; yield the local port.""" local_port = find_unused_port() pf = kr8s.portforward.PortForward(obj, remote_port=remote_port, local_port=local_port) pf.start() try: + # PortForward.start() returns before the tunnel is listening. wait_until_listening(local_port) yield local_port finally: @@ -105,20 +62,13 @@ def object_port_forward(obj, remote_port: int): @contextmanager def service_port_forward(namespace: str, service: str, remote_port: int): - """Port-forward ``service:remote_port`` via kr8s; yield the local port.""" svc = kr8s.objects.Service.get(service, namespace=namespace) with object_port_forward(svc, remote_port) as local_port: yield local_port class IngressTransport: - """Reach the fingerprint API over the ERAG ingress with a Keycloak token. - - The token is fetched per session rather than cached, because a sweep runs for - hours and a cached one would expire mid-product. ``keycloak_helper`` is the - maintained helper (see :mod:`.authentication`), whose ``access_token`` - property already re-mints on each read. - """ + """Reach the fingerprint API over the ERAG ingress with a Keycloak token.""" def __init__(self, keycloak_helper, domain: str | None = None): self.keycloak_helper = keycloak_helper @@ -140,11 +90,7 @@ def session(self): class PortForwardTransport: - """Reach the fingerprint API by port-forwarding to the service via kr8s. - - The forward is scoped to the ``session()`` context and torn down afterwards, - so a sweep holds no tunnel open between property reads. - """ + """Reach the fingerprint API by port-forwarding to the service via kr8s.""" def __init__( self, @@ -164,16 +110,7 @@ def session(self): class HelperFingerprintClient: - """Adapter exposing the pysweep client interface over the suite helper. - - When pysweep runs as part of the e2e validation suite the maintained - :class:`tests.e2e.helpers.fingerprint_api_helper.FingerprintApiHelper` - already knows how to reach the fingerprint API over ingress (with the suite's - Keycloak auth). Reusing it keeps the e2e property tests exercising the same - transport the rest of the suite does, rather than a pysweep-only one. This - adapter just re-expresses it as the ``change_arguments`` / ``read_values`` - interface the property classes expect. - """ + """FingerprintClient interface over the suite's FingerprintApiHelper.""" def __init__(self, fingerprint_api_helper): self._helper = fingerprint_api_helper @@ -195,11 +132,7 @@ def read_values(self, component: str) -> dict: class FingerprintClient: - """Thin client over ``/v1/system_fingerprint/{change_arguments,config}``. - - Delegates connectivity to a transport so the same logic works whether the - API is reached over ingress or a port-forward. - """ + """Client for /v1/system_fingerprint/{change_arguments,config}.""" def __init__(self, transport, pipeline: str = PIPELINE, tenant: str = TENANT): self.transport = transport @@ -238,11 +171,7 @@ def read_values(self, component: str) -> dict: def default_transport(keycloak_helper=None): - """Pick a transport from the environment. - - ``PYSWEEP_FINGERPRINT_TRANSPORT=portforward`` (default) forwards to the - service; ``=ingress`` uses the ERAG domain and requires a Keycloak helper. - """ + """Pick a transport from PYSWEEP_FINGERPRINT_TRANSPORT: portforward (default) or ingress.""" mode = os.getenv("PYSWEEP_FINGERPRINT_TRANSPORT", "portforward").lower() if mode == "ingress": if keycloak_helper is None: diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py b/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py index a65c2922..d7125d62 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py @@ -1,26 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""The model the ChatQNA pipeline is **observed** to generate with. - -Not a knob: nothing here writes. The runner needs the served model whether or not -a sweep varies it, because ``benchmark.py``'s ``-m`` must be that model's -tokenizer (see ``pysweep_bench.resolve_tokenizer``). - -The model is read where it takes effect. ChatQNA's LLM microservice (``llm-usvc``) -sends ``LLM_MODEL_NAME`` as ``model=`` on every request, and that variable comes -from the ``llm-usvc-config`` ConfigMap through ``envFrom``, which is resolved once, -at container start. So :meth:`ServedModel.read` execs into every live replica for -the value its process actually has, and additionally requires that model to be a -Ready ``LLMInferenceService`` in ``llm-inference``: a pipeline pointed at a model -nothing serves answers nothing, and that is not a configuration to benchmark. - -**Values are catalog names, not repo ids.** ``llama3-8b-awq``, not -``casperhansen/llama-3-8b-instruct-awq``: the short name is what the gateway routes -on and what ``LLM_MODEL_NAME`` contains. :mod:`.model_catalog` maps it to the -HuggingFace repo id the tokenizer needs. -""" - import logging import kr8s @@ -32,22 +12,15 @@ logger = logging.getLogger(__name__) -# The ChatQNA LLM microservice: the Deployment is 'llm-svc-deployment' but the -# stable handle across chart versions is the label, and the container name is -# needed because the pod also has an init container. +# The label, unlike the Deployment name, is stable across chart versions. LLM_USVC_LABEL_SELECTOR = {"app.kubernetes.io/name": "llm-usvc"} +# Named because the pod also has an init container. LLM_USVC_CONTAINER = "llm-usvc" MODEL_NAME_ENV = "LLM_MODEL_NAME" class LLMInferenceService(APIObject): - """Minimal kr8s binding for KServe's ``LLMInferenceService``. - - Hand-written rather than looked up dynamically so the apiVersion this - property depends on is stated in one visible place: if the CRD moves past - ``v1alpha2``, the failure is a clear "not found" here rather than a subtle - mismatch elsewhere. - """ + """Minimal kr8s binding for KServe's ``LLMInferenceService``.""" kind = "LLMInferenceService" version = "serving.kserve.io/v1alpha2" @@ -69,18 +42,16 @@ def __init__( self.inference_namespace = inference_namespace def _pipeline_pods(self) -> list: - """Return the LLM microservice pods, or raise if none are selectable.""" try: pods = list( kr8s.get("pods", namespace=self.namespace, label_selector=LLM_USVC_LABEL_SELECTOR) ) - except Exception as exc: # noqa: BLE001 - reported as an unreadable state + except Exception as exc: # noqa: BLE001 raise PropertyReadError( f"Cannot list llm-usvc pods in ns/{self.namespace} " f"(selector {LLM_USVC_LABEL_SELECTOR}): {exc}" ) from exc - # Pods being replaced are not part of the observed configuration; counting - # them would make read() disagree with itself for the whole grace period. + # Terminating pods are not part of the observed configuration. live = [pod for pod in pods if not pod.metadata.get("deletionTimestamp")] if not live: raise PropertyReadError( @@ -90,17 +61,11 @@ def _pipeline_pods(self) -> list: return live def _pod_model(self, pod) -> str: - """Return the model name one replica's process actually has in its env. - - Read by exec, not from the ConfigMap or the pod spec, because ``envFrom`` - is resolved once at container start: the ConfigMap can already hold the - new value while this process still runs with the old one, and that gap is - precisely what must not be reported as converged. - """ + # Exec, not the ConfigMap: envFrom is resolved only at container start. command = ["sh", "-c", f"printf %s \"${MODEL_NAME_ENV}\""] try: result = pod.exec(command, container=LLM_USVC_CONTAINER) - except Exception as exc: # noqa: BLE001 - starting/terminating pod + except Exception as exc: # noqa: BLE001 raise PropertyReadError( f"Cannot read ${MODEL_NAME_ENV} from pod {pod.name}: {exc}" ) from exc @@ -116,10 +81,9 @@ def _pod_model(self, pod) -> str: return model def _model_ready(self, model: str) -> bool: - """Whether ``model`` is a Ready ``LLMInferenceService`` in the inference namespace.""" try: llmisvc = LLMInferenceService.get(model, namespace=self.inference_namespace) - except Exception as exc: # noqa: BLE001 - absent or CRD missing + except Exception as exc: # noqa: BLE001 logger.debug("LLMInferenceService %r not readable: %s", model, exc) return False conditions = (llmisvc.raw.get("status", {}) or {}).get("conditions", []) or [] @@ -129,15 +93,7 @@ def _model_ready(self, model: str) -> bool: ) def read(self) -> str: - """Return the model the pipeline is **observed** to be generating with. - - Raises :class:`PropertyReadError` unless the whole picture is consistent: - every live replica names the same model, and that model is Ready in - ``llm-inference``. Replicas disagreeing means a rollout is in flight; - the model not being Ready means the pipeline points somewhere that cannot - answer. Neither is a configuration a benchmark may be run against, so - both fail loudly rather than being reported as a model. - """ + """Return the model all live replicas agree on, raising unless it is Ready.""" observed = {pod.name: self._pod_model(pod) for pod in self._pipeline_pods()} distinct = set(observed.values()) diff --git a/src/tests/e2e/validation/pysweep/conftest.py b/src/tests/e2e/validation/pysweep/conftest.py index 70b71979..37e2a00f 100644 --- a/src/tests/e2e/validation/pysweep/conftest.py +++ b/src/tests/e2e/validation/pysweep/conftest.py @@ -1,29 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Fixtures for pysweep's e2e tests, run *inside* the validation suite. - -These tests live under ``validation`` (next to ``test_fingerprint.py`` et al.) -so they collect and report through the shared ``src/tests/e2e/conftest.py`` — -same invocation (``tox -e e2e``), same allure report, same session fixtures -(``k8s_helper``, ``keycloak_helper``, ``fingerprint_api_helper``, the -required-actions handling). The pysweep *package* itself lives at -``tests/e2e/benchmarks/chatqna/pysweep`` and is imported by absolute path. - -Per DESIGN.md objective 6, these are the "stay in sync with the deployment" -contract for the property classes: they exercise ``read`` / ``apply`` / -``is_satisfied`` against the live deployment so a drift in the runtime-API -contract fails here rather than silently mis-configuring a benchmark. - -Access is layered on the maintained suite helpers rather than duplicated: -- the fingerprint API is reached via the suite's ``fingerprint_api_helper`` - (ingress + Keycloak auth), falling back to a kr8s port-forward for - deployments where the API has no ingress route; -- the pysweep-specific RBAC preflight (:class:`KubernetesAccess`) is layered on - the suite ``k8s_helper`` to fail early and clearly if the kubeconfig identity - lacks a permission a sweep will need. -""" - import logging import pytest @@ -41,18 +18,13 @@ logger = logging.getLogger(__name__) -# Component asked for when probing whether the fingerprint API answers at all. -# Any deployed component would do; 'llm' is present in every ChatQNA pipeline. +# 'llm' is present in every ChatQNA pipeline. PROBE_COMPONENT = "llm" @pytest.fixture(scope="session") def pysweep_kubernetes_access(k8s_helper): - """Verify (without mutation) that pysweep has the cluster access it needs. - - Layered on the suite ``k8s_helper``. Skips if a required permission is - missing — that is an environment/RBAC problem, not a property regression. - """ + """Skip unless the kubeconfig identity has the RBAC a sweep needs.""" access = KubernetesAccess(k8s_helper=k8s_helper) try: access.verify() @@ -63,18 +35,10 @@ def pysweep_kubernetes_access(k8s_helper): @pytest.fixture(scope="session") def fingerprint_client(fingerprint_api_helper, pysweep_kubernetes_access): - """A pysweep FingerprintClient backed by the suite helper. - - Prefers the maintained ingress helper. If the fingerprint API is not routed - on this deployment (no ingress route -> the probe fails), falls back to a - kr8s port-forward to ``fingerprint-svc``. Skips if neither path reaches the - API, so individual tests fail only on genuine property regressions. - """ + """Prefer the ingress helper, fall back to a port-forward, skip if neither answers.""" if not cfg.get("fingerprint_enabled"): pytest.skip("Fingerprint is not deployed") - # Reachability probe. The reader is per-component, so probing needs a - # component name; 'llm' is the one every ChatQNA deployment has. helper_client = HelperFingerprintClient(fingerprint_api_helper) try: helper_client.read_values(PROBE_COMPONENT) diff --git a/src/tests/e2e/validation/pysweep/test_config_unit.py b/src/tests/e2e/validation/pysweep/test_config_unit.py index 21a48a81..4087904d 100644 --- a/src/tests/e2e/validation/pysweep/test_config_unit.py +++ b/src/tests/e2e/validation/pysweep/test_config_unit.py @@ -1,17 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the pysweep sweep-config validator. - -These test the schema/validation/expansion logic only — no cluster is needed, -so they run anywhere the requirements are installed. They assert three guarantees -the design leans on: (1) any YAML that violates the schema raises ConfigError, -(2) each declared deployment knob is bound to the correct Property class and -expands into the right cartesian product, and (3) client knobs are required, -bound to the right ``benchmark.py`` flag, and expand into their own separate -product (the runner's inner loop). -""" - import ast import textwrap from pathlib import Path @@ -29,9 +18,6 @@ ) from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens -# The client section is mandatory, so every config in these tests carries one. -# Kept minimal and boring: these values are never asserted on except by the -# client-specific tests below, which override what they care about. CLIENT = { "question_file": "questions-short.csv", "concurrency": 4, @@ -42,7 +28,6 @@ "warmup_requests": 1, } -# Same, as YAML, for the file-loading tests. CLIENT_YAML = """ client: question_file: questions-short.csv @@ -72,13 +57,7 @@ def _write(tmp_path, text): def _benchmark_option_flags(): - """The flags ``benchmark.parse_args`` adds, read from its source. - - Parsed rather than imported: ``benchmark.py`` pulls in ``transformers``, which - is only needed to *run* a load test and is not in the validation suite's - requirements (the runner imports it lazily for the same reason). Reading the - source keeps this check on the real parser without that dependency. - """ + """Parsed from source: importing benchmark.py pulls in transformers.""" source = ( Path(__file__).resolve().parents[3] / "e2e/benchmarks/chatqna/benchmark.py" ).read_text() @@ -101,28 +80,15 @@ def _benchmark_option_flags(): @allure.feature("pysweep") def test_config_with_only_client_knobs_is_valid(): - """A sweep may vary load alone: no deployment knobs is a valid sweep. - - Nothing is declared, so the deployment product is the single empty - combination — one pass with nothing to apply, benchmarking the deployment - exactly as it stands. - """ cfg = load_config(_sweep()) assert isinstance(cfg, SweepConfig) assert list(cfg.iter_settings()) == [] assert cfg.deployment_combinations() == [()] - # The client product is never empty either — the knobs are required. assert len(cfg.client_combinations()) == 1 @allure.feature("pysweep") def test_config_without_client_section_raises(): - """Load parameters must be declared; an empty config is no longer valid. - - An omitted deployment knob means "leave it alone", which is observable. An - omitted client knob has no such reading — the load test would silently run on - benchmark.py's defaults and no record of it would exist. - """ with pytest.raises(ConfigError, match="client"): load_config({}) @@ -156,10 +122,8 @@ def test_list_value_expands_to_product(): @allure.feature("pysweep") def test_omitted_knob_is_not_swept(): - """Optional *deployment* knobs left out contribute nothing to the sweep.""" cfg = load_config(_sweep(llms={})) assert list(cfg.iter_settings()) == [] - # No dimension to expand, so the product stays at its one empty combination. assert cfg.deployment_combinations() == [()] @@ -218,17 +182,9 @@ def test_max_new_tokens_is_runtime_api_plane(): assert MaxNewTokens.plane == Plane.RUNTIME_API -# -- client knobs ------------------------------------------------------------- - - @allure.feature("pysweep") @pytest.mark.parametrize("missing", sorted(CLIENT)) def test_every_scenario_client_knob_is_required(missing): - """Omitting any load parameter is a config error, naming the missing key. - - Parametrised over the whole set rather than spot-checking one, because the - point is that none of them silently falls back to benchmark.py's default. - """ section = {k: v for k, v in CLIENT.items() if k != missing} with pytest.raises(ConfigError, match=missing): load_config({"client": section}) @@ -236,7 +192,6 @@ def test_every_scenario_client_knob_is_required(missing): @allure.feature("pysweep") def test_client_knobs_bind_to_benchmark_flags(): - """Each client knob is bound to the benchmark.py option it renders to.""" cfg = load_config(_client()) bound = {path: arg.flag for path, arg, _ in cfg.iter_client_settings()} assert bound == { @@ -252,26 +207,17 @@ def test_client_knobs_bind_to_benchmark_flags(): @allure.feature("pysweep") def test_every_benchmark_option_is_mirrored(): - """The adapter must cover benchmark.parse_args exactly — no drift either way. - - A ``benchmark.py`` option missing here cannot be swept; one that exists here - but not there would be rendered into argv and rejected at run time. Compared - against the real parser so the two cannot diverge silently. - """ mirrored = [a.flag for a in client_args.CLIENT_ARGS] assert set(mirrored) == _benchmark_option_flags() assert len(mirrored) == len(set(mirrored)), "a benchmark option is mirrored twice" - # Mirrored != declarable: every option is covered, but -m is supplied by the - # runner (from the served model) and so has no field on ClientConfig. + # -m is derived from the served model, so it has no ClientConfig field. declarable = {a.yaml_name for a in client_args.CLIENT_ARGS if not a.derived} assert set(SweepConfig.model_fields["client"].annotation.model_fields) == declarable @allure.feature("pysweep") def test_client_list_expands_to_its_own_product(): - """Client knobs form a separate product — the runner's inner loop.""" cfg = load_config(_client(concurrency=[1, 16])) - # The deployment product is untouched by client knobs: still one empty pass. assert cfg.deployment_combinations() == [()] combos = cfg.client_combinations() assert len(combos) == 2 @@ -280,15 +226,8 @@ def test_client_list_expands_to_its_own_product(): @allure.feature("pysweep") def test_max_concurrency_is_the_widest_declared_value(): - """One bearer file serves every combination, so it is sized to the widest one. - - Taking the max rather than the last/first value is the point: a sweep that - ramps 1 -> 128 would otherwise leave the 128-worker run short of tokens, and - benchmark.py quits any worker whose bearer line is empty. - """ assert load_config(_client(concurrency=[1, 16, 128])).max_concurrency() == 128 assert load_config(_client(concurrency=[128, 16, 1])).max_concurrency() == 128 - # A scalar is the whole sweep's concurrency. assert load_config(_client(concurrency=4)).max_concurrency() == 4 @@ -308,12 +247,6 @@ def test_client_product_multiplies_dimensions(): @allure.feature("pysweep") def test_client_knobs_are_not_properties(): - """Client settings must never reach the apply/converge/verify path. - - ``iter_settings`` (which feeds ``combinations()`` and thus ``build_property``) - yields only Property-bound knobs, so a client knob cannot be mistaken for - something the runner should apply to the cluster. - """ cfg = load_config(_client(concurrency=[1, 16])) assert list(cfg.iter_settings()) == [] assert not hasattr(cfg.client_combinations()[0][0], "property_cls") @@ -321,11 +254,9 @@ def test_client_knobs_are_not_properties(): @allure.feature("pysweep") def test_server_and_bearer_file_are_optional_and_not_swept(): - """The auto-provisioned connection settings default to absent.""" cfg = load_config(_client()) assert cfg.client_provisioning_argv() == [] assert "server" not in cfg.declared_client_names() - # Declared, they render once for the whole sweep rather than as a dimension. cfg = load_config(_client(server="https://erag.com/api/v1/chatqna", bearer_file="uat.txt")) assert cfg.client_provisioning_argv() == [ "-s", "https://erag.com/api/v1/chatqna", "-b", "uat.txt", @@ -336,11 +267,7 @@ def test_server_and_bearer_file_are_optional_and_not_swept(): @allure.feature("pysweep") @pytest.mark.parametrize("bad", ["3 minutes", "3", "m", "3d", 3, ""]) def test_duration_must_be_a_parsable_duration(bad): - """benchmark.duration_to_seconds raises KeyError on anything else. - - Catching the shape here turns a crash an hour into a sweep into a config - error before anything is applied. - """ + """benchmark.duration_to_seconds raises KeyError on anything else.""" with pytest.raises(ConfigError): load_config(_client(duration=bad)) @@ -348,7 +275,6 @@ def test_duration_must_be_a_parsable_duration(bad): @allure.feature("pysweep") @pytest.mark.parametrize("bad", [0, -1, "many", 1.5]) def test_concurrency_must_be_a_positive_integer(bad): - """``-c 0`` starts no workers and would produce an empty result CSV.""" with pytest.raises(ConfigError): load_config(_client(concurrency=bad)) @@ -356,7 +282,6 @@ def test_concurrency_must_be_a_positive_integer(bad): @allure.feature("pysweep") @pytest.mark.parametrize("knob", ["input_tokens", "warmup_requests", "failures_allowed"]) def test_zero_is_allowed_where_it_is_meaningful(knob): - """0 is a real setting for these: no input fixing, no warmup, no failures.""" cfg = load_config(_client(**{knob: 0})) assert next(v for p, _, v in cfg.iter_client_settings() if p.endswith(knob)) == [0] @@ -364,21 +289,14 @@ def test_zero_is_allowed_where_it_is_meaningful(knob): @allure.feature("pysweep") def test_unknown_client_knob_raises(): with pytest.raises(ConfigError): - load_config(_client(concurency=4)) # missing 'r' + load_config(_client(concurency=4)) @allure.feature("pysweep") def test_tokenizer_cannot_be_declared(): - """``-m`` is not a knob: it must be the served model, so it is derived. - - Rejecting the key rather than accepting and overriding it is the point — the - only thing declaring it could express is a tokenizer that disagrees with the - model whose tokens are being counted. - """ with pytest.raises(ConfigError): load_config(_client(tokenizer="nomic-ai/nomic-embed-text-v1")) assert client_args.TOKENIZER.derived - # Still mirrored, so the runner can render it; just not swept or declared. assert client_args.TOKENIZER in client_args.CLIENT_ARGS assert not client_args.TOKENIZER.sweepable cfg = load_config(_client()) @@ -387,7 +305,6 @@ def test_tokenizer_cannot_be_declared(): @allure.feature("pysweep") def test_varying_paths_reports_only_multi_valued_knobs(): - """Result files are named by what varies; scalars distinguish nothing.""" cfg = load_config( { "client": {**CLIENT, "concurrency": [1, 16]}, @@ -399,7 +316,6 @@ def test_varying_paths_reports_only_multi_valued_knobs(): @allure.feature("pysweep") def test_shipped_example_sweep_config_is_valid(): - """The committed configs/sweep.yaml must load (docs stay honest).""" example = ( Path(__file__).resolve().parents[3] / "e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml" @@ -409,9 +325,6 @@ def test_shipped_example_sweep_config_is_valid(): assert cfg.client_combinations() -# -- run config (--config) ---------------------------------------------------- - - @allure.feature("pysweep") def test_run_config_reads_display_kubernetes_client_logs(tmp_path): path = tmp_path / "config.yaml" @@ -421,15 +334,13 @@ def test_run_config_reads_display_kubernetes_client_logs(tmp_path): @allure.feature("pysweep") def test_kubernetes_client_logs_default_to_off(): - """The kr8s/httpx per-call chatter is noise by default (one line per request).""" assert load_run_config({}).display_kubernetes_client_logs is False @allure.feature("pysweep") def test_run_config_rejects_unknown_key(): - """Same strictness as the sweep config: a typo must not be ignored.""" with pytest.raises(ConfigError): - load_run_config({"display_kubernetes_client_log": False}) # missing trailing 's' + load_run_config({"display_kubernetes_client_log": False}) @allure.feature("pysweep") @@ -440,7 +351,6 @@ def test_run_config_rejects_non_boolean(): @allure.feature("pysweep") def test_shipped_example_run_config_is_valid(): - """The committed configs/general.yaml must load (docs stay honest).""" example = ( Path(__file__).resolve().parents[3] / "e2e/benchmarks/chatqna/pysweep/configs/general.yaml" diff --git a/src/tests/e2e/validation/pysweep/test_max_tokens.py b/src/tests/e2e/validation/pysweep/test_max_tokens.py index cda86cad..81334e8d 100644 --- a/src/tests/e2e/validation/pysweep/test_max_tokens.py +++ b/src/tests/e2e/validation/pysweep/test_max_tokens.py @@ -1,17 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""e2e test for the ``MaxNewTokens`` property. - -This is the DESIGN.md objective-6 contract: it exercises ``read`` / ``apply`` / -``is_satisfied`` against the live ``system_fingerprint`` API, so if the -deployment's runtime-API contract drifts (endpoint path, payload shape, or the -``values`` response key) this test fails *before* a benchmark silently runs -against the wrong configuration. - -The test restores the original value on teardown so it leaves no side effect. -""" - import logging import allure @@ -29,7 +18,6 @@ def max_tokens_property(fingerprint_client): @pytest.fixture def restore_max_tokens(max_tokens_property): - """Snapshot the observed value and restore it after the test.""" original = max_tokens_property.read() yield original max_tokens_property.apply(original) @@ -37,22 +25,12 @@ def restore_max_tokens(max_tokens_property): @allure.feature("pysweep") def test_read_returns_int(max_tokens_property): - """read() must return an int parsed from observed API state. - - A missing value is not acceptable — read() raises rather than returning - None (see MaxNewTokens.read / PropertyReadError), so any deployment where - the value is absent fails here. - """ value = max_tokens_property.read() assert isinstance(value, int) @allure.feature("pysweep") def test_apply_then_read_reflects_desired(max_tokens_property, restore_max_tokens): - """apply(desired) makes the observed value satisfy desired. - - Uses a value different from the current one so the write path is exercised. - """ current = restore_max_tokens desired = 256 if current != 256 else 128 @@ -64,11 +42,9 @@ def test_apply_then_read_reflects_desired(max_tokens_property, restore_max_token @allure.feature("pysweep") def test_apply_is_idempotent(max_tokens_property, restore_max_tokens): - """A second apply of an already-satisfied value is a no-op that still holds.""" desired = 200 max_tokens_property.apply(desired) assert max_tokens_property.is_satisfied(desired) - # Applying again must not change or break the observed state. max_tokens_property.apply(desired) assert max_tokens_property.read() == desired diff --git a/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py b/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py index 3cee5d8d..62a1f886 100644 --- a/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py +++ b/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py @@ -1,20 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the ``MaxNewTokens`` property. - -The fingerprint client is stubbed, so these cover the property's own logic with no -deployment: the request body it sends, the component it reads back from, and its -refusal to guess when the observed value is missing or unparseable. The live -contract (that the deployment really exposes ``llm``/``max_new_tokens`` at this -shape) is ``test_max_tokens.py``. - -The payload assertions are the API contract: ``change_arguments`` takes -``[{"name": "llm", "data": {"max_new_tokens": N}}]``, and a property that posted -anything else would be accepted and change nothing — the worst outcome for a -sweep, since every row would then be a rerun of the previous configuration. -""" - import allure import pytest @@ -23,8 +9,6 @@ class FakeClient: - """Records what was written and read, and serves a settable values dict.""" - def __init__(self, values=None): self.values = {"max_new_tokens": 128} if values is None else values self.bodies = [] @@ -42,7 +26,6 @@ def change_arguments(self, body): @allure.feature("pysweep") def test_is_runtime_api_plane(): - """Runtime-API plane: varies as an inner dimension, no rollout to wait out.""" assert MaxNewTokens.plane == Plane.RUNTIME_API @@ -53,7 +36,6 @@ def test_read_returns_the_observed_value(): @allure.feature("pysweep") def test_read_asks_for_the_llm_component(): - """The reader is per-component; another component could carry a same-named key.""" client = FakeClient() MaxNewTokens(client).read() assert client.read_components == ["llm"] @@ -61,17 +43,12 @@ def test_read_asks_for_the_llm_component(): @allure.feature("pysweep") def test_read_coerces_a_string_value(): - """The API may return the value as a string; the sweep compares ints.""" assert MaxNewTokens(FakeClient({"max_new_tokens": "512"})).read() == 512 @allure.feature("pysweep") def test_read_raises_when_the_parameter_is_absent(): - """Unknown is not a value. - - Returning ``None`` would make ``is_satisfied`` permanently false and the sweep - would re-apply forever; failing says which keys were actually offered. - """ + """The error lists the keys that were offered.""" with pytest.raises(PropertyReadError) as excinfo: MaxNewTokens(FakeClient({"streaming": True})).read() assert "streaming" in str(excinfo.value) @@ -85,7 +62,6 @@ def test_read_raises_on_an_unparseable_value(): @allure.feature("pysweep") def test_is_satisfied_compares_as_integers(): - """YAML can hand over a string; a type mismatch must not force a needless write.""" prop = MaxNewTokens(FakeClient({"max_new_tokens": 128})) assert prop.is_satisfied("128") assert not prop.is_satisfied(256) @@ -109,7 +85,6 @@ def test_apply_then_read_reflects_the_desired_value(): @allure.feature("pysweep") def test_apply_skips_the_write_when_already_satisfied(): - """Idempotence: re-running a combination must not touch the deployment.""" client = FakeClient({"max_new_tokens": 128}) MaxNewTokens(client).apply(128) assert client.bodies == [] @@ -117,7 +92,6 @@ def test_apply_skips_the_write_when_already_satisfied(): @allure.feature("pysweep") def test_apply_coerces_the_desired_value(): - """A value read from YAML arrives as a string; the API expects a number.""" client = FakeClient({"max_new_tokens": 128}) MaxNewTokens(client).apply("256") (body,) = client.bodies diff --git a/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py b/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py index d122c083..3aecf66a 100644 --- a/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py +++ b/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py @@ -1,23 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the model-manager catalog reader. - -Two things are being pinned here, both of which pysweep depends on and neither of -which it owns: - -* **The catalog's shape** — ``models:`` is a *list* of entries each carrying a - ``name`` and a ``model_id``. ``CATALOG_SAMPLE`` below is copied from the - deployed ``env/local/models.yaml``, so a format change in model-manager's - catalog fails here rather than as an empty "available models" list in a - preflight message. -* **Which file is read** — the deployment's own catalog, not this repo's shipped - default, since the two drift and only the former lists the names the cluster was - built from. - -No cluster and no model-manager CLI are involved: this module is a YAML reader. -""" - from pathlib import Path import allure @@ -33,8 +16,7 @@ tokenizer_for, ) -# Trimmed from the deployed env/local/models.yaml: two model entries plus the -# surrounding sections the reader has to ignore. +# Trimmed copy of the deployed env/local/models.yaml. CATALOG_SAMPLE = """\ defaults: namespace: llm-inference @@ -78,7 +60,6 @@ def test_loads_every_named_model(catalog_file): @allure.feature("pysweep") def test_entries_are_returned_verbatim(catalog_file): - """Callers read whichever field they need, so nothing is dropped or renamed.""" entry = model_entry("llama3-8b-awq") assert entry["model_id"] == "casperhansen/llama-3-8b-instruct-awq" assert entry["cpu"] == 16 @@ -87,29 +68,17 @@ def test_entries_are_returned_verbatim(catalog_file): @allure.feature("pysweep") def test_known_models_is_sorted(catalog_file): - """These names go into error messages, where a stable order is what makes them readable.""" assert known_models() == ["llama3-8b-awq", "qwen3-5-2b-ovms"] @allure.feature("pysweep") def test_tokenizer_is_the_huggingface_repo_id(catalog_file): - """The name/repo-id distinction the whole module exists for. - - ``LLM_MODEL_NAME`` carries the catalog name; ``benchmark.py``'s - ``-m`` needs the repo id. Conflating them would count every token with the - wrong tokenizer. - """ assert tokenizer_for("llama3-8b-awq") == "casperhansen/llama-3-8b-instruct-awq" assert tokenizer_for("qwen3-5-2b-ovms") == "OpenVINO/Qwen3.5-2B-int4-ov" @allure.feature("pysweep") def test_unknown_model_error_lists_the_available_names(catalog_file): - """The failure is nearly always a typo or a repo id in a name's place. - - Both are obvious the moment the real names are on screen, so the message - carries them. - """ with pytest.raises(CatalogError) as excinfo: model_entry("casperhansen/llama-3-8b-instruct-awq") message = str(excinfo.value) @@ -119,7 +88,6 @@ def test_unknown_model_error_lists_the_available_names(catalog_file): @allure.feature("pysweep") def test_entry_without_a_model_id_has_no_tokenizer(tmp_path, monkeypatch): - """Better to fail than to report throughput per token off a guessed tokenizer.""" path = tmp_path / "models.yaml" path.write_text("models:\n - name: mystery\n category: llm\n") monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(path)) @@ -130,7 +98,6 @@ def test_entry_without_a_model_id_has_no_tokenizer(tmp_path, monkeypatch): @allure.feature("pysweep") def test_env_var_selects_the_catalog(catalog_file, tmp_path, monkeypatch): - """The deployment's catalog must win over this repo's shipped default.""" assert catalog_path() == catalog_file other = tmp_path / "other.yaml" @@ -141,11 +108,6 @@ def test_env_var_selects_the_catalog(catalog_file, tmp_path, monkeypatch): @allure.feature("pysweep") def test_mm_config_is_honoured_as_a_fallback(tmp_path, monkeypatch): - """``MM_CONFIG`` is what the model-manager wrapper exports. - - Honouring it means pysweep reads the same catalog the deploy will, with - nothing extra to configure. - """ path = tmp_path / "models.yaml" path.write_text(CATALOG_SAMPLE) monkeypatch.delenv("PYSWEEP_MODEL_CATALOG", raising=False) @@ -156,7 +118,6 @@ def test_mm_config_is_honoured_as_a_fallback(tmp_path, monkeypatch): @allure.feature("pysweep") def test_pysweep_var_wins_over_mm_config(tmp_path, monkeypatch): - """An explicit pysweep setting is the one place to override a wrong environment.""" preferred = tmp_path / "preferred.yaml" preferred.write_text(CATALOG_SAMPLE) other = tmp_path / "other.yaml" @@ -169,7 +130,6 @@ def test_pysweep_var_wins_over_mm_config(tmp_path, monkeypatch): @allure.feature("pysweep") def test_a_configured_path_that_does_not_exist_is_an_error(tmp_path, monkeypatch): - """Silently falling through would read a *different* catalog than asked for.""" monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(tmp_path / "missing.yaml")) with pytest.raises(CatalogError, match="PYSWEEP_MODEL_CATALOG"): catalog_path() @@ -177,7 +137,6 @@ def test_a_configured_path_that_does_not_exist_is_an_error(tmp_path, monkeypatch @allure.feature("pysweep") def test_no_catalog_anywhere_is_an_error(monkeypatch): - """An empty catalog would make every model name 'unknown', which misreports the cause.""" monkeypatch.delenv("PYSWEEP_MODEL_CATALOG", raising=False) monkeypatch.delenv("MM_CONFIG", raising=False) monkeypatch.setattr(model_catalog, "CATALOG_FALLBACKS", ()) @@ -187,20 +146,18 @@ def test_no_catalog_anywhere_is_an_error(monkeypatch): @allure.feature("pysweep") -# Explicit ids: these values are multi-line YAML, and the suite's conftest names -# per-test log files after the test id. +# Explicit ids: conftest names per-test log files after the test id. @pytest.mark.parametrize( "content", [ - "models: [", # not YAML at all - "- just\n- a\n- list\n", # not a mapping at the top level - "models:\n llama3-8b-awq:\n model_id: org/x\n", # a mapping, not a list - "defaults:\n namespace: llm-inference\n", # no models section + "models: [", + "- just\n- a\n- list\n", + "models:\n llama3-8b-awq:\n model_id: org/x\n", + "defaults:\n namespace: llm-inference\n", ], ids=["not-yaml", "top-level-list", "models-as-mapping", "no-models-section"], ) def test_a_malformed_catalog_is_reported_as_such(tmp_path, monkeypatch, content): - """Every one of these would otherwise surface as 'model X is not in the catalog'.""" path = tmp_path / "models.yaml" path.write_text(content) monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(path)) @@ -211,12 +168,7 @@ def test_a_malformed_catalog_is_reported_as_such(tmp_path, monkeypatch, content) @allure.feature("pysweep") def test_the_repo_default_catalog_is_readable(): - """The shipped ``deployment/models.yaml`` must parse with this reader. - - It is the fallback for anyone running pysweep from a checkout, and it is also - the check that the fallback path (``paths.REPO_ROOT``) still points at the repo - root after any move of this package. - """ + """Also checks that ``paths.REPO_ROOT`` still points at the repo root.""" repo_default = model_catalog.CATALOG_FALLBACKS[-1] models = known_models(repo_default) assert models, "the shipped catalog declares no models" @@ -226,12 +178,7 @@ def test_the_repo_default_catalog_is_readable(): @allure.feature("pysweep") def test_the_rag_catalog_is_preferred_over_the_platform_one(): - """An install has both; the RAG pipeline's models come from models-rag.yaml. - - The platform catalog shares only some names (it calls Llama 3.1 8B - 'llama-3-1-8b' where the RAG one says 'llama3-1-8b'), so reading it first - would fail to resolve models the pipeline really serves. - """ + """Fallbacks pair models-rag.yaml then models.yaml per root, then the repo default.""" fallbacks = [Path(p).name for p in model_catalog.CATALOG_FALLBACKS] for root_rag, root_platform in zip(fallbacks[0:-1:2], fallbacks[1:-1:2]): assert (root_rag, root_platform) == ("models-rag.yaml", "models.yaml") diff --git a/src/tests/e2e/validation/pysweep/test_paths_unit.py b/src/tests/e2e/validation/pysweep/test_paths_unit.py index 8ab3f856..0d57b6f1 100644 --- a/src/tests/e2e/validation/pysweep/test_paths_unit.py +++ b/src/tests/e2e/validation/pysweep/test_paths_unit.py @@ -1,18 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Unit tests for where pysweep looks for the installed environment. - -Two regressions are pinned: - -* **The deploy root follows the checkout.** The installer keeps this repo at - ``/ext/enterprise.ai-erag``, so the environment is found next to it - for whichever user installed it, not only under ``/root/ai-solutions``. -* **An unreadable candidate is skipped, not fatal.** On Python < 3.14 - ``Path.is_dir()`` raises ``PermissionError`` for a path under ``/root``; probing - that fallback as a non-root user used to crash the sweep before it started. -""" - from pathlib import Path import allure @@ -28,7 +16,6 @@ @allure.feature("pysweep") def test_repo_root_is_the_checkout(): - """``REPO_ROOT`` must still point at the repo after any move of the package.""" assert (paths.REPO_ROOT / "src" / "tests" / "e2e").is_dir() assert (paths.REPO_ROOT / "deployment").is_dir() @@ -42,7 +29,6 @@ def test_deploy_root_is_derived_from_an_installer_layout(monkeypatch, tmp_path): @allure.feature("pysweep") def test_a_plain_checkout_only_falls_back_to_root(monkeypatch, tmp_path): - """Outside ``ext/`` the checkout's parent is not a deploy root; don't guess one.""" monkeypatch.setattr(paths, "REPO_ROOT", tmp_path / "PycharmProjects" / "ai-erag") assert paths.deploy_roots() == (paths.ROOT_DEPLOY_ROOT,) @@ -85,7 +71,6 @@ def test_no_build_config_dir_anywhere_is_an_error(monkeypatch): @allure.feature("pysweep") def test_build_config_files_match_the_e2e_suite(): - """pysweep must load the same env files ``tests/e2e/conftest.py`` does.""" conftest = (paths.REPO_ROOT / "src" / "tests" / "e2e" / "conftest.py").read_text() for filename in BUILD_CONFIG_FILES: assert f'"{filename}"' in conftest, filename diff --git a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py index b710aefa..2a8df92f 100644 --- a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -1,15 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the pysweep_bench orchestration. - -These cover the glue logic — argument splitting, property building, the -apply/converge/verify step, and the nesting of the client loop inside the -deployment loop — with a fake fingerprint client, so no cluster, transformers, or -benchmark load is needed. The actual benchmark run (``benchmark.run_benchmark``) -is exercised by the existing benchmark tooling, not re-tested here. -""" - import argparse import ast import csv @@ -35,13 +26,7 @@ from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens from tests.e2e.benchmarks.chatqna.pysweep.served_model import ServedModel -# The client section is mandatory; these tests care about the deployment side, so -# it stays fixed and minimal except where a test overrides a knob. -# -# question_file is the real corpus path (relative to pysweep_bench.py, hence the -# '../'), because the tests that call main() run preflight(), which -# resolves and stats it. A placeholder name would fail there rather than in the -# logic under test. +# question_file must exist (relative to pysweep_bench.py): main() runs preflight, which stats it. CLIENT = { "question_file": "../questions-short.csv", "concurrency": 4, @@ -62,16 +47,7 @@ def _client(**overrides): def _parse_benchmark_argv(argv): - """Parse argv with a parser rebuilt from ``benchmark.parse_args``'s source. - - Predates the lazy ``transformers`` import inside ``run_benchmark``: importing - ``benchmark`` used to mean importing ``transformers``, which this suite does not - install, so the parser was rebuilt from the file instead. That is no longer a - constraint — this could call ``benchmark.parse_args`` directly — but rebuilding - from the real source is still a genuine check that the adapter's argv is - acceptable: a flag or type the tool does not actually declare would not be - reconstructed here either. - """ + """Parse argv with a parser rebuilt from ``benchmark.parse_args``'s source.""" source = ( Path(__file__).resolve().parents[3] / "e2e/benchmarks/chatqna/benchmark.py" ).read_text() @@ -98,12 +74,7 @@ def _parse_benchmark_argv(argv): class FakeFingerprintClient: - """In-memory stand-in for FingerprintClient that actually applies writes. - - The real reader is per-component; the properties under test here all read the - values of the component they write, so one dict is enough and the component - name is ignored. - """ + """In-memory FingerprintClient that applies writes; the component name is ignored.""" def __init__(self, initial=999): self.params = {"max_new_tokens": initial} @@ -138,7 +109,6 @@ def test_parse_args_without_benchmark_args(): @allure.feature("pysweep") def test_parse_args_run_config_is_optional(): - """``--sweep`` alone is valid; ``--config`` is the optional run config.""" assert psb.parse_args(["--sweep", "s.yaml"]).config is None args = psb.parse_args(["--sweep", "s.yaml", "--config", "c.yaml"]) assert (args.sweep, args.config) == ("s.yaml", "c.yaml") @@ -154,7 +124,6 @@ def test_build_property_dispatches_runtime_api_to_fingerprint_client(): @allure.feature("pysweep") def test_build_property_dispatches_k8s_plane_without_fingerprint_client(): - """K8s-plane properties reach the cluster themselves, so take no client.""" class _K8sKnob(Property): plane = Plane.K8S_SPEC @@ -174,12 +143,6 @@ def apply(self, desired): @allure.feature("pysweep") def test_apply_combination_reports_unestablishable_state_as_sweep_error(monkeypatch): - """A property that cannot establish its value aborts the sweep cleanly. - - E.g. a value the deployment rejects: apply raises PropertyApplyError and - apply_combination must surface it as a SweepError naming the knob, rather - than letting it escape as a crash. - """ cfg = load_config(_sweep(llms={"max_new_tokens": 128})) def refuse(self, desired): @@ -192,7 +155,6 @@ def refuse(self, desired): @allure.feature("pysweep") def test_apply_combination_reports_failed_convergence_as_sweep_error(monkeypatch): - """Applied but never ready must abort, not benchmark the old config.""" cfg = load_config(_sweep(llms={"max_new_tokens": 128})) monkeypatch.setattr(MaxNewTokens, "apply", lambda self, desired: None) @@ -224,35 +186,19 @@ def test_apply_combination_raises_when_not_converged(): @allure.feature("pysweep") def test_combination_slug_is_unique_per_combination(): - """Each combination must map to a distinct result filename fragment. - - Regression guard: combinations previously shared one timestamped CSV, so a - later combination silently clobbered an earlier one's results. - """ cfg = load_config(_sweep(llms={"max_new_tokens": [128, 256]})) slugs = [psb.combination_slug(c) for c in cfg.deployment_combinations()] assert slugs == ["max_new_tokens-128", "max_new_tokens-256"] assert len(set(slugs)) == len(slugs) -# -- client knobs: the innermost loop ----------------------------------------- - - class FakeBenchmark: - """Stand-in for the benchmark module, recording each invocation. - - Lets the nesting be asserted without transformers, a cluster, or minutes of - load: what matters is *which* argv each run got and in what order. - """ + """Stand-in for the benchmark module that records each invocation.""" def __init__(self, rows=1): self.calls = [] self._rows = rows - #: Mirrors benchmark.parse_args's signature without importing it (that pulls - #: in transformers, which only a real load test needs). The faithfulness of - #: the mirror is what test_rendered_argv_is_accepted_by_benchmark_parse_args - #: checks against the real parser. parse_args = staticmethod(lambda argv: _parse_benchmark_argv(argv)) def run_benchmark(self, args, output_file=None): @@ -264,18 +210,10 @@ def run_benchmark(self, args, output_file=None): @allure.feature("pysweep") def test_client_combination_renders_to_benchmark_argv(): - """Every declared client knob reaches benchmark.py as its own flag. - - ``-m`` is absent by design: it is not declared, so the client combination - cannot carry it. The runner appends it from the served model (see - ``test_tokenizer_comes_from_the_served_model``). - """ + """``-m`` is absent: the runner appends it from the served model.""" cfg = load_config(_client(concurrency=16)) argv = BenchmarkClientArgs.from_settings(cfg.client_combinations()[0]).to_argv() - # The DECLARED path, verbatim: the adapter is a pure translation. Anchoring it - # to an absolute path happens later, at the argv boundary - # (``resolve_question_file_argv``), so that the recorded value stays the one - # the config author wrote. + # The declared path verbatim; anchoring happens later, at the argv boundary. assert argv == [ "-f", "../questions-short.csv", "-c", "16", @@ -289,12 +227,7 @@ def test_client_combination_renders_to_benchmark_argv(): @allure.feature("pysweep") def test_rendered_argv_is_accepted_by_benchmark_parse_args(): - """The adapter's output must actually parse — the mirror has to be faithful. - - Types matter as much as flag names: every value is rendered through ``str``, - so a knob bound to an option benchmark.py declares as ``type=int`` has to - round-trip back to an int. - """ + """Values rendered through ``str`` must round-trip to benchmark.py's declared types.""" cfg = load_config(_client(concurrency=16, input_tokens=0)) argv = BenchmarkClientArgs.from_settings(cfg.client_combinations()[0]).to_argv() parsed = _parse_benchmark_argv(argv) @@ -304,11 +237,6 @@ def test_rendered_argv_is_accepted_by_benchmark_parse_args(): @allure.feature("pysweep") def test_client_knobs_vary_innermost(monkeypatch, tmp_path): - """The whole point of the nesting: load varies within a fixed deployment. - - Each deployment combination must be applied once and then benchmarked under - every client combination before the next (expensive) deployment change. - """ monkeypatch.chdir(tmp_path) cfg = load_config( {"client": {**CLIENT, "concurrency": [1, 16]}, "llms": {"max_new_tokens": [128, 256]}} @@ -333,9 +261,7 @@ def record_apply(combination, client): assert psb.main(["--sweep", "ignored.yaml"]) == 0 - # Two deployment combinations, applied once each — not once per load level. assert applied == [(128,), (256,)] - # ...each benchmarked under both concurrencies before the next apply. assert [args.c for args, _ in fake.calls] == [1, 16, 1, 16] assert [args.d for args, _ in fake.calls] == ["3m"] * 4 # The derived tokenizer reaches every run, though no config declares it. @@ -344,14 +270,6 @@ def record_apply(combination, client): @allure.feature("pysweep") def test_sweep_writes_one_summary_row_per_run(monkeypatch, tmp_path): - """The sweep's own artifact: every run, its knob values, and its KPIs. - - Checked through ``main`` rather than against ``SweepSummary`` directly - (``test_results.py`` covers the arithmetic), because what could realistically - break here is the wiring: a row per run, the observed deployment value and - the declared client value in their dotted-path columns, and the served model - recorded even though nothing declares it. - """ monkeypatch.chdir(tmp_path) cfg = load_config( {"client": {**CLIENT, "concurrency": [1, 16]}, "llms": {"max_new_tokens": [128, 256]}} @@ -378,30 +296,20 @@ def test_sweep_writes_one_summary_row_per_run(monkeypatch, tmp_path): assert [(r["llms.max_new_tokens"], r["client.concurrency"]) for r in rows] == [ ("128", "1"), ("128", "16"), ("256", "1"), ("256", "16"), ] - # Constant knobs get columns too, so a row says what it was measured under. assert {r["client.duration"] for r in rows} == {"3m"} # FakeBenchmark writes 128,128,0.8,6.9,,200 twice per run. assert {r["requests"] for r in rows} == {"2"} assert {r["mean_ttft"] for r in rows} == {"0.8"} assert {r["mean_tpot"] for r in rows} == {str(round((6.9 - 0.8) / 127, 6))} assert {r["served_model"] for r in rows} == {"served/model"} - # And each row points back at the per-request CSV it summarises, by a path - # relative to the summary itself — so the whole directory can be copied off the - # benchmark host with its pointers intact. + # Relative to the summary, so the directory can be copied off the host intact. assert all(not Path(r["result_file"]).is_absolute() for r in rows) assert all((summary_file.parent / r["result_file"]).exists() for r in rows) - # ...and that CSV lives in the per-case subdirectory, not beside the summary. assert {Path(r["result_file"]).parent.name for r in rows} == {results.PER_CASE_DIR_NAME} @allure.feature("pysweep") def test_the_previous_sweeps_results_are_gone_before_this_one_starts(monkeypatch, tmp_path): - """``--summaries`` is a clean slate per sweep, wired through ``main``. - - ``test_results.py`` covers what gets deleted; what matters here is that the - sweep does it at all. Without it, a per-case CSV from a longer previous sweep - survives with no row in the new summary, and reads exactly like a result of it. - """ monkeypatch.chdir(tmp_path) cfg = load_config(_client()) stale = tmp_path / "out" / results.PER_CASE_DIR_NAME / "bench_from_last_week.result.csv" @@ -421,16 +329,11 @@ def test_the_previous_sweeps_results_are_gone_before_this_one_starts(monkeypatch assert psb.main(["--sweep", "ignored.yaml", "--summaries", "out"]) == 0 assert not stale.exists() - # And this sweep's own run is there, so the wipe happened before it, not after. assert [p.name for p in stale.parent.iterdir()] == ["bench_single.result.csv"] def _passthrough_provision(benchmark_args, workers=1): - """provision_benchmark_target with no cluster: yield the args unchanged. - - ``workers`` is accepted and ignored — nothing is minted here, but the runner - passes the sweep's widest concurrency, so the signature has to match. - """ + """provision_benchmark_target without a cluster.""" from contextlib import contextmanager @contextmanager @@ -441,23 +344,11 @@ def cm(): def _install_fake_benchmark(monkeypatch, fake): - """Point the runner's module-level ``benchmark`` at ``fake``. - - Without it, a test that runs ``main()`` would start a real load test against - whatever ``-s`` happened to be set. One binding is enough: ``main()`` reads the - name off this module, and monkeypatch restores it afterwards. - """ monkeypatch.setattr(psb, "benchmark", fake) @allure.feature("pysweep") def test_result_file_names_are_unique_per_run(): - """Deployment x client must not collide: each run gets its own CSV. - - Regression guard in the same spirit as the per-combination slug — with the - client loop added, a name built from the deployment alone would have every - load level overwrite the previous one's results. - """ cfg = load_config( {"client": {**CLIENT, "concurrency": [1, 16]}, "llms": {"max_new_tokens": [128, 256]}} ) @@ -478,7 +369,6 @@ def test_result_file_names_are_unique_per_run(): @allure.feature("pysweep") def test_result_file_name_omits_constant_knobs(): - """Only the knobs that vary are named; the rest are constant and logged.""" cfg = load_config(_client(concurrency=[1, 16])) name = psb.result_file_name((), cfg.client_combinations()[0], only=cfg.varying_paths()) assert name == "bench_concurrency-1.result.csv" @@ -486,13 +376,7 @@ def test_result_file_name_omits_constant_knobs(): @allure.feature("pysweep") def test_result_file_name_stays_within_the_filesystem_limit(): - """Naming every declared knob can overflow the 255-byte filename limit. - - Why names carry only the varying knobs. The values here are all plausible — - an HF repo id and a question file under a real path — and together they push - the all-knobs name past what the filesystem accepts, while the filtered name - stays short regardless of how many knobs are held constant. - """ + """Naming every declared knob would overflow the 255-byte filename limit.""" cfg = load_config( { "client": { @@ -512,7 +396,7 @@ def test_result_file_name_stays_within_the_filesystem_limit(): assert len(Path(psb.result_file_name(combination, client_combination)).name) > 255 filtered = psb.result_file_name(combination, client_combination, only=cfg.varying_paths()) assert len(Path(filtered).name) <= 255 - # And the shipped example, whatever it declares, must also be nameable. + # The shipped example must also be nameable. example = ( Path(__file__).resolve().parents[3] / "e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml" @@ -526,7 +410,6 @@ def test_result_file_name_stays_within_the_filesystem_limit(): @allure.feature("pysweep") def test_result_file_name_falls_back_when_nothing_varies(): - """A single-combination sweep still needs a name.""" cfg = load_config(_client()) name = psb.result_file_name((), cfg.client_combinations()[0], only=cfg.varying_paths()) assert name == "bench_single.result.csv" @@ -534,13 +417,7 @@ def test_result_file_name_falls_back_when_nothing_varies(): @allure.feature("pysweep") def test_tokenizer_is_the_catalog_model_id_not_the_served_name(monkeypatch, tmp_path): - """The two names differ, and using the wrong one breaks every token count. - - What the deployment serves is a catalog name ('llama3-8b-awq' — the value of - LLM_MODEL_NAME and the name of the LLMInferenceService); AutoTokenizer needs a - HuggingFace repo id. This goes through the real catalog lookup, so a wiring - mistake that passed the served name straight to -m fails here. - """ + """AutoTokenizer needs the catalog's HF repo id, not the served catalog name.""" catalog = tmp_path / "models.yaml" catalog.write_text( "models:\n" @@ -556,11 +433,6 @@ def test_tokenizer_is_the_catalog_model_id_not_the_served_name(monkeypatch, tmp_ @allure.feature("pysweep") def test_unreadable_model_aborts_rather_than_guessing_a_tokenizer(monkeypatch): - """No served model means no defensible token counts, so the sweep stops. - - Falling back to benchmark.py's default (an embedding model's tokenizer) would - produce numbers on a basis nobody chose, which is worse than failing. - """ def unreadable(self): raise PropertyReadError("no llm-usvc pods") @@ -571,11 +443,6 @@ def unreadable(self): @allure.feature("pysweep") def test_a_served_model_missing_from_the_catalog_aborts(monkeypatch, tmp_path): - """Same reasoning one step later: a name with no model_id has no tokenizer. - - This is reachable without a config typo — the deployment may serve a model the - local catalog does not list — so it must fail rather than tokenize on a guess. - """ catalog = tmp_path / "models.yaml" catalog.write_text("models:\n - name: other-model\n model_id: org/other\n") monkeypatch.setenv("PYSWEEP_MODEL_CATALOG", str(catalog)) @@ -587,12 +454,6 @@ def test_a_served_model_missing_from_the_catalog_aborts(monkeypatch, tmp_path): @allure.feature("pysweep") def test_forwarded_tokenizer_flag_is_refused(): - """``-m`` cannot be passed after ``--``: it is derived, not configurable. - - Unlike -s/-b there is no "omit it from the config to pass it here" escape — - there is no config key at all, and any value other than the served model - misattributes the token counts. - """ cfg = load_config(_client()) with pytest.raises(psb.SweepError, match=r"-m"): psb.resolve_benchmark_argv(cfg, ["-m", "nomic-ai/nomic-embed-text-v1"]) @@ -600,12 +461,6 @@ def test_forwarded_tokenizer_flag_is_refused(): @allure.feature("pysweep") def test_forwarded_flag_that_the_config_declares_is_refused(): - """A load flag in both places has no defensible winner, so it is an error. - - Honouring the YAML would ignore an explicit command line; honouring the - command line would silently collapse a declared sweep dimension. Both leave - "what was tested" unanswerable, so the sweep refuses to start. - """ cfg = load_config(_client(concurrency=[1, 16])) with pytest.raises(psb.SweepError, match=r"-c"): psb.resolve_benchmark_argv(cfg, ["-c", "8"]) @@ -613,7 +468,6 @@ def test_forwarded_flag_that_the_config_declares_is_refused(): @allure.feature("pysweep") def test_forwarded_server_is_allowed_when_the_config_omits_it(): - """Passing -s/-b on the command line is the supported provisioning bypass.""" cfg = load_config(_client()) assert psb.resolve_benchmark_argv(cfg, ["-s", "https://erag.com/api/v1/chatqna"]) == [ "-s", "https://erag.com/api/v1/chatqna", @@ -622,18 +476,16 @@ def test_forwarded_server_is_allowed_when_the_config_omits_it(): @allure.feature("pysweep") def test_config_declared_server_and_bearer_reach_benchmark(): - """Declared connection settings render once and suppress auto-provisioning.""" + """Declared connection settings also suppress auto-provisioning.""" cfg = load_config(_client(server="https://erag.com/api/v1/chatqna", bearer_file="uat.txt")) argv = psb.resolve_benchmark_argv(cfg, []) assert argv == ["-s", "https://erag.com/api/v1/chatqna", "-b", "uat.txt"] - # provision_benchmark_target sees both as supplied and touches neither. with psb.provision_benchmark_target(argv) as provisioned: assert provisioned == argv @allure.feature("pysweep") def test_count_result_rows_counts_and_tolerates_missing(tmp_path): - """An absent file counts as zero rows rather than raising.""" assert psb.count_result_rows(tmp_path / "nope.csv") == 0 csv_file = tmp_path / "r.csv" csv_file.write_text("128,128,0.8,6.9,,200\n128,128,1.2,7.1,,200\n") @@ -647,8 +499,7 @@ def _fake_keycloak(monkeypatch, domain="box.example"): minted = itertools.count(1) - # access_token must yield a *fresh* value per read, as the real property does - # (each read is a new password grant), which is what makes the tokens distinct. + # Like the real property, each read is a new grant and yields a fresh token. class _Helper: @property def access_token(self): @@ -676,11 +527,6 @@ def _lifespan(helper, seconds=authentication.SWEEP_TOKEN_LIFESPAN_S): @allure.feature("pysweep") def test_provision_defaults_to_the_deployments_chatqna_endpoint(monkeypatch): - """With no -s, the endpoint is built from the deployment's own domain. - - The host must come from the build config rather than a constant, or a sweep - would drive load at a different cluster than the one it configures. - """ _fake_keycloak(monkeypatch) with psb.provision_benchmark_target([]) as args: assert args[args.index("-s") + 1] == "https://box.example/api/v1/chatqna" @@ -688,13 +534,7 @@ def test_provision_defaults_to_the_deployments_chatqna_endpoint(monkeypatch): @allure.feature("pysweep") def test_provision_mints_one_distinct_token_per_worker(monkeypatch): - """The bearer file holds ``workers`` *different* tokens, one per line. - - benchmark.py quits a worker whose line is empty, so the file must cover every - worker index. They must also be distinct: APISIX rate-limits /api/v1/chatqna - per Authorization header value, so one repeated token would put all workers in - a single bucket and cap the sweep's throughput regardless of concurrency. - """ + """Distinct because APISIX rate-limits per Authorization header value.""" _fake_keycloak(monkeypatch) with psb.provision_benchmark_target([], workers=8) as args: lines = Path(args[args.index("-b") + 1]).read_text().splitlines() @@ -705,12 +545,7 @@ def test_provision_mints_one_distinct_token_per_worker(monkeypatch): @allure.feature("pysweep") def test_provision_refresh_mints_new_tokens_benchmark_can_see(monkeypatch): - """Each run gets fresh tokens, and benchmark.py's linecache reads the new ones. - - A token only has to outlive one run that way. Without invalidating linecache, - the rewrite would be invisible: benchmark.py would hand out the cached, - possibly expired, tokens of the first run. - """ + """Without invalidating linecache, benchmark.py would reuse the first run's tokens.""" _fake_keycloak(monkeypatch) with psb.provision_benchmark_target([], workers=2) as args: bearer = args[args.index("-b") + 1] @@ -723,7 +558,6 @@ def test_provision_refresh_mints_new_tokens_benchmark_can_see(monkeypatch): @allure.feature("pysweep") def test_provision_lengthens_tokens_for_the_sweep_and_restores(monkeypatch): - """The lifespan override spans exactly the sweep: set on entry, undone on exit.""" calls = _fake_keycloak(monkeypatch) with psb.provision_benchmark_target([], workers=1): assert calls == [("set", 3600)] @@ -732,7 +566,6 @@ def test_provision_lengthens_tokens_for_the_sweep_and_restores(monkeypatch): @allure.feature("pysweep") def test_a_supplied_bearer_is_neither_refreshed_nor_lengthened(monkeypatch, tmp_path): - """-b is the caller's file: pysweep must not overwrite it or touch Keycloak.""" calls = _fake_keycloak(monkeypatch) uat = tmp_path / "uat.txt" uat.write_text("real-token\n") @@ -744,7 +577,6 @@ def test_a_supplied_bearer_is_neither_refreshed_nor_lengthened(monkeypatch, tmp_ @allure.feature("pysweep") def test_main_refreshes_tokens_before_every_run(monkeypatch, tmp_path): - """One refresh per load test, each one before that test starts.""" monkeypatch.chdir(tmp_path) cfg = load_config( {"client": {**CLIENT, "concurrency": [1, 16]}, "llms": {"max_new_tokens": [128, 256]}} @@ -781,7 +613,7 @@ def _provision(benchmark_args, workers=1): @allure.feature("pysweep") def test_configure_kubernetes_client_logs_quiets_httpx(): - """Disabled: the kr8s/httpx loggers stop emitting INFO but keep warnings.""" + """kr8s/httpx loggers drop INFO but keep warnings; asyncio gains the noise filter.""" levels = {n: logging.getLogger(n).level for n in psb.KUBERNETES_CLIENT_LOGGERS} asyncio_log = logging.getLogger("asyncio") installed = list(asyncio_log.filters) @@ -791,7 +623,6 @@ def test_configure_kubernetes_client_logs_quiets_httpx(): log = logging.getLogger(name) assert not log.isEnabledFor(logging.INFO) assert log.isEnabledFor(logging.WARNING) - # asyncio keeps its level (real errors matter) but gains the noise filter. assert asyncio_log.isEnabledFor(logging.ERROR) assert any( isinstance(f, psb._DropPortForwardTeardownNoise) for f in asyncio_log.filters @@ -804,7 +635,6 @@ def test_configure_kubernetes_client_logs_quiets_httpx(): @allure.feature("pysweep") def test_kubernetes_client_log_filter_drops_only_teardown_noise(): - """kr8s's port-forward resets are dropped; other asyncio errors survive.""" log_filter = psb._DropPortForwardTeardownNoise() def record(msg, exc=None): @@ -815,13 +645,11 @@ def record(msg, exc=None): assert not log_filter.filter(record("Unhandled exception in client_connected_cb")) assert not log_filter.filter(record("boom", ConnectionResetError("Connection lost"))) - # A genuine problem must still be reported. assert log_filter.filter(record("Task exception was never retrieved")) @allure.feature("pysweep") def test_configure_kubernetes_client_logs_enabled_is_a_noop(): - """Enabled: levels are left exactly as the caller/CLI configured them.""" levels = {n: logging.getLogger(n).level for n in psb.KUBERNETES_CLIENT_LOGGERS} psb.configure_kubernetes_client_logs(enabled=True) assert {n: logging.getLogger(n).level for n in psb.KUBERNETES_CLIENT_LOGGERS} == levels @@ -829,7 +657,6 @@ def test_configure_kubernetes_client_logs_enabled_is_a_noop(): @allure.feature("pysweep") def test_provision_preserves_caller_supplied_server_and_bearer(tmp_path): - """Explicit -s/-b are left untouched (no port-forward, no token minting).""" uat = tmp_path / "uat.txt" uat.write_text("real-token\n") original = ["-s", "https://erag.com/api/v1/chatqna", "-b", str(uat), "-c", "8"] @@ -837,28 +664,21 @@ def test_provision_preserves_caller_supplied_server_and_bearer(tmp_path): assert args == original -# -- preflight: question_file resolution & verification ----------------------- -# The CWD-relative bug these cover: benchmark.py opens question_file with a bare -# open(), so before anchoring, the documented repo-root invocation could not find -# the corpus at all, and a same-named file in some other CWD would have been used -# silently while the summary recorded only the declared string. +# benchmark.py opens question_file with a bare open(), i.e. relative to its CWD. @allure.feature("pysweep") def test_question_file_resolves_against_pysweep_dir_not_cwd(monkeypatch, tmp_path): - """The anchor is the harness directory, whatever the process's CWD is.""" monkeypatch.chdir(tmp_path) resolved = psb.resolve_question_file("../questions-short.csv") assert resolved.is_absolute() assert resolved == (psb.PYSWEEP_DIR / ".." / "questions-short.csv") - # The shipped corpora really are one level up, beside benchmark.py. assert resolved.resolve().is_file() @allure.feature("pysweep") def test_question_file_absolute_path_is_untouched(tmp_path): - """An absolute path is already unambiguous; rewriting it would surprise.""" corpus = tmp_path / "questions.csv" corpus.write_text("q\n") assert psb.resolve_question_file(str(corpus)) == corpus @@ -866,10 +686,6 @@ def test_question_file_absolute_path_is_untouched(tmp_path): @allure.feature("pysweep") def test_preflight_accepts_the_shipped_example_config(monkeypatch): - """The example must pass its own preflight, or the docs ship a broken config. - - That is, every path the example declares really resolves. - """ example = psb.PYSWEEP_DIR / "configs" / "sweep.yaml" psb.preflight_check(load_config(example)) @@ -883,7 +699,6 @@ def test_preflight_rejects_a_missing_question_file(): @allure.feature("pysweep") def test_preflight_error_names_the_resolved_path_and_the_anchor(): - """The message has to be actionable: what was looked for, and relative to what.""" cfg = load_config(_client(question_file="questions-short.csv")) # missing '../' with pytest.raises(psb.PreflightError) as excinfo: psb.preflight_check(cfg) @@ -895,8 +710,6 @@ def test_preflight_error_names_the_resolved_path_and_the_anchor(): @allure.feature("pysweep") def test_preflight_checks_every_declared_corpus_not_just_the_first(): - """question_file is sweepable: a bad path in the last value must fail up front, - not after the earlier runs have already spent their load.""" cfg = load_config(_client(question_file=["../questions-short.csv", "../gone.csv"])) with pytest.raises(psb.PreflightError, match="gone.csv"): psb.preflight_check(cfg) @@ -904,16 +717,11 @@ def test_preflight_checks_every_declared_corpus_not_just_the_first(): @allure.feature("pysweep") def test_preflight_error_is_a_sweep_error(): - """Callers catching SweepError keep working; the subclass only adds meaning.""" assert issubclass(psb.PreflightError, psb.SweepError) @allure.feature("pysweep") def test_preflight_runs_before_anything_is_applied(monkeypatch, tmp_path): - """The whole point of the up-front call: a bad path costs no rollout. - - A model swap takes hours, so a config typo must fail before apply, not after. - """ monkeypatch.chdir(tmp_path) cfg = load_config({"client": {**CLIENT, "question_file": "../gone.csv"}}) applied = [] @@ -934,8 +742,6 @@ def test_preflight_runs_before_anything_is_applied(monkeypatch, tmp_path): @allure.feature("pysweep") def test_benchmark_receives_the_resolved_absolute_question_file(monkeypatch, tmp_path): - """benchmark.py opens the value relative to ITS CWD, so it must get an absolute - path — that is what makes the anchor authoritative without editing benchmark.py.""" monkeypatch.chdir(tmp_path) cfg = load_config(_client()) fake = FakeBenchmark() @@ -959,8 +765,6 @@ def test_benchmark_receives_the_resolved_absolute_question_file(monkeypatch, tmp @allure.feature("pysweep") def test_summary_records_the_declared_path_not_the_resolved_one(monkeypatch, tmp_path): - """Provenance shows what the config asked for; an absolute path would be - machine-specific and make two identical configs look different.""" monkeypatch.chdir(tmp_path) cfg = load_config(_client()) fake = FakeBenchmark() @@ -984,10 +788,6 @@ def test_summary_records_the_declared_path_not_the_resolved_one(monkeypatch, tmp @allure.feature("pysweep") def test_preflight_runs_once_for_the_whole_sweep(monkeypatch, tmp_path): - """Checked before the sweep and not again: every check is about the config and - its environment, so no run can change the answer and repeating it per load test - would only re-learn it. - """ monkeypatch.chdir(tmp_path) corpus = tmp_path / "questions.csv" corpus.write_text("q\n") @@ -1012,15 +812,12 @@ def counting_preflight(config): assert psb.main(["--sweep", "ignored.yaml"]) == 0 - # Once, with no run done yet — and both client combinations still ran. assert calls == [0] assert len(fake.calls) == 2 @allure.feature("pysweep") def test_preflight_runs_the_corpus_check(monkeypatch): - """One entry point, so a new precondition is wired in one place and callers - (and this test) do not have to know how many checks there are.""" called = [] monkeypatch.setattr(psb, "question_file_verify", lambda config: called.append("corpus")) @@ -1029,29 +826,15 @@ def test_preflight_runs_the_corpus_check(monkeypatch): assert called == ["corpus"] -# -- logging: what a run is announced as -------------------------------------- - - @allure.feature("pysweep") def test_format_settings_yaml_nests_dotted_paths_with_four_spaces(): - """The block has to read like the sweep config it came from. - - Dotted paths back into sections, four-space indentation to match the config - files — so the logged text is comparable to (and pasteable into) a sweep YAML - rather than being a Python repr of the runner's internals. - """ block = psb.format_settings_yaml({"client.concurrency": 16, "client.duration": "3m"}) assert block == "client:\n concurrency: 16\n duration: 3m" @allure.feature("pysweep") def test_format_settings_yaml_groups_sections_and_keeps_kpis_top_level(): - """A summary row mixes knob paths with undotted KPIs; both have to read well. - - Sections group (in the caller's order, not sorted — for load parameters that - order is benchmark.py's own), and the KPI keys have no section to belong to, - so they stay at the top level instead of being invented one. - """ + """Sections keep the caller's order rather than being sorted.""" block = psb.format_settings_yaml( { "llms.max_new_tokens": 1024, @@ -1078,29 +861,17 @@ def test_format_settings_yaml_groups_sections_and_keeps_kpis_top_level(): @allure.feature("pysweep") def test_format_settings_yaml_is_empty_for_no_settings(): - """So a caller can say '(unchanged)' instead of logging an empty block.""" assert psb.format_settings_yaml({}) == "" @allure.feature("pysweep") def test_format_settings_yaml_stringifies_what_yaml_cannot_represent(): - """A log line must never be what kills a four-hour sweep. - - Property read-backs are ints and strings today, but yaml.safe_dump raises on - anything else, so unknown types are rendered rather than propagated. - """ block = psb.format_settings_yaml({"client.question_file": Path("/tmp/q.csv")}) assert block == "client:\n question_file: /tmp/q.csv" @allure.feature("pysweep") def test_load_parameters_are_logged_as_yaml(caplog, tmp_path): - """The 'load parameters' step announces the client section, not a dict repr. - - That line is how a reader of a multi-hour log knows what the next load test - is about to do, so it is asserted here: YAML block, four-space indent, the - declared corpus path (not the anchored absolute one), and no dict/JSON braces. - """ cfg = load_config(_client(concurrency=16)) with caplog.at_level(logging.INFO, logger=psb.logger.name): @@ -1121,12 +892,7 @@ def test_load_parameters_are_logged_as_yaml(caplog, tmp_path): @allure.feature("pysweep") def test_load_parameters_line_names_the_derived_tokenizer(): - """It is a load parameter too (-m), but it has no config key. - - So it is reported in the prose rather than inside the YAML block: a block - containing 'tokenizer:' would look declarable, and 'client.tokenizer' is a - ConfigError by design. - """ + """Named in the prose, not the YAML block: ``client.tokenizer`` is a ConfigError.""" cfg = load_config(_client()) block = psb.format_settings_yaml( BenchmarkClientArgs.from_settings(cfg.client_combinations()[0]).snapshot() diff --git a/src/tests/e2e/validation/pysweep/test_results_unit.py b/src/tests/e2e/validation/pysweep/test_results_unit.py index 375cd999..311503fb 100644 --- a/src/tests/e2e/validation/pysweep/test_results_unit.py +++ b/src/tests/e2e/validation/pysweep/test_results_unit.py @@ -1,13 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the sweep summary post-processing (``pysweep/results.py``). - -Pure computation over CSV files, so nothing here needs a cluster, transformers, -or a load test — the inputs are hand-written result files whose KPIs can be -checked by arithmetic. -""" - import csv import allure @@ -48,31 +41,20 @@ def _result_file(tmp_path, rows, name="bench_x.result.csv"): @allure.feature("pysweep") def test_tpot_excludes_the_first_token(): - """TPOT is the *inter-token* gap, so neither TTFT nor its token counts in it. - - With 11 output tokens, 1.0s to the first and 3.0s overall, decode produced - the remaining 10 tokens in 2.0s: 0.2s per token. Dividing by 11 instead (as - ``parse.py``'s next_token_lat does) would report 0.1818 and understate the - decode cost, which is the distinction this KPI exists to make. - """ + """11 tokens, 2.0s after the first: 10 gaps of 0.2s, not parse.py's 2.0/11.""" record = RequestRecord(128, 11, 1.0, 3.0, "", 200) assert record.tpot == pytest.approx(0.2) @allure.feature("pysweep") def test_tpot_is_undefined_for_a_single_token_answer(): - """One token means no gap between tokens; its whole latency is TTFT.""" assert RequestRecord(128, 1, 1.0, 1.0, "", 200).tpot is None assert RequestRecord(128, 0, 1.0, 1.0, "", 200).tpot is None @allure.feature("pysweep") def test_percentile_interpolates_like_pandas(): - """p90 must agree with what parse.py reports, i.e. numpy's default method. - - For 1..10 the 0.9 quantile sits between the 9th and 10th values at 9.1 — - not 9 (nearest-rank) and not 10 (ceiling). - """ + """Must match numpy's default method, as parse.py reports.""" assert percentile(list(range(1, 11)), 0.9) == pytest.approx(9.1) assert percentile([5.0], 0.9) == 5.0 assert percentile([], 0.9) is None @@ -80,12 +62,6 @@ def test_percentile_interpolates_like_pandas(): @allure.feature("pysweep") def test_kpis_are_computed_over_the_recorded_requests(tmp_path): - """The four KPIs come out of the per-request rows by plain arithmetic. - - Two requests, TTFT 1.0 and 2.0 -> mean 1.5, p90 1.9 (interpolated). Each has - 11 output tokens and 2.0s/4.0s of decode after the first token -> TPOT 0.2 - and 0.4, mean 0.3, p90 0.38. - """ path = _result_file( tmp_path, [ @@ -103,13 +79,6 @@ def test_kpis_are_computed_over_the_recorded_requests(tmp_path): @allure.feature("pysweep") def test_unsuccessful_and_implausible_rows_are_excluded(tmp_path): - """A summary must describe successful requests only. - - A non-200, an errored row, one that never timed a first chunk, and a - malformed line would each poison the mean if counted. Dropping them (rather - than raising) also means one damaged line cannot cost an hours-long sweep its - summary. - """ path = _result_file( tmp_path, [ @@ -128,11 +97,6 @@ def test_unsuccessful_and_implausible_rows_are_excluded(tmp_path): @allure.feature("pysweep") def test_a_run_that_recorded_nothing_still_gets_a_row(tmp_path): - """"This configuration produced no data" is a result, not a reason to abort. - - Blank KPIs with ``requests`` 0 says exactly that; dropping the row would - leave a hole in the sweep that looks like a configuration never tried. - """ summary = SweepSummary(["client.concurrency"], path=tmp_path / "s.csv") row = summary.add_run({"client.concurrency": 128}, tmp_path / "missing.csv", error=1) assert row["requests"] == 0 @@ -155,13 +119,6 @@ def test_a_run_that_recorded_nothing_still_gets_a_row(tmp_path): @allure.feature("pysweep") def test_result_file_is_recorded_relative_to_the_summary(tmp_path): - """The pointer column is relative, so the results directory can be moved. - - A sweep runs on the benchmark host and is read somewhere else. An absolute - path in the column would name a directory that only ever existed on the host; - ``per_case_results/bench_x.result.csv`` still resolves after the directory is - copied off it or renamed. - """ per_case = tmp_path / PER_CASE_DIR_NAME per_case.mkdir() result = _result_file(per_case, [[128, 11, 1.0, 3.0, "", 200]]) @@ -175,11 +132,6 @@ def test_result_file_is_recorded_relative_to_the_summary(tmp_path): @allure.feature("pysweep") def test_a_result_file_from_outside_the_directory_is_recorded_verbatim(tmp_path): - """There is no meaningful relative name for it, so the absolute one is kept. - - Not a shape the sweep produces, but the column must stay resolvable rather - than becoming a ``../..``-prefixed guess at where the reader will stand. - """ elsewhere = _result_file(tmp_path, [[128, 11, 1.0, 3.0, "", 200]]) root = tmp_path / "results" root.mkdir() @@ -192,14 +144,7 @@ def test_a_result_file_from_outside_the_directory_is_recorded_verbatim(tmp_path) @allure.feature("pysweep") def test_summary_columns_are_the_declared_knobs_in_dot_notation(tmp_path): - """Header = every declared knob as its dotted config path, then the KPIs. - - Dotted paths are the point: the column name is the key the sweep YAML used, - so a reader can go from a column back to the config with no lookup table. - Constants get columns too (``client.duration`` is single-valued here), because a - summary that only named the varying knobs would not say what the numbers - were measured under. - """ + """Single-valued knobs get columns too.""" cfg = load_config( { "client": {**CLIENT, "concurrency": [1, 16], "input_tokens": [128, 256]}, @@ -222,12 +167,6 @@ def test_summary_columns_are_the_declared_knobs_in_dot_notation(tmp_path): @allure.feature("pysweep") def test_header_exists_before_the_first_run_finishes(tmp_path): - """A sweep's first row can be an hour away; the file must not be missing. - - The first run sits behind a multi-replica rollout, and until it completes a - missing file is indistinguishable from a harness that never summarizes at - all. A header-only file says "running, and here is the shape of the results". - """ path = tmp_path / "sweep_summary.csv" summary = SweepSummary(["client.concurrency"], path=path) assert path.exists() @@ -237,11 +176,6 @@ def test_header_exists_before_the_first_run_finishes(tmp_path): @allure.feature("pysweep") def test_summary_is_readable_after_every_run(tmp_path): - """Rewritten per run, so a sweep killed at hour three still leaves a table. - - An hours-long sweep that only wrote its summary at the end would lose - everything to a failed rollout in the middle. - """ path = tmp_path / "sweep_summary.csv" summary = SweepSummary(["client.concurrency"], path=path) for index, concurrency in enumerate((1, 16), start=1): @@ -257,12 +191,6 @@ def test_summary_is_readable_after_every_run(tmp_path): @allure.feature("pysweep") def test_unset_knobs_render_blank_rather_than_shifting_columns(tmp_path): - """A knob with no value for a run leaves an empty cell. - - The columns are fixed from the config up front, so a missing value must not - be able to misalign a row — that would silently attribute one knob's value - to another column. - """ summary = SweepSummary(["llms.max_new_tokens", "client.concurrency"], path=tmp_path / "s.csv") row = summary.add_run({"client.concurrency": 4}, tmp_path / "none.csv") assert row["llms.max_new_tokens"] == "" @@ -272,11 +200,7 @@ def test_unset_knobs_render_blank_rather_than_shifting_columns(tmp_path): @allure.feature("pysweep") def test_the_output_layout_is_created_when_nothing_is_there(tmp_path): - """A sweep must not fail because its output directory does not exist yet. - - That includes intermediate directories: ``--summaries runs/today`` is a - reasonable thing to type on a fresh host. - """ + """Including intermediate directories.""" layout = prepare_summaries_dir(tmp_path / "runs" / "today") assert layout.root.is_dir() @@ -287,11 +211,6 @@ def test_the_output_layout_is_created_when_nothing_is_there(tmp_path): @allure.feature("pysweep") def test_the_paths_are_absolute(tmp_path, monkeypatch): - """``benchmark.py`` opens its output with a bare ``open()``. - - A relative per-case path would land against the working directory of whatever - process happened to do the opening, so the layout is resolved once, here. - """ monkeypatch.chdir(tmp_path) layout = prepare_summaries_dir("results") @@ -303,12 +222,6 @@ def test_the_paths_are_absolute(tmp_path, monkeypatch): @allure.feature("pysweep") def test_the_previous_sweep_is_discarded(tmp_path): - """A sweep's artifacts only make sense as a set, so the slate is wiped clean. - - Keeping them would mix two sweeps: per-case CSVs with no row in the current - summary, or — if the previous sweep was longer — rows in a stale summary - pointing at files this one never overwrote. - """ root = tmp_path / "results" per_case = root / PER_CASE_DIR_NAME per_case.mkdir(parents=True) @@ -325,12 +238,6 @@ def test_the_previous_sweep_is_discarded(tmp_path): @allure.feature("pysweep") def test_nothing_else_in_the_directory_is_touched(tmp_path): - """The deletion is confined to the summary and the per-case subdirectory. - - ``--summaries`` is a path a user types, and it may well point at a directory - that already holds notes, a copy of the sweep YAML, or someone's plots. Only - what this sweep is about to rewrite is removed. - """ root = tmp_path / "results" root.mkdir() (root / "sweep.yaml").write_text("client: {}\n") @@ -345,11 +252,6 @@ def test_nothing_else_in_the_directory_is_touched(tmp_path): @allure.feature("pysweep") def test_a_symlinked_per_case_directory_is_refused(tmp_path): - """Emptying it would delete files outside the directory the caller named. - - The flag is destructive by design, but only within the tree it was pointed at; - following a link out of that tree is not something to do quietly. - """ outside = tmp_path / "outside" outside.mkdir() (outside / "precious.csv").write_text("keep\n") @@ -365,11 +267,6 @@ def test_a_symlinked_per_case_directory_is_refused(tmp_path): @allure.feature("pysweep") def test_a_file_where_a_directory_belongs_is_refused(tmp_path): - """``--summaries`` names a directory; a file there means the wrong path. - - Most likely the old ``--summary sweep_summary.csv`` habit. Failing beats - guessing at the parent directory, and beats deleting the file. - """ as_file = tmp_path / "results" as_file.write_text("not a directory\n") @@ -381,11 +278,6 @@ def test_a_file_where_a_directory_belongs_is_refused(tmp_path): @allure.feature("pysweep") def test_nothing_is_deleted_when_the_layout_is_refused(tmp_path): - """The checks all run before the first deletion. - - Otherwise a directory that turns out to be unusable would still have lost the - previous sweep's results by the time the error was raised. - """ root = tmp_path / "results" root.mkdir() (root / SUMMARY_FILE_NAME).write_text("previous sweep\n") diff --git a/src/tests/e2e/validation/pysweep/test_served_model.py b/src/tests/e2e/validation/pysweep/test_served_model.py index 881bcf0c..5f7255e6 100644 --- a/src/tests/e2e/validation/pysweep/test_served_model.py +++ b/src/tests/e2e/validation/pysweep/test_served_model.py @@ -1,19 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""e2e test for :mod:`served_model` — its bindings to the live deployment. - -The runner tokenizes every load test with the model this module reads, and the -read rests on assumptions about objects this repo does not own: the ``llm-usvc`` -label selector and container name, ``LLM_MODEL_NAME`` in the pods' env, and -KServe's ``LLMInferenceService`` at ``serving.kserve.io/v1alpha2``. Any of them can -be renamed by a chart bump without a single unit test noticing, and the symptom -would be a sweep that cannot pick a tokenizer. This module is where that drift -fails. - -Read-only: nothing here changes the deployment. -""" - import logging import allure @@ -28,12 +15,6 @@ @pytest.fixture(scope="module") def observed_model(pysweep_kubernetes_access): - """The model the deployment is observed to serve, gated on the RBAC preflight. - - Every test needs it, and it comes from ``read()`` — so a deployment that is - mid-rollout or pointed at an unserved model fails here once, with the reason, - rather than in each test. - """ model = ServedModel().read() logger.info("Deployment observed serving model %r.", model) return model @@ -41,23 +22,12 @@ def observed_model(pysweep_kubernetes_access): @allure.feature("pysweep") def test_read_returns_the_served_model_name(observed_model): - """The selector selects, the exec works, and the env var is populated. - - ``read`` must observe the pods, so if the label selector or the container name - stopped matching, this is where it surfaces. - """ assert observed_model assert observed_model == observed_model.strip() @allure.feature("pysweep") def test_the_observed_model_is_a_catalog_name(observed_model): - """Not a HuggingFace repo id. - - ``LLM_MODEL_NAME`` carries model-manager's short name, which is what the - gateway routes on. If a deployment ever put a repo id here, the tokenizer - lookup in :mod:`.model_catalog` would have nothing to map. - """ known = model_catalog.known_models() assert observed_model in known, ( f"The deployment serves {observed_model!r}, which is not a name in the " @@ -67,11 +37,6 @@ def test_the_observed_model_is_a_catalog_name(observed_model): @allure.feature("pysweep") def test_the_observed_model_has_a_tokenizer(observed_model): - """The benchmark's ``-m`` is derived, never configured. - - Every token count in every result row depends on this mapping resolving for the - model actually being served. - """ tokenizer = model_catalog.tokenizer_for(observed_model) assert "/" in tokenizer, ( f"{tokenizer!r} does not look like a HuggingFace repo id; the benchmark " @@ -81,12 +46,6 @@ def test_the_observed_model_has_a_tokenizer(observed_model): @allure.feature("pysweep") def test_the_served_model_is_a_ready_llminferenceservice(observed_model): - """Binds the hand-written kr8s class to the live CRD. - - The apiVersion is pinned in one place on purpose (see - :class:`LLMInferenceService`); when KServe moves past ``v1alpha2`` this test is - the notice. - """ llmisvc = LLMInferenceService.get(observed_model, namespace=LLM_INFERENCE_NAMESPACE) conditions = (llmisvc.raw.get("status", {}) or {}).get("conditions", []) or [] assert any( diff --git a/src/tests/e2e/validation/pysweep/test_served_model_unit.py b/src/tests/e2e/validation/pysweep/test_served_model_unit.py index db698d25..0810341d 100644 --- a/src/tests/e2e/validation/pysweep/test_served_model_unit.py +++ b/src/tests/e2e/validation/pysweep/test_served_model_unit.py @@ -1,18 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Unit tests for :mod:`served_model`, the read-only served-model probe. - -The runner tokenizes with whatever this returns, so what is pinned is that it -observes the running pods (not a ConfigMap), and that every inconsistent picture -(replicas disagreeing, nothing serving the named model, a model still loading, -an unreadable pod) is an error rather than a model name. - -``kr8s`` and ``LLMInferenceService`` are replaced module-locally. That the real -objects have this shape is covered by ``test_served_model.py``, which needs a -deployment. -""" - from types import SimpleNamespace import allure @@ -42,11 +30,9 @@ def exec(self, command, container=None): class FakeCluster: - """The pipeline's LLM pods and the models being served.""" - def __init__(self, pods=None, served=None): self.pods = [FakePod("llm-usvc-a", MODEL)] if pods is None else list(pods) - # model name -> replica count; membership means "an LLMInferenceService exists". + # model name -> replicas; a key means an LLMInferenceService exists. self.served = {MODEL: 4} if served is None else dict(served) self.not_ready = set() @@ -72,7 +58,6 @@ def cluster(monkeypatch): def install(monkeypatch, fake): - """Point the probe at ``fake`` instead of a cluster.""" monkeypatch.setattr(served_model, "kr8s", SimpleNamespace(get=fake.get)) monkeypatch.setattr( served_model, "LLMInferenceService", SimpleNamespace(get=fake.llmisvc_get) @@ -80,9 +65,6 @@ def install(monkeypatch, fake): return fake -# -- read --------------------------------------------------------------------- - - @allure.feature("pysweep") def test_read_returns_the_model_the_pods_actually_run(cluster): assert ServedModel().read() == MODEL @@ -90,7 +72,6 @@ def test_read_returns_the_model_the_pods_actually_run(cluster): @allure.feature("pysweep") def test_read_execs_into_the_application_container(cluster): - """Not the init container: it has no ``LLM_MODEL_NAME`` and is gone by then.""" ServedModel().read() (_, container), = cluster.pods[0].exec_calls assert container == served_model.LLM_USVC_CONTAINER @@ -98,12 +79,6 @@ def test_read_execs_into_the_application_container(cluster): @allure.feature("pysweep") def test_read_reports_the_pods_model_even_when_another_is_served(monkeypatch): - """Serving a model is not the pipeline using it. - - Two models can be Ready at once (e.g. mid-swap); only the one the replicas' - processes name is what the benchmark exercises, so that is the one to tokenize - with. - """ fake = FakeCluster(served={MODEL: 4, OTHER: 4}) install(monkeypatch, fake) @@ -112,11 +87,6 @@ def test_read_reports_the_pods_model_even_when_another_is_served(monkeypatch): @allure.feature("pysweep") def test_read_ignores_terminating_pods(monkeypatch): - """A pod being replaced is not part of the observed configuration. - - Counting it would make ``read`` report a disagreement for the whole grace - period after a restart that has otherwise already converged. - """ fake = FakeCluster( pods=[FakePod("old", OTHER, terminating=True), FakePod("new", MODEL)], served={MODEL: 4, OTHER: 4}, @@ -128,7 +98,6 @@ def test_read_ignores_terminating_pods(monkeypatch): @allure.feature("pysweep") def test_read_raises_when_replicas_disagree(monkeypatch): - """Half the fleet on each model is not a configuration a benchmark may run against.""" fake = FakeCluster( pods=[FakePod("a", MODEL), FakePod("b", OTHER)], served={MODEL: 4, OTHER: 4}, @@ -150,7 +119,6 @@ def test_read_raises_when_no_pods_are_running(monkeypatch): @allure.feature("pysweep") def test_read_raises_when_the_named_model_is_not_served(monkeypatch): - """A pipeline pointed at an absent model answers nothing; that is not 'configured'.""" fake = FakeCluster(served={}) install(monkeypatch, fake) @@ -160,7 +128,6 @@ def test_read_raises_when_the_named_model_is_not_served(monkeypatch): @allure.feature("pysweep") def test_read_raises_when_the_model_is_served_but_not_ready(monkeypatch): - """Weights still loading is exactly the window a sweep must not benchmark in.""" fake = FakeCluster() fake.not_ready = {MODEL} install(monkeypatch, fake) @@ -180,7 +147,6 @@ def test_read_raises_on_an_empty_env_var(monkeypatch): @allure.feature("pysweep") def test_read_raises_when_exec_fails(monkeypatch): - """A starting container cannot be exec'd into; unreadable is not 'unchanged'.""" fake = FakeCluster(pods=[FakePod("a", MODEL, exec_error=RuntimeError("container not running"))]) install(monkeypatch, fake) diff --git a/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py b/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py index 2457c023..6fc7493e 100644 --- a/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py +++ b/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py @@ -1,14 +1,6 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Unit tests for the sweep-long access-token lifespan override. - -Pinned: the override is per client (nothing else in the realm changes), the -client's previous value comes back afterwards, including after a failed sweep, and -a client with no override goes back to inheriting the realm setting. -No Keycloak is involved: ``requests`` is replaced with an in-memory client store. -""" - import allure import pytest @@ -38,8 +30,6 @@ def raise_for_status(self): class _FakeKeycloak: - """Just enough of the admin API: list clients by clientId, GET/PUT one client.""" - def __init__(self, attributes=None, exists=True): self.client = {"id": "uuid-1", "clientId": VITE_KEYCLOAK_CLIENT_ID, "attributes": dict(attributes or {})} @@ -85,7 +75,6 @@ def install(**kwargs): @allure.feature("pysweep") def test_the_sweep_value_is_arbitrary_but_outlasts_a_long_run(): - """Only has to cover one run; 15m runs are the longest used so far.""" assert authentication.SWEEP_TOKEN_LIFESPAN_S == 3600 diff --git a/src/tox.ini b/src/tox.ini index df2f8931..eafc0a07 100644 --- a/src/tox.ini +++ b/src/tox.ini @@ -332,22 +332,11 @@ setenv = deps = pytest==9.0.3 PyYAML==6.0.2 - # Every test module in the suite is @allure.feature-tagged, so the plugin is - # needed even when no report is generated. allure-pytest==2.15.3 - # The sweep config schema is pydantic, and the property/runtime-API modules - # the tests import pull in kr8s and requests at import time. pydantic==2.13.4 kr8s==0.20.15 requests==2.33.1 commands = - # Only the *_unit.py modules: they stub the cluster and the fingerprint API, so - # they run anywhere. The rest of tests/e2e/validation/pysweep needs a live - # deployment and runs under `tox -e e2e` (which collects both). - # - # --confcutdir stops pytest loading tests/e2e/conftest.py, whose session - # fixtures read a deployment's config files and talk to the cluster. Without it - # these tests could not run off a deployment host at all. pytest -s --disable-warnings --confcutdir=tests/e2e/validation/pysweep -k "_unit" tests/e2e/validation/pysweep {posargs} # ----------------------------------------------------------------------------- From c454d75449193f19db09b2a9a2b48b6a69ebf9bc Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Wed, 25 Nov 2026 19:35:20 +0100 Subject: [PATCH 05/11] feat(benchmarks): record pysweep runs as nested records in results.json Each run is now a record of run metadata, settings (observed deployment knobs and declared client knobs, plus the derived tokenizer) and results (TTFT, TPOT and end-to-end mean/p50/p90/p99, token counts, throughput), logged as YAML when the run finishes. The sweep writes them to results.json under runs, with the sweep date and the commit_info of the checked-out commit, and keeps the summary CSV with the same records as dotted columns. commit_info (sha, committer datetime, author, subject, branch) is read with git and is mandatory: the preflight fails without it, including on a detached HEAD. Signed-off-by: Kurzacz, Kamil --- .../e2e/benchmarks/chatqna/pysweep/DESIGN.md | 8 +- .../e2e/benchmarks/chatqna/pysweep/README.md | 121 ++++++---- .../benchmarks/chatqna/pysweep/commit_info.py | 51 ++++ .../chatqna/pysweep/configs/README.md | 6 +- .../chatqna/pysweep/pysweep_bench.py | 80 +++++-- .../e2e/benchmarks/chatqna/pysweep/results.py | 211 ++++++++++------- .../pysweep/test_commit_info_unit.py | 74 ++++++ .../pysweep/test_pysweep_bench_unit.py | 90 ++++++- .../validation/pysweep/test_results_unit.py | 221 +++++++++++------- 9 files changed, 606 insertions(+), 256 deletions(-) create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/commit_info.py create mode 100644 src/tests/e2e/validation/pysweep/test_commit_info_unit.py diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md b/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md index d22c9f5c..7dc26c30 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md @@ -357,15 +357,15 @@ sweep dimensions with no plane". **Summarizing is part of the flow, not a separate tool.** The runner is the only thing that knows which configuration produced which CSV — the per-request files -carry neither, and their names carry only what varied — so it writes the row while -it still holds both. That is also why the summary is rewritten after every run +carry neither, and their names carry only what varied — so it writes the record +while it still holds both, with the commit it ran from. That is also why the summary is rewritten after every run rather than at the end: a sweep is hours long, and a table of what finished is worth more than a complete one that a failed rollout prevents. Aggregation stays lossless-by-default: the per-request CSVs are untouched and every row points back to its own. **One output directory per sweep, cleared before the sweep starts.** `--summaries` -(default `./results`) holds `benchmark_summary_results.csv` and a +(default `./results`) holds `results.json`, `benchmark_summary_results.csv` and a `per_case_results/` subdirectory, and both are wiped of the previous sweep's artifacts first. The alternative — writing each run's CSV into the CWD and accumulating across sweeps, which is what `benchmark.py` alone does — makes the two @@ -374,7 +374,7 @@ in the current summary is indistinguishable from a result of it, and a re-run shorter than its predecessor leaves rows pointing at files it never overwrote. Refusing to merge is a stronger guarantee than any naming scheme, because the failure it prevents is misattribution, not collision. The wipe is confined to the -one file and the one subdirectory the harness owns, so the directory can hold other +two files and the one subdirectory the harness owns, so the directory can hold other things; it happens after the config is validated and the preflight has passed, so a mistake that would have failed every run costs nothing. `result_file` is recorded relative to the summary so the directory survives being copied off the benchmark host. diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md index f6c35b78..a6c9f0a3 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -163,7 +163,7 @@ for each deployment combination: # outer — costs a rollout tokenizer = observed served model # -m, derived once per combination for each client combination: # inner — costs one more load test run benchmark.py - append a row to benchmark_summary_results.csv # knobs + TTFT/TPOT KPIs + log the run's record as YAML; add it to results.json and the summary CSV ``` Within the deployment product, `deployment_combinations()` sorts K8s-plane knobs first so @@ -229,7 +229,7 @@ pysweep provisions the things the raw `benchmark.py` makes you prepare by hand: | Results of each combination overwrote one another (same timestamped CSV) | Each run writes `per_case_results/bench_-_..._-.result.csv`. | | An unreachable endpoint still exited `0` with an empty CSV | A run that records **zero** result rows is reported as a failure (non-zero exit). | | Load parameters lived only in whatever shell command produced the CSV | Declared in `--sweep` and logged per run alongside the observed deployment state. | -| Comparing runs meant `parse.py` over a directory of headerless CSVs, with the configuration recoverable only from filenames | One `benchmark_summary_results.csv`: a row per run, a column per declared knob (dotted paths), TTFT/TPOT mean and p90. | +| Comparing runs meant `parse.py` over a directory of headerless CSVs, with the configuration recoverable only from filenames | One `results.json` with a record per run (settings, KPIs, the commit that produced it), and the same records as dotted-column rows in `benchmark_summary_results.csv`. | | `-m` had to be kept in step with the served model by hand, and defaulted to an embedding model's tokenizer if forgotten | Derived per combination from the model the LLM engine is observed to serve, so token counts always come from that model's tokenizer. | Supplying `-s` / `-b` (on the command line or as `client.server` / @@ -244,69 +244,89 @@ logged instead. ### Where the results go (`--summaries`) Everything a sweep writes goes under one directory, `--summaries` (default -`./results`, relative to the CWD like any other command-line path): +`./results`, relative to the CWD): ``` results/ - benchmark_summary_results.csv # the sweep's table: one row per run + results.json # the sweep document: commit, date, one record per run + benchmark_summary_results.csv # the same records, one dotted-column row per run per_case_results/ # one per-request CSV per run bench_max_new_tokens-128_concurrency-1_input_tokens-128.result.csv - bench_max_new_tokens-128_concurrency-16_input_tokens-128.result.csv ... ``` -The directory is created if missing (parents included), and **the previous -sweep's artifacts in it are deleted before this one starts**: the summary file is -removed and `per_case_results/` is emptied. A sweep's outputs only mean anything -as a set — the summary indexes the per-case CSVs, and a per-case CSV means nothing -without the row saying what produced it — so merging two sweeps into one directory -would leave stale CSVs that read exactly like results of the current run. Nothing -else under the directory is touched, so pointing `--summaries` at a directory that -also holds a copy of the sweep YAML or someone's plots loses none of it. The wipe -happens after the config is validated and the preflight has passed, so a typo in -the YAML or a missing question file does not cost you the previous results. +The directory is created if missing. **The previous sweep's outputs in it are +deleted before this one starts** (both summary files, and everything in +`per_case_results/`), after the config is validated and the preflight has passed. +Nothing else in the directory is touched. Both summary files are rewritten after +every run, so an interrupted sweep still leaves valid files for the runs it +finished. + +### The results + +`results.json`: + +```json +{ + "schema_version": 1, + "date": "2026-11-26T09:02:11Z", + "commit_info": { + "sha": "9022de7e…", + "datetime": "2026-11-25T18:02:44+01:00", + "author": "Kurzacz, Kamil", + "description": "refactor(benchmarks): …", + "branch": "kkurzacz/pysweep-core" + }, + "runs": [ { "run": {…}, "settings": {…}, "results": {…} } ] +} +``` -### The summary CSV +`date` is when the sweep started (UTC). `commit_info` is the committed `HEAD` of +the checkout pysweep runs from; uncommitted changes are not recorded. -Each `bench_*.result.csv` is one row per *request* with no header and no record -of the configuration, so a sweep also writes a single summary table -(`benchmark_summary_results.csv`, `results.py`): +Each record, also logged as YAML when its run finishes: -``` -llms.max_new_tokens,client.concurrency,client.duration,...,requests,mean_ttft,p90_ttft,mean_tpot,p90_tpot,served_model,error,result_file -128,1,10m,...,412,0.284192,0.41133,0.021975,0.02698,casperhansen/llama-3-8b-instruct-awq,0,per_case_results/bench_max_new_tokens-128_concurrency-1_input_tokens-128.result.csv -128,16,10m,...,3907,1.10442,1.83206,0.0344,0.04102,casperhansen/llama-3-8b-instruct-awq,0,per_case_results/bench_max_new_tokens-128_concurrency-16_input_tokens-128.result.csv +```yaml +run: + index: '1.2' # deployment combination . client combination + started_at: '2026-11-26T09:14:03Z' + finished_at: '2026-11-26T09:29:05Z' + exit_code: 0 + result_file: per_case_results/bench_max_new_tokens-128_concurrency-16.result.csv +settings: + deployment: # observed on the cluster after apply + llms: + max_new_tokens: 128 + client: # declared, plus the derived tokenizer (-m) + concurrency: 16 + duration: 15m + ... + tokenizer: casperhansen/llama-3-8b-instruct-awq +results: + requests: {ok: 1893} + ttft_s: {mean: 1.45, p50: 1.38, p90: 2.31, p99: 3.02} + tpot_s: {mean: 0.069, p50: 0.068, p90: 0.081, p99: 0.094} + e2e_s: {mean: 5.82, p50: 5.71, p90: 7.4, p99: 9.12} + input_tokens: {mean: 128} + output_tokens: {mean: 61, total: 115473} + throughput: {requests_per_s: 2.1, output_tokens_per_s: 128.3} ``` -One row per run. The knob columns come first, named by the **dotted config path** -the sweep YAML used (`client.input_tokens` for `client: input_tokens:`), so a -column maps back to the config with no lookup table. *Every* declared knob gets a -column, not only the varying ones — a summary that dropped the constants would not -say what the numbers were measured under, and including them makes two sweeps' -summaries concatenable. Deployment values are the **observed** read-backs; client -values are the declared ones (there is nothing to observe — they are arguments to -a process). `server` / `bearer_file` are excluded as connection plumbing. +| Result | Meaning | +|---|---| +| `requests.ok` | Successful requests the statistics are over (`benchmark.py` records only those, after warmup). | +| `ttft_s` | Time to first token: request sent to first streamed chunk, so it includes the whole pipeline and any queueing. | +| `tpot_s` | Time per output token: `(e2e - ttft) / (output_tokens - 1)`. The first token is excluded from both sides; `parse.py` divides by `output_tokens`. | +| `e2e_s` | Request sent to the end of the stream. | +| `input_tokens`, `output_tokens` | Counted client-side with the run's tokenizer; input is the question only, not the full prompt. | +| `throughput` | Per declared `client.duration`. | -Then the KPIs, in seconds: +Percentiles are linearly interpolated (numpy's default), like `parse.py`. -| Column | Meaning | -|---|---| -| `requests` | Successful requests the statistics are over. A p90 over four requests is a number, not a measurement — this is what licenses reading the rest. | -| `mean_ttft`, `p90_ttft` | **Time to first token**: `first_chunk` as `benchmark.py` records it — request issued to first streamed chunk. Prefill plus all queueing ahead of it, so this is the KPI that moves with concurrency. | -| `mean_tpot`, `p90_tpot` | **Time per output token**: `(end_to_end - ttft) / (output_tokens - 1)`, the mean inter-token gap during decode. | -| `served_model`, `error`, `result_file` | The **tokenizer repo id** the tokens were counted with (resolved from the observed served model's catalog name), the run's exit code, and the pointer back to the per-request CSV — relative to the summary itself, so the whole directory can be copied off the benchmark host with its pointers intact. | - -TPOT excludes the first token from **both** the time and the token count, because -its cost is TTFT. `parse.py`'s `next_token_lat` divides by `output_tokens` -instead, which charges decode for a token it did not generate — under a percent at -128 output tokens, material at 8. p90 is linearly interpolated (numpy/pandas' -default method), so it agrees with `parse.py`'s figures. - -The file is rewritten after every run, so a sweep killed at hour three — or a -model rollout that fails midway — still leaves a complete, valid table of what it -got through. The per-request CSVs are untouched: anything the four KPIs do not -answer (distribution shape, drift within a run, the tail past p90) is still there, -and `result_file` is how you get to it. +`benchmark_summary_results.csv` has one row per run: `date`, `commit_info.*`, then +every field of the record as a dotted column (`run.index`, +`settings.deployment.llms.max_new_tokens`, `settings.client.concurrency`, +`results.ttft_s.p90`, …). Missing values are blank. ### Run config (`--config`) @@ -364,6 +384,7 @@ In increasing cost order: | Check | What it asserts | |---|---| | `question_file_verify()` | Every declared `client.question_file` (the knob is sweepable, so a config may name several) resolves to a readable file. A stat per corpus. | +| `commit_info_verify()` | The checkout pysweep runs from is a git repository with a commit on a branch (not a detached `HEAD`), so the results can name it. A synced copy needs a readable `.git`. | ## Requirements diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/commit_info.py b/src/tests/e2e/benchmarks/chatqna/pysweep/commit_info.py new file mode 100644 index 00000000..516fdee8 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/commit_info.py @@ -0,0 +1,51 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import shutil +import subprocess +from pathlib import Path + +from .paths import REPO_ROOT + +GIT_TIMEOUT = 30 +COMMIT_INFO_FIELDS = ("sha", "datetime", "author", "description", "branch") + + +class CommitInfoError(Exception): + """The checked-out commit cannot be identified.""" + + +def _git(repo: Path, *args: str) -> subprocess.CompletedProcess: + return subprocess.run( + ["git", "-C", str(repo), *args], + capture_output=True, text=True, timeout=GIT_TIMEOUT, check=False, + ) + + +def read_commit_info(repo: Path = REPO_ROOT) -> dict[str, str]: + """Return the committed HEAD's sha, committer datetime, author, subject and branch.""" + if shutil.which("git") is None: + raise CommitInfoError("git is not installed, so the checked-out commit cannot be read.") + + log = _git(repo, "log", "-1", "--format=%H%x00%cI%x00%an%x00%s") + if log.returncode != 0: + raise CommitInfoError( + f"Cannot read the checked-out commit of {repo}: {log.stderr.strip() or log.stdout.strip()}. " + "pysweep must run from a git checkout (a synced copy needs a readable .git)." + ) + sha, committed_at, author, description = log.stdout.rstrip("\n").split("\x00") + + branch = _git(repo, "symbolic-ref", "--short", "-q", "HEAD") + if branch.returncode != 0 or not branch.stdout.strip(): + raise CommitInfoError( + f"HEAD of {repo} is detached ({sha[:12]}); check out a branch so the results " + "can be attributed to one." + ) + + return { + "sha": sha, + "datetime": committed_at, + "author": author, + "description": description, + "branch": branch.stdout.strip(), + } diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md index 9a5d0ea9..f4492884 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md @@ -44,9 +44,9 @@ is one more load test, and nothing on the cluster changes. There is no `tokenizer` key: `-m` is derived from the model the deployment serves, and declaring it is an error. -Every run adds a row to `benchmark_summary_results.csv` in `--summaries` -(default `./results`), with one column per declared knob; the previous sweep's -results there are deleted first. +Every run adds a record to `results.json` and a row to +`benchmark_summary_results.csv` in `--summaries` (default `./results`); the +previous sweep's results there are deleted first. ## `general.yaml` diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py index 0b169f67..5c092429 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -10,11 +10,13 @@ import sys import tempfile from contextlib import ExitStack, contextmanager +from datetime import datetime, timezone from pathlib import Path import yaml from tests.e2e.benchmarks.chatqna import benchmark +from tests.e2e.benchmarks.chatqna.benchmark import duration_to_seconds from tests.e2e.benchmarks.chatqna.pysweep.base import ( Plane, Property, @@ -38,10 +40,14 @@ load_run_config, ) from tests.e2e.benchmarks.chatqna.pysweep import model_catalog +from tests.e2e.benchmarks.chatqna.pysweep.commit_info import CommitInfoError, read_commit_info from tests.e2e.benchmarks.chatqna.pysweep.results import ( DEFAULT_SUMMARIES_DIR, - SweepSummary, + SweepResults, prepare_summaries_dir, + read_requests, + run_record, + summarize_requests, ) from tests.e2e.benchmarks.chatqna.pysweep.runtime_api import ( FingerprintClient, @@ -223,8 +229,23 @@ def question_file_verify(config: SweepConfig) -> None: logger.debug("Preflight: question_file '%s' -> %s", value, path) -def preflight_check(config: SweepConfig) -> None: +def commit_info_verify() -> dict[str, str]: + """Raise PreflightError unless the checked-out commit can be identified; return it.""" + try: + info = read_commit_info() + except CommitInfoError as exc: + raise PreflightError(f"commit_info: {exc}") from exc + logger.info( + "Preflight: results are attributed to %s on %s (%s).", + info["sha"][:12], info["branch"], info["description"], + ) + return info + + +def preflight_check(config: SweepConfig) -> dict[str, str]: + """Run every preflight check; return the commit the results are attributed to.""" question_file_verify(config) + return commit_info_verify() def chatqna_url() -> str: @@ -308,11 +329,11 @@ def parse_args(argv=None): "--summaries", default=DEFAULT_SUMMARIES_DIR, help=( - "Directory a sweep writes into: benchmark_summary_results.csv (a row " - "per run, a column per declared knob, TTFT/TPOT mean/p90) and " - "per_case_results/ (one per-request CSV per run). Created if missing. " - "WARNING: the previous sweep's summary and per-case CSVs there are " - f"DELETED before this one starts (default: {DEFAULT_SUMMARIES_DIR})." + "Directory a sweep writes into: results.json (the sweep's run records), " + "benchmark_summary_results.csv (the same records, one dotted-column row " + "per run) and per_case_results/ (one per-request CSV per run). Created if " + "missing. WARNING: the previous sweep's outputs there are DELETED before " + f"this one starts (default: {DEFAULT_SUMMARIES_DIR})." ), ) parser.add_argument( @@ -383,6 +404,16 @@ def format_settings_yaml(values: dict, indent: int = LOG_YAML_INDENT) -> str: ).rstrip("\n") +def format_record_yaml(record: dict, indent: int = LOG_YAML_INDENT) -> str: + return yaml.safe_dump( + record, indent=indent, sort_keys=False, default_flow_style=False + ).rstrip("\n") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") + + def run_client_combination( benchmark, bench_argv: list[str], @@ -431,13 +462,13 @@ def main(argv=None): config = load_config(args.sweep) bench_argv = resolve_benchmark_argv(config, args.benchmark_args) - preflight_check(config) + commit_info = preflight_check(config) deployment_combinations = config.deployment_combinations() client_combinations = config.client_combinations() varying_paths = config.varying_paths() layout = prepare_summaries_dir(args.summaries) - summary = SweepSummary(config.knob_paths(), path=layout.summary_file) + sweep_results = SweepResults(layout, date=utc_now(), commit_info=commit_info) fingerprint_client = FingerprintClient(default_transport()) @@ -472,25 +503,36 @@ def main(argv=None): # Test doubles may yield a plain list. if isinstance(provisioned_argv, ProvisionedArgv): provisioned_argv.refresh() + started_at = utc_now() error, output_file = run_client_combination( benchmark, provisioned_argv, combination, client_combination, label, results_dir=layout.per_case_dir, varying_paths=varying_paths, tokenizer=tokenizer, ) + finished_at = utc_now() overall_error = overall_error or error - row = summary.add_run( - knob_values={ - **snapshot, - **{s.path: s.value for s in client_combination}, - }, - result_file=output_file, - error=error, - served_model=tokenizer, + client = {s.path: s.value for s in client_combination} + record = sweep_results.add_run( + run_record( + index=f"{index}.{client_index}", + started_at=started_at, + finished_at=finished_at, + exit_code=error, + result_file=sweep_results.pointer(output_file), + deployment=snapshot, + client={**client, "client.tokenizer": tokenizer}, + results=summarize_requests( + read_requests(output_file), + duration_to_seconds(str(client["client.duration"])), + ), + ) ) - logger.info("%s summary:\n%s", label, format_settings_yaml(row)) + logger.info("%s record:\n%s", label, format_record_yaml(record)) - logger.info("Sweep summary (%d run(s)) written to %s", len(summary.rows), summary.write()) + logger.info( + "Sweep results (%d run(s)) written to %s", len(sweep_results.runs), sweep_results.write() + ) return overall_error diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py index 997cf250..bcffef6e 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py @@ -2,31 +2,27 @@ # SPDX-License-Identifier: Apache-2.0 import csv +import json import logging import math import shutil from pathlib import Path from typing import Any, Iterable, NamedTuple, Sequence +from .commit_info import COMMIT_INFO_FIELDS + logger = logging.getLogger(__name__) DEFAULT_SUMMARIES_DIR = "./results" # Not bench_*.csv: parse.py globs that as per-request data. SUMMARY_FILE_NAME = "benchmark_summary_results.csv" +RESULTS_FILE_NAME = "results.json" PER_CASE_DIR_NAME = "per_case_results" -SUMMARY_COLUMNS: tuple[str, ...] = ( - "requests", - "mean_ttft", - "p90_ttft", - "mean_tpot", - "p90_tpot", - "served_model", - "error", - "result_file", -) +SCHEMA_VERSION = 1 +PERCENTILES = (("p50", 0.5), ("p90", 0.9), ("p99", 0.99)) _PRECISION = 6 @@ -40,6 +36,7 @@ class SummariesLayout(NamedTuple): root: Path summary_file: Path + results_file: Path per_case_dir: Path @@ -65,12 +62,13 @@ def prepare_summaries_dir(root=DEFAULT_SUMMARIES_DIR) -> SummariesLayout: ) summary_file = root / SUMMARY_FILE_NAME + results_file = root / RESULTS_FILE_NAME per_case_dir = root / PER_CASE_DIR_NAME - if summary_file.is_dir(): - raise SummariesLayoutError( - f"{summary_file} is a directory; a sweep needs to write its summary " - "table there." - ) + for output in (summary_file, results_file): + if output.is_dir(): + raise SummariesLayoutError( + f"{output} is a directory; a sweep needs to write its summary there." + ) if per_case_dir.is_symlink(): raise SummariesLayoutError( f"{per_case_dir} is a symlink. It is emptied before every sweep, and " @@ -85,9 +83,10 @@ def prepare_summaries_dir(root=DEFAULT_SUMMARIES_DIR) -> SummariesLayout: root.mkdir(parents=True, exist_ok=True) - if summary_file.exists(): - summary_file.unlink() - logger.info("Discarded the previous summary %s.", summary_file) + for output in (summary_file, results_file): + if output.exists(): + output.unlink() + logger.info("Discarded the previous summary %s.", output) if per_case_dir.is_dir(): removed = _clear_directory(per_case_dir) @@ -101,11 +100,12 @@ def prepare_summaries_dir(root=DEFAULT_SUMMARIES_DIR) -> SummariesLayout: layout = SummariesLayout( root=root.resolve(), summary_file=summary_file.resolve(), + results_file=results_file.resolve(), per_case_dir=per_case_dir.resolve(), ) logger.info( - "Writing results to %s (summary: %s, per-case CSVs: %s/).", - layout.root, SUMMARY_FILE_NAME, PER_CASE_DIR_NAME, + "Writing results to %s (%s, %s, per-case CSVs: %s/).", + layout.root, RESULTS_FILE_NAME, SUMMARY_FILE_NAME, PER_CASE_DIR_NAME, ) return layout @@ -180,79 +180,134 @@ def _mean(values: Sequence[float]) -> float | None: return sum(values) / len(values) if values else None -def _round(value: float | None) -> str: - return "" if value is None else f"{round(value, _PRECISION)}" +def _round(value: float | None) -> float | None: + return None if value is None else round(value, _PRECISION) -def summarize_requests(records: Iterable[RequestRecord]) -> dict[str, Any]: - """Aggregate request records into the KPI columns.""" +def _distribution(values: Sequence[float]) -> dict[str, float | None]: + stats = {"mean": _round(_mean(values))} + stats.update({name: _round(percentile(values, q)) for name, q in PERCENTILES}) + return stats + + +def summarize_requests(records: Iterable[RequestRecord], duration_s: float) -> dict[str, Any]: + """Aggregate request records into a run's ``results``; rates are per declared duration.""" records = list(records) - ttfts = [record.ttft for record in records] - tpots = [record.tpot for record in records if record.tpot is not None] + output_total = sum(record.output_tokens for record in records) return { - "requests": len(records), - "mean_ttft": _mean(ttfts), - "p90_ttft": percentile(ttfts, 0.9), - "mean_tpot": _mean(tpots), - "p90_tpot": percentile(tpots, 0.9), + "requests": {"ok": len(records)}, + "ttft_s": _distribution([record.ttft for record in records]), + "tpot_s": _distribution([record.tpot for record in records if record.tpot is not None]), + "e2e_s": _distribution([record.end_to_end for record in records]), + "input_tokens": {"mean": _round(_mean([record.input_tokens for record in records]))}, + "output_tokens": { + "mean": _round(_mean([record.output_tokens for record in records])), + "total": output_total, + }, + "throughput": { + "requests_per_s": _round(len(records) / duration_s) if duration_s > 0 else None, + "output_tokens_per_s": _round(output_total / duration_s) if duration_s > 0 else None, + }, } -class SweepSummary: - """Accumulates one row per run and rewrites the summary CSV after each.""" +def nest(dotted: dict[str, Any]) -> dict[str, Any]: + """Turn ``{"a.b": 1}`` into ``{"a": {"b": 1}}``, keeping key order.""" + tree: dict[str, Any] = {} + for path, value in dotted.items(): + *parents, leaf = path.split(".") + node = tree + for part in parents: + node = node.setdefault(part, {}) + node[leaf] = value + return tree + + +def flatten(tree: dict[str, Any], prefix: str = "") -> dict[str, Any]: + """Turn nested dicts into dotted keys, keeping key order.""" + flat: dict[str, Any] = {} + for key, value in tree.items(): + path = f"{prefix}{key}" + if isinstance(value, dict): + flat.update(flatten(value, f"{path}.")) + else: + flat[path] = value + return flat + + +def run_record( + index: str, + started_at: str, + finished_at: str, + exit_code: int, + result_file: str, + deployment: dict[str, Any], + client: dict[str, Any], + results: dict[str, Any], +) -> dict[str, Any]: + """One run's record; ``deployment``/``client`` take dotted knob paths.""" + return { + "run": { + "index": index, + "started_at": started_at, + "finished_at": finished_at, + "exit_code": exit_code, + "result_file": result_file, + }, + "settings": { + "deployment": nest(deployment), + "client": nest({path.removeprefix("client."): value for path, value in client.items()}), + }, + "results": results, + } + - def __init__( - self, - knob_paths: Sequence[str], - path=Path(DEFAULT_SUMMARIES_DIR) / SUMMARY_FILE_NAME, - ): - self.knob_paths = list(knob_paths) - self.path = Path(path) - self.rows: list[dict[str, Any]] = [] +class SweepResults: + """Accumulates run records and rewrites results.json and the summary CSV after each.""" + + def __init__(self, layout: SummariesLayout, date: str, commit_info: dict[str, str]): + self.layout = layout + self.date = date + self.commit_info = commit_info + self.runs: list[dict[str, Any]] = [] self.write() - def _pointer(self, result_file) -> str: + def pointer(self, result_file) -> str: + """``result_file`` relative to the summaries directory, so the directory can be moved.""" path = Path(result_file) try: - return str(path.relative_to(self.path.parent)) + return str(path.relative_to(self.layout.root)) except ValueError: return str(result_file) - @property - def columns(self) -> list[str]: - return self.knob_paths + list(SUMMARY_COLUMNS) - - def add_run( - self, - knob_values: dict[str, Any], - result_file, - error: int = 0, - served_model: str | None = None, - ) -> dict[str, Any]: - """Summarize one finished run and return the recorded row.""" - summary = summarize_requests(read_requests(result_file)) - row: dict[str, Any] = {path: knob_values.get(path, "") for path in self.knob_paths} - row.update(summary) - row["served_model"] = served_model or "" - row["error"] = error - row["result_file"] = self._pointer(result_file) - self.rows.append(row) + def document(self) -> dict[str, Any]: + return { + "schema_version": SCHEMA_VERSION, + "date": self.date, + "commit_info": self.commit_info, + "runs": self.runs, + } + + def add_run(self, record: dict[str, Any]) -> dict[str, Any]: + self.runs.append(record) self.write() - return row + return record + + def _csv_rows(self) -> list[dict[str, Any]]: + sweep = { + "date": self.date, + **{f"commit_info.{field}": self.commit_info.get(field) for field in COMMIT_INFO_FIELDS}, + } + return [{**sweep, **flatten(record)} for record in self.runs] def write(self) -> Path: - with self.path.open("w", newline="") as handle: - writer = csv.DictWriter(handle, fieldnames=self.columns) - writer.writeheader() - for row in self.rows: - writer.writerow( - { - column: ( - _round(row[column]) - if column in ("mean_ttft", "p90_ttft", "mean_tpot", "p90_tpot") - else row.get(column, "") - ) - for column in self.columns - } - ) - return self.path + self.layout.results_file.write_text(json.dumps(self.document(), indent=2) + "\n") + rows = self._csv_rows() + columns = list(rows[0]) if rows else [] + with self.layout.summary_file.open("w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=columns) + if columns: + writer.writeheader() + for row in rows: + writer.writerow({column: "" if row.get(column) is None else row[column] for column in columns}) + return self.layout.results_file diff --git a/src/tests/e2e/validation/pysweep/test_commit_info_unit.py b/src/tests/e2e/validation/pysweep/test_commit_info_unit.py new file mode 100644 index 00000000..9f09f025 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_commit_info_unit.py @@ -0,0 +1,74 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import shutil +import subprocess + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import commit_info +from tests.e2e.benchmarks.chatqna.pysweep.commit_info import ( + COMMIT_INFO_FIELDS, + CommitInfoError, + read_commit_info, +) + +needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed") + + +def _git(repo, *args): + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True) + + +@pytest.fixture +def repo(tmp_path): + _git(tmp_path, "init", "-q", "-b", "feature/x") + _git(tmp_path, "config", "user.name", "A. Author") + _git(tmp_path, "config", "user.email", "author@example.com") + (tmp_path / "f.txt").write_text("one\n") + _git(tmp_path, "add", "f.txt") + _git(tmp_path, "commit", "-q", "-m", "feat: first change", "-m", "Body that must not appear.") + return tmp_path + + +@allure.feature("pysweep") +@needs_git +def test_commit_info_describes_the_committed_head(repo): + info = read_commit_info(repo) + assert tuple(info) == COMMIT_INFO_FIELDS + assert len(info["sha"]) == 40 + assert info["author"] == "A. Author" + assert info["description"] == "feat: first change" + assert info["branch"] == "feature/x" + assert "T" in info["datetime"] + + +@allure.feature("pysweep") +@needs_git +def test_uncommitted_changes_do_not_count(repo): + before = read_commit_info(repo) + (repo / "f.txt").write_text("edited\n") + assert read_commit_info(repo) == before + + +@allure.feature("pysweep") +@needs_git +def test_a_detached_head_is_an_error(repo): + _git(repo, "checkout", "-q", "--detach") + with pytest.raises(CommitInfoError, match="detached"): + read_commit_info(repo) + + +@allure.feature("pysweep") +@needs_git +def test_a_directory_without_git_is_an_error(tmp_path): + with pytest.raises(CommitInfoError, match="readable .git"): + read_commit_info(tmp_path) + + +@allure.feature("pysweep") +def test_missing_git_is_an_error(monkeypatch, tmp_path): + monkeypatch.setattr(commit_info.shutil, "which", lambda name: None) + with pytest.raises(CommitInfoError, match="git is not installed"): + read_commit_info(tmp_path) diff --git a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py index 2a8df92f..643fbb8d 100644 --- a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -5,6 +5,7 @@ import ast import csv import itertools +import json import linecache import logging from contextlib import contextmanager @@ -12,6 +13,7 @@ import allure import pytest +import yaml from tests.e2e.benchmarks.chatqna.pysweep import pysweep_bench as psb from tests.e2e.benchmarks.chatqna.pysweep.base import ( @@ -38,6 +40,21 @@ } +COMMIT = { + "sha": "0123456789abcdef0123456789abcdef01234567", + "datetime": "2026-11-25T18:02:44+01:00", + "author": "A. Author", + "description": "feat: something", + "branch": "kkurzacz/pysweep-core", +} + + +@pytest.fixture(autouse=True) +def _committed_checkout(monkeypatch): + # CI checks out without git, so no test may depend on the real repository. + monkeypatch.setattr(psb, "read_commit_info", lambda: dict(COMMIT)) + + def _sweep(**sections): return {"client": dict(CLIENT), **sections} @@ -293,19 +310,28 @@ def test_sweep_writes_one_summary_row_per_run(monkeypatch, tmp_path): summary_file = tmp_path / "out" / results.SUMMARY_FILE_NAME rows = list(csv.DictReader(summary_file.open())) assert len(rows) == 4 - assert [(r["llms.max_new_tokens"], r["client.concurrency"]) for r in rows] == [ - ("128", "1"), ("128", "16"), ("256", "1"), ("256", "16"), - ] - assert {r["client.duration"] for r in rows} == {"3m"} + assert [ + (r["settings.deployment.llms.max_new_tokens"], r["settings.client.concurrency"]) + for r in rows + ] == [("128", "1"), ("128", "16"), ("256", "1"), ("256", "16")] + assert [r["run.index"] for r in rows] == ["1.1", "1.2", "2.1", "2.2"] + assert {r["settings.client.duration"] for r in rows} == {"3m"} # FakeBenchmark writes 128,128,0.8,6.9,,200 twice per run. - assert {r["requests"] for r in rows} == {"2"} - assert {r["mean_ttft"] for r in rows} == {"0.8"} - assert {r["mean_tpot"] for r in rows} == {str(round((6.9 - 0.8) / 127, 6))} - assert {r["served_model"] for r in rows} == {"served/model"} + assert {r["results.requests.ok"] for r in rows} == {"2"} + assert {r["results.ttft_s.mean"] for r in rows} == {"0.8"} + assert {r["results.tpot_s.mean"] for r in rows} == {str(round((6.9 - 0.8) / 127, 6))} + assert {r["settings.client.tokenizer"] for r in rows} == {"served/model"} + assert {r["commit_info.sha"] for r in rows} == {COMMIT["sha"]} # Relative to the summary, so the directory can be copied off the host intact. - assert all(not Path(r["result_file"]).is_absolute() for r in rows) - assert all((summary_file.parent / r["result_file"]).exists() for r in rows) - assert {Path(r["result_file"]).parent.name for r in rows} == {results.PER_CASE_DIR_NAME} + pointers = [r["run.result_file"] for r in rows] + assert all(not Path(p).is_absolute() for p in pointers) + assert all((summary_file.parent / p).exists() for p in pointers) + assert {Path(p).parent.name for p in pointers} == {results.PER_CASE_DIR_NAME} + + document = json.loads((tmp_path / "out" / results.RESULTS_FILE_NAME).read_text()) + assert document["commit_info"] == COMMIT + assert [run["run"]["index"] for run in document["runs"]] == ["1.1", "1.2", "2.1", "2.2"] + assert document["runs"][0]["settings"]["deployment"] == {"llms": {"max_new_tokens": 128}} @allure.feature("pysweep") @@ -783,7 +809,46 @@ def test_summary_records_the_declared_path_not_the_resolved_one(monkeypatch, tmp summary = tmp_path / results.DEFAULT_SUMMARIES_DIR / results.SUMMARY_FILE_NAME rows = list(csv.DictReader(summary.read_text().splitlines())) - assert rows[0]["client.question_file"] == "../questions-short.csv" + assert rows[0]["settings.client.question_file"] == "../questions-short.csv" + + +@allure.feature("pysweep") +def test_preflight_returns_the_commit_the_results_are_attributed_to(): + assert psb.preflight_check(load_config(_client())) == COMMIT + + +@allure.feature("pysweep") +def test_preflight_fails_without_commit_info(monkeypatch): + def unreadable(): + raise psb.CommitInfoError("not a git repository") + + monkeypatch.setattr(psb, "read_commit_info", unreadable) + with pytest.raises(psb.PreflightError, match="commit_info: not a git repository"): + psb.preflight_check(load_config(_client())) + + +@allure.feature("pysweep") +def test_each_run_logs_its_record_as_yaml(monkeypatch, tmp_path, caplog): + monkeypatch.chdir(tmp_path) + cfg = load_config(_client()) + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr(psb, "apply_combination", lambda c, f: {}) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, FakeBenchmark()) + + with caplog.at_level(logging.INFO, logger=psb.logger.name): + assert psb.main(["--sweep", "ignored.yaml", "--summaries", "out"]) == 0 + + (message,) = [r.getMessage() for r in caplog.records if " record:\n" in r.getMessage()] + logged = yaml.safe_load(message.split(" record:\n", 1)[1]) + document = json.loads((tmp_path / "out" / results.RESULTS_FILE_NAME).read_text()) + assert logged == document["runs"][0] + assert list(logged) == ["run", "settings", "results"] @allure.feature("pysweep") @@ -798,6 +863,7 @@ def test_preflight_runs_once_for_the_whole_sweep(monkeypatch, tmp_path): def counting_preflight(config): calls.append(len(fake.calls)) + return dict(COMMIT) run_config = psb.load_run_config({}) monkeypatch.setattr(psb, "preflight_check", counting_preflight) diff --git a/src/tests/e2e/validation/pysweep/test_results_unit.py b/src/tests/e2e/validation/pysweep/test_results_unit.py index 311503fb..e2319a21 100644 --- a/src/tests/e2e/validation/pysweep/test_results_unit.py +++ b/src/tests/e2e/validation/pysweep/test_results_unit.py @@ -2,24 +2,36 @@ # SPDX-License-Identifier: Apache-2.0 import csv +import json import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep.config import load_config from tests.e2e.benchmarks.chatqna.pysweep.results import ( PER_CASE_DIR_NAME, - SUMMARY_COLUMNS, + RESULTS_FILE_NAME, + SCHEMA_VERSION, SUMMARY_FILE_NAME, RequestRecord, SummariesLayoutError, - SweepSummary, + SweepResults, + flatten, + nest, percentile, prepare_summaries_dir, read_requests, + run_record, summarize_requests, ) +COMMIT = { + "sha": "0123456789abcdef0123456789abcdef01234567", + "datetime": "2026-11-25T18:02:44+01:00", + "author": "A. Author", + "description": "feat: something", + "branch": "kkurzacz/pysweep-core", +} + CLIENT = { "question_file": "questions-short.csv", "concurrency": 4, @@ -61,7 +73,7 @@ def test_percentile_interpolates_like_pandas(): @allure.feature("pysweep") -def test_kpis_are_computed_over_the_recorded_requests(tmp_path): +def test_results_are_computed_over_the_recorded_requests(tmp_path): path = _result_file( tmp_path, [ @@ -69,12 +81,32 @@ def test_kpis_are_computed_over_the_recorded_requests(tmp_path): [128, 11, 2.0, 6.0, "", 200], ], ) - summary = summarize_requests(read_requests(path)) - assert summary["requests"] == 2 - assert summary["mean_ttft"] == pytest.approx(1.5) - assert summary["p90_ttft"] == pytest.approx(1.9) - assert summary["mean_tpot"] == pytest.approx(0.3) - assert summary["p90_tpot"] == pytest.approx(0.38) + results = summarize_requests(read_requests(path), duration_s=10) + assert results["requests"] == {"ok": 2} + assert results["ttft_s"]["mean"] == pytest.approx(1.5) + assert results["ttft_s"]["p50"] == pytest.approx(1.5) + assert results["ttft_s"]["p90"] == pytest.approx(1.9) + assert results["tpot_s"]["mean"] == pytest.approx(0.3) + assert results["tpot_s"]["p90"] == pytest.approx(0.38) + assert results["e2e_s"]["mean"] == pytest.approx(4.5) + assert results["input_tokens"] == {"mean": 128} + assert results["output_tokens"] == {"mean": 11, "total": 22} + assert results["throughput"] == {"requests_per_s": 0.2, "output_tokens_per_s": 2.2} + + +@allure.feature("pysweep") +def test_results_keep_their_shape_when_nothing_was_recorded(): + results = summarize_requests([], duration_s=10) + assert results["requests"] == {"ok": 0} + assert results["ttft_s"] == {"mean": None, "p50": None, "p90": None, "p99": None} + assert results["output_tokens"] == {"mean": None, "total": 0} + assert results["throughput"] == {"requests_per_s": 0.0, "output_tokens_per_s": 0.0} + + +@allure.feature("pysweep") +def test_throughput_is_undefined_without_a_duration(): + results = summarize_requests([RequestRecord(128, 11, 1.0, 3.0, "", 200)], duration_s=0) + assert results["throughput"] == {"requests_per_s": None, "output_tokens_per_s": None} @allure.feature("pysweep") @@ -92,110 +124,115 @@ def test_unsuccessful_and_implausible_rows_are_excluded(tmp_path): ) records = read_requests(path) assert len(records) == 1 - assert summarize_requests(records)["requests"] == 1 + assert summarize_requests(records, duration_s=10)["requests"] == {"ok": 1} @allure.feature("pysweep") -def test_a_run_that_recorded_nothing_still_gets_a_row(tmp_path): - summary = SweepSummary(["client.concurrency"], path=tmp_path / "s.csv") - row = summary.add_run({"client.concurrency": 128}, tmp_path / "missing.csv", error=1) - assert row["requests"] == 0 - assert row["mean_ttft"] is None - written = list(csv.DictReader((tmp_path / "s.csv").open())) - assert written == [ - { - "client.concurrency": "128", - "requests": "0", - "mean_ttft": "", - "p90_ttft": "", - "mean_tpot": "", - "p90_tpot": "", - "served_model": "", - "error": "1", - "result_file": "missing.csv", - } - ] +def test_nest_and_flatten_are_inverse(): + dotted = {"llms.max_new_tokens": 128, "retriever.k": 5, "top": 1} + assert nest(dotted) == {"llms": {"max_new_tokens": 128}, "retriever": {"k": 5}, "top": 1} + assert flatten(nest(dotted)) == dotted + + +def _record(index="1.1", result_file="per_case_results/r.csv", concurrency=4, results=None): + return run_record( + index=index, + started_at="2026-11-26T09:14:03Z", + finished_at="2026-11-26T09:29:05Z", + exit_code=0, + result_file=result_file, + deployment={"llms.max_new_tokens": 128}, + client={"client.concurrency": concurrency, "client.tokenizer": "org/tok"}, + results=results or summarize_requests([], duration_s=60), + ) @allure.feature("pysweep") -def test_result_file_is_recorded_relative_to_the_summary(tmp_path): - per_case = tmp_path / PER_CASE_DIR_NAME - per_case.mkdir() - result = _result_file(per_case, [[128, 11, 1.0, 3.0, "", 200]]) - summary = SweepSummary(["client.concurrency"], path=tmp_path / SUMMARY_FILE_NAME) - - row = summary.add_run({"client.concurrency": 4}, result) - - assert row["result_file"] == f"{PER_CASE_DIR_NAME}/bench_x.result.csv" - assert (summary.path.parent / row["result_file"]).exists() +def test_a_record_groups_settings_into_deployment_and_client(): + record = _record() + assert list(record) == ["run", "settings", "results"] + assert record["run"] == { + "index": "1.1", + "started_at": "2026-11-26T09:14:03Z", + "finished_at": "2026-11-26T09:29:05Z", + "exit_code": 0, + "result_file": "per_case_results/r.csv", + } + assert record["settings"] == { + "deployment": {"llms": {"max_new_tokens": 128}}, + "client": {"concurrency": 4, "tokenizer": "org/tok"}, + } + + +@pytest.fixture +def layout(tmp_path): + return prepare_summaries_dir(tmp_path / "out") @allure.feature("pysweep") -def test_a_result_file_from_outside_the_directory_is_recorded_verbatim(tmp_path): - elsewhere = _result_file(tmp_path, [[128, 11, 1.0, 3.0, "", 200]]) - root = tmp_path / "results" - root.mkdir() - summary = SweepSummary([], path=root / SUMMARY_FILE_NAME) +def test_results_json_exists_before_the_first_run_finishes(layout): + SweepResults(layout, date="2026-11-26T09:02:11Z", commit_info=COMMIT) + assert json.loads(layout.results_file.read_text()) == { + "schema_version": SCHEMA_VERSION, + "date": "2026-11-26T09:02:11Z", + "commit_info": COMMIT, + "runs": [], + } - row = summary.add_run({}, elsewhere) - assert row["result_file"] == str(elsewhere) +@allure.feature("pysweep") +def test_results_json_holds_every_run_after_each_one(layout): + sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", commit_info=COMMIT) + for index in (1, 2): + sweep.add_run(_record(index=f"1.{index}")) + document = json.loads(layout.results_file.read_text()) + assert [run["run"]["index"] for run in document["runs"]] == [f"1.{i}" for i in range(1, index + 1)] @allure.feature("pysweep") -def test_summary_columns_are_the_declared_knobs_in_dot_notation(tmp_path): - """Single-valued knobs get columns too.""" - cfg = load_config( - { - "client": {**CLIENT, "concurrency": [1, 16], "input_tokens": [128, 256]}, - "llms": {"max_new_tokens": [128, 256]}, - } - ) - summary = SweepSummary(cfg.knob_paths(), path=tmp_path / "s.csv") - assert summary.columns == [ - "llms.max_new_tokens", - "client.concurrency", - "client.duration", - "client.failures_allowed", - "client.input_tokens", - "client.question_file", - "client.warmup_requests", - "client.worker_startup_delay", - *SUMMARY_COLUMNS, +def test_the_csv_has_one_dotted_row_per_run(layout): + sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", commit_info=COMMIT) + sweep.add_run(_record(concurrency=1)) + sweep.add_run(_record(index="1.2", concurrency=16)) + + rows = list(csv.DictReader(layout.summary_file.open())) + assert [row["settings.client.concurrency"] for row in rows] == ["1", "16"] + header = next(csv.reader(layout.summary_file.open())) + assert header[:7] == [ + "date", + "commit_info.sha", + "commit_info.datetime", + "commit_info.author", + "commit_info.description", + "commit_info.branch", + "run.index", ] + assert "settings.deployment.llms.max_new_tokens" in header + assert "results.ttft_s.p90" in header + assert rows[0]["commit_info.branch"] == "kkurzacz/pysweep-core" @allure.feature("pysweep") -def test_header_exists_before_the_first_run_finishes(tmp_path): - path = tmp_path / "sweep_summary.csv" - summary = SweepSummary(["client.concurrency"], path=path) - assert path.exists() - assert next(csv.reader(path.open())) == summary.columns - assert list(csv.DictReader(path.open())) == [] +def test_missing_values_render_blank_in_the_csv(layout): + sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", commit_info=COMMIT) + sweep.add_run(_record()) + (row,) = csv.DictReader(layout.summary_file.open()) + assert row["results.ttft_s.mean"] == "" + assert row["results.requests.ok"] == "0" @allure.feature("pysweep") -def test_summary_is_readable_after_every_run(tmp_path): - path = tmp_path / "sweep_summary.csv" - summary = SweepSummary(["client.concurrency"], path=path) - for index, concurrency in enumerate((1, 16), start=1): - result = _result_file( - tmp_path, [[128, 11, 1.0, 3.0, "", 200]], name=f"bench_{concurrency}.csv" - ) - summary.add_run({"client.concurrency": concurrency}, result) - rows = list(csv.DictReader(path.open())) - assert len(rows) == index - assert [row["client.concurrency"] for row in rows] == ["1", "16"] - assert [row["mean_tpot"] for row in rows] == ["0.2", "0.2"] +def test_result_file_pointer_is_relative_to_the_summaries_directory(layout): + sweep = SweepResults(layout, date="d", commit_info=COMMIT) + inside = layout.per_case_dir / "bench_x.result.csv" + assert sweep.pointer(inside) == f"{PER_CASE_DIR_NAME}/bench_x.result.csv" @allure.feature("pysweep") -def test_unset_knobs_render_blank_rather_than_shifting_columns(tmp_path): - summary = SweepSummary(["llms.max_new_tokens", "client.concurrency"], path=tmp_path / "s.csv") - row = summary.add_run({"client.concurrency": 4}, tmp_path / "none.csv") - assert row["llms.max_new_tokens"] == "" - header = next(csv.reader((tmp_path / "s.csv").open())) - assert header[:2] == ["llms.max_new_tokens", "client.concurrency"] +def test_a_result_file_from_outside_the_directory_is_recorded_verbatim(layout, tmp_path): + sweep = SweepResults(layout, date="d", commit_info=COMMIT) + elsewhere = tmp_path / "elsewhere.csv" + assert sweep.pointer(elsewhere) == str(elsewhere) @allure.feature("pysweep") @@ -206,6 +243,7 @@ def test_the_output_layout_is_created_when_nothing_is_there(tmp_path): assert layout.root.is_dir() assert layout.per_case_dir.is_dir() assert layout.summary_file == layout.root / SUMMARY_FILE_NAME + assert layout.results_file == layout.root / RESULTS_FILE_NAME assert layout.per_case_dir == layout.root / PER_CASE_DIR_NAME @@ -217,6 +255,7 @@ def test_the_paths_are_absolute(tmp_path, monkeypatch): assert layout.root.is_absolute() assert layout.summary_file.is_absolute() + assert layout.results_file.is_absolute() assert layout.per_case_dir.is_absolute() @@ -226,6 +265,7 @@ def test_the_previous_sweep_is_discarded(tmp_path): per_case = root / PER_CASE_DIR_NAME per_case.mkdir(parents=True) (root / SUMMARY_FILE_NAME).write_text("stale header\n") + (root / RESULTS_FILE_NAME).write_text("{}\n") (per_case / "bench_old.result.csv").write_text("stale\n") (per_case / "nested").mkdir() (per_case / "nested" / "deeper.csv").write_text("stale\n") @@ -233,6 +273,7 @@ def test_the_previous_sweep_is_discarded(tmp_path): layout = prepare_summaries_dir(root) assert not layout.summary_file.exists() + assert not layout.results_file.exists() assert list(layout.per_case_dir.iterdir()) == [] From 07c2f05b55bdd52011f02d5d7e59fd0a3d68ddbf Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 27 Nov 2026 17:08:27 +0100 Subject: [PATCH 06/11] refactor(benchmarks): group pysweep modules into cluster/, provenance/ and properties/ Move the modules that talk to the deployment into cluster/ (auth.py, fingerprint.py, served_model.py, model_catalog.py), the ones that record where results come from into provenance/ (commit_info.py, paths.py), and the Property interface next to the knobs in properties/base.py. Only imports change, plus paths.REPO_ROOT counting one more parent directory. Signed-off-by: Kurzacz, Kamil --- .../e2e/benchmarks/chatqna/pysweep/DESIGN.md | 2 +- .../e2e/benchmarks/chatqna/pysweep/README.md | 23 ++++++++++--------- .../chatqna/pysweep/cluster/__init__.py | 2 ++ .../{authentication.py => cluster/auth.py} | 2 +- .../fingerprint.py} | 4 ++-- .../pysweep/{ => cluster}/model_catalog.py | 2 +- .../pysweep/{ => cluster}/served_model.py | 2 +- .../e2e/benchmarks/chatqna/pysweep/config.py | 2 +- .../chatqna/pysweep/{ => properties}/base.py | 0 .../chatqna/pysweep/properties/max_tokens.py | 4 ++-- .../chatqna/pysweep/provenance/__init__.py | 2 ++ .../pysweep/{ => provenance}/commit_info.py | 0 .../chatqna/pysweep/{ => provenance}/paths.py | 4 ++-- .../chatqna/pysweep/pysweep_bench.py | 14 +++++------ .../e2e/benchmarks/chatqna/pysweep/results.py | 2 +- src/tests/e2e/validation/pysweep/conftest.py | 4 ++-- .../pysweep/test_commit_info_unit.py | 4 ++-- .../validation/pysweep/test_config_unit.py | 2 +- .../pysweep/test_max_tokens_unit.py | 2 +- .../pysweep/test_model_catalog_unit.py | 4 ++-- .../e2e/validation/pysweep/test_paths_unit.py | 13 ++++++----- .../pysweep/test_pysweep_bench_unit.py | 14 +++++------ .../validation/pysweep/test_served_model.py | 4 ++-- .../pysweep/test_served_model_unit.py | 6 ++--- .../pysweep/test_token_lifespan_unit.py | 10 ++++---- 25 files changed, 67 insertions(+), 61 deletions(-) create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/cluster/__init__.py rename src/tests/e2e/benchmarks/chatqna/pysweep/{authentication.py => cluster/auth.py} (99%) rename src/tests/e2e/benchmarks/chatqna/pysweep/{runtime_api.py => cluster/fingerprint.py} (97%) rename src/tests/e2e/benchmarks/chatqna/pysweep/{ => cluster}/model_catalog.py (98%) rename src/tests/e2e/benchmarks/chatqna/pysweep/{ => cluster}/served_model.py (98%) rename src/tests/e2e/benchmarks/chatqna/pysweep/{ => properties}/base.py (100%) create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py rename src/tests/e2e/benchmarks/chatqna/pysweep/{ => provenance}/commit_info.py (100%) rename src/tests/e2e/benchmarks/chatqna/pysweep/{ => provenance}/paths.py (84%) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md b/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md index 7dc26c30..3b1a10d4 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/DESIGN.md @@ -10,7 +10,7 @@ SPDX-License-Identifier: Apache-2.0 > designed and land next. The K8s-spec plane's one designed knob, `llms.model` > (`LlmModel`: model-manager + `gmc-config`), is **not implemented yet**; the > sections on it describe the design it will follow. Until then the runner only *reads* the served model, -> to derive the benchmark's tokenizer (`served_model.py`). +> to derive the benchmark's tokenizer (`cluster/served_model.py`). ## Problem diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md index a6c9f0a3..765cacbf 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -18,21 +18,22 @@ environment gotchas. | Path | What it is | |---|---| -| `base.py` | `Property` interface + `Plane` enum (K8s-spec plane vs Runtime-API plane). | +| `pysweep_bench.py` | Sweep runner: load config → apply/converge/verify each deployment combination → run one load test per client combination, reusing `benchmark.py`. | | `config.py` | Pydantic-validated configs: `load_config()` / `SweepConfig` (+ the `deployment_combinations()` and `client_combinations()` cartesian `product` expansions) and `load_run_config()` / `RunConfig`. | +| `results.py` | Run records, `results.json` and the summary CSV. | | `client_args.py` | Adapter mirroring `benchmark.py`'s CLI options as sweep knobs. Not properties — no plane, nothing to apply or read back; see below. | -| `pysweep_bench.py` | Sweep runner: load config → apply/converge/verify each deployment combination → run one load test per client combination, reusing `benchmark.py`. | +| `properties/` | Deployment knobs: `base.py` (the `Property` interface and `Plane` enum) and one module per knob, e.g. `max_tokens.py` (`MaxNewTokens`, LLM `max_new_tokens`, Runtime-API plane). | +| `cluster/auth.py` | `KubernetesAccess` (side-effect-free RBAC preflight via `SelfSubjectAccessReview`), `load_build_config()` (the installed environment's config), `keycloak_helper()` (the maintained `KeycloakHelper`, for user tokens) and `client_token_lifespan()` (a sweep-long access-token lifespan for the UI client, restored afterwards). | +| `cluster/fingerprint.py` | `system_fingerprint` client. `HelperFingerprintClient` adapts the suite's `FingerprintApiHelper`; `PortForwardTransport` / `IngressTransport` cover deployments the helper can't reach. | +| `cluster/served_model.py` | `ServedModel`: reads the model the pipeline is **observed** to generate with, out of the running `llm-usvc` pods. Not a knob — the runner uses it to pick the benchmark's tokenizer. | +| `cluster/model_catalog.py` | Reader for the model-manager catalog (`models-rag.yaml` / `models.yaml`): maps a served model name to the HuggingFace repo id the benchmark's tokenizer needs. | +| `provenance/commit_info.py` | The checked-out commit the results are attributed to. | +| `provenance/paths.py` | Where the installed environment's files are looked for (deploy root derived from the checkout's location). | | `configs/sweep.yaml` | Sweep config (`--sweep`): what to vary. Keys are described in [`configs/README.md`](./configs/README.md). | | `configs/general.yaml` | Run config (`--config`): how to run. | -| `authentication.py` | `KubernetesAccess` (side-effect-free RBAC preflight via `SelfSubjectAccessReview`), `load_build_config()` (the installed environment's config), `keycloak_helper()` (the maintained `KeycloakHelper`, for user tokens) and `client_token_lifespan()` (a sweep-long access-token lifespan for the UI client, restored afterwards). | -| `runtime_api.py` | `system_fingerprint` client. `HelperFingerprintClient` adapts the suite's `FingerprintApiHelper`; `PortForwardTransport` / `IngressTransport` cover deployments the helper can't reach. | -| `properties/max_tokens.py` | First property: `MaxNewTokens` (LLM `max_new_tokens`, Runtime-API plane). | -| `served_model.py` | `ServedModel`: reads the model the pipeline is **observed** to generate with, out of the running `llm-usvc` pods. Not a knob — the runner uses it to pick the benchmark's tokenizer. | -| `model_catalog.py` | Reader for the model-manager catalog (`models-rag.yaml` / `models.yaml`): maps a served model name to the HuggingFace repo id the benchmark's tokenizer needs. | -| `paths.py` | Where the installed environment's files are looked for (deploy root derived from the checkout's location). | - -Only the modules directly under `properties/` define knobs. A file there means a -`Property` subclass bound to a YAML leaf in `config.py`. + +Every module in `properties/` except `base.py` defines one knob: a `Property` +subclass bound to a YAML leaf in `config.py`. The **e2e tests live with the rest of the validation suite** at `src/tests/e2e/validation/pysweep/`, not inside this package. That keeps them in diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/__init__.py new file mode 100644 index 00000000..91da480a --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py similarity index 99% rename from src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py rename to src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py index b6165773..56fb18a2 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/authentication.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py @@ -25,7 +25,7 @@ VITE_KEYCLOAK_REALM, ) -from .paths import deploy_roots, is_dir, is_file +from ..provenance.paths import deploy_roots, is_dir, is_file urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/fingerprint.py similarity index 97% rename from src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py rename to src/tests/e2e/benchmarks/chatqna/pysweep/cluster/fingerprint.py index 7605f44a..db98c7ac 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/runtime_api.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/fingerprint.py @@ -76,7 +76,7 @@ def __init__(self, keycloak_helper, domain: str | None = None): if not self.domain: raise ValueError( "No ERAG domain available for the ingress transport; call " - "authentication.load_build_config() first or pass domain=." + "auth.load_build_config() first or pass domain=." ) @contextmanager @@ -175,7 +175,7 @@ def default_transport(keycloak_helper=None): mode = os.getenv("PYSWEEP_FINGERPRINT_TRANSPORT", "portforward").lower() if mode == "ingress": if keycloak_helper is None: - from .authentication import keycloak_helper as build_keycloak_helper + from .auth import keycloak_helper as build_keycloak_helper keycloak_helper = build_keycloak_helper() return IngressTransport(keycloak_helper) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/model_catalog.py similarity index 98% rename from src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py rename to src/tests/e2e/benchmarks/chatqna/pysweep/cluster/model_catalog.py index 526a66df..1702d724 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/model_catalog.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/model_catalog.py @@ -7,7 +7,7 @@ import yaml -from .paths import REPO_ROOT, deploy_roots, is_file +from ..provenance.paths import REPO_ROOT, deploy_roots, is_file logger = logging.getLogger(__name__) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/served_model.py similarity index 98% rename from src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py rename to src/tests/e2e/benchmarks/chatqna/pysweep/cluster/served_model.py index d7125d62..50f48bd1 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/served_model.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/served_model.py @@ -8,7 +8,7 @@ from tests.e2e.validation.constants import CHATQNA_NAMESPACE, LLM_INFERENCE_NAMESPACE -from .base import PropertyReadError +from ..properties.base import PropertyReadError logger = logging.getLogger(__name__) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py index 3b54d364..a0fbfd37 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py @@ -17,7 +17,7 @@ ValidationError, ) -from .base import Plane, Property +from .properties.base import Plane, Property from .client_args import ( BEARER_FILE, CONCURRENCY, diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/base.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/base.py similarity index 100% rename from src/tests/e2e/benchmarks/chatqna/pysweep/base.py rename to src/tests/e2e/benchmarks/chatqna/pysweep/properties/base.py diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py index ea60bfa2..fe84af84 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py @@ -3,8 +3,8 @@ import logging -from ..base import Plane, Property, PropertyReadError -from ..runtime_api import FingerprintClient +from .base import Plane, Property, PropertyReadError +from ..cluster.fingerprint import FingerprintClient logger = logging.getLogger(__name__) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py new file mode 100644 index 00000000..91da480a --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/commit_info.py b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/commit_info.py similarity index 100% rename from src/tests/e2e/benchmarks/chatqna/pysweep/commit_info.py rename to src/tests/e2e/benchmarks/chatqna/pysweep/provenance/commit_info.py diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/paths.py similarity index 84% rename from src/tests/e2e/benchmarks/chatqna/pysweep/paths.py rename to src/tests/e2e/benchmarks/chatqna/pysweep/provenance/paths.py index d7f65ea7..14dc4daf 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/paths.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/paths.py @@ -5,8 +5,8 @@ ROOT_DEPLOY_ROOT = Path("/root/ai-solutions") -# parents[6] is the repo root: pysweep/chatqna/benchmarks/e2e/tests/src/. -REPO_ROOT = Path(__file__).resolve().parents[6] +# parents[7] is the repo root: provenance/pysweep/chatqna/benchmarks/e2e/tests/src/. +REPO_ROOT = Path(__file__).resolve().parents[7] def deploy_roots() -> tuple[Path, ...]: diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py index 5c092429..46b31d43 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -17,7 +17,7 @@ from tests.e2e.benchmarks.chatqna import benchmark from tests.e2e.benchmarks.chatqna.benchmark import duration_to_seconds -from tests.e2e.benchmarks.chatqna.pysweep.base import ( +from tests.e2e.benchmarks.chatqna.pysweep.properties.base import ( Plane, Property, PropertyApplyError, @@ -39,8 +39,8 @@ load_config, load_run_config, ) -from tests.e2e.benchmarks.chatqna.pysweep import model_catalog -from tests.e2e.benchmarks.chatqna.pysweep.commit_info import CommitInfoError, read_commit_info +from tests.e2e.benchmarks.chatqna.pysweep.cluster import model_catalog +from tests.e2e.benchmarks.chatqna.pysweep.provenance.commit_info import CommitInfoError, read_commit_info from tests.e2e.benchmarks.chatqna.pysweep.results import ( DEFAULT_SUMMARIES_DIR, SweepResults, @@ -49,11 +49,11 @@ run_record, summarize_requests, ) -from tests.e2e.benchmarks.chatqna.pysweep.runtime_api import ( +from tests.e2e.benchmarks.chatqna.pysweep.cluster.fingerprint import ( FingerprintClient, default_transport, ) -from tests.e2e.benchmarks.chatqna.pysweep.served_model import ServedModel +from tests.e2e.benchmarks.chatqna.pysweep.cluster.served_model import ServedModel logger = logging.getLogger(__name__) @@ -250,7 +250,7 @@ def preflight_check(config: SweepConfig) -> dict[str, str]: def chatqna_url() -> str: """Return the ChatQNA URL on the deployment's base_domain_name.""" - from tests.e2e.benchmarks.chatqna.pysweep.authentication import load_build_config + from tests.e2e.benchmarks.chatqna.pysweep.cluster.auth import load_build_config return f"https://{load_build_config()['base_domain_name']}{CHATQNA_PATH}" @@ -291,7 +291,7 @@ def provision_benchmark_target(benchmark_args: list[str], workers: int = 1): tmp = stack.enter_context( tempfile.NamedTemporaryFile("w", suffix=".uat", delete=True) ) - from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( + from tests.e2e.benchmarks.chatqna.pysweep.cluster.auth import ( client_token_lifespan, keycloak_helper, ) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py index bcffef6e..4ccb54ee 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py @@ -9,7 +9,7 @@ from pathlib import Path from typing import Any, Iterable, NamedTuple, Sequence -from .commit_info import COMMIT_INFO_FIELDS +from .provenance.commit_info import COMMIT_INFO_FIELDS logger = logging.getLogger(__name__) diff --git a/src/tests/e2e/validation/pysweep/conftest.py b/src/tests/e2e/validation/pysweep/conftest.py index 37e2a00f..70059ddd 100644 --- a/src/tests/e2e/validation/pysweep/conftest.py +++ b/src/tests/e2e/validation/pysweep/conftest.py @@ -5,11 +5,11 @@ import pytest -from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( +from tests.e2e.benchmarks.chatqna.pysweep.cluster.auth import ( AccessError, KubernetesAccess, ) -from tests.e2e.benchmarks.chatqna.pysweep.runtime_api import ( +from tests.e2e.benchmarks.chatqna.pysweep.cluster.fingerprint import ( HelperFingerprintClient, PortForwardTransport, FingerprintClient, diff --git a/src/tests/e2e/validation/pysweep/test_commit_info_unit.py b/src/tests/e2e/validation/pysweep/test_commit_info_unit.py index 9f09f025..14927168 100644 --- a/src/tests/e2e/validation/pysweep/test_commit_info_unit.py +++ b/src/tests/e2e/validation/pysweep/test_commit_info_unit.py @@ -7,8 +7,8 @@ import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep import commit_info -from tests.e2e.benchmarks.chatqna.pysweep.commit_info import ( +from tests.e2e.benchmarks.chatqna.pysweep.provenance import commit_info +from tests.e2e.benchmarks.chatqna.pysweep.provenance.commit_info import ( COMMIT_INFO_FIELDS, CommitInfoError, read_commit_info, diff --git a/src/tests/e2e/validation/pysweep/test_config_unit.py b/src/tests/e2e/validation/pysweep/test_config_unit.py index 4087904d..ea1504d7 100644 --- a/src/tests/e2e/validation/pysweep/test_config_unit.py +++ b/src/tests/e2e/validation/pysweep/test_config_unit.py @@ -9,7 +9,7 @@ import pytest from tests.e2e.benchmarks.chatqna.pysweep import client_args -from tests.e2e.benchmarks.chatqna.pysweep.base import Plane +from tests.e2e.benchmarks.chatqna.pysweep.properties.base import Plane from tests.e2e.benchmarks.chatqna.pysweep.config import ( ConfigError, SweepConfig, diff --git a/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py b/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py index 62a1f886..1472b8dd 100644 --- a/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py +++ b/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py @@ -4,7 +4,7 @@ import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep.base import Plane, PropertyReadError +from tests.e2e.benchmarks.chatqna.pysweep.properties.base import Plane, PropertyReadError from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens diff --git a/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py b/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py index 3aecf66a..1bef3700 100644 --- a/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py +++ b/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py @@ -6,8 +6,8 @@ import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep import model_catalog -from tests.e2e.benchmarks.chatqna.pysweep.model_catalog import ( +from tests.e2e.benchmarks.chatqna.pysweep.cluster import model_catalog +from tests.e2e.benchmarks.chatqna.pysweep.cluster.model_catalog import ( CatalogError, catalog_path, known_models, diff --git a/src/tests/e2e/validation/pysweep/test_paths_unit.py b/src/tests/e2e/validation/pysweep/test_paths_unit.py index 0d57b6f1..a6f9c50b 100644 --- a/src/tests/e2e/validation/pysweep/test_paths_unit.py +++ b/src/tests/e2e/validation/pysweep/test_paths_unit.py @@ -6,8 +6,9 @@ import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep import authentication, paths -from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( +from tests.e2e.benchmarks.chatqna.pysweep.cluster import auth +from tests.e2e.benchmarks.chatqna.pysweep.provenance import paths +from tests.e2e.benchmarks.chatqna.pysweep.cluster.auth import ( BUILD_CONFIG_FILES, BuildConfigError, build_config_dir, @@ -55,16 +56,16 @@ def stat(self, *args, **kwargs): raise PermissionError(13, "Permission denied", str(self)) return real_stat(self, *args, **kwargs) - monkeypatch.delenv(authentication.BUILD_CONFIG_DIR_ENV_VAR, raising=False) + monkeypatch.delenv(auth.BUILD_CONFIG_DIR_ENV_VAR, raising=False) monkeypatch.setattr(Path, "stat", stat) - monkeypatch.setattr(authentication, "BUILD_CONFIG_FALLBACKS", (str(unreadable), str(readable))) + monkeypatch.setattr(auth, "BUILD_CONFIG_FALLBACKS", (str(unreadable), str(readable))) assert build_config_dir() == readable @allure.feature("pysweep") def test_no_build_config_dir_anywhere_is_an_error(monkeypatch): - monkeypatch.delenv(authentication.BUILD_CONFIG_DIR_ENV_VAR, raising=False) - monkeypatch.setattr(authentication, "BUILD_CONFIG_FALLBACKS", ()) + monkeypatch.delenv(auth.BUILD_CONFIG_DIR_ENV_VAR, raising=False) + monkeypatch.setattr(auth, "BUILD_CONFIG_FALLBACKS", ()) with pytest.raises(BuildConfigError, match="Cannot find"): build_config_dir() diff --git a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py index 643fbb8d..980e9e40 100644 --- a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -16,7 +16,7 @@ import yaml from tests.e2e.benchmarks.chatqna.pysweep import pysweep_bench as psb -from tests.e2e.benchmarks.chatqna.pysweep.base import ( +from tests.e2e.benchmarks.chatqna.pysweep.properties.base import ( Plane, Property, PropertyApplyError, @@ -26,7 +26,7 @@ from tests.e2e.benchmarks.chatqna.pysweep import results from tests.e2e.benchmarks.chatqna.pysweep.config import PropertySetting, load_config from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens -from tests.e2e.benchmarks.chatqna.pysweep.served_model import ServedModel +from tests.e2e.benchmarks.chatqna.pysweep.cluster.served_model import ServedModel # question_file must exist (relative to pysweep_bench.py): main() runs preflight, which stats it. CLIENT = { @@ -521,7 +521,7 @@ def test_count_result_rows_counts_and_tolerates_missing(tmp_path): @allure.feature("pysweep") def _fake_keycloak(monkeypatch, domain="box.example"): """Point provisioning at a fake deployment whose every token mint differs.""" - from tests.e2e.benchmarks.chatqna.pysweep import authentication + from tests.e2e.benchmarks.chatqna.pysweep.cluster import auth minted = itertools.count(1) @@ -532,22 +532,22 @@ def access_token(self): return f"token-{next(minted)}" monkeypatch.setattr( - authentication, "load_build_config", lambda: {"base_domain_name": domain} + auth, "load_build_config", lambda: {"base_domain_name": domain} ) - monkeypatch.setattr(authentication, "keycloak_helper", _Helper) + monkeypatch.setattr(auth, "keycloak_helper", _Helper) # Record the lifespan override instead of calling the Keycloak admin API. lifespan_calls = [] @contextmanager - def _lifespan(helper, seconds=authentication.SWEEP_TOKEN_LIFESPAN_S): + def _lifespan(helper, seconds=auth.SWEEP_TOKEN_LIFESPAN_S): lifespan_calls.append(("set", seconds)) try: yield finally: lifespan_calls.append(("restored", seconds)) - monkeypatch.setattr(authentication, "client_token_lifespan", _lifespan) + monkeypatch.setattr(auth, "client_token_lifespan", _lifespan) return lifespan_calls diff --git a/src/tests/e2e/validation/pysweep/test_served_model.py b/src/tests/e2e/validation/pysweep/test_served_model.py index 5f7255e6..711a5b50 100644 --- a/src/tests/e2e/validation/pysweep/test_served_model.py +++ b/src/tests/e2e/validation/pysweep/test_served_model.py @@ -6,8 +6,8 @@ import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep import model_catalog -from tests.e2e.benchmarks.chatqna.pysweep.served_model import LLMInferenceService, ServedModel +from tests.e2e.benchmarks.chatqna.pysweep.cluster import model_catalog +from tests.e2e.benchmarks.chatqna.pysweep.cluster.served_model import LLMInferenceService, ServedModel from tests.e2e.validation.constants import LLM_INFERENCE_NAMESPACE logger = logging.getLogger(__name__) diff --git a/src/tests/e2e/validation/pysweep/test_served_model_unit.py b/src/tests/e2e/validation/pysweep/test_served_model_unit.py index 0810341d..903a3ade 100644 --- a/src/tests/e2e/validation/pysweep/test_served_model_unit.py +++ b/src/tests/e2e/validation/pysweep/test_served_model_unit.py @@ -6,9 +6,9 @@ import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep import served_model -from tests.e2e.benchmarks.chatqna.pysweep.base import PropertyReadError -from tests.e2e.benchmarks.chatqna.pysweep.served_model import ServedModel +from tests.e2e.benchmarks.chatqna.pysweep.cluster import served_model +from tests.e2e.benchmarks.chatqna.pysweep.properties.base import PropertyReadError +from tests.e2e.benchmarks.chatqna.pysweep.cluster.served_model import ServedModel MODEL = "llama3-8b-awq" OTHER = "qwen3-5-2b-ovms" diff --git a/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py b/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py index 6fc7493e..f18d740f 100644 --- a/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py +++ b/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py @@ -4,8 +4,8 @@ import allure import pytest -from tests.e2e.benchmarks.chatqna.pysweep import authentication -from tests.e2e.benchmarks.chatqna.pysweep.authentication import ( +from tests.e2e.benchmarks.chatqna.pysweep.cluster import auth +from tests.e2e.benchmarks.chatqna.pysweep.cluster.auth import ( CLIENT_TOKEN_LIFESPAN_ATTRIBUTE, KeycloakConfigError, client_token_lifespan, @@ -66,8 +66,8 @@ class _Helper: def keycloak(monkeypatch): def install(**kwargs): fake = _FakeKeycloak(**kwargs) - monkeypatch.setattr(authentication.requests, "get", fake.get) - monkeypatch.setattr(authentication.requests, "put", fake.put) + monkeypatch.setattr(auth.requests, "get", fake.get) + monkeypatch.setattr(auth.requests, "put", fake.put) return fake return install @@ -75,7 +75,7 @@ def install(**kwargs): @allure.feature("pysweep") def test_the_sweep_value_is_arbitrary_but_outlasts_a_long_run(): - assert authentication.SWEEP_TOKEN_LIFESPAN_S == 3600 + assert auth.SWEEP_TOKEN_LIFESPAN_S == 3600 @allure.feature("pysweep") From 2da8f81559f502c9b56324129d059fd00d782940 Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 27 Nov 2026 17:12:45 +0100 Subject: [PATCH 07/11] feat(benchmarks): add a pysweep pre_bench phase that seeds the vector DB A new pre_bench section in the sweep config holds what every run shares and is done once, before the first run; it takes single values only and is never part of the product. Its first setting, pre_bench.edp.vector_db.num_vectors, is applied by pre_bench.seed.seed(): it loads the vector DB through EDP until it holds at least that many vectors, first with the documents in documents.csv and then with Simple English Wikipedia split by wikiparse.py, two files at a time, as prepare_1M_vectors.sh does. Unlike the script it skips files EDP already has, checks every download and upload, caches downloads in ~/.cache/pysweep/seed, and fails when the data runs out first. The declared value is recorded in every run as settings.edp.vector_db.num_vectors. pre_bench runs before the summaries directory is cleared, so a failed seed keeps the previous results, and the preflight checks that the seeding inputs exist. configs/sweep.yaml seeds 50000 vectors, as the SPR nightlies do. Signed-off-by: Kurzacz, Kamil --- .../e2e/benchmarks/chatqna/pysweep/README.md | 5 +- .../e2e/benchmarks/chatqna/pysweep/config.py | 30 +++ .../chatqna/pysweep/configs/README.md | 10 +- .../chatqna/pysweep/configs/sweep.yaml | 5 + .../chatqna/pysweep/pre_bench/__init__.py | 33 +++ .../chatqna/pysweep/pre_bench/seed.py | 191 ++++++++++++++++++ .../chatqna/pysweep/pysweep_bench.py | 14 ++ .../e2e/benchmarks/chatqna/pysweep/results.py | 4 +- .../validation/pysweep/test_config_unit.py | 30 +++ .../pysweep/test_pysweep_bench_unit.py | 42 ++++ .../validation/pysweep/test_results_unit.py | 12 ++ .../e2e/validation/pysweep/test_seed_unit.py | 188 +++++++++++++++++ 12 files changed, 561 insertions(+), 3 deletions(-) create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py create mode 100644 src/tests/e2e/validation/pysweep/test_seed_unit.py diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md index 765cacbf..87cb33ad 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -22,6 +22,7 @@ environment gotchas. | `config.py` | Pydantic-validated configs: `load_config()` / `SweepConfig` (+ the `deployment_combinations()` and `client_combinations()` cartesian `product` expansions) and `load_run_config()` / `RunConfig`. | | `results.py` | Run records, `results.json` and the summary CSV. | | `client_args.py` | Adapter mirroring `benchmark.py`'s CLI options as sweep knobs. Not properties — no plane, nothing to apply or read back; see below. | +| `pre_bench/` | Done once before the first run: `run_pre_bench()` in `__init__.py`, and `seed.py`, which loads the vector DB through EDP up to `pre_bench.edp.vector_db.num_vectors`. | | `properties/` | Deployment knobs: `base.py` (the `Property` interface and `Plane` enum) and one module per knob, e.g. `max_tokens.py` (`MaxNewTokens`, LLM `max_new_tokens`, Runtime-API plane). | | `cluster/auth.py` | `KubernetesAccess` (side-effect-free RBAC preflight via `SelfSubjectAccessReview`), `load_build_config()` (the installed environment's config), `keycloak_helper()` (the maintained `KeycloakHelper`, for user tokens) and `client_token_lifespan()` (a sweep-long access-token lifespan for the UI client, restored afterwards). | | `cluster/fingerprint.py` | `system_fingerprint` client. `HelperFingerprintClient` adapts the suite's `FingerprintApiHelper`; `PortForwardTransport` / `IngressTransport` cover deployments the helper can't reach. | @@ -156,9 +157,11 @@ to `benchmark.py`'s default (an embedding model's tokenizer). ## Iteration order -The two products are **nested**, not merged into one: +The two products are **nested**, not merged into one, and both follow a +one-off `pre_bench` phase: ``` +pre_bench (once): seed the vector DB, … # state every run shares for each deployment combination: # outer — costs a rollout apply / wait / verify (once) tokenizer = observed served model # -m, derived once per combination diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py index a0fbfd37..95de2d45 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py @@ -89,6 +89,20 @@ class _StrictModel(BaseModel): model_config = ConfigDict(extra="forbid") +class VectorDbPreBench(_StrictModel): + num_vectors: PositiveInt | None = None + + +class EdpPreBench(_StrictModel): + vector_db: VectorDbPreBench | None = None + + +class PreBenchConfig(_StrictModel): + """Done once before the first run; single values only, never part of the product.""" + + edp: EdpPreBench | None = None + + class LlmsConfig(_StrictModel): max_new_tokens: Annotated[MaxTokensValue | None, PropertyBinding(MaxNewTokens)] = None @@ -117,6 +131,7 @@ class RunConfig(_StrictModel): class SweepConfig(_StrictModel): + pre_bench: PreBenchConfig | None = None llms: LlmsConfig | None = None client: ClientConfig @@ -188,6 +203,10 @@ def varying_paths(self) -> set[str]: """Dotted paths of the knobs declared with more than one value.""" return {path for path, _, values in _walk_bindings(self) if len(values) > 1} + def pre_bench_settings(self) -> dict[str, Any]: + """Declared pre_bench values as dotted paths, e.g. ``{"edp.vector_db.num_vectors": 50000}``.""" + return _declared_values(self.pre_bench) if self.pre_bench else {} + def knob_paths(self) -> list[str]: """Declared knob paths (minus ``server``/``bearer_file``), deployment first.""" deployment = sorted(path for path, _, _ in self.iter_settings()) @@ -232,6 +251,17 @@ def _walk_bindings( yield from _walk_bindings(value, prefix=f"{path}.") +def _declared_values(model: BaseModel, prefix: str = "") -> dict[str, Any]: + values: dict[str, Any] = {} + for name in type(model).model_fields: + value = getattr(model, name) + if isinstance(value, BaseModel): + values.update(_declared_values(value, f"{prefix}{name}.")) + elif value is not None: + values[f"{prefix}{name}"] = value + return values + + def _as_list(value: Any) -> list[Any]: return list(value) if isinstance(value, list) else [value] diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md index f4492884..5afe63a0 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md @@ -13,7 +13,15 @@ out-of-range value is a `ConfigError`. ## `sweep.yaml` -Any knob takes a single value (fixed for the whole sweep) or a list (one +**`pre_bench`** prepares what every run shares, once, before the first run. +Single values only; it is not part of the product. Each value is recorded in +every run as `settings.` (e.g. `settings.edp.vector_db.num_vectors`). + +| Key | Meaning | +|---|---| +| `pre_bench.edp.vector_db.num_vectors` | Load the vector DB through EDP until it holds at least this many vectors: first the documents in `../documents.csv`, then Simple English Wikipedia, split by `../wikiparse.py`, two files at a time. Files already in EDP are not uploaded again; downloads are cached in `$PYSWEEP_SEED_CACHE` (default `~/.cache/pysweep/seed`). Fails if the data runs out first. It never removes vectors: use `../prepare_cleanup_vectors.sh` to start from an empty DB. | + +Any other knob takes a single value (fixed for the whole sweep) or a list (one dimension of the product). Runs = deployment combinations × client combinations; the file here is 2 × (3 × 2) = 12 runs. diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml index 72f3bd9e..fae9aea0 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml @@ -1,6 +1,11 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 +pre_bench: + edp: + vector_db: + num_vectors: 50000 + llms: max_new_tokens: [128, 256] diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py new file mode 100644 index 00000000..a2f86730 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py @@ -0,0 +1,33 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging +from typing import Any + +from . import seed +from .seed import SeedError + +logger = logging.getLogger(__name__) + +NUM_VECTORS = "edp.vector_db.num_vectors" + +__all__ = ["NUM_VECTORS", "SeedError", "edp_client", "run_pre_bench", "seed"] + + +def edp_client(): + from tests.e2e.helpers.edp_helper import EdpHelper + + from ..cluster.auth import keycloak_helper + + return EdpHelper(keycloak_helper()) + + +def run_pre_bench(settings: dict[str, Any], edp=None) -> None: + """Prepare the deployment state every run of the sweep shares; ``settings`` are dotted pre_bench paths.""" + if not settings: + logger.info("No pre_bench settings declared.") + return + logger.info("=== pre_bench: %s ===", settings) + num_vectors = settings.get(NUM_VECTORS) + if num_vectors is not None: + seed.seed(num_vectors, edp or edp_client()) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py new file mode 100644 index 00000000..8d67be72 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py @@ -0,0 +1,191 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import bz2 +import csv +import logging +import os +import shutil +import subprocess +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Iterable + +import requests + +logger = logging.getLogger(__name__) + +BENCHMARK_DIR = Path(__file__).resolve().parents[2] +DOCUMENTS_CSV = BENCHMARK_DIR / "documents.csv" +WIKIPARSE = BENCHMARK_DIR / "wikiparse.py" +WIKI_DUMP_URL = ( + "https://dumps.wikimedia.org/simplewiki/latest/simplewiki-latest-pages-articles-multistream.xml.bz2" +) +CACHE_ENV_VAR = "PYSWEEP_SEED_CACHE" +DEFAULT_CACHE_DIR = Path.home() / ".cache" / "pysweep" / "seed" + +POLL_INTERVAL_S = 30.0 +INGEST_TIMEOUT_S = 4 * 3600.0 +DOWNLOAD_TIMEOUT_S = 600 +# EDP processes two files at a time, so pairs keep it busy without queueing. +WIKI_BATCH = 2 + + +class SeedError(Exception): + """The vector DB could not be seeded to the requested size.""" + + +@dataclass +class VectorDbState: + vectors: int = 0 + in_progress: int = 0 + failed: int = 0 + files: set[str] = field(default_factory=set) + + +def read_state(edp) -> VectorDbState: + """Ingested vectors (chunks) and files, as EDP reports them.""" + response = edp.list_files() + if response.status_code != 200: + raise SeedError(f"EDP /files returned HTTP {response.status_code}: {response.text[:300]}") + state = VectorDbState() + for item in response.json(): + status = item.get("status") + state.files.add(Path(item.get("object_name", "")).name) + if status == "ingested": + state.vectors += int(item.get("chunks_processed") or 0) + elif status == "error": + state.failed += 1 + else: + state.in_progress += 1 + return state + + +def wait_until_idle(edp, timeout=INGEST_TIMEOUT_S, poll=POLL_INTERVAL_S, sleep=time.sleep, clock=time.monotonic): + deadline = clock() + timeout + while True: + state = read_state(edp) + if not state.in_progress: + return state + if clock() >= deadline: + raise SeedError( + f"EDP still processes {state.in_progress} file(s) after {timeout:.0f}s " + f"({state.vectors} vectors ingested so far)." + ) + logger.info("Waiting for EDP: %d file(s) in progress, %d vectors ingested.", state.in_progress, state.vectors) + sleep(poll) + + +def upload(edp, path: Path) -> None: + presigned = edp.generate_presigned_url(path.name) + if presigned.status_code != 200: + raise SeedError(f"No presigned URL for {path.name}: HTTP {presigned.status_code} {presigned.text[:300]}") + response = edp.upload_file(str(path), presigned.json()["url"]) + if response.status_code not in (200, 201, 204): + raise SeedError(f"Upload of {path.name} failed: HTTP {response.status_code} {response.text[:300]}") + logger.info("Uploaded %s.", path.name) + + +def download(url: str, target: Path) -> Path: + if target.is_file() and target.stat().st_size > 0: + return target + target.parent.mkdir(parents=True, exist_ok=True) + partial = target.with_name(target.name + ".part") + logger.info("Downloading %s.", url) + with requests.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT_S) as response: + if response.status_code != 200: + raise SeedError(f"Download of {url} failed: HTTP {response.status_code}") + with partial.open("wb") as handle: + for chunk in response.iter_content(chunk_size=1 << 20): + handle.write(chunk) + partial.rename(target) + return target + + +def relevant_documents(cache_dir: Path) -> list[Path]: + """The documents the benchmark's questions are about, in documents.csv order.""" + with DOCUMENTS_CSV.open(newline="") as handle: + rows = [row for row in csv.reader(handle, delimiter=";") if row] + return [download(url, cache_dir / "documents" / name) for url, name in rows] + + +def wikipedia_files(cache_dir: Path) -> list[Path]: + """Simple English Wikipedia split by wikiparse.py into upload-sized text files.""" + out_dir = cache_dir / "wiki" + parsed = sorted(out_dir.glob("wiki*.txt")) + if parsed: + return parsed + dump = download(WIKI_DUMP_URL, cache_dir / WIKI_DUMP_URL.rsplit("/", 1)[1]) + xml = dump.with_suffix("") + with bz2.open(dump, "rb") as source, xml.open("wb") as target: + shutil.copyfileobj(source, target, 1 << 20) + staging = cache_dir / "wiki.part" + shutil.rmtree(staging, ignore_errors=True) + staging.mkdir(parents=True) + subprocess.run([sys.executable, str(WIKIPARSE), str(xml), str(staging)], check=True) + xml.unlink() + staging.rename(out_dir) + return sorted(out_dir.glob("wiki*.txt")) + + +def cache_dir() -> Path: + return Path(os.getenv(CACHE_ENV_VAR) or DEFAULT_CACHE_DIR) + + +def _batches(paths: Iterable[Path], size: int): + batch = [] + for path in paths: + batch.append(path) + if len(batch) == size: + yield batch + batch = [] + if batch: + yield batch + + +def seed( + num_vectors: int, + edp, + documents: Callable[[], list[Path]] | None = None, + wikipedia: Callable[[], list[Path]] | None = None, + sleep=time.sleep, + clock=time.monotonic, +) -> VectorDbState: + """Load the vector DB until it holds at least ``num_vectors`` vectors.""" + documents = documents or (lambda: relevant_documents(cache_dir())) + wikipedia = wikipedia or (lambda: wikipedia_files(cache_dir())) + + def wait() -> VectorDbState: + return wait_until_idle(edp, sleep=sleep, clock=clock) + + state = wait() + logger.info("Vector DB holds %d vectors in %d file(s); seeding to %d.", state.vectors, len(state.files), num_vectors) + if state.vectors >= num_vectors: + return state + + for path in documents(): + if path.name not in state.files: + upload(edp, path) + state = wait() + + if state.vectors < num_vectors: + for batch in _batches(wikipedia(), WIKI_BATCH): + pending = [path for path in batch if path.name not in state.files] + if not pending: + continue + for path in pending: + upload(edp, path) + state = wait() + if state.vectors >= num_vectors: + break + + if state.vectors < num_vectors: + raise SeedError( + f"Seeding ran out of data at {state.vectors} vectors; {num_vectors} were requested." + ) + if state.failed: + logger.warning("%d file(s) failed ingestion in EDP; they hold no vectors.", state.failed) + logger.info("Vector DB seeded: %d vectors in %d file(s).", state.vectors, len(state.files)) + return state diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py index 46b31d43..48643594 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -40,6 +40,7 @@ load_run_config, ) from tests.e2e.benchmarks.chatqna.pysweep.cluster import model_catalog +from tests.e2e.benchmarks.chatqna.pysweep.pre_bench import NUM_VECTORS, run_pre_bench, seed from tests.e2e.benchmarks.chatqna.pysweep.provenance.commit_info import CommitInfoError, read_commit_info from tests.e2e.benchmarks.chatqna.pysweep.results import ( DEFAULT_SUMMARIES_DIR, @@ -242,9 +243,18 @@ def commit_info_verify() -> dict[str, str]: return info +def pre_bench_verify(config: SweepConfig) -> None: + """Raise PreflightError unless the inputs of every declared pre_bench step exist.""" + if NUM_VECTORS in config.pre_bench_settings(): + for path in (seed.DOCUMENTS_CSV, seed.WIKIPARSE): + if not path.is_file(): + raise PreflightError(f"pre_bench.{NUM_VECTORS} needs {path}, which does not exist.") + + def preflight_check(config: SweepConfig) -> dict[str, str]: """Run every preflight check; return the commit the results are attributed to.""" question_file_verify(config) + pre_bench_verify(config) return commit_info_verify() @@ -467,6 +477,9 @@ def main(argv=None): deployment_combinations = config.deployment_combinations() client_combinations = config.client_combinations() varying_paths = config.varying_paths() + pre_bench = config.pre_bench_settings() + run_pre_bench(pre_bench) + layout = prepare_summaries_dir(args.summaries) sweep_results = SweepResults(layout, date=utc_now(), commit_info=commit_info) @@ -522,6 +535,7 @@ def main(argv=None): result_file=sweep_results.pointer(output_file), deployment=snapshot, client={**client, "client.tokenizer": tokenizer}, + pre_bench=pre_bench, results=summarize_requests( read_requests(output_file), duration_to_seconds(str(client["client.duration"])), diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py index 4ccb54ee..fed50d64 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py @@ -244,8 +244,9 @@ def run_record( deployment: dict[str, Any], client: dict[str, Any], results: dict[str, Any], + pre_bench: dict[str, Any] | None = None, ) -> dict[str, Any]: - """One run's record; ``deployment``/``client`` take dotted knob paths.""" + """One run's record; ``deployment``/``client``/``pre_bench`` take dotted setting paths.""" return { "run": { "index": index, @@ -257,6 +258,7 @@ def run_record( "settings": { "deployment": nest(deployment), "client": nest({path.removeprefix("client."): value for path, value in client.items()}), + **nest(pre_bench or {}), }, "results": results, } diff --git a/src/tests/e2e/validation/pysweep/test_config_unit.py b/src/tests/e2e/validation/pysweep/test_config_unit.py index ea1504d7..c4eb527c 100644 --- a/src/tests/e2e/validation/pysweep/test_config_unit.py +++ b/src/tests/e2e/validation/pysweep/test_config_unit.py @@ -356,3 +356,33 @@ def test_shipped_example_run_config_is_valid(): / "e2e/benchmarks/chatqna/pysweep/configs/general.yaml" ) assert load_run_config(example).display_kubernetes_client_logs is False + + +def _pre_bench(num_vectors): + return {**_sweep(), "pre_bench": {"edp": {"vector_db": {"num_vectors": num_vectors}}}} + + +@allure.feature("pysweep") +def test_pre_bench_settings_are_dotted_paths(): + assert load_config(_pre_bench(50000)).pre_bench_settings() == {"edp.vector_db.num_vectors": 50000} + assert load_config(_sweep()).pre_bench_settings() == {} + + +@allure.feature("pysweep") +@pytest.mark.parametrize("bad", [[50000, 100000], 0, -1, "many"]) +def test_num_vectors_is_a_single_positive_integer(bad): + with pytest.raises(ConfigError): + load_config(_pre_bench(bad)) + + +@allure.feature("pysweep") +def test_pre_bench_rejects_unknown_keys(): + with pytest.raises(ConfigError): + load_config({**_sweep(), "pre_bench": {"edp": {"vector_db": {"vectors": 1}}}}) + + +@allure.feature("pysweep") +def test_pre_bench_is_neither_a_knob_nor_a_dimension(): + cfg = load_config({**_pre_bench(50000), "llms": {"max_new_tokens": [128, 256]}}) + assert not any(path.startswith(("pre_bench", "edp")) for path in cfg.knob_paths()) + assert len(cfg.deployment_combinations()) == 2 diff --git a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py index 980e9e40..4ec23942 100644 --- a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -827,6 +827,48 @@ def unreadable(): psb.preflight_check(load_config(_client())) +@allure.feature("pysweep") +def test_pre_bench_runs_once_before_the_summaries_and_the_first_run(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + cfg = load_config({ + **_client(concurrency=[1, 16]), + "pre_bench": {"edp": {"vector_db": {"num_vectors": 50000}}}, + }) + events = [] + + class _RecordingBenchmark(FakeBenchmark): + def run_benchmark(self, args, output_file=None): + events.append("run") + return super().run_benchmark(args, output_file=output_file) + + real_prepare = psb.prepare_summaries_dir + run_config = psb.load_run_config({}) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "run_pre_bench", lambda settings: events.append(("pre_bench", settings))) + monkeypatch.setattr(psb, "prepare_summaries_dir", lambda root: events.append("summaries") or real_prepare(root)) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr(psb, "apply_combination", lambda c, f: {}) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, _RecordingBenchmark()) + + assert psb.main(["--sweep", "ignored.yaml", "--summaries", "out"]) == 0 + + assert events == [("pre_bench", {"edp.vector_db.num_vectors": 50000}), "summaries", "run", "run"] + document = json.loads((tmp_path / "out" / results.RESULTS_FILE_NAME).read_text()) + assert {run["settings"]["edp"]["vector_db"]["num_vectors"] for run in document["runs"]} == {50000} + + +@allure.feature("pysweep") +def test_preflight_fails_when_a_seed_input_is_missing(monkeypatch, tmp_path): + monkeypatch.setattr(psb.seed, "WIKIPARSE", tmp_path / "missing.py") + cfg = load_config({**_client(), "pre_bench": {"edp": {"vector_db": {"num_vectors": 1}}}}) + with pytest.raises(psb.PreflightError, match="missing.py"): + psb.preflight_check(cfg) + + @allure.feature("pysweep") def test_each_run_logs_its_record_as_yaml(monkeypatch, tmp_path, caplog): monkeypatch.chdir(tmp_path) diff --git a/src/tests/e2e/validation/pysweep/test_results_unit.py b/src/tests/e2e/validation/pysweep/test_results_unit.py index e2319a21..b1dd13fe 100644 --- a/src/tests/e2e/validation/pysweep/test_results_unit.py +++ b/src/tests/e2e/validation/pysweep/test_results_unit.py @@ -164,6 +164,18 @@ def test_a_record_groups_settings_into_deployment_and_client(): } +@allure.feature("pysweep") +def test_pre_bench_settings_sit_next_to_deployment_and_client(): + record = run_record( + index="1.1", started_at="s", finished_at="f", exit_code=0, result_file="r.csv", + deployment={}, client={"client.concurrency": 1}, + results=summarize_requests([], duration_s=60), + pre_bench={"edp.vector_db.num_vectors": 50000}, + ) + assert record["settings"]["edp"] == {"vector_db": {"num_vectors": 50000}} + assert flatten(record)["settings.edp.vector_db.num_vectors"] == 50000 + + @pytest.fixture def layout(tmp_path): return prepare_summaries_dir(tmp_path / "out") diff --git a/src/tests/e2e/validation/pysweep/test_seed_unit.py b/src/tests/e2e/validation/pysweep/test_seed_unit.py new file mode 100644 index 00000000..645cd1b4 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_seed_unit.py @@ -0,0 +1,188 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from types import SimpleNamespace + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import pre_bench +from tests.e2e.benchmarks.chatqna.pysweep.pre_bench import seed as seed_module +from tests.e2e.benchmarks.chatqna.pysweep.pre_bench.seed import ( + SeedError, + download, + read_state, + seed, + wait_until_idle, +) + + +def _response(status=200, payload=None, text=""): + return SimpleNamespace(status_code=status, json=lambda: payload, text=text) + + +class FakeEdp: + """EDP whose uploads move from processing to ingested on the next /files poll.""" + + def __init__(self, files=None, chunks=10): + self.files = {name: dict(item) for name, item in (files or {}).items()} + self.chunks = chunks + self.uploads = [] + self.presigned_status = 200 + self.upload_status = 204 + self.list_status = 200 + + def list_files(self): + listing = [dict(object_name=name, **item) for name, item in self.files.items()] + for item in self.files.values(): + if item["status"] == "processing": + item.update(status="ingested", chunks_processed=self.chunks) + return _response(self.list_status, listing, "boom") + + def generate_presigned_url(self, object_name): + return _response(self.presigned_status, {"url": f"http://s3/{object_name}"}, "denied") + + def upload_file(self, path, url): + name = url.rsplit("/", 1)[1] + self.uploads.append(name) + self.files[name] = {"status": "processing", "chunks_processed": 0} + return _response(self.upload_status, text="nope") + + +def _paths(tmp_path, *names): + paths = [] + for name in names: + path = tmp_path / name + path.write_text(name) + paths.append(path) + return paths + + +def _seed(edp, num_vectors, documents=(), wiki=()): + return seed( + num_vectors, edp, + documents=lambda: list(documents), wikipedia=lambda: list(wiki), + sleep=lambda seconds: None, + ) + + +@allure.feature("pysweep") +def test_read_state_counts_ingested_chunks_and_open_work(): + edp = FakeEdp({ + "a.pdf": {"status": "ingested", "chunks_processed": 7}, + "Docs/b.pdf": {"status": "ingested", "chunks_processed": 5}, + "c.pdf": {"status": "error", "chunks_processed": 0}, + "d.pdf": {"status": "embedding", "chunks_processed": 0}, + }) + state = read_state(edp) + assert (state.vectors, state.failed, state.in_progress) == (12, 1, 1) + assert state.files == {"a.pdf", "b.pdf", "c.pdf", "d.pdf"} + + +@allure.feature("pysweep") +def test_an_edp_error_is_a_seed_error(): + edp = FakeEdp() + edp.list_status = 503 + with pytest.raises(SeedError, match="HTTP 503"): + read_state(edp) + + +@allure.feature("pysweep") +def test_nothing_is_uploaded_when_the_target_is_already_met(tmp_path): + edp = FakeEdp({"a.pdf": {"status": "ingested", "chunks_processed": 60}}) + state = _seed(edp, 50, documents=_paths(tmp_path, "doc.pdf")) + assert edp.uploads == [] + assert state.vectors == 60 + + +@allure.feature("pysweep") +def test_documents_first_then_wikipedia_in_pairs_until_the_target(tmp_path): + edp = FakeEdp(chunks=10) + documents = _paths(tmp_path, "d1.pdf", "d2.pdf") + wiki = _paths(tmp_path, "wiki0000.txt", "wiki0001.txt", "wiki0002.txt", "wiki0003.txt", "wiki0004.txt", "wiki0005.txt") + state = _seed(edp, 50, documents=documents, wiki=wiki) + assert edp.uploads == ["d1.pdf", "d2.pdf", "wiki0000.txt", "wiki0001.txt", "wiki0002.txt", "wiki0003.txt"] + assert state.vectors == 60 + + +@allure.feature("pysweep") +def test_wikipedia_is_not_needed_when_the_documents_suffice(tmp_path): + edp = FakeEdp(chunks=30) + state = _seed(edp, 50, documents=_paths(tmp_path, "d1.pdf", "d2.pdf"), wiki=_paths(tmp_path, "wiki0000.txt")) + assert edp.uploads == ["d1.pdf", "d2.pdf"] + assert state.vectors == 60 + + +@allure.feature("pysweep") +def test_files_already_in_edp_are_not_uploaded_again(tmp_path): + edp = FakeEdp({"d1.pdf": {"status": "ingested", "chunks_processed": 10}}, chunks=10) + _seed(edp, 30, documents=_paths(tmp_path, "d1.pdf", "d2.pdf"), wiki=_paths(tmp_path, "wiki0000.txt")) + assert edp.uploads == ["d2.pdf", "wiki0000.txt"] + + +@allure.feature("pysweep") +def test_running_out_of_data_is_an_error(tmp_path): + edp = FakeEdp(chunks=10) + with pytest.raises(SeedError, match="ran out of data at 30 vectors; 100"): + _seed(edp, 100, documents=_paths(tmp_path, "d1.pdf"), wiki=_paths(tmp_path, "wiki0000.txt", "wiki0001.txt")) + + +@allure.feature("pysweep") +@pytest.mark.parametrize("failure", ["presigned_status", "upload_status"]) +def test_a_failed_upload_stops_seeding(tmp_path, failure): + edp = FakeEdp() + setattr(edp, failure, 500) + with pytest.raises(SeedError, match="HTTP 500"): + _seed(edp, 10, documents=_paths(tmp_path, "d1.pdf")) + + +@allure.feature("pysweep") +def test_wait_until_idle_polls_while_files_are_processed(): + edp = FakeEdp({"a.pdf": {"status": "processing", "chunks_processed": 0}}, chunks=4) + sleeps = [] + state = wait_until_idle(edp, sleep=sleeps.append, clock=lambda: 0.0) + assert sleeps == [seed_module.POLL_INTERVAL_S] + assert state.vectors == 4 + + +@allure.feature("pysweep") +def test_wait_until_idle_gives_up_after_the_timeout(): + class Stuck(FakeEdp): + def list_files(self): + return _response(200, [{"object_name": "a.pdf", "status": "embedding"}]) + + now = iter([0.0, 10.0, 20.0]) + with pytest.raises(SeedError, match="still processes 1 file"): + wait_until_idle(Stuck(), timeout=15, sleep=lambda s: None, clock=lambda: next(now)) + + +@allure.feature("pysweep") +def test_a_downloaded_file_is_reused(tmp_path, monkeypatch): + target = tmp_path / "doc.pdf" + target.write_bytes(b"cached") + + def no_network(*args, **kwargs): + raise AssertionError("downloaded again") + + monkeypatch.setattr(seed_module.requests, "get", no_network) + assert download("http://example/doc.pdf", target) == target + + +@allure.feature("pysweep") +def test_the_seed_inputs_exist_in_the_repo(): + assert seed_module.DOCUMENTS_CSV.is_file() + assert seed_module.WIKIPARSE.is_file() + + +@allure.feature("pysweep") +def test_run_pre_bench_does_nothing_without_settings(monkeypatch): + monkeypatch.setattr(pre_bench, "edp_client", lambda: pytest.fail("EDP contacted")) + pre_bench.run_pre_bench({}) + + +@allure.feature("pysweep") +def test_run_pre_bench_seeds_the_declared_number_of_vectors(monkeypatch): + calls = [] + monkeypatch.setattr(pre_bench.seed, "seed", lambda num_vectors, edp: calls.append((num_vectors, edp))) + pre_bench.run_pre_bench({pre_bench.NUM_VECTORS: 50000}, edp="edp") + assert calls == [(50000, "edp")] From f89cc5e65b66a8a0b9ba28837db0d7ae14d18f2e Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 27 Nov 2026 17:18:22 +0100 Subject: [PATCH 08/11] feat(benchmarks): use the pubmed questions in the shipped pysweep sweep They ask about the pubmed documents pre_bench seeds, as the nightly benchmarks do, so retrieval finds real matches. Signed-off-by: Kurzacz, Kamil --- src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml index fae9aea0..5eeda69b 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml @@ -10,7 +10,7 @@ llms: max_new_tokens: [128, 256] client: - question_file: ../questions-short.csv + question_file: ../questions-pubmed.csv concurrency: [1, 16, 128] duration: 5m worker_startup_delay: 0s From 45c7cc939d85ef0adaa6d7e2e5ae6d997c3bd4bf Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 27 Nov 2026 17:28:38 +0100 Subject: [PATCH 09/11] feat(benchmarks): record the observed vector DB size in every pysweep run settings.edp.vector_db.num_vectors is now the number of vectors EDP holds, read after each deployment combination is applied (once EDP is idle), like the deployment knobs, instead of the declared pre_bench target. The EDP state reader moves from pre_bench/seed.py to cluster/vector_db.py, which seed() and the runner share. With EDP disabled nothing is recorded under settings.edp, and declaring pre_bench.edp.vector_db.num_vectors fails the preflight. Signed-off-by: Kurzacz, Kamil --- .../e2e/benchmarks/chatqna/pysweep/README.md | 1 + .../chatqna/pysweep/cluster/vector_db.py | 76 +++++++++++++++++++ .../chatqna/pysweep/configs/README.md | 7 +- .../chatqna/pysweep/pre_bench/__init__.py | 9 +-- .../chatqna/pysweep/pre_bench/seed.py | 46 +---------- .../chatqna/pysweep/pysweep_bench.py | 12 ++- .../e2e/benchmarks/chatqna/pysweep/results.py | 6 +- .../pysweep/test_pysweep_bench_unit.py | 41 +++++++++- .../validation/pysweep/test_results_unit.py | 8 +- .../e2e/validation/pysweep/test_seed_unit.py | 49 +----------- .../validation/pysweep/test_vector_db_unit.py | 72 ++++++++++++++++++ 11 files changed, 211 insertions(+), 116 deletions(-) create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/cluster/vector_db.py create mode 100644 src/tests/e2e/validation/pysweep/test_vector_db_unit.py diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md index 87cb33ad..e2821854 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -27,6 +27,7 @@ environment gotchas. | `cluster/auth.py` | `KubernetesAccess` (side-effect-free RBAC preflight via `SelfSubjectAccessReview`), `load_build_config()` (the installed environment's config), `keycloak_helper()` (the maintained `KeycloakHelper`, for user tokens) and `client_token_lifespan()` (a sweep-long access-token lifespan for the UI client, restored afterwards). | | `cluster/fingerprint.py` | `system_fingerprint` client. `HelperFingerprintClient` adapts the suite's `FingerprintApiHelper`; `PortForwardTransport` / `IngressTransport` cover deployments the helper can't reach. | | `cluster/served_model.py` | `ServedModel`: reads the model the pipeline is **observed** to generate with, out of the running `llm-usvc` pods. Not a knob — the runner uses it to pick the benchmark's tokenizer. | +| `cluster/vector_db.py` | Reads the vector DB's state from EDP (ingested vectors, files in progress); every run records the observed count as `settings.edp.vector_db.num_vectors`. | | `cluster/model_catalog.py` | Reader for the model-manager catalog (`models-rag.yaml` / `models.yaml`): maps a served model name to the HuggingFace repo id the benchmark's tokenizer needs. | | `provenance/commit_info.py` | The checked-out commit the results are attributed to. | | `provenance/paths.py` | Where the installed environment's files are looked for (deploy root derived from the checkout's location). | diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/vector_db.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/vector_db.py new file mode 100644 index 00000000..5de143ad --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/vector_db.py @@ -0,0 +1,76 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging +import time +from dataclasses import dataclass, field +from pathlib import Path + +logger = logging.getLogger(__name__) + +POLL_INTERVAL_S = 30.0 +INGEST_TIMEOUT_S = 4 * 3600.0 + + +class VectorDbError(Exception): + """The vector DB's state cannot be read from EDP.""" + + +@dataclass +class VectorDbState: + vectors: int = 0 + in_progress: int = 0 + failed: int = 0 + files: set[str] = field(default_factory=set) + + +def read_state(edp) -> VectorDbState: + """Ingested vectors (chunks) and files, as EDP reports them.""" + response = edp.list_files() + if response.status_code != 200: + raise VectorDbError(f"EDP /files returned HTTP {response.status_code}: {response.text[:300]}") + state = VectorDbState() + for item in response.json(): + status = item.get("status") + state.files.add(Path(item.get("object_name", "")).name) + if status == "ingested": + state.vectors += int(item.get("chunks_processed") or 0) + elif status == "error": + state.failed += 1 + else: + state.in_progress += 1 + return state + + +def wait_until_idle(edp, timeout=INGEST_TIMEOUT_S, poll=POLL_INTERVAL_S, sleep=time.sleep, clock=time.monotonic): + deadline = clock() + timeout + while True: + state = read_state(edp) + if not state.in_progress: + return state + if clock() >= deadline: + raise VectorDbError( + f"EDP still processes {state.in_progress} file(s) after {timeout:.0f}s " + f"({state.vectors} vectors ingested so far)." + ) + logger.info("Waiting for EDP: %d file(s) in progress, %d vectors ingested.", state.in_progress, state.vectors) + sleep(poll) + + +def edp_client(): + from tests.e2e.helpers.edp_helper import EdpHelper + + from .auth import keycloak_helper + + return EdpHelper(keycloak_helper()) + + +def edp_enabled() -> bool: + from .auth import load_build_config + + return bool(load_build_config().get("edp_enabled")) + + +def observed_settings(edp, **wait) -> dict[str, int]: + """The vector DB as each run records it, under ``settings.edp``.""" + return {"vector_db.num_vectors": wait_until_idle(edp, **wait).vectors} diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md index 5afe63a0..b2f4277e 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md @@ -14,8 +14,11 @@ out-of-range value is a `ConfigError`. ## `sweep.yaml` **`pre_bench`** prepares what every run shares, once, before the first run. -Single values only; it is not part of the product. Each value is recorded in -every run as `settings.` (e.g. `settings.edp.vector_db.num_vectors`). +Single values only; it is not part of the product. Like the deployment knobs, +every run records the observed state, not the declared value: with EDP enabled, +`settings.edp.vector_db.num_vectors` is the number of vectors EDP holds (read +after each deployment combination is applied), which is at least the target and +usually above it, since whole files are loaded. | Key | Meaning | |---|---| diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py index a2f86730..e62c4465 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py @@ -4,6 +4,7 @@ import logging from typing import Any +from ..cluster.vector_db import edp_client from . import seed from .seed import SeedError @@ -14,14 +15,6 @@ __all__ = ["NUM_VECTORS", "SeedError", "edp_client", "run_pre_bench", "seed"] -def edp_client(): - from tests.e2e.helpers.edp_helper import EdpHelper - - from ..cluster.auth import keycloak_helper - - return EdpHelper(keycloak_helper()) - - def run_pre_bench(settings: dict[str, Any], edp=None) -> None: """Prepare the deployment state every run of the sweep shares; ``settings`` are dotted pre_bench paths.""" if not settings: diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py index 8d67be72..b2432c4e 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py @@ -9,12 +9,13 @@ import subprocess import sys import time -from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Iterable import requests +from ..cluster.vector_db import VectorDbState, wait_until_idle + logger = logging.getLogger(__name__) BENCHMARK_DIR = Path(__file__).resolve().parents[2] @@ -26,8 +27,6 @@ CACHE_ENV_VAR = "PYSWEEP_SEED_CACHE" DEFAULT_CACHE_DIR = Path.home() / ".cache" / "pysweep" / "seed" -POLL_INTERVAL_S = 30.0 -INGEST_TIMEOUT_S = 4 * 3600.0 DOWNLOAD_TIMEOUT_S = 600 # EDP processes two files at a time, so pairs keep it busy without queueing. WIKI_BATCH = 2 @@ -37,47 +36,6 @@ class SeedError(Exception): """The vector DB could not be seeded to the requested size.""" -@dataclass -class VectorDbState: - vectors: int = 0 - in_progress: int = 0 - failed: int = 0 - files: set[str] = field(default_factory=set) - - -def read_state(edp) -> VectorDbState: - """Ingested vectors (chunks) and files, as EDP reports them.""" - response = edp.list_files() - if response.status_code != 200: - raise SeedError(f"EDP /files returned HTTP {response.status_code}: {response.text[:300]}") - state = VectorDbState() - for item in response.json(): - status = item.get("status") - state.files.add(Path(item.get("object_name", "")).name) - if status == "ingested": - state.vectors += int(item.get("chunks_processed") or 0) - elif status == "error": - state.failed += 1 - else: - state.in_progress += 1 - return state - - -def wait_until_idle(edp, timeout=INGEST_TIMEOUT_S, poll=POLL_INTERVAL_S, sleep=time.sleep, clock=time.monotonic): - deadline = clock() + timeout - while True: - state = read_state(edp) - if not state.in_progress: - return state - if clock() >= deadline: - raise SeedError( - f"EDP still processes {state.in_progress} file(s) after {timeout:.0f}s " - f"({state.vectors} vectors ingested so far)." - ) - logger.info("Waiting for EDP: %d file(s) in progress, %d vectors ingested.", state.in_progress, state.vectors) - sleep(poll) - - def upload(edp, path: Path) -> None: presigned = edp.generate_presigned_url(path.name) if presigned.status_code != 200: diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py index 48643594..7e188701 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -40,6 +40,7 @@ load_run_config, ) from tests.e2e.benchmarks.chatqna.pysweep.cluster import model_catalog +from tests.e2e.benchmarks.chatqna.pysweep.cluster.vector_db import edp_client, edp_enabled, observed_settings from tests.e2e.benchmarks.chatqna.pysweep.pre_bench import NUM_VECTORS, run_pre_bench, seed from tests.e2e.benchmarks.chatqna.pysweep.provenance.commit_info import CommitInfoError, read_commit_info from tests.e2e.benchmarks.chatqna.pysweep.results import ( @@ -246,6 +247,8 @@ def commit_info_verify() -> dict[str, str]: def pre_bench_verify(config: SweepConfig) -> None: """Raise PreflightError unless the inputs of every declared pre_bench step exist.""" if NUM_VECTORS in config.pre_bench_settings(): + if not edp_enabled(): + raise PreflightError(f"pre_bench.{NUM_VECTORS} needs EDP, which this deployment does not enable.") for path in (seed.DOCUMENTS_CSV, seed.WIKIPARSE): if not path.is_file(): raise PreflightError(f"pre_bench.{NUM_VECTORS} needs {path}, which does not exist.") @@ -477,8 +480,8 @@ def main(argv=None): deployment_combinations = config.deployment_combinations() client_combinations = config.client_combinations() varying_paths = config.varying_paths() - pre_bench = config.pre_bench_settings() - run_pre_bench(pre_bench) + edp = edp_client() if edp_enabled() else None + run_pre_bench(config.pre_bench_settings(), edp) layout = prepare_summaries_dir(args.summaries) sweep_results = SweepResults(layout, date=utc_now(), commit_info=commit_info) @@ -505,6 +508,9 @@ def main(argv=None): ) tokenizer = resolve_tokenizer() + edp_settings = observed_settings(edp) if edp else {} + if edp_settings: + logger.info("Observed EDP state:\n%s", format_settings_yaml(edp_settings)) logger.info("Counting tokens with the served model's tokenizer: %s", tokenizer) for client_index, client_combination in enumerate(client_combinations, start=1): @@ -535,7 +541,7 @@ def main(argv=None): result_file=sweep_results.pointer(output_file), deployment=snapshot, client={**client, "client.tokenizer": tokenizer}, - pre_bench=pre_bench, + edp=edp_settings, results=summarize_requests( read_requests(output_file), duration_to_seconds(str(client["client.duration"])), diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py index fed50d64..a94c3e6e 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py @@ -244,9 +244,9 @@ def run_record( deployment: dict[str, Any], client: dict[str, Any], results: dict[str, Any], - pre_bench: dict[str, Any] | None = None, + edp: dict[str, Any] | None = None, ) -> dict[str, Any]: - """One run's record; ``deployment``/``client``/``pre_bench`` take dotted setting paths.""" + """One run's record; ``deployment``/``client``/``edp`` take dotted setting paths.""" return { "run": { "index": index, @@ -258,7 +258,7 @@ def run_record( "settings": { "deployment": nest(deployment), "client": nest({path.removeprefix("client."): value for path, value in client.items()}), - **nest(pre_bench or {}), + **({"edp": nest(edp)} if edp else {}), }, "results": results, } diff --git a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py index 4ec23942..7bf7690d 100644 --- a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -53,6 +53,7 @@ def _committed_checkout(monkeypatch): # CI checks out without git, so no test may depend on the real repository. monkeypatch.setattr(psb, "read_commit_info", lambda: dict(COMMIT)) + monkeypatch.setattr(psb, "edp_enabled", lambda: False) def _sweep(**sections): @@ -712,6 +713,7 @@ def test_question_file_absolute_path_is_untouched(tmp_path): @allure.feature("pysweep") def test_preflight_accepts_the_shipped_example_config(monkeypatch): + monkeypatch.setattr(psb, "edp_enabled", lambda: True) example = psb.PYSWEEP_DIR / "configs" / "sweep.yaml" psb.preflight_check(load_config(example)) @@ -828,7 +830,7 @@ def unreadable(): @allure.feature("pysweep") -def test_pre_bench_runs_once_before_the_summaries_and_the_first_run(monkeypatch, tmp_path): +def test_pre_bench_runs_once_before_the_summaries_and_runs_record_the_observed_edp(monkeypatch, tmp_path): monkeypatch.chdir(tmp_path) cfg = load_config({ **_client(concurrency=[1, 16]), @@ -845,7 +847,11 @@ def run_benchmark(self, args, output_file=None): run_config = psb.load_run_config({}) monkeypatch.setattr(psb, "load_config", lambda _: cfg) monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) - monkeypatch.setattr(psb, "run_pre_bench", lambda settings: events.append(("pre_bench", settings))) + edp = object() + monkeypatch.setattr(psb, "edp_enabled", lambda: True) + monkeypatch.setattr(psb, "edp_client", lambda: edp) + monkeypatch.setattr(psb, "observed_settings", lambda client: {"vector_db.num_vectors": 55312}) + monkeypatch.setattr(psb, "run_pre_bench", lambda settings, client: events.append(("pre_bench", settings, client is edp))) monkeypatch.setattr(psb, "prepare_summaries_dir", lambda root: events.append("summaries") or real_prepare(root)) monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) monkeypatch.setattr(psb, "default_transport", lambda: None) @@ -856,19 +862,46 @@ def run_benchmark(self, args, output_file=None): assert psb.main(["--sweep", "ignored.yaml", "--summaries", "out"]) == 0 - assert events == [("pre_bench", {"edp.vector_db.num_vectors": 50000}), "summaries", "run", "run"] + assert events == [("pre_bench", {"edp.vector_db.num_vectors": 50000}, True), "summaries", "run", "run"] document = json.loads((tmp_path / "out" / results.RESULTS_FILE_NAME).read_text()) - assert {run["settings"]["edp"]["vector_db"]["num_vectors"] for run in document["runs"]} == {50000} + assert {run["settings"]["edp"]["vector_db"]["num_vectors"] for run in document["runs"]} == {55312} @allure.feature("pysweep") def test_preflight_fails_when_a_seed_input_is_missing(monkeypatch, tmp_path): + monkeypatch.setattr(psb, "edp_enabled", lambda: True) monkeypatch.setattr(psb.seed, "WIKIPARSE", tmp_path / "missing.py") cfg = load_config({**_client(), "pre_bench": {"edp": {"vector_db": {"num_vectors": 1}}}}) with pytest.raises(psb.PreflightError, match="missing.py"): psb.preflight_check(cfg) +@allure.feature("pysweep") +def test_seeding_without_edp_fails_the_preflight(): + cfg = load_config({**_client(), "pre_bench": {"edp": {"vector_db": {"num_vectors": 1}}}}) + with pytest.raises(psb.PreflightError, match="needs EDP"): + psb.preflight_check(cfg) + + +@allure.feature("pysweep") +def test_runs_record_no_edp_settings_without_edp(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + run_config = psb.load_run_config({}) + cfg = load_config(_client()) + monkeypatch.setattr(psb, "load_config", lambda _: cfg) + monkeypatch.setattr(psb, "load_run_config", lambda _: run_config) + monkeypatch.setattr(psb, "FingerprintClient", lambda transport: None) + monkeypatch.setattr(psb, "default_transport", lambda: None) + monkeypatch.setattr(psb, "apply_combination", lambda c, f: {}) + monkeypatch.setattr(psb, "resolve_tokenizer", lambda: "served/model") + monkeypatch.setattr(psb, "provision_benchmark_target", _passthrough_provision) + _install_fake_benchmark(monkeypatch, FakeBenchmark()) + + assert psb.main(["--sweep", "ignored.yaml", "--summaries", "out"]) == 0 + document = json.loads((tmp_path / "out" / results.RESULTS_FILE_NAME).read_text()) + assert "edp" not in document["runs"][0]["settings"] + + @allure.feature("pysweep") def test_each_run_logs_its_record_as_yaml(monkeypatch, tmp_path, caplog): monkeypatch.chdir(tmp_path) diff --git a/src/tests/e2e/validation/pysweep/test_results_unit.py b/src/tests/e2e/validation/pysweep/test_results_unit.py index b1dd13fe..83db2917 100644 --- a/src/tests/e2e/validation/pysweep/test_results_unit.py +++ b/src/tests/e2e/validation/pysweep/test_results_unit.py @@ -165,15 +165,15 @@ def test_a_record_groups_settings_into_deployment_and_client(): @allure.feature("pysweep") -def test_pre_bench_settings_sit_next_to_deployment_and_client(): +def test_edp_settings_sit_next_to_deployment_and_client(): record = run_record( index="1.1", started_at="s", finished_at="f", exit_code=0, result_file="r.csv", deployment={}, client={"client.concurrency": 1}, results=summarize_requests([], duration_s=60), - pre_bench={"edp.vector_db.num_vectors": 50000}, + edp={"vector_db.num_vectors": 55312}, ) - assert record["settings"]["edp"] == {"vector_db": {"num_vectors": 50000}} - assert flatten(record)["settings.edp.vector_db.num_vectors"] == 50000 + assert record["settings"]["edp"] == {"vector_db": {"num_vectors": 55312}} + assert flatten(record)["settings.edp.vector_db.num_vectors"] == 55312 @pytest.fixture diff --git a/src/tests/e2e/validation/pysweep/test_seed_unit.py b/src/tests/e2e/validation/pysweep/test_seed_unit.py index 645cd1b4..d7113666 100644 --- a/src/tests/e2e/validation/pysweep/test_seed_unit.py +++ b/src/tests/e2e/validation/pysweep/test_seed_unit.py @@ -8,13 +8,7 @@ from tests.e2e.benchmarks.chatqna.pysweep import pre_bench from tests.e2e.benchmarks.chatqna.pysweep.pre_bench import seed as seed_module -from tests.e2e.benchmarks.chatqna.pysweep.pre_bench.seed import ( - SeedError, - download, - read_state, - seed, - wait_until_idle, -) +from tests.e2e.benchmarks.chatqna.pysweep.pre_bench.seed import SeedError, download, seed def _response(status=200, payload=None, text=""): @@ -66,27 +60,6 @@ def _seed(edp, num_vectors, documents=(), wiki=()): ) -@allure.feature("pysweep") -def test_read_state_counts_ingested_chunks_and_open_work(): - edp = FakeEdp({ - "a.pdf": {"status": "ingested", "chunks_processed": 7}, - "Docs/b.pdf": {"status": "ingested", "chunks_processed": 5}, - "c.pdf": {"status": "error", "chunks_processed": 0}, - "d.pdf": {"status": "embedding", "chunks_processed": 0}, - }) - state = read_state(edp) - assert (state.vectors, state.failed, state.in_progress) == (12, 1, 1) - assert state.files == {"a.pdf", "b.pdf", "c.pdf", "d.pdf"} - - -@allure.feature("pysweep") -def test_an_edp_error_is_a_seed_error(): - edp = FakeEdp() - edp.list_status = 503 - with pytest.raises(SeedError, match="HTTP 503"): - read_state(edp) - - @allure.feature("pysweep") def test_nothing_is_uploaded_when_the_target_is_already_met(tmp_path): edp = FakeEdp({"a.pdf": {"status": "ingested", "chunks_processed": 60}}) @@ -136,26 +109,6 @@ def test_a_failed_upload_stops_seeding(tmp_path, failure): _seed(edp, 10, documents=_paths(tmp_path, "d1.pdf")) -@allure.feature("pysweep") -def test_wait_until_idle_polls_while_files_are_processed(): - edp = FakeEdp({"a.pdf": {"status": "processing", "chunks_processed": 0}}, chunks=4) - sleeps = [] - state = wait_until_idle(edp, sleep=sleeps.append, clock=lambda: 0.0) - assert sleeps == [seed_module.POLL_INTERVAL_S] - assert state.vectors == 4 - - -@allure.feature("pysweep") -def test_wait_until_idle_gives_up_after_the_timeout(): - class Stuck(FakeEdp): - def list_files(self): - return _response(200, [{"object_name": "a.pdf", "status": "embedding"}]) - - now = iter([0.0, 10.0, 20.0]) - with pytest.raises(SeedError, match="still processes 1 file"): - wait_until_idle(Stuck(), timeout=15, sleep=lambda s: None, clock=lambda: next(now)) - - @allure.feature("pysweep") def test_a_downloaded_file_is_reused(tmp_path, monkeypatch): target = tmp_path / "doc.pdf" diff --git a/src/tests/e2e/validation/pysweep/test_vector_db_unit.py b/src/tests/e2e/validation/pysweep/test_vector_db_unit.py new file mode 100644 index 00000000..da2f8114 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_vector_db_unit.py @@ -0,0 +1,72 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from types import SimpleNamespace + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.cluster import vector_db +from tests.e2e.benchmarks.chatqna.pysweep.cluster.vector_db import ( + VectorDbError, + observed_settings, + read_state, + wait_until_idle, +) + + +class Edp: + """EDP whose /files answers come from a list of listings, one per call.""" + + def __init__(self, *listings, status=200): + self.listings = list(listings) + self.status = status + + def list_files(self): + listing = self.listings.pop(0) if len(self.listings) > 1 else self.listings[0] + return SimpleNamespace(status_code=self.status, json=lambda: listing, text="boom") + + +def _file(name, status, chunks=0): + return {"object_name": name, "status": status, "chunks_processed": chunks} + + +@allure.feature("pysweep") +def test_read_state_counts_ingested_chunks_and_open_work(): + edp = Edp([ + _file("a.pdf", "ingested", 7), + _file("Docs/b.pdf", "ingested", 5), + _file("c.pdf", "error"), + _file("d.pdf", "embedding"), + ]) + state = read_state(edp) + assert (state.vectors, state.failed, state.in_progress) == (12, 1, 1) + assert state.files == {"a.pdf", "b.pdf", "c.pdf", "d.pdf"} + + +@allure.feature("pysweep") +def test_an_edp_error_is_a_vector_db_error(): + with pytest.raises(VectorDbError, match="HTTP 503"): + read_state(Edp([], status=503)) + + +@allure.feature("pysweep") +def test_wait_until_idle_polls_while_files_are_processed(): + edp = Edp([_file("a.pdf", "embedding")], [_file("a.pdf", "ingested", 4)]) + sleeps = [] + state = wait_until_idle(edp, sleep=sleeps.append, clock=lambda: 0.0) + assert sleeps == [vector_db.POLL_INTERVAL_S] + assert state.vectors == 4 + + +@allure.feature("pysweep") +def test_wait_until_idle_gives_up_after_the_timeout(): + now = iter([0.0, 10.0, 20.0]) + with pytest.raises(VectorDbError, match="still processes 1 file"): + wait_until_idle(Edp([_file("a.pdf", "embedding")]), timeout=15, sleep=lambda s: None, clock=lambda: next(now)) + + +@allure.feature("pysweep") +def test_observed_settings_report_the_ingested_vectors_once_idle(): + edp = Edp([_file("a.pdf", "embedding")], [_file("a.pdf", "ingested", 55312)]) + assert observed_settings(edp, sleep=lambda s: None) == {"vector_db.num_vectors": 55312} From 0155d5e226c9633a338dc0d5f4655f0029f1c54b Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 27 Nov 2026 17:47:19 +0100 Subject: [PATCH 10/11] feat(benchmarks): group pysweep commit and hardware info under metadata results.json (schema_version 2) now carries a metadata object with commit_info and hardware, the CPU, memory and OS of the node serving the model: CPU model, sockets, cores, threads and NUMA nodes from /proc/cpuinfo in a model-server pod, vendor, family and AMX from Node Feature Discovery labels, memory and OS from the node object. Only SPR and GNR are recognized; any other CPU raises with the values found. Collection is switched by metadata in general.yaml (default true) and done in the preflight, before pre_bench or any run; when enabled every part is mandatory. With metadata: false the document has no metadata key. The RBAC preflight checks the model-server pods and nodes access. Signed-off-by: Kurzacz, Kamil --- .../e2e/benchmarks/chatqna/pysweep/README.md | 42 +++-- .../chatqna/pysweep/cluster/auth.py | 6 +- .../e2e/benchmarks/chatqna/pysweep/config.py | 1 + .../chatqna/pysweep/configs/README.md | 1 + .../chatqna/pysweep/configs/general.yaml | 1 + .../chatqna/pysweep/provenance/__init__.py | 23 +++ .../chatqna/pysweep/provenance/hardware.py | 129 +++++++++++++++ .../chatqna/pysweep/pysweep_bench.py | 32 ++-- .../e2e/benchmarks/chatqna/pysweep/results.py | 24 +-- .../validation/pysweep/test_hardware_unit.py | 154 ++++++++++++++++++ .../validation/pysweep/test_metadata_unit.py | 55 +++++++ .../pysweep/test_pysweep_bench_unit.py | 39 +++-- .../validation/pysweep/test_results_unit.py | 42 +++-- 13 files changed, 488 insertions(+), 61 deletions(-) create mode 100644 src/tests/e2e/benchmarks/chatqna/pysweep/provenance/hardware.py create mode 100644 src/tests/e2e/validation/pysweep/test_hardware_unit.py create mode 100644 src/tests/e2e/validation/pysweep/test_metadata_unit.py diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md index e2821854..7a88518d 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -29,7 +29,7 @@ environment gotchas. | `cluster/served_model.py` | `ServedModel`: reads the model the pipeline is **observed** to generate with, out of the running `llm-usvc` pods. Not a knob — the runner uses it to pick the benchmark's tokenizer. | | `cluster/vector_db.py` | Reads the vector DB's state from EDP (ingested vectors, files in progress); every run records the observed count as `settings.edp.vector_db.num_vectors`. | | `cluster/model_catalog.py` | Reader for the model-manager catalog (`models-rag.yaml` / `models.yaml`): maps a served model name to the HuggingFace repo id the benchmark's tokenizer needs. | -| `provenance/commit_info.py` | The checked-out commit the results are attributed to. | +| `provenance/` | The results' `metadata`: `collect_metadata()` in `__init__.py`, `commit_info.py` (the checked-out commit) and `hardware.py` (the CPU, memory and OS of the node serving the model; SPR or GNR only). | | `provenance/paths.py` | Where the installed environment's files are looked for (deploy root derived from the checkout's location). | | `configs/sweep.yaml` | Sweep config (`--sweep`): what to vary. Keys are described in [`configs/README.md`](./configs/README.md). | | `configs/general.yaml` | Run config (`--config`): how to run. | @@ -273,21 +273,39 @@ finished. ```json { - "schema_version": 1, + "schema_version": 2, "date": "2026-11-26T09:02:11Z", - "commit_info": { - "sha": "9022de7e…", - "datetime": "2026-11-25T18:02:44+01:00", - "author": "Kurzacz, Kamil", - "description": "refactor(benchmarks): …", - "branch": "kkurzacz/pysweep-core" + "metadata": { + "commit_info": { + "sha": "9022de7e…", + "datetime": "2026-11-25T18:02:44+01:00", + "author": "Kurzacz, Kamil", + "description": "refactor(benchmarks): …", + "branch": "kkurzacz/pysweep-core" + }, + "hardware": { + "nodes": ["localhost"], + "cpu": {"vendor": "Intel", "model": "Intel(R) Xeon(R) Platinum 8468H", "family": "SPR", "model_id": 143, + "sockets": 2, "cores": 96, "threads": 192, "numa_nodes": 2, "amx": true}, + "memory_gib": 2011, + "os": "Ubuntu 24.10", + "kernel": "6.11.0-29-generic", + "kubernetes": "v1.35.4" + } }, "runs": [ { "run": {…}, "settings": {…}, "results": {…} } ] } ``` -`date` is when the sweep started (UTC). `commit_info` is the committed `HEAD` of -the checkout pysweep runs from; uncommitted changes are not recorded. +`date` is when the sweep started (UTC). `metadata` describes where the results +come from, not the benchmark itself, and is collected in the preflight when +`metadata: true` in `general.yaml` (the default); every part is then mandatory. +`commit_info` is the committed `HEAD` of the checkout pysweep runs from +(uncommitted changes are not recorded). `hardware` is the node(s) running the +served model's model-server pods: CPU facts from Node Feature Discovery and +`/proc/cpuinfo` in a model-server pod, memory and OS from the node object. Only +SPR and GNR are recognized; any other CPU fails the preflight with the values it +found. With `metadata: false` the document has no `metadata` key. Each record, also logged as YAML when its run finishes: @@ -328,7 +346,7 @@ results: Percentiles are linearly interpolated (numpy's default), like `parse.py`. -`benchmark_summary_results.csv` has one row per run: `date`, `commit_info.*`, then +`benchmark_summary_results.csv` has one row per run: `date`, `metadata.*` (lists joined with `;`), then every field of the record as a dotted column (`run.index`, `settings.deployment.llms.max_new_tokens`, `settings.client.concurrency`, `results.ttft_s.p90`, …). Missing values are blank. @@ -389,7 +407,7 @@ In increasing cost order: | Check | What it asserts | |---|---| | `question_file_verify()` | Every declared `client.question_file` (the knob is sweepable, so a config may name several) resolves to a readable file. A stat per corpus. | -| `commit_info_verify()` | The checkout pysweep runs from is a git repository with a commit on a branch (not a detached `HEAD`), so the results can name it. A synced copy needs a readable `.git`. | +| `metadata_verify()` | With `metadata: true`: the checkout pysweep runs from is a git repository with a commit on a branch (not a detached `HEAD`; a synced copy needs a readable `.git`), and the node serving the model has Node Feature Discovery labels, readable `/proc/cpuinfo` and an SPR or GNR CPU. | ## Requirements diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py index 56fb18a2..1c053e37 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py @@ -68,7 +68,8 @@ class RequiredAccess: def describe(self) -> str: grp = f"{self.group}/" if self.group else "" - return f"{self.verb} {grp}{self.resource} in ns/{self.namespace}" + scope = f"in ns/{self.namespace}" if self.namespace else "(cluster-scoped)" + return f"{self.verb} {grp}{self.resource} {scope}" @dataclass @@ -85,6 +86,9 @@ class AccessCheckResult: "get", "llminferenceservices", LLM_INFERENCE_NAMESPACE, group="serving.kserve.io", reason="observed model readiness", ), + RequiredAccess("list", "pods", LLM_INFERENCE_NAMESPACE, reason="locate the model-server pods"), + RequiredAccess("create", "pods/exec", LLM_INFERENCE_NAMESPACE, reason="read /proc/cpuinfo on the model server"), + RequiredAccess("get", "nodes", "", reason="read the model server node's CPU labels and capacity"), RequiredAccess("list", "pods", FINGERPRINT_NAMESPACE, reason="locate fingerprint-svc endpoints"), RequiredAccess( "create", "pods/portforward", FINGERPRINT_NAMESPACE, diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py index 95de2d45..f80c1ee2 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/config.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py @@ -128,6 +128,7 @@ class RunConfig(_StrictModel): # kr8s/httpx logs a '101 Switching Protocols' line for every port-forwarded request. display_kubernetes_client_logs: bool = False + metadata: bool = True class SweepConfig(_StrictModel): diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md index b2f4277e..299890d0 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md @@ -64,3 +64,4 @@ previous sweep's results there are deleted first. | Key | Default | Meaning | |---|---|---| | `display_kubernetes_client_logs` | `false` | Show the Kubernetes client's per-request and port-forward teardown log noise; for debugging connectivity. | +| `metadata` | `true` | Collect `metadata.commit_info` and `metadata.hardware` for `results.json` in the preflight; every part is then mandatory and a failure stops the sweep before anything runs. Needed for loading results into Elasticsearch. | diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml index a603bad2..70eb30eb 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml @@ -2,3 +2,4 @@ # SPDX-License-Identifier: Apache-2.0 display_kubernetes_client_logs: false +metadata: true diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py index 91da480a..a0b3ab24 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py @@ -1,2 +1,25 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 + +from .commit_info import CommitInfoError, read_commit_info +from .hardware import HardwareError, read_hardware + + +class MetadataError(Exception): + """A piece of the results' metadata cannot be collected.""" + + +def collect_metadata() -> dict: + """``commit_info`` and the served model's ``hardware``; every part is mandatory.""" + from ..cluster.served_model import ServedModel + from ..properties.base import PropertyReadError + + try: + commit_info = read_commit_info() + except CommitInfoError as exc: + raise MetadataError(f"commit_info: {exc}") from exc + try: + hardware = read_hardware(ServedModel().read()) + except (HardwareError, PropertyReadError) as exc: + raise MetadataError(f"hardware: {exc}") from exc + return {"commit_info": commit_info, "hardware": hardware} diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/hardware.py b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/hardware.py new file mode 100644 index 00000000..dd991e9f --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/hardware.py @@ -0,0 +1,129 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging + +import kr8s + +from tests.e2e.validation.constants import LLM_INFERENCE_NAMESPACE + +logger = logging.getLogger(__name__) + +MODEL_SERVER_CONTAINER = "main" +NFD = "feature.node.kubernetes.io/" +CPUINFO_COMMAND = [ + "sh", "-c", + "cat /proc/cpuinfo; echo '#numa'; ls -d /sys/devices/system/node/node[0-9]* 2>/dev/null | wc -l", +] + +# The supported CPUs: Intel family 6 model ids, as NFD's cpu-model.id label reports them. +CPU_FAMILIES = { + ("Intel", "6", 143): "SPR", + ("Intel", "6", 173): "GNR", + ("Intel", "6", 174): "GNR", +} + + +class HardwareError(Exception): + """The hardware the served model runs on cannot be identified.""" + + +def model_server_pods(model: str, namespace: str = LLM_INFERENCE_NAMESPACE) -> list: + pods = [ + pod + for pod in kr8s.get( + "pods", namespace=namespace, + label_selector={"app.kubernetes.io/name": model, "kserve.io/component": "workload"}, + ) + if pod.status.get("phase") == "Running" and not pod.metadata.get("deletionTimestamp") + ] + if not pods: + raise HardwareError(f"No running model-server pod of {model!r} in ns/{namespace}.") + return pods + + +def parse_cpuinfo(text: str) -> dict: + cpuinfo, _, numa = text.partition("#numa") + blocks = [dict(line.split(":", 1) for line in block.splitlines() if ":" in line) + for block in cpuinfo.strip().split("\n\n")] + blocks = [{k.strip(): v.strip() for k, v in block.items()} for block in blocks if block] + if not blocks or "model name" not in blocks[0]: + raise HardwareError("/proc/cpuinfo has no 'model name'.") + sockets = {block.get("physical id") for block in blocks} + cores = {(block.get("physical id"), block.get("core id")) for block in blocks} + numa_nodes = int(numa.strip() or 0) + if not numa_nodes: + raise HardwareError("No NUMA nodes under /sys/devices/system/node.") + return { + "model": blocks[0]["model name"], + "sockets": len(sockets), + "cores": len(cores), + "threads": len(blocks), + "numa_nodes": numa_nodes, + } + + +def node_facts(node) -> tuple[dict, dict]: + """CPU facts from the node's Node Feature Discovery labels, and the node's memory and OS.""" + labels = node.metadata.get("labels", {}) + try: + vendor = labels[f"{NFD}cpu-model.vendor_id"] + family_id = labels[f"{NFD}cpu-model.family"] + model_id = int(labels[f"{NFD}cpu-model.id"]) + except (KeyError, ValueError) as exc: + raise HardwareError( + f"Node {node.name} has no Node Feature Discovery cpu-model labels ({exc})." + ) from exc + memory = node.status.get("capacity", {}).get("memory", "") + if not memory.endswith("Ki"): + raise HardwareError(f"Node {node.name} reports memory capacity {memory!r}, not in Ki.") + info = node.status.get("nodeInfo", {}) + cpu = { + "vendor": vendor, + "family": CPU_FAMILIES.get((vendor, family_id, model_id)), + "family_id": family_id, + "model_id": model_id, + "amx": labels.get(f"{NFD}cpu-cpuid.AMXTILE") == "true", + } + system = { + "memory_gib": round(int(memory[:-2]) / 1024 ** 2), + "os": info.get("osImage"), + "kernel": info.get("kernelVersion"), + "kubernetes": info.get("kubeletVersion"), + } + return cpu, system + + +def read_hardware(model: str) -> dict: + """The CPU, memory and OS of the node(s) serving ``model``.""" + nodes: dict[str, dict] = {} + for pod in model_server_pods(model): + node_name = pod.spec.get("nodeName") + if node_name in nodes: + continue + try: + result = pod.exec(CPUINFO_COMMAND, container=MODEL_SERVER_CONTAINER) + except Exception as exc: # noqa: BLE001 + raise HardwareError(f"Cannot read /proc/cpuinfo in pod {pod.name}: {exc}") from exc + stdout = result.stdout.decode() if isinstance(result.stdout, bytes) else result.stdout + cpu, system = node_facts(kr8s.objects.Node.get(node_name)) + topology = parse_cpuinfo(stdout) + if cpu["family"] is None: + raise HardwareError( + f"Unrecognized CPU family on node {node_name}: vendor {cpu['vendor']}, family " + f"{cpu['family_id']}, model id {cpu['model_id']} ({topology['model']}); " + f"supported: {', '.join(sorted(set(CPU_FAMILIES.values())))}." + ) + nodes[node_name] = { + "cpu": { + "vendor": cpu["vendor"], "model": topology.pop("model"), "family": cpu["family"], + "model_id": cpu["model_id"], **topology, "amx": cpu["amx"], + }, + **system, + } + + if len({repr(hardware) for hardware in nodes.values()}) > 1: + raise HardwareError(f"{model!r} is served from nodes with different hardware: {sorted(nodes)}.") + hardware = next(iter(nodes.values())) + logger.info("Model %r is served on %s: %s.", model, sorted(nodes), hardware["cpu"]["model"]) + return {"nodes": sorted(nodes), **hardware} diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py index 7e188701..9b7b21a3 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -42,7 +42,7 @@ from tests.e2e.benchmarks.chatqna.pysweep.cluster import model_catalog from tests.e2e.benchmarks.chatqna.pysweep.cluster.vector_db import edp_client, edp_enabled, observed_settings from tests.e2e.benchmarks.chatqna.pysweep.pre_bench import NUM_VECTORS, run_pre_bench, seed -from tests.e2e.benchmarks.chatqna.pysweep.provenance.commit_info import CommitInfoError, read_commit_info +from tests.e2e.benchmarks.chatqna.pysweep.provenance import MetadataError, collect_metadata from tests.e2e.benchmarks.chatqna.pysweep.results import ( DEFAULT_SUMMARIES_DIR, SweepResults, @@ -231,17 +231,21 @@ def question_file_verify(config: SweepConfig) -> None: logger.debug("Preflight: question_file '%s' -> %s", value, path) -def commit_info_verify() -> dict[str, str]: - """Raise PreflightError unless the checked-out commit can be identified; return it.""" +def metadata_verify(enabled: bool) -> dict | None: + """Raise PreflightError unless every piece of the results' metadata can be collected; return it.""" + if not enabled: + logger.info("Preflight: metadata collection is off; results will carry no commit_info or hardware.") + return None try: - info = read_commit_info() - except CommitInfoError as exc: - raise PreflightError(f"commit_info: {exc}") from exc + metadata = collect_metadata() + except MetadataError as exc: + raise PreflightError(f"metadata: {exc}") from exc + commit, cpu = metadata["commit_info"], metadata["hardware"]["cpu"] logger.info( - "Preflight: results are attributed to %s on %s (%s).", - info["sha"][:12], info["branch"], info["description"], + "Preflight: results are attributed to %s on %s (%s), measured on %s (%s).", + commit["sha"][:12], commit["branch"], commit["description"], cpu["model"], cpu["family"], ) - return info + return metadata def pre_bench_verify(config: SweepConfig) -> None: @@ -254,11 +258,11 @@ def pre_bench_verify(config: SweepConfig) -> None: raise PreflightError(f"pre_bench.{NUM_VECTORS} needs {path}, which does not exist.") -def preflight_check(config: SweepConfig) -> dict[str, str]: - """Run every preflight check; return the commit the results are attributed to.""" +def preflight_check(config: SweepConfig, metadata: bool = True) -> dict | None: + """Run every preflight check; return the results' metadata, if collected.""" question_file_verify(config) pre_bench_verify(config) - return commit_info_verify() + return metadata_verify(metadata) def chatqna_url() -> str: @@ -475,7 +479,7 @@ def main(argv=None): config = load_config(args.sweep) bench_argv = resolve_benchmark_argv(config, args.benchmark_args) - commit_info = preflight_check(config) + metadata = preflight_check(config, run_config.metadata) deployment_combinations = config.deployment_combinations() client_combinations = config.client_combinations() @@ -484,7 +488,7 @@ def main(argv=None): run_pre_bench(config.pre_bench_settings(), edp) layout = prepare_summaries_dir(args.summaries) - sweep_results = SweepResults(layout, date=utc_now(), commit_info=commit_info) + sweep_results = SweepResults(layout, date=utc_now(), metadata=metadata) fingerprint_client = FingerprintClient(default_transport()) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py index a94c3e6e..6a98fccd 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/results.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py @@ -9,7 +9,6 @@ from pathlib import Path from typing import Any, Iterable, NamedTuple, Sequence -from .provenance.commit_info import COMMIT_INFO_FIELDS logger = logging.getLogger(__name__) @@ -21,7 +20,7 @@ PER_CASE_DIR_NAME = "per_case_results" -SCHEMA_VERSION = 1 +SCHEMA_VERSION = 2 PERCENTILES = (("p50", 0.5), ("p90", 0.9), ("p99", 0.99)) _PRECISION = 6 @@ -267,10 +266,10 @@ def run_record( class SweepResults: """Accumulates run records and rewrites results.json and the summary CSV after each.""" - def __init__(self, layout: SummariesLayout, date: str, commit_info: dict[str, str]): + def __init__(self, layout: SummariesLayout, date: str, metadata: dict[str, Any] | None): self.layout = layout self.date = date - self.commit_info = commit_info + self.metadata = metadata self.runs: list[dict[str, Any]] = [] self.write() @@ -286,7 +285,7 @@ def document(self) -> dict[str, Any]: return { "schema_version": SCHEMA_VERSION, "date": self.date, - "commit_info": self.commit_info, + **({"metadata": self.metadata} if self.metadata else {}), "runs": self.runs, } @@ -296,10 +295,7 @@ def add_run(self, record: dict[str, Any]) -> dict[str, Any]: return record def _csv_rows(self) -> list[dict[str, Any]]: - sweep = { - "date": self.date, - **{f"commit_info.{field}": self.commit_info.get(field) for field in COMMIT_INFO_FIELDS}, - } + sweep = flatten({"date": self.date, **({"metadata": self.metadata} if self.metadata else {})}) return [{**sweep, **flatten(record)} for record in self.runs] def write(self) -> Path: @@ -311,5 +307,13 @@ def write(self) -> Path: if columns: writer.writeheader() for row in rows: - writer.writerow({column: "" if row.get(column) is None else row[column] for column in columns}) + writer.writerow({column: _csv_value(row.get(column)) for column in columns}) return self.layout.results_file + + +def _csv_value(value: Any) -> Any: + if value is None: + return "" + if isinstance(value, list): + return ";".join(str(item) for item in value) + return value diff --git a/src/tests/e2e/validation/pysweep/test_hardware_unit.py b/src/tests/e2e/validation/pysweep/test_hardware_unit.py new file mode 100644 index 00000000..74dc04d7 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_hardware_unit.py @@ -0,0 +1,154 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from types import SimpleNamespace + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.provenance import hardware +from tests.e2e.benchmarks.chatqna.pysweep.provenance.hardware import ( + HardwareError, + parse_cpuinfo, + read_hardware, +) + +NFD = hardware.NFD + + +def cpuinfo(model="Intel(R) Xeon(R) Platinum 8468H", sockets=2, cores=2, threads_per_core=2, numa=2): + blocks, processor = [], 0 + for socket in range(sockets): + for core in range(cores): + for _ in range(threads_per_core): + blocks.append( + f"processor\t: {processor}\nmodel name\t: {model}\n" + f"physical id\t: {socket}\ncore id\t\t: {core}\nflags\t\t: fpu amx_tile" + ) + processor += 1 + return "\n\n".join(blocks) + f"\n\n#numa\n{numa}\n" + + +def node(name="node-1", model_id="143", vendor="Intel", family="6", memory="2109061508Ki", labels=None): + nfd = {f"{NFD}cpu-model.vendor_id": vendor, f"{NFD}cpu-model.family": family, + f"{NFD}cpu-model.id": model_id, f"{NFD}cpu-cpuid.AMXTILE": "true"} + return SimpleNamespace( + name=name, + metadata={"labels": nfd if labels is None else labels}, + status={"capacity": {"memory": memory}, + "nodeInfo": {"osImage": "Ubuntu 24.10", "kernelVersion": "6.11.0", "kubeletVersion": "v1.35.4"}}, + ) + + +class Pod: + def __init__(self, name, node_name, stdout, phase="Running"): + self.name = name + self.spec = {"nodeName": node_name} + self.status = {"phase": phase} + self.metadata = {} + self.stdout = stdout + self.exec_calls = [] + + def exec(self, command, container=None): + self.exec_calls.append(container) + return SimpleNamespace(stdout=self.stdout.encode()) + + +def install(monkeypatch, pods, nodes): + by_name = {n.name: n for n in nodes} + selectors = [] + + def get(resource, namespace=None, label_selector=None): + selectors.append((resource, namespace, label_selector)) + return pods + + monkeypatch.setattr(hardware, "kr8s", SimpleNamespace( + get=get, objects=SimpleNamespace(Node=SimpleNamespace(get=lambda name: by_name[name])), + )) + return selectors + + +@allure.feature("pysweep") +def test_cpuinfo_gives_the_model_and_topology(): + assert parse_cpuinfo(cpuinfo(sockets=2, cores=48, threads_per_core=2)) == { + "model": "Intel(R) Xeon(R) Platinum 8468H", + "sockets": 2, + "cores": 96, + "threads": 192, + "numa_nodes": 2, + } + + +@allure.feature("pysweep") +def test_cpuinfo_without_a_model_name_is_an_error(): + with pytest.raises(HardwareError, match="model name"): + parse_cpuinfo("processor\t: 0\n\n#numa\n1\n") + + +@allure.feature("pysweep") +def test_the_served_models_node_is_described(monkeypatch): + pod = Pod("llama-0", "node-1", cpuinfo()) + selectors = install(monkeypatch, [pod], [node()]) + assert read_hardware("llama3-8b-awq") == { + "nodes": ["node-1"], + "cpu": {"vendor": "Intel", "model": "Intel(R) Xeon(R) Platinum 8468H", "family": "SPR", + "model_id": 143, "sockets": 2, "cores": 4, "threads": 8, "numa_nodes": 2, "amx": True}, + "memory_gib": 2011, + "os": "Ubuntu 24.10", + "kernel": "6.11.0", + "kubernetes": "v1.35.4", + } + assert selectors[0][2] == {"app.kubernetes.io/name": "llama3-8b-awq", "kserve.io/component": "workload"} + assert pod.exec_calls == [hardware.MODEL_SERVER_CONTAINER] + + +@allure.feature("pysweep") +@pytest.mark.parametrize("model_id", ["173", "174"]) +def test_granite_rapids_is_gnr(monkeypatch, model_id): + install(monkeypatch, [Pod("p", "node-1", cpuinfo("Intel(R) Xeon(R) 6980P"))], [node(model_id=model_id)]) + assert read_hardware("m")["cpu"]["family"] == "GNR" + + +@allure.feature("pysweep") +@pytest.mark.parametrize("vendor, model_id", [("Intel", "207"), ("Intel", "175"), ("AMD", "143")]) +def test_any_other_cpu_is_unrecognized_and_named(monkeypatch, vendor, model_id): + install(monkeypatch, [Pod("p", "node-1", cpuinfo("Some CPU"))], [node(vendor=vendor, model_id=model_id)]) + with pytest.raises(HardwareError, match=f"Unrecognized CPU family.*vendor {vendor}, family 6, model id {model_id} \\(Some CPU\\); supported: GNR, SPR"): + read_hardware("m") + + +@allure.feature("pysweep") +def test_a_node_without_nfd_labels_is_an_error(monkeypatch): + install(monkeypatch, [Pod("p", "node-1", cpuinfo())], [node(labels={})]) + with pytest.raises(HardwareError, match="Node Feature Discovery"): + read_hardware("m") + + +@allure.feature("pysweep") +def test_no_running_model_server_is_an_error(monkeypatch): + install(monkeypatch, [Pod("p", "node-1", cpuinfo(), phase="Pending")], [node()]) + with pytest.raises(HardwareError, match="No running model-server pod"): + read_hardware("m") + + +@allure.feature("pysweep") +def test_each_node_is_read_once(monkeypatch): + first, second = Pod("a", "node-1", cpuinfo()), Pod("b", "node-1", cpuinfo()) + install(monkeypatch, [first, second], [node()]) + assert read_hardware("m")["nodes"] == ["node-1"] + assert second.exec_calls == [] + + +@allure.feature("pysweep") +def test_nodes_with_different_hardware_are_an_error(monkeypatch): + pods = [Pod("a", "node-1", cpuinfo(sockets=2)), Pod("b", "node-2", cpuinfo(sockets=1))] + install(monkeypatch, pods, [node("node-1"), node("node-2")]) + with pytest.raises(HardwareError, match="different hardware"): + read_hardware("m") + + +@allure.feature("pysweep") +def test_nodes_with_the_same_hardware_are_listed(monkeypatch): + pods = [Pod("a", "node-2", cpuinfo()), Pod("b", "node-1", cpuinfo())] + install(monkeypatch, pods, [node("node-1"), node("node-2")]) + assert read_hardware("m")["nodes"] == ["node-1", "node-2"] diff --git a/src/tests/e2e/validation/pysweep/test_metadata_unit.py b/src/tests/e2e/validation/pysweep/test_metadata_unit.py new file mode 100644 index 00000000..cc626c00 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_metadata_unit.py @@ -0,0 +1,55 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep import provenance +from tests.e2e.benchmarks.chatqna.pysweep.cluster.served_model import ServedModel +from tests.e2e.benchmarks.chatqna.pysweep.properties.base import PropertyReadError +from tests.e2e.benchmarks.chatqna.pysweep.provenance import MetadataError, collect_metadata + + +@pytest.fixture +def sources(monkeypatch): + monkeypatch.setattr(provenance, "read_commit_info", lambda: {"sha": "abc"}) + monkeypatch.setattr(ServedModel, "read", lambda self: "llama3-8b-awq") + monkeypatch.setattr(provenance, "read_hardware", lambda model: {"nodes": ["n"], "model": model}) + + +@allure.feature("pysweep") +def test_metadata_groups_commit_info_and_the_served_models_hardware(sources): + assert collect_metadata() == { + "commit_info": {"sha": "abc"}, + "hardware": {"nodes": ["n"], "model": "llama3-8b-awq"}, + } + + +@allure.feature("pysweep") +def test_a_missing_commit_is_a_metadata_error(sources, monkeypatch): + def unreadable(): + raise provenance.CommitInfoError("not a git repository") + + monkeypatch.setattr(provenance, "read_commit_info", unreadable) + with pytest.raises(MetadataError, match="commit_info: not a git repository"): + collect_metadata() + + +@allure.feature("pysweep") +def test_an_unrecognized_cpu_is_a_metadata_error(sources, monkeypatch): + def unrecognized(model): + raise provenance.HardwareError("Unrecognized CPU family on node n") + + monkeypatch.setattr(provenance, "read_hardware", unrecognized) + with pytest.raises(MetadataError, match="hardware: Unrecognized CPU family"): + collect_metadata() + + +@allure.feature("pysweep") +def test_an_unreadable_served_model_is_a_metadata_error(sources, monkeypatch): + def unreadable(self): + raise PropertyReadError("no llm-usvc pods") + + monkeypatch.setattr(ServedModel, "read", unreadable) + with pytest.raises(MetadataError, match="hardware: no llm-usvc pods"): + collect_metadata() diff --git a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py index 7bf7690d..855df0b7 100644 --- a/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -47,12 +47,22 @@ "description": "feat: something", "branch": "kkurzacz/pysweep-core", } +HARDWARE = { + "nodes": ["node-1"], + "cpu": {"vendor": "Intel", "model": "Intel(R) Xeon(R) Platinum 8468H", "family": "SPR", "model_id": 143, + "sockets": 2, "cores": 96, "threads": 192, "numa_nodes": 2, "amx": True}, + "memory_gib": 2011, + "os": "Ubuntu 24.10", + "kernel": "6.11.0", + "kubernetes": "v1.35.4", +} +METADATA = {"commit_info": COMMIT, "hardware": HARDWARE} @pytest.fixture(autouse=True) def _committed_checkout(monkeypatch): # CI checks out without git, so no test may depend on the real repository. - monkeypatch.setattr(psb, "read_commit_info", lambda: dict(COMMIT)) + monkeypatch.setattr(psb, "collect_metadata", lambda: json.loads(json.dumps(METADATA))) monkeypatch.setattr(psb, "edp_enabled", lambda: False) @@ -322,7 +332,9 @@ def test_sweep_writes_one_summary_row_per_run(monkeypatch, tmp_path): assert {r["results.ttft_s.mean"] for r in rows} == {"0.8"} assert {r["results.tpot_s.mean"] for r in rows} == {str(round((6.9 - 0.8) / 127, 6))} assert {r["settings.client.tokenizer"] for r in rows} == {"served/model"} - assert {r["commit_info.sha"] for r in rows} == {COMMIT["sha"]} + assert {r["metadata.commit_info.sha"] for r in rows} == {COMMIT["sha"]} + assert {r["metadata.hardware.cpu.family"] for r in rows} == {"SPR"} + assert {r["metadata.hardware.nodes"] for r in rows} == {"node-1"} # Relative to the summary, so the directory can be copied off the host intact. pointers = [r["run.result_file"] for r in rows] assert all(not Path(p).is_absolute() for p in pointers) @@ -330,7 +342,8 @@ def test_sweep_writes_one_summary_row_per_run(monkeypatch, tmp_path): assert {Path(p).parent.name for p in pointers} == {results.PER_CASE_DIR_NAME} document = json.loads((tmp_path / "out" / results.RESULTS_FILE_NAME).read_text()) - assert document["commit_info"] == COMMIT + assert document["schema_version"] == 2 + assert document["metadata"] == METADATA assert [run["run"]["index"] for run in document["runs"]] == ["1.1", "1.2", "2.1", "2.2"] assert document["runs"][0]["settings"]["deployment"] == {"llms": {"max_new_tokens": 128}} @@ -816,19 +829,25 @@ def test_summary_records_the_declared_path_not_the_resolved_one(monkeypatch, tmp @allure.feature("pysweep") def test_preflight_returns_the_commit_the_results_are_attributed_to(): - assert psb.preflight_check(load_config(_client())) == COMMIT + assert psb.preflight_check(load_config(_client())) == METADATA @allure.feature("pysweep") -def test_preflight_fails_without_commit_info(monkeypatch): +def test_preflight_fails_when_any_metadata_is_missing(monkeypatch): def unreadable(): - raise psb.CommitInfoError("not a git repository") + raise psb.MetadataError("hardware: No running model-server pod") - monkeypatch.setattr(psb, "read_commit_info", unreadable) - with pytest.raises(psb.PreflightError, match="commit_info: not a git repository"): + monkeypatch.setattr(psb, "collect_metadata", unreadable) + with pytest.raises(psb.PreflightError, match="metadata: hardware: No running model-server pod"): psb.preflight_check(load_config(_client())) +@allure.feature("pysweep") +def test_metadata_off_collects_and_checks_nothing(monkeypatch): + monkeypatch.setattr(psb, "collect_metadata", lambda: pytest.fail("metadata collected")) + assert psb.preflight_check(load_config(_client()), metadata=False) is None + + @allure.feature("pysweep") def test_pre_bench_runs_once_before_the_summaries_and_runs_record_the_observed_edp(monkeypatch, tmp_path): monkeypatch.chdir(tmp_path) @@ -936,9 +955,9 @@ def test_preflight_runs_once_for_the_whole_sweep(monkeypatch, tmp_path): calls = [] - def counting_preflight(config): + def counting_preflight(config, metadata=True): calls.append(len(fake.calls)) - return dict(COMMIT) + return METADATA run_config = psb.load_run_config({}) monkeypatch.setattr(psb, "preflight_check", counting_preflight) diff --git a/src/tests/e2e/validation/pysweep/test_results_unit.py b/src/tests/e2e/validation/pysweep/test_results_unit.py index 83db2917..cdab1bdd 100644 --- a/src/tests/e2e/validation/pysweep/test_results_unit.py +++ b/src/tests/e2e/validation/pysweep/test_results_unit.py @@ -31,6 +31,7 @@ "description": "feat: something", "branch": "kkurzacz/pysweep-core", } +METADATA = {"commit_info": COMMIT, "hardware": {"nodes": ["node-1", "node-2"], "cpu": {"family": "SPR"}}} CLIENT = { "question_file": "questions-short.csv", @@ -176,6 +177,16 @@ def test_edp_settings_sit_next_to_deployment_and_client(): assert flatten(record)["settings.edp.vector_db.num_vectors"] == 55312 +@allure.feature("pysweep") +def test_without_metadata_the_document_has_no_metadata_key(tmp_path): + layout = prepare_summaries_dir(tmp_path / "out") + sweep = SweepResults(layout, date="d", metadata=None) + sweep.add_run(_record()) + assert "metadata" not in json.loads(layout.results_file.read_text()) + header = next(csv.reader(layout.summary_file.open())) + assert header[:2] == ["date", "run.index"] + + @pytest.fixture def layout(tmp_path): return prepare_summaries_dir(tmp_path / "out") @@ -183,18 +194,18 @@ def layout(tmp_path): @allure.feature("pysweep") def test_results_json_exists_before_the_first_run_finishes(layout): - SweepResults(layout, date="2026-11-26T09:02:11Z", commit_info=COMMIT) + SweepResults(layout, date="2026-11-26T09:02:11Z", metadata=METADATA) assert json.loads(layout.results_file.read_text()) == { "schema_version": SCHEMA_VERSION, "date": "2026-11-26T09:02:11Z", - "commit_info": COMMIT, + "metadata": METADATA, "runs": [], } @allure.feature("pysweep") def test_results_json_holds_every_run_after_each_one(layout): - sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", commit_info=COMMIT) + sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", metadata=METADATA) for index in (1, 2): sweep.add_run(_record(index=f"1.{index}")) document = json.loads(layout.results_file.read_text()) @@ -203,30 +214,33 @@ def test_results_json_holds_every_run_after_each_one(layout): @allure.feature("pysweep") def test_the_csv_has_one_dotted_row_per_run(layout): - sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", commit_info=COMMIT) + sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", metadata=METADATA) sweep.add_run(_record(concurrency=1)) sweep.add_run(_record(index="1.2", concurrency=16)) rows = list(csv.DictReader(layout.summary_file.open())) assert [row["settings.client.concurrency"] for row in rows] == ["1", "16"] header = next(csv.reader(layout.summary_file.open())) - assert header[:7] == [ + assert header[:9] == [ "date", - "commit_info.sha", - "commit_info.datetime", - "commit_info.author", - "commit_info.description", - "commit_info.branch", + "metadata.commit_info.sha", + "metadata.commit_info.datetime", + "metadata.commit_info.author", + "metadata.commit_info.description", + "metadata.commit_info.branch", + "metadata.hardware.nodes", + "metadata.hardware.cpu.family", "run.index", ] assert "settings.deployment.llms.max_new_tokens" in header assert "results.ttft_s.p90" in header - assert rows[0]["commit_info.branch"] == "kkurzacz/pysweep-core" + assert rows[0]["metadata.commit_info.branch"] == "kkurzacz/pysweep-core" + assert rows[0]["metadata.hardware.nodes"] == "node-1;node-2" @allure.feature("pysweep") def test_missing_values_render_blank_in_the_csv(layout): - sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", commit_info=COMMIT) + sweep = SweepResults(layout, date="2026-11-26T09:02:11Z", metadata=METADATA) sweep.add_run(_record()) (row,) = csv.DictReader(layout.summary_file.open()) assert row["results.ttft_s.mean"] == "" @@ -235,14 +249,14 @@ def test_missing_values_render_blank_in_the_csv(layout): @allure.feature("pysweep") def test_result_file_pointer_is_relative_to_the_summaries_directory(layout): - sweep = SweepResults(layout, date="d", commit_info=COMMIT) + sweep = SweepResults(layout, date="d", metadata=METADATA) inside = layout.per_case_dir / "bench_x.result.csv" assert sweep.pointer(inside) == f"{PER_CASE_DIR_NAME}/bench_x.result.csv" @allure.feature("pysweep") def test_a_result_file_from_outside_the_directory_is_recorded_verbatim(layout, tmp_path): - sweep = SweepResults(layout, date="d", commit_info=COMMIT) + sweep = SweepResults(layout, date="d", metadata=METADATA) elsewhere = tmp_path / "elsewhere.csv" assert sweep.pointer(elsewhere) == str(elsewhere) From ea09bbb181b8b57f03678a3929d2f87ded18fd8d Mon Sep 17 00:00:00 2001 From: "Kurzacz, Kamil" Date: Fri, 27 Nov 2026 18:13:50 +0100 Subject: [PATCH 11/11] fix(benchmarks): retry pysweep seed downloads and skip unavailable documents Each download is tried 3 times, 10s apart. A documents.csv entry that still fails is skipped with a warning instead of stopping pre_bench, as prepare_1M_vectors.sh does: Project Gutenberg answers the Intel proxy with HTTP 503, so the three books were never part of the nightlies' data either. The Wikipedia dump is retried but not skipped. Signed-off-by: Kurzacz, Kamil --- .../chatqna/pysweep/configs/README.md | 2 +- .../chatqna/pysweep/pre_bench/seed.py | 45 ++++++++++---- .../e2e/validation/pysweep/test_seed_unit.py | 60 +++++++++++++++++++ 3 files changed, 95 insertions(+), 12 deletions(-) diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md index 299890d0..20ee5566 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md @@ -22,7 +22,7 @@ usually above it, since whole files are loaded. | Key | Meaning | |---|---| -| `pre_bench.edp.vector_db.num_vectors` | Load the vector DB through EDP until it holds at least this many vectors: first the documents in `../documents.csv`, then Simple English Wikipedia, split by `../wikiparse.py`, two files at a time. Files already in EDP are not uploaded again; downloads are cached in `$PYSWEEP_SEED_CACHE` (default `~/.cache/pysweep/seed`). Fails if the data runs out first. It never removes vectors: use `../prepare_cleanup_vectors.sh` to start from an empty DB. | +| `pre_bench.edp.vector_db.num_vectors` | Load the vector DB through EDP until it holds at least this many vectors: first the documents in `../documents.csv`, then Simple English Wikipedia, split by `../wikiparse.py`, two files at a time. Files already in EDP are not uploaded again; downloads are cached in `$PYSWEEP_SEED_CACHE` (default `~/.cache/pysweep/seed`) and retried 3 times, 10s apart. A document that still can't be downloaded is skipped with a warning (Project Gutenberg, for one, refuses some proxies); the Wikipedia dump is not, and seeding fails if the data runs out before the target. It never removes vectors: use `../prepare_cleanup_vectors.sh` to start from an empty DB. | Any other knob takes a single value (fixed for the whole sweep) or a list (one dimension of the product). Runs = deployment combinations × client combinations; diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py index b2432c4e..dbcab601 100644 --- a/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py @@ -28,6 +28,8 @@ DEFAULT_CACHE_DIR = Path.home() / ".cache" / "pysweep" / "seed" DOWNLOAD_TIMEOUT_S = 600 +DOWNLOAD_ATTEMPTS = 3 +DOWNLOAD_RETRY_DELAY_S = 10.0 # EDP processes two files at a time, so pairs keep it busy without queueing. WIKI_BATCH = 2 @@ -46,27 +48,48 @@ def upload(edp, path: Path) -> None: logger.info("Uploaded %s.", path.name) -def download(url: str, target: Path) -> Path: - if target.is_file() and target.stat().st_size > 0: - return target - target.parent.mkdir(parents=True, exist_ok=True) - partial = target.with_name(target.name + ".part") - logger.info("Downloading %s.", url) +def _fetch(url: str, partial: Path) -> None: with requests.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT_S) as response: if response.status_code != 200: raise SeedError(f"Download of {url} failed: HTTP {response.status_code}") with partial.open("wb") as handle: for chunk in response.iter_content(chunk_size=1 << 20): handle.write(chunk) - partial.rename(target) - return target -def relevant_documents(cache_dir: Path) -> list[Path]: - """The documents the benchmark's questions are about, in documents.csv order.""" +def download(url: str, target: Path, sleep=time.sleep) -> Path: + if target.is_file() and target.stat().st_size > 0: + return target + target.parent.mkdir(parents=True, exist_ok=True) + partial = target.with_name(target.name + ".part") + for attempt in range(1, DOWNLOAD_ATTEMPTS + 1): + logger.info("Downloading %s (attempt %d/%d).", url, attempt, DOWNLOAD_ATTEMPTS) + try: + _fetch(url, partial) + except (SeedError, requests.RequestException) as exc: + if attempt == DOWNLOAD_ATTEMPTS: + raise SeedError(f"Download of {url} failed after {attempt} attempts: {exc}") from exc + logger.warning("Download of %s failed (%s); retrying in %.0fs.", url, exc, DOWNLOAD_RETRY_DELAY_S) + sleep(DOWNLOAD_RETRY_DELAY_S) + else: + partial.rename(target) + return target + + +def relevant_documents(cache_dir: Path, sleep=time.sleep) -> list[Path]: + """The documents the benchmark's questions are about, in documents.csv order; unavailable ones are skipped.""" with DOCUMENTS_CSV.open(newline="") as handle: rows = [row for row in csv.reader(handle, delimiter=";") if row] - return [download(url, cache_dir / "documents" / name) for url, name in rows] + documents, skipped = [], [] + for url, name in rows: + try: + documents.append(download(url, cache_dir / "documents" / name, sleep=sleep)) + except SeedError as exc: + logger.warning("Skipping %s: %s", name, exc) + skipped.append(name) + if skipped: + logger.warning("Seeding without %d of %d documents: %s", len(skipped), len(rows), ", ".join(skipped)) + return documents def wikipedia_files(cache_dir: Path) -> list[Path]: diff --git a/src/tests/e2e/validation/pysweep/test_seed_unit.py b/src/tests/e2e/validation/pysweep/test_seed_unit.py index d7113666..ceddcdb6 100644 --- a/src/tests/e2e/validation/pysweep/test_seed_unit.py +++ b/src/tests/e2e/validation/pysweep/test_seed_unit.py @@ -139,3 +139,63 @@ def test_run_pre_bench_seeds_the_declared_number_of_vectors(monkeypatch): monkeypatch.setattr(pre_bench.seed, "seed", lambda num_vectors, edp: calls.append((num_vectors, edp))) pre_bench.run_pre_bench({pre_bench.NUM_VECTORS: 50000}, edp="edp") assert calls == [(50000, "edp")] + + +class _Download: + """requests.get stand-in: one scripted outcome (status code or exception) per call.""" + + def __init__(self, *outcomes): + self.outcomes = list(outcomes) + self.urls = [] + + def __call__(self, url, stream=True, timeout=None): + self.urls.append(url) + outcome = self.outcomes.pop(0) + if isinstance(outcome, Exception): + raise outcome + return _Body(outcome) + + +class _Body: + def __init__(self, status): + self.status_code = status + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def iter_content(self, chunk_size): + yield b"data" + + +@allure.feature("pysweep") +def test_a_failed_download_is_retried(tmp_path, monkeypatch): + fake = _Download(503, seed_module.requests.ConnectionError("reset"), 200) + monkeypatch.setattr(seed_module.requests, "get", fake) + sleeps = [] + target = download("http://example/doc.pdf", tmp_path / "doc.pdf", sleep=sleeps.append) + assert target.read_bytes() == b"data" + assert len(fake.urls) == 3 + assert sleeps == [seed_module.DOWNLOAD_RETRY_DELAY_S] * 2 + + +@allure.feature("pysweep") +def test_a_download_failing_every_attempt_is_an_error(tmp_path, monkeypatch): + monkeypatch.setattr(seed_module.requests, "get", _Download(503, 503, 503)) + with pytest.raises(SeedError, match="after 3 attempts: Download of http://example/doc.pdf failed: HTTP 503"): + download("http://example/doc.pdf", tmp_path / "doc.pdf", sleep=lambda s: None) + assert not (tmp_path / "doc.pdf").exists() + + +@allure.feature("pysweep") +def test_unavailable_documents_are_skipped(tmp_path, monkeypatch, caplog): + listing = tmp_path / "documents.csv" + listing.write_text("http://ok/a.pdf;a.pdf\nhttp://blocked/b.txt;b.txt\nhttp://ok/c.pdf;c.pdf\n") + monkeypatch.setattr(seed_module, "DOCUMENTS_CSV", listing) + monkeypatch.setattr(seed_module.requests, "get", _Download(200, 503, 503, 503, 200)) + with caplog.at_level("WARNING", logger=seed_module.logger.name): + documents = seed_module.relevant_documents(tmp_path / "cache", sleep=lambda s: None) + assert [path.name for path in documents] == ["a.pdf", "c.pdf"] + assert "Seeding without 1 of 3 documents: b.txt" in caplog.text