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..c3106dc7 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,7 @@ def __init__(self): self.err = None self.code = 0 -def parse_args(): +def parse_args(argv=None): 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 +90,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 +181,15 @@ 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)``.""" 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 +197,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 +233,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..3b1a10d4 --- /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 (`cluster/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 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 `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 +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 +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. + +## 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..7a88518d --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/README.md @@ -0,0 +1,496 @@ + + + +# 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 | +|---|---| +| `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. | +| `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. | +| `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/` | 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. | + +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 +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, 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 + for each client combination: # inner — costs one more load test + run benchmark.py + 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 +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) | `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 +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/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* +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 `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` / +`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): + +``` +results/ + 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 + ... +``` + +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": 2, + "date": "2026-11-26T09:02:11Z", + "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). `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: + +```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} +``` + +| 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`. | + +Percentiles are linearly interpolated (numpy's default), like `parse.py`. + +`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. + +### Run config (`--config`) + +Validated by `config.load_run_config()`, with the same strictness as the sweep +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 +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. | +| `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 + +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 +`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 +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 +``` + +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 +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..91da480a --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/__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/client_args.py b/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py new file mode 100644 index 00000000..d8b8aa0e --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/client_args.py @@ -0,0 +1,185 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass +from typing import Any, Iterable + + +@dataclass(frozen=True) +class ClientArg: + """One ``benchmark.py`` CLI option; pydantic field metadata and its argv rendering rule.""" + + flag: str + dest: str + yaml_name: str + summary: str + sweepable: bool = True + # Supplied by pysweep with no config key; passing its flag is refused. + derived: bool = False + + @property + def path(self) -> str: + return f"client.{self.yaml_name}" + + def __repr__(self) -> str: # pragma: no cover - debugging aid + return f"ClientArg({self.flag} -> client.{self.yaml_name})" + + +# Keep in step with benchmark.parse_args. +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.", +) + +CLIENT_ARGS: tuple[ClientArg, ...] = ( + QUESTION_FILE, + SERVER, + CONCURRENCY, + DURATION, + WORKER_STARTUP_DELAY, + TOKENIZER, + FAILURES_ALLOWED, + BEARER_FILE, + INPUT_TOKENS, + WARMUP_REQUESTS, +) + +PROVISIONED_ARGS: tuple[ClientArg, ...] = (SERVER, BEARER_FILE) + +# 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) + +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.""" + + 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`; duplicates raise.""" + 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, in ``CLIENT_ARGS`` order.""" + 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]: + """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 + rendered = " ".join(self.to_argv()) + return f"" + + +def conflicting_flags(benchmark_argv: Iterable[str], declared_names: Iterable[str]) -> list[str]: + """Return flags after ``--`` owned by the config: declared knobs and every derived flag.""" + 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: + 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/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/cluster/auth.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py new file mode 100644 index 00000000..1c053e37 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/auth.py @@ -0,0 +1,289 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +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 ( + CHATQNA_NAMESPACE, + FINGERPRINT_NAMESPACE, + KEYCLOAK_NAMESPACE, + LLM_INFERENCE_NAMESPACE, + VITE_KEYCLOAK_CLIENT_ID, + VITE_KEYCLOAK_REALM, +) + +from ..provenance.paths import deploy_roots, is_dir, is_file + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +logger = logging.getLogger(__name__) + +BUILD_CONFIG_DIR_ENV_VAR = "PYSWEEP_BUILD_CONFIG_DIR" +BUILD_CONFIG_FALLBACKS = tuple(str(root / "env" / "local") for root in deploy_roots()) +# Same files and order as tests/e2e/conftest.py; later files win. +BUILD_CONFIG_FILES = ("global_config.yaml", "config.erag.yaml", "config.inference.yaml") + + +# Arbitrary; only has to outlast one run. +SWEEP_TOKEN_LIFESPAN_S = 3600 +# An empty value means "inherit the realm setting". +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 "" + scope = f"in ns/{self.namespace}" if self.namespace else "(cluster-scoped)" + return f"{self.verb} {grp}{self.resource} {scope}" + + +@dataclass +class AccessCheckResult: + required: RequiredAccess + allowed: bool + reason: str = "" + + +REQUIRED_ACCESS = [ + 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", + ), + 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, + reason="port-forward the fingerprint API", + ), + RequiredAccess("get", "secrets", KEYCLOAK_NAMESPACE, reason="Keycloak admin password for token minting"), +] + + +class _SelfSubjectAccessReview(APIObject): + 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): + self.k8s = k8s_helper or K8sHelper() + + def ensure_reachable(self) -> None: + try: + api = kr8s.api() + api.version() + 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" + f"Underlying error: {exc}" + ) from exc + + def check(self, required: RequiredAccess) -> AccessCheckResult: + # The API wants subresources (pods/exec) split out, not slash-joined. + 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 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]: + """Check every required permission; raise AccessError naming the denied ones.""" + 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: + 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 the helpers read, and return it.""" + 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 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: + 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 + 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: + # 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 + ) + 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, then restore.""" + 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/cluster/fingerprint.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/fingerprint.py new file mode 100644 index 00000000..db98c7ac --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/fingerprint.py @@ -0,0 +1,182 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +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 +from tests.e2e.validation.constants import FINGERPRINT_NAMESPACE + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +logger = logging.getLogger(__name__) + +FINGERPRINT_SERVICE = "fingerprint-svc" +FINGERPRINT_PORT = 6012 +API_PREFIX = "/v1/system_fingerprint" + +# The scope the ChatQNA router reads component arguments from. +PIPELINE = "chatqna" +TENANT = "_global" + + +def find_unused_port(start: int = 10000, end: int = 60000) -> int: + 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: + 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 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: + pf.stop() + + +@contextmanager +def service_port_forward(namespace: str, service: str, remote_port: int): + 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.""" + + 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 " + "auth.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.""" + + 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: + """FingerprintClient interface over the suite's FingerprintApiHelper.""" + + 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: + """Client for /v1/system_fingerprint/{change_arguments,config}.""" + + 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 PYSWEEP_FINGERPRINT_TRANSPORT: portforward (default) or ingress.""" + mode = os.getenv("PYSWEEP_FINGERPRINT_TRANSPORT", "portforward").lower() + if mode == "ingress": + if keycloak_helper is None: + from .auth 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/cluster/model_catalog.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/model_catalog.py new file mode 100644 index 00000000..1702d724 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/model_catalog.py @@ -0,0 +1,114 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging +import os +from pathlib import Path + +import yaml + +from ..provenance.paths import REPO_ROOT, deploy_roots, is_file + +logger = logging.getLogger(__name__) + +# MM_CONFIG is what the ai-solutions ./model-manager wrapper exports. +CATALOG_ENV_VARS = ("PYSWEEP_MODEL_CATALOG", "MM_CONFIG") + +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: + 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.""" + 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]: + """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 listing the available names.""" + 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``.""" + 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/cluster/served_model.py b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/served_model.py new file mode 100644 index 00000000..50f48bd1 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/cluster/served_model.py @@ -0,0 +1,114 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging + +import kr8s +from kr8s.objects import APIObject + +from tests.e2e.validation.constants import CHATQNA_NAMESPACE, LLM_INFERENCE_NAMESPACE + +from ..properties.base import PropertyReadError + +logger = logging.getLogger(__name__) + +# 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``.""" + + 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 = CHATQNA_NAMESPACE, + inference_namespace: str = LLM_INFERENCE_NAMESPACE, + ): + self.namespace = namespace + self.inference_namespace = inference_namespace + + def _pipeline_pods(self) -> list: + try: + pods = list( + kr8s.get("pods", namespace=self.namespace, label_selector=LLM_USVC_LABEL_SELECTOR) + ) + 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 + # 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( + 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: + # 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 + 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: + try: + llmisvc = LLMInferenceService.get(model, namespace=self.inference_namespace) + 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 [] + return any( + cond.get("type") == "Ready" and cond.get("status") == "True" + for cond in conditions + ) + + def read(self) -> str: + """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()) + 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/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/config.py b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py new file mode 100644 index 00000000..f80c1ee2 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/config.py @@ -0,0 +1,305 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +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 .properties.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.""" + + 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 + property_cls: type[Property] + value: Any + + +@dataclass(frozen=True) +class ClientSetting: + """One resolved client knob value within a single client combination.""" + + path: str + arg: ClientArg + value: Any + + +Combination = tuple[PropertySetting, ...] +ClientCombination = tuple[ClientSetting, ...] + + +MaxTokensValue = PositiveInt | list[PositiveInt] + +# 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 raises KeyError on anything but . +DurationValue = Annotated[ + str, StringConstraints(strip_whitespace=True, pattern=r"^\d+(\.\d+)?[smh]$") +] +DurationListValue = DurationValue | list[DurationValue] + + +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 + + +class ClientConfig(_StrictModel): + """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] + 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): + """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 + metadata: bool = True + + +class SweepConfig(_StrictModel): + pre_bench: PreBenchConfig | None = None + llms: LlmsConfig | None = None + client: ClientConfig + + def iter_settings(self) -> Iterator[tuple[str, type[Property], list[Any]]]: + """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 ``(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]: + """Cartesian product of deployment knobs, K8s-plane outermost; never empty.""" + settings = list(self.iter_settings()) + # 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]: + """Cartesian product of sweepable client knobs, ordered by path.""" + 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.""" + 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: + """Largest ``client.concurrency`` in the sweep; sizes the shared bearer file.""" + 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.""" + 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()) + 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.""" + return { + binding.yaml_name + for _, binding, _ in _walk_bindings(self) + if isinstance(binding, ClientArg) + } + + def declared_question_files(self) -> list[str]: + 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: + 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]]]: + 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 _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] + + +def _load_model(source: str | Path | dict, model: type[BaseModel], what: str): + 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.""" + return _load_model(source, SweepConfig, "sweep") + + +def load_run_config(source: str | Path | dict) -> RunConfig: + """Load and validate a pysweep run config (``--config``).""" + return _load_model(source, RunConfig, "run") 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..20ee5566 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/README.md @@ -0,0 +1,67 @@ + + + +# 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` + +**`pre_bench`** prepares what every run shares, once, before the first run. +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 | +|---|---| +| `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; +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 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` + +| 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 new file mode 100644 index 00000000..70eb30eb --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/general.yaml @@ -0,0 +1,5 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +display_kubernetes_client_logs: false +metadata: true 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..5eeda69b --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml @@ -0,0 +1,19 @@ +# 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] + +client: + question_file: ../questions-pubmed.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/pre_bench/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py new file mode 100644 index 00000000..e62c4465 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/__init__.py @@ -0,0 +1,26 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging +from typing import Any + +from ..cluster.vector_db import edp_client +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 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..dbcab601 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pre_bench/seed.py @@ -0,0 +1,172 @@ +# 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 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] +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" + +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 + + +class SeedError(Exception): + """The vector DB could not be seeded to the requested size.""" + + +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 _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) + + +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] + 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]: + """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/properties/__init__.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py new file mode 100644 index 00000000..a16d09bf --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/__init__.py @@ -0,0 +1,6 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from .max_tokens import MaxNewTokens + +__all__ = ["MaxNewTokens"] diff --git a/src/tests/e2e/benchmarks/chatqna/pysweep/properties/base.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/base.py new file mode 100644 index 00000000..b75f568e --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/base.py @@ -0,0 +1,48 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +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.""" + + +class PropertyApplyError(Exception): + """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" + RUNTIME_API = "runtime_api" + + +class Property(ABC): + """Interface every application (=not client's) configuration knob must implement.""" + + # 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, 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`` idempotently, without waiting for convergence.""" + raise NotImplementedError + + def wait_until_ready(self, desired: Any, timeout: float = 300.0) -> None: + """Block until the applied change is live; a no-op for synchronous planes.""" + 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/properties/max_tokens.py b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py new file mode 100644 index 00000000..fe84af84 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/properties/max_tokens.py @@ -0,0 +1,53 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging + +from .base import Plane, Property, PropertyReadError +from ..cluster.fingerprint import FingerprintClient + +logger = logging.getLogger(__name__) + +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.""" + 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}}] + ) + + # change_arguments is synchronous, so the inherited no-op wait_until_ready suffices. 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..a0b3ab24 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/__init__.py @@ -0,0 +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/commit_info.py b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/commit_info.py new file mode 100644 index 00000000..516fdee8 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/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/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/provenance/paths.py b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/paths.py new file mode 100644 index 00000000..14dc4daf --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/provenance/paths.py @@ -0,0 +1,34 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path + +ROOT_DEPLOY_ROOT = Path("/root/ai-solutions") + +# 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, ...]: + """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) + + +# Path.is_file/is_dir raise PermissionError under /root on Python < 3.14. +def is_file(path: Path) -> bool: + try: + return path.is_file() + except OSError: + return False + + +def is_dir(path: Path) -> bool: + try: + return path.is_dir() + except OSError: + return False 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..9b7b21a3 --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/pysweep_bench.py @@ -0,0 +1,564 @@ +#!/bin/python3 +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import argparse +import csv +import linecache +import logging +import re +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.properties.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.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 import MetadataError, collect_metadata +from tests.e2e.benchmarks.chatqna.pysweep.results import ( + DEFAULT_SUMMARIES_DIR, + SweepResults, + prepare_summaries_dir, + read_requests, + run_record, + summarize_requests, +) +from tests.e2e.benchmarks.chatqna.pysweep.cluster.fingerprint import ( + FingerprintClient, + default_transport, +) +from tests.e2e.benchmarks.chatqna.pysweep.cluster.served_model import ServedModel + +logger = logging.getLogger(__name__) + +CHATQNA_PATH = "/api/v1/chatqna" + +# Relative sweep-config paths resolve against this directory, not the CWD. +PYSWEEP_DIR = Path(__file__).resolve().parent + + +class SweepError(Exception): + """Raised when a combination cannot be applied or fails verification.""" + + +class PreflightError(SweepError): + """Raised before anything is applied when a sweep precondition is not met.""" + + +def build_property(setting: PropertySetting, fingerprint_client: FingerprintClient) -> Property: + """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: + 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.""" + 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: + raise SweepError(f"{setting.path}: {exc}") from exc + + for setting, prop in properties: + try: + prop.wait_until_ready(setting.value) + except PropertyApplyError as exc: + raise SweepError(f"{setting.path}: {exc}") from exc + + 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: + """Return the HF tokenizer of the observed served model.""" + try: + served = ServedModel().read() + except PropertyReadError as exc: + 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: + return re.sub(r"[^0-9A-Za-z_]+", "-", str(value)).strip("-") + + +def _settings_slug(settings, only=None) -> str: + 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 run; names only the varying knobs to stay under 255 bytes.""" + 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)) + + +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): + _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: + 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 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: + """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(): + 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 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: + 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), measured on %s (%s).", + commit["sha"][:12], commit["branch"], commit["description"], cpu["model"], cpu["family"], + ) + return metadata + + +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.") + + +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 metadata_verify(metadata) + + +def chatqna_url() -> str: + """Return the ChatQNA URL on the deployment's base_domain_name.""" + from tests.e2e.benchmarks.chatqna.pysweep.cluster.auth import load_build_config + + return f"https://{load_build_config()['base_domain_name']}{CHATQNA_PATH}" + + +class ProvisionedArgv(list): + """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: + if self._refresh is not None: + self._refresh() + + +def write_bearer_file(path: str, helper, workers: int) -> None: + """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 tokens via linecache; checkcache() misses same-size, same-mtime rewrites. + linecache.clearcache() + + +@contextmanager +def provision_benchmark_target(benchmark_args: list[str], workers: int = 1): + """Yield the argv with -s and a minted bearer file (one token per worker) added unless supplied.""" + 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) + ) + from tests.e2e.benchmarks.chatqna.pysweep.cluster.auth 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 configs/sweep.yaml).", + ) + parser.add_argument( + "--config", + help="Path to the pysweep run config YAML (how to run; see configs/general.yaml).", + ) + parser.add_argument( + "--summaries", + default=DEFAULT_SUMMARIES_DIR, + help=( + "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( + "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 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: + 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." + ) + return config.client_provisioning_argv() + list(benchmark_args) + + +def resolve_question_file_argv(argv: list[str]) -> list[str]: + """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 + argv[index] = str(resolve_question_file(argv[index])) + return argv + + +LOG_YAML_INDENT = 4 + + +def format_settings_yaml(values: dict, indent: int = LOG_YAML_INDENT) -> str: + """Render a {dotted_path: value} mapping as sectioned YAML for logging; "" if empty.""" + 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 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], + combination: Combination, + client_combination: ClientCombination, + label: str, + results_dir, + varying_paths=None, + tokenizer: str | None = None, +) -> tuple[int, Path]: + """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] + logger.info( + "%s load parameters (tokenizer: %s):\n%s", + label, tokenizer, format_settings_yaml(client_args.snapshot()), + ) + + 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: + 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 = 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) + + metadata = preflight_check(config, run_config.metadata) + + deployment_combinations = config.deployment_combinations() + client_combinations = config.client_combinations() + varying_paths = config.varying_paths() + 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(), metadata=metadata) + + 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 + 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)", + ) + + snapshot = apply_combination(combination, fingerprint_client) + logger.info( + "Observed configuration under test:\n%s", format_settings_yaml(snapshot) + ) + + 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): + label = ( + f"Run {index}.{client_index} " + f"(deployment {index}/{len(deployment_combinations)}, " + f"client {client_index}/{len(client_combinations)})" + ) + # 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 + + 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}, + edp=edp_settings, + results=summarize_requests( + read_requests(output_file), + duration_to_seconds(str(client["client.duration"])), + ), + ) + ) + logger.info("%s record:\n%s", label, format_record_yaml(record)) + + logger.info( + "Sweep results (%d run(s)) written to %s", len(sweep_results.runs), sweep_results.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..6a98fccd --- /dev/null +++ b/src/tests/e2e/benchmarks/chatqna/pysweep/results.py @@ -0,0 +1,319 @@ +# Copyright (C) 2026 Intel Corporation +# 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 + + +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" + +SCHEMA_VERSION = 2 +PERCENTILES = (("p50", 0.5), ("p90", 0.9), ("p99", 0.99)) + +_PRECISION = 6 + + +class SummariesLayoutError(Exception): + """The ``--summaries`` directory cannot be prepared for a sweep.""" + + +class SummariesLayout(NamedTuple): + """Where a sweep's artifacts go, as absolute paths (benchmark.py opens them bare).""" + + root: Path + summary_file: Path + results_file: Path + per_case_dir: Path + + +def _clear_directory(directory: Path) -> int: + 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 the previous run's summary and per-case CSVs.""" + 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 + results_file = root / RESULTS_FILE_NAME + per_case_dir = root / PER_CASE_DIR_NAME + 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 " + "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) + + 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) + 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(), + results_file=results_file.resolve(), + per_case_dir=per_case_dir.resolve(), + ) + logger.info( + "Writing results to %s (%s, %s, per-case CSVs: %s/).", + layout.root, RESULTS_FILE_NAME, 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; ``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, dropping malformed or unsuccessful rows.""" + 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: + 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 (numpy's default); ``None`` for an empty sample.""" + 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) -> float | None: + return None if value is None else round(value, _PRECISION) + + +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) + output_total = sum(record.output_tokens for record in records) + return { + "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, + }, + } + + +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], + edp: dict[str, Any] | None = None, +) -> dict[str, Any]: + """One run's record; ``deployment``/``client``/``edp`` take dotted setting 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()}), + **({"edp": nest(edp)} if edp else {}), + }, + "results": results, + } + + +class SweepResults: + """Accumulates run records and rewrites results.json and the summary CSV after each.""" + + def __init__(self, layout: SummariesLayout, date: str, metadata: dict[str, Any] | None): + self.layout = layout + self.date = date + self.metadata = metadata + self.runs: list[dict[str, Any]] = [] + self.write() + + 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.layout.root)) + except ValueError: + return str(result_file) + + def document(self) -> dict[str, Any]: + return { + "schema_version": SCHEMA_VERSION, + "date": self.date, + **({"metadata": self.metadata} if self.metadata else {}), + "runs": self.runs, + } + + def add_run(self, record: dict[str, Any]) -> dict[str, Any]: + self.runs.append(record) + self.write() + return record + + def _csv_rows(self) -> list[dict[str, Any]]: + 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: + 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: _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/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/conftest.py b/src/tests/e2e/validation/pysweep/conftest.py new file mode 100644 index 00000000..70059ddd --- /dev/null +++ b/src/tests/e2e/validation/pysweep/conftest.py @@ -0,0 +1,58 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging + +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.cluster.auth import ( + AccessError, + KubernetesAccess, +) +from tests.e2e.benchmarks.chatqna.pysweep.cluster.fingerprint import ( + HelperFingerprintClient, + PortForwardTransport, + FingerprintClient, +) +from tests.e2e.validation.buildcfg import cfg + +logger = logging.getLogger(__name__) + +# 'llm' is present in every ChatQNA pipeline. +PROBE_COMPONENT = "llm" + + +@pytest.fixture(scope="session") +def pysweep_kubernetes_access(k8s_helper): + """Skip unless the kubeconfig identity has the RBAC a sweep needs.""" + 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): + """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") + + 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_commit_info_unit.py b/src/tests/e2e/validation/pysweep/test_commit_info_unit.py new file mode 100644 index 00000000..14927168 --- /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.provenance import commit_info +from tests.e2e.benchmarks.chatqna.pysweep.provenance.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_config_unit.py b/src/tests/e2e/validation/pysweep/test_config_unit.py new file mode 100644 index 00000000..c4eb527c --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_config_unit.py @@ -0,0 +1,388 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +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.properties.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 + +CLIENT = { + "question_file": "questions-short.csv", + "concurrency": 4, + "duration": "3m", + "worker_startup_delay": "0s", + "failures_allowed": 200, + "input_tokens": 128, + "warmup_requests": 1, +} + +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(): + """Parsed from source: importing benchmark.py pulls in transformers.""" + 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(): + cfg = load_config(_sweep()) + assert isinstance(cfg, SweepConfig) + assert list(cfg.iter_settings()) == [] + assert cfg.deployment_combinations() == [()] + assert len(cfg.client_combinations()) == 1 + + +@allure.feature("pysweep") +def test_config_without_client_section_raises(): + 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(): + cfg = load_config(_sweep(llms={})) + assert list(cfg.iter_settings()) == [] + 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 + + +@allure.feature("pysweep") +@pytest.mark.parametrize("missing", sorted(CLIENT)) +def test_every_scenario_client_knob_is_required(missing): + 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(): + 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(): + 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" + # -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(): + cfg = load_config(_client(concurrency=[1, 16])) + 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(): + assert load_config(_client(concurrency=[1, 16, 128])).max_concurrency() == 128 + assert load_config(_client(concurrency=[128, 16, 1])).max_concurrency() == 128 + 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(): + 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(): + cfg = load_config(_client()) + assert cfg.client_provisioning_argv() == [] + assert "server" not in cfg.declared_client_names() + 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.""" + 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): + 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): + 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)) + + +@allure.feature("pysweep") +def test_tokenizer_cannot_be_declared(): + with pytest.raises(ConfigError): + load_config(_client(tokenizer="nomic-ai/nomic-embed-text-v1")) + assert client_args.TOKENIZER.derived + 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(): + 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(): + example = ( + Path(__file__).resolve().parents[3] + / "e2e/benchmarks/chatqna/pysweep/configs/sweep.yaml" + ) + cfg = load_config(example) + assert cfg.deployment_combinations() + assert cfg.client_combinations() + + +@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(): + assert load_run_config({}).display_kubernetes_client_logs is False + + +@allure.feature("pysweep") +def test_run_config_rejects_unknown_key(): + with pytest.raises(ConfigError): + load_run_config({"display_kubernetes_client_log": False}) + + +@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(): + example = ( + Path(__file__).resolve().parents[3] + / "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_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_max_tokens.py b/src/tests/e2e/validation/pysweep/test_max_tokens.py new file mode 100644 index 00000000..81334e8d --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_max_tokens.py @@ -0,0 +1,50 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +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): + original = max_tokens_property.read() + yield original + max_tokens_property.apply(original) + + +@allure.feature("pysweep") +def test_read_returns_int(max_tokens_property): + 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): + 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): + desired = 200 + max_tokens_property.apply(desired) + assert max_tokens_property.is_satisfied(desired) + + 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..1472b8dd --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_max_tokens_unit.py @@ -0,0 +1,98 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.properties.base import Plane, PropertyReadError +from tests.e2e.benchmarks.chatqna.pysweep.properties.max_tokens import MaxNewTokens + + +class FakeClient: + 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(): + 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(): + client = FakeClient() + MaxNewTokens(client).read() + assert client.read_components == ["llm"] + + +@allure.feature("pysweep") +def test_read_coerces_a_string_value(): + assert MaxNewTokens(FakeClient({"max_new_tokens": "512"})).read() == 512 + + +@allure.feature("pysweep") +def test_read_raises_when_the_parameter_is_absent(): + """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) + + +@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(): + 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(): + client = FakeClient({"max_new_tokens": 128}) + MaxNewTokens(client).apply(128) + assert client.bodies == [] + + +@allure.feature("pysweep") +def test_apply_coerces_the_desired_value(): + 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_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_model_catalog_unit.py b/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py new file mode 100644 index 00000000..1bef3700 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_model_catalog_unit.py @@ -0,0 +1,184 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path + +import allure +import pytest + +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, + load_catalog, + model_entry, + tokenizer_for, +) + +# Trimmed copy of the deployed env/local/models.yaml. +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): + 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): + assert known_models() == ["llama3-8b-awq", "qwen3-5-2b-ovms"] + + +@allure.feature("pysweep") +def test_tokenizer_is_the_huggingface_repo_id(catalog_file): + 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): + 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): + 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): + 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): + 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): + 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): + 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): + 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: conftest names per-test log files after the test id. +@pytest.mark.parametrize( + "content", + [ + "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): + 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(): + """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" + for name in models: + assert tokenizer_for(name, repo_default) + + +@allure.feature("pysweep") +def test_the_rag_catalog_is_preferred_over_the_platform_one(): + """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 new file mode 100644 index 00000000..a6f9c50b --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_paths_unit.py @@ -0,0 +1,77 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path + +import allure +import pytest + +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, +) + + +@allure.feature("pysweep") +def test_repo_root_is_the_checkout(): + 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): + 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(auth.BUILD_CONFIG_DIR_ENV_VAR, raising=False) + monkeypatch.setattr(Path, "stat", stat) + 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(auth.BUILD_CONFIG_DIR_ENV_VAR, raising=False) + monkeypatch.setattr(auth, "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(): + 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..855df0b7 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_pysweep_bench_unit.py @@ -0,0 +1,1060 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import argparse +import ast +import csv +import itertools +import json +import linecache +import logging +from contextlib import contextmanager +from pathlib import Path + +import allure +import pytest +import yaml + +from tests.e2e.benchmarks.chatqna.pysweep import pysweep_bench as psb +from tests.e2e.benchmarks.chatqna.pysweep.properties.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.cluster.served_model import ServedModel + +# question_file must exist (relative to pysweep_bench.py): main() runs preflight, which stats it. +CLIENT = { + "question_file": "../questions-short.csv", + "concurrency": 4, + "duration": "3m", + "worker_startup_delay": "0s", + "failures_allowed": 200, + "input_tokens": 128, + "warmup_requests": 1, +} + + +COMMIT = { + "sha": "0123456789abcdef0123456789abcdef01234567", + "datetime": "2026-11-25T18:02:44+01:00", + "author": "A. Author", + "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, "collect_metadata", lambda: json.loads(json.dumps(METADATA))) + monkeypatch.setattr(psb, "edp_enabled", lambda: False) + + +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.""" + 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 FingerprintClient that applies writes; 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(): + 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(): + + 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): + 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): + 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(): + 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) + + +class FakeBenchmark: + """Stand-in for the benchmark module that records each invocation.""" + + def __init__(self, rows=1): + self.calls = [] + self._rows = rows + + 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(): + """``-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; anchoring happens later, at the argv boundary. + 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(): + """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) + 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): + 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 + + assert applied == [(128,), (256,)] + 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): + 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["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["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["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) + 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["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}} + + +@allure.feature("pysweep") +def test_the_previous_sweeps_results_are_gone_before_this_one_starts(monkeypatch, tmp_path): + 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() + assert [p.name for p in stale.parent.iterdir()] == ["bench_single.result.csv"] + + +def _passthrough_provision(benchmark_args, workers=1): + """provision_benchmark_target without a cluster.""" + 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): + monkeypatch.setattr(psb, "benchmark", fake) + + +@allure.feature("pysweep") +def test_result_file_names_are_unique_per_run(): + 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(): + 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 would overflow the 255-byte filename limit.""" + 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 + # The shipped example must also be nameable. + example = ( + Path(__file__).resolve().parents[3] + / "e2e/benchmarks/chatqna/pysweep/configs/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(): + 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): + """AutoTokenizer needs the catalog's HF repo id, not the served catalog name.""" + 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): + 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): + 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(): + 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(): + 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(): + 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 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"] + 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): + 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.cluster import auth + + minted = itertools.count(1) + + # Like the real property, each read is a new grant and yields a fresh token. + class _Helper: + @property + def access_token(self): + return f"token-{next(minted)}" + + monkeypatch.setattr( + auth, "load_build_config", lambda: {"base_domain_name": domain} + ) + monkeypatch.setattr(auth, "keycloak_helper", _Helper) + + # Record the lifespan override instead of calling the Keycloak admin API. + lifespan_calls = [] + + @contextmanager + def _lifespan(helper, seconds=auth.SWEEP_TOKEN_LIFESPAN_S): + lifespan_calls.append(("set", seconds)) + try: + yield + finally: + lifespan_calls.append(("restored", seconds)) + + monkeypatch.setattr(auth, "client_token_lifespan", _lifespan) + return lifespan_calls + + +@allure.feature("pysweep") +def test_provision_defaults_to_the_deployments_chatqna_endpoint(monkeypatch): + _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): + """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() + 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): + """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] + 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): + 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): + 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): + 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(): + """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) + 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) + 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(): + 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"))) + assert log_filter.filter(record("Task exception was never retrieved")) + + +@allure.feature("pysweep") +def test_configure_kubernetes_client_logs_enabled_is_a_noop(): + 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): + 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 + + +# 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): + monkeypatch.chdir(tmp_path) + resolved = psb.resolve_question_file("../questions-short.csv") + + assert resolved.is_absolute() + assert resolved == (psb.PYSWEEP_DIR / ".." / "questions-short.csv") + assert resolved.resolve().is_file() + + +@allure.feature("pysweep") +def test_question_file_absolute_path_is_untouched(tmp_path): + 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): + monkeypatch.setattr(psb, "edp_enabled", lambda: True) + example = psb.PYSWEEP_DIR / "configs" / "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(): + 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(): + 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(): + assert issubclass(psb.PreflightError, psb.SweepError) + + +@allure.feature("pysweep") +def test_preflight_runs_before_anything_is_applied(monkeypatch, tmp_path): + 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): + 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): + 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]["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())) == METADATA + + +@allure.feature("pysweep") +def test_preflight_fails_when_any_metadata_is_missing(monkeypatch): + def unreadable(): + raise psb.MetadataError("hardware: No running model-server pod") + + 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) + 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) + 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) + 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}, 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"]} == {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) + 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") +def test_preflight_runs_once_for_the_whole_sweep(monkeypatch, tmp_path): + 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, metadata=True): + calls.append(len(fake.calls)) + return METADATA + + 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 + + assert calls == [0] + assert len(fake.calls) == 2 + + +@allure.feature("pysweep") +def test_preflight_runs_the_corpus_check(monkeypatch): + called = [] + monkeypatch.setattr(psb, "question_file_verify", lambda config: called.append("corpus")) + + psb.preflight_check(load_config(_client())) + + assert called == ["corpus"] + + +@allure.feature("pysweep") +def test_format_settings_yaml_nests_dotted_paths_with_four_spaces(): + 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(): + """Sections keep the caller's order rather than being sorted.""" + 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(): + assert psb.format_settings_yaml({}) == "" + + +@allure.feature("pysweep") +def test_format_settings_yaml_stringifies_what_yaml_cannot_represent(): + 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): + 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(): + """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() + ) + 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..cdab1bdd --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_results_unit.py @@ -0,0 +1,356 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import csv +import json + +import allure +import pytest + +from tests.e2e.benchmarks.chatqna.pysweep.results import ( + PER_CASE_DIR_NAME, + RESULTS_FILE_NAME, + SCHEMA_VERSION, + SUMMARY_FILE_NAME, + RequestRecord, + SummariesLayoutError, + 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", +} +METADATA = {"commit_info": COMMIT, "hardware": {"nodes": ["node-1", "node-2"], "cpu": {"family": "SPR"}}} + +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(): + """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(): + 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(): + """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 + + +@allure.feature("pysweep") +def test_results_are_computed_over_the_recorded_requests(tmp_path): + path = _result_file( + tmp_path, + [ + [128, 11, 1.0, 3.0, "", 200], + [128, 11, 2.0, 6.0, "", 200], + ], + ) + 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") +def test_unsuccessful_and_implausible_rows_are_excluded(tmp_path): + 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, duration_s=10)["requests"] == {"ok": 1} + + +@allure.feature("pysweep") +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_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"}, + } + + +@allure.feature("pysweep") +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), + edp={"vector_db.num_vectors": 55312}, + ) + assert record["settings"]["edp"] == {"vector_db": {"num_vectors": 55312}} + 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") + + +@allure.feature("pysweep") +def test_results_json_exists_before_the_first_run_finishes(layout): + 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", + "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", metadata=METADATA) + 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_the_csv_has_one_dotted_row_per_run(layout): + 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[:9] == [ + "date", + "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]["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", metadata=METADATA) + 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_result_file_pointer_is_relative_to_the_summaries_directory(layout): + 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", metadata=METADATA) + elsewhere = tmp_path / "elsewhere.csv" + assert sweep.pointer(elsewhere) == str(elsewhere) + + +@allure.feature("pysweep") +def test_the_output_layout_is_created_when_nothing_is_there(tmp_path): + """Including intermediate directories.""" + 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.results_file == layout.root / RESULTS_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): + monkeypatch.chdir(tmp_path) + + layout = prepare_summaries_dir("results") + + assert layout.root.is_absolute() + assert layout.summary_file.is_absolute() + assert layout.results_file.is_absolute() + assert layout.per_case_dir.is_absolute() + + +@allure.feature("pysweep") +def test_the_previous_sweep_is_discarded(tmp_path): + 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") + (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") + + layout = prepare_summaries_dir(root) + + assert not layout.summary_file.exists() + assert not layout.results_file.exists() + assert list(layout.per_case_dir.iterdir()) == [] + + +@allure.feature("pysweep") +def test_nothing_else_in_the_directory_is_touched(tmp_path): + 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): + 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): + 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): + 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_seed_unit.py b/src/tests/e2e/validation/pysweep/test_seed_unit.py new file mode 100644 index 00000000..ceddcdb6 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_seed_unit.py @@ -0,0 +1,201 @@ +# 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, seed + + +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_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_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")] + + +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 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..711a5b50 --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_served_model.py @@ -0,0 +1,53 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import logging + +import allure +import pytest + +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__) + + +@pytest.fixture(scope="module") +def observed_model(pysweep_kubernetes_access): + 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): + assert observed_model + assert observed_model == observed_model.strip() + + +@allure.feature("pysweep") +def test_the_observed_model_is_a_catalog_name(observed_model): + 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): + 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): + 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 + ), 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..903a3ade --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_served_model_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.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" + + +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: + def __init__(self, pods=None, served=None): + self.pods = [FakePod("llm-usvc-a", MODEL)] if pods is None else list(pods) + # model name -> replicas; a key 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): + monkeypatch.setattr(served_model, "kr8s", SimpleNamespace(get=fake.get)) + monkeypatch.setattr( + served_model, "LLMInferenceService", SimpleNamespace(get=fake.llmisvc_get) + ) + return fake + + +@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): + 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): + fake = FakeCluster(served={MODEL: 4, OTHER: 4}) + install(monkeypatch, fake) + + assert ServedModel().read() == MODEL + + +@allure.feature("pysweep") +def test_read_ignores_terminating_pods(monkeypatch): + 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): + 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): + 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): + 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): + 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..f18d740f --- /dev/null +++ b/src/tests/e2e/validation/pysweep/test_token_lifespan_unit.py @@ -0,0 +1,124 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import allure +import pytest + +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, +) +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: + 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(auth.requests, "get", fake.get) + monkeypatch.setattr(auth.requests, "put", fake.put) + return fake + + return install + + +@allure.feature("pysweep") +def test_the_sweep_value_is_arbitrary_but_outlasts_a_long_run(): + assert auth.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/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} 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..eafc0a07 100644 --- a/src/tox.ini +++ b/src/tox.ini @@ -325,6 +325,22 @@ 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 + allure-pytest==2.15.3 + pydantic==2.13.4 + kr8s==0.20.15 + requests==2.33.1 +commands = + 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 =